/**
 * Кастомные выпадашки фильтров /reports (без нативного select macOS).
 * Скрытый <select> сохраняется для совместимости с существующим кодом.
 * data-multiselect — чекбоксы (ферма, кормораздатчик, рейс).
 */
(function (global) {
  const instances = new Map();

  function closeAll(exceptMenu) {
    instances.forEach(({ menu }) => {
      if (menu && menu !== exceptMenu) menu.hidden = true;
    });
  }

  function getMultiSelected(wrap) {
    try {
      const raw = wrap?.dataset?.selectedValues || "[]";
      const parsed = JSON.parse(raw);
      return Array.isArray(parsed) ? parsed.filter(Boolean) : [];
    } catch (_e) {
      return [];
    }
  }

  function setMultiSelected(wrap, values) {
    if (!wrap) return;
    wrap.dataset.selectedValues = JSON.stringify(values || []);
  }

  function countSelectableOptions(select) {
    return Array.from(select.options).filter((opt) => opt.value).length;
  }

  const MULTI_COUNT_LABELS = {
    "farm-select": "Фермы",
    "dispenser-select": "Кормораздатчики",
    "recipe-select": "Рейсы",
  };

  function formatMultiLabel(select, selected) {
    const allLabel =
      select.querySelector('option[value=""]')?.textContent?.trim() || "—";
    const total = countSelectableOptions(select);
    const count = selected.length;

    if (!count || (total > 0 && count >= total)) return allLabel;
    if (count === 1) return selected[0];

    const entity = MULTI_COUNT_LABELS[select.id];
    if (entity) return `${entity} (${count})`;
    return `Выбрано: ${count}`;
  }

  function updateTriggerLabel(select, trigger, wrap) {
    const textEl = trigger.querySelector(".reports-filter-dropdown__label");
    let label;
    if (select.dataset.multiselect === "true" && wrap) {
      label = formatMultiLabel(select, getMultiSelected(wrap));
    } else {
      const opt = select.selectedOptions?.[0];
      label = opt?.textContent?.trim() || "—";
    }
    if (textEl) textEl.textContent = label;
    trigger.setAttribute(
      "aria-label",
      select.getAttribute("aria-label") || label
    );
  }

  function dispatchSelectChange(select) {
    select.dispatchEvent(new Event("change", { bubbles: true }));
  }

  function createCheckboxRow(labelText, checked, onChange) {
    const row = document.createElement("label");
    row.className = "reports-filter-dropdown__check";

    const boxWrap = document.createElement("span");
    boxWrap.className = "zt-checkbox";

    const input = document.createElement("input");
    input.type = "checkbox";
    input.className = "zt-checkbox__input";
    input.checked = checked;

    const box = document.createElement("span");
    box.className = "zt-checkbox__box";
    box.setAttribute("aria-hidden", "true");

    boxWrap.appendChild(input);
    boxWrap.appendChild(box);

    const text = document.createElement("span");
    text.className = "reports-filter-dropdown__check-label";
    text.textContent = labelText;

    input.addEventListener("change", (e) => {
      e.stopPropagation();
      onChange(input);
    });

    row.appendChild(boxWrap);
    row.appendChild(text);
    return { row, input };
  }

  function buildSingleMenu(select, menu, trigger, wrap) {
    menu.innerHTML = "";
    Array.from(select.options).forEach((opt) => {
      const item = document.createElement("button");
      item.type = "button";
      item.className = "reports-filter-dropdown__item";
      item.setAttribute("role", "option");
      item.dataset.value = opt.value;
      item.textContent = opt.textContent;
      if (opt.value === select.value) {
        item.classList.add("reports-filter-dropdown__item--active");
        item.setAttribute("aria-selected", "true");
      }
      item.addEventListener("click", (e) => {
        e.stopPropagation();
        select.value = opt.value;
        updateTriggerLabel(select, trigger, wrap);
        buildSingleMenu(select, menu, trigger, wrap);
        menu.hidden = true;
        trigger.setAttribute("aria-expanded", "false");
        dispatchSelectChange(select);
      });
      menu.appendChild(item);
    });
    updateTriggerLabel(select, trigger, wrap);
  }

  function buildMultiMenu(select, menu, trigger, wrap) {
    menu.innerHTML = "";
    const selected = getMultiSelected(wrap);
    const allLabel =
      select.querySelector('option[value=""]')?.textContent?.trim() || "—";

    const { row: allRow, input: allInput } = createCheckboxRow(
      allLabel,
      selected.length === 0,
      (input) => {
        if (input.checked) {
          setMultiSelected(wrap, []);
          select.value = "";
        }
        buildMultiMenu(select, menu, trigger, wrap);
        dispatchSelectChange(select);
      }
    );
    menu.appendChild(allRow);

    Array.from(select.options).forEach((opt) => {
      if (!opt.value) return;
      const { row } = createCheckboxRow(opt.textContent, selected.includes(opt.value), (input) => {
        let next = getMultiSelected(wrap);
        if (input.checked) {
          if (!next.includes(opt.value)) next = next.concat(opt.value);
        } else {
          next = next.filter((v) => v !== opt.value);
        }
        setMultiSelected(wrap, next);
        select.value = "";
        buildMultiMenu(select, menu, trigger, wrap);
        dispatchSelectChange(select);
      });
      menu.appendChild(row);
    });

    updateTriggerLabel(select, trigger, wrap);
  }

  function buildMenu(select, menu, trigger, wrap) {
    if (select.dataset.multiselect === "true") {
      buildMultiMenu(select, menu, trigger, wrap);
    } else {
      buildSingleMenu(select, menu, trigger, wrap);
    }
  }

  function bindSelect(selectId) {
    const select = document.getElementById(selectId);
    if (!select || select.dataset.dropdownBound === "1") {
      return instances.get(selectId);
    }
    select.dataset.dropdownBound = "1";

    const wrap = select.closest(".reports-filter-select");
    if (!wrap) return null;

    if (select.dataset.multiselect === "true" && !wrap.dataset.selectedValues) {
      wrap.dataset.selectedValues = "[]";
    }

    wrap.querySelector(".reports-filter-select__chev")?.remove();

    const trigger = document.createElement("button");
    trigger.type = "button";
    trigger.className =
      "reports-filter-dropdown__trigger reports-filter-bar__control";
    trigger.setAttribute("aria-haspopup", "listbox");
    trigger.setAttribute("aria-expanded", "false");
    trigger.innerHTML =
      '<span class="reports-filter-dropdown__label"></span>' +
      '<i class="fas fa-chevron-down reports-filter-dropdown__chev" aria-hidden="true"></i>';

    const menu = document.createElement("div");
    menu.className = "reports-filter-dropdown__menu";
    menu.hidden = true;
    menu.setAttribute("role", "listbox");

    select.classList.add("reports-filter-select__native");
    wrap.insertBefore(trigger, select);
    wrap.insertBefore(menu, select);

    trigger.addEventListener("click", (e) => {
      e.stopPropagation();
      const willOpen = menu.hidden;
      closeAll(willOpen ? menu : null);
      menu.hidden = !willOpen;
      trigger.setAttribute("aria-expanded", willOpen ? "true" : "false");
    });

    menu.addEventListener("mousedown", (e) => e.stopPropagation());
    menu.addEventListener("click", (e) => e.stopPropagation());

    const observer = new MutationObserver(() => {
      buildMenu(select, menu, trigger, wrap);
    });
    observer.observe(select, { childList: true, subtree: true, attributes: true });

    buildMenu(select, menu, trigger, wrap);

    const api = {
      select,
      wrap,
      trigger,
      menu,
      rebuild: () => buildMenu(select, menu, trigger, wrap),
      observer,
      getMultiSelected: () => getMultiSelected(wrap),
      setMultiSelected: (values) => {
        setMultiSelected(wrap, values);
        select.value = "";
        buildMenu(select, menu, trigger, wrap);
      },
    };
    instances.set(selectId, api);
    return api;
  }

  function init() {
    bindSelect("farm-select");
    bindSelect("dispenser-select");
    bindSelect("recipe-select");
    document.addEventListener("click", () => closeAll());
    document.addEventListener("keydown", (e) => {
      if (e.key === "Escape") closeAll();
    });
  }

  function refreshAll() {
    instances.forEach((api) => api.rebuild?.());
  }

  function getMultiSelectValues(selectId) {
    return instances.get(selectId)?.getMultiSelected?.() || [];
  }

  function setMultiSelectValues(selectId, values) {
    instances.get(selectId)?.setMultiSelected?.(values);
  }

  global.WespReportsFilterDropdown = {
    init,
    refreshAll,
    bindSelect,
    getMultiSelectValues,
    setMultiSelectValues,
  };
})(typeof window !== "undefined" ? window : globalThis);
