/**
 * Экспорт /reports — выбор раздела и формата (Excel / PDF).
 */
(function (global) {
  let btnEl = null;
  let menuEl = null;
  let isOpen = false;
  let suppressOutsideCloseUntil = 0;

  function appendFilterContext(params) {
    const farms = global.WespReportsFilters?.getSelectedFarmNames?.() || [];
    const dispensers = global.WespReportsFilters?.getSelectedDispenserNames?.() || [];
    const recipes = global.WespReportsFilters?.getSelectedRecipeNames?.() || [];
    params.set("filter_farms", farms.length ? farms.join(",") : "all");
    params.set("filter_dispensers", dispensers.length ? dispensers.join(",") : "all");
    params.set("filter_recipes", recipes.length ? recipes.join(",") : "all");
    return params;
  }

  function buildExportUrl(format, section) {
    const params = global.WespReportsFilters?.buildAnalyticsParams?.() || new URLSearchParams();
    appendFilterContext(params);
    params.set("format", format || "xlsx");
    params.set("section", section || "all");
    return `/api/analytics/export?${params.toString()}`;
  }

  function ensureDates() {
    const { date_from, date_to } = global.WespReportsFilters?.getDateParams?.() || {};
    if (!date_from || !date_to) {
      global.WespZootechNotify?.error?.("Выберите период для экспорта");
      return false;
    }
    return true;
  }

  function download(format, section) {
    if (!ensureDates()) return;
    window.location.href = buildExportUrl(format, section);
  }

  function isMenuTarget(target) {
    if (!target || !btnEl || !menuEl) return false;
    return btnEl.contains(target) || menuEl.contains(target);
  }

  function positionMenu() {
    if (!btnEl || !menuEl || !isOpen) return;
    const rect = btnEl.getBoundingClientRect();
    let top = rect.bottom + 6;
    const menuHeight = menuEl.offsetHeight || 320;
    if (top + menuHeight > window.innerHeight - 12) {
      top = Math.max(12, rect.top - menuHeight - 6);
    }
    menuEl.style.top = `${top}px`;
    menuEl.style.right = `${Math.max(12, window.innerWidth - rect.right)}px`;
    menuEl.style.left = "auto";
    menuEl.style.width = "";
    menuEl.style.transform = "";
  }

  function closeMenu() {
    isOpen = false;
    suppressOutsideCloseUntil = 0;
    if (menuEl) {
      menuEl.hidden = true;
      menuEl.setAttribute("hidden", "");
      menuEl.classList.remove("reports-export-dropdown__menu--open");
      menuEl.style.top = "";
      menuEl.style.right = "";
      menuEl.style.left = "";
      menuEl.style.width = "";
      menuEl.style.transform = "";
    }
    if (btnEl) btnEl.setAttribute("aria-expanded", "false");
    window.removeEventListener("resize", positionMenu);
    window.removeEventListener("scroll", positionMenu, true);
  }

  function openMenu() {
    global.WespReportsDateRange?.close?.();
    global.WespReportsFilterDropdown?.closeAll?.();
    isOpen = true;
    suppressOutsideCloseUntil = Date.now() + 180;
    if (menuEl) {
      menuEl.removeAttribute("hidden");
      menuEl.hidden = false;
      menuEl.classList.add("reports-export-dropdown__menu--open");
    }
    if (btnEl) btnEl.setAttribute("aria-expanded", "true");
    positionMenu();
    requestAnimationFrame(() => positionMenu());
    window.addEventListener("resize", positionMenu);
    window.addEventListener("scroll", positionMenu, true);
  }

  function toggleMenu() {
    if (isOpen) closeMenu();
    else openMenu();
  }

  function init() {
    btnEl = document.getElementById("reportsExportBtn");
    menuEl = document.getElementById("reportsExportMenu");
    if (!btnEl || !menuEl || btnEl.dataset.bound) return;
    btnEl.dataset.bound = "1";

    if (menuEl.parentElement !== document.body) {
      document.body.appendChild(menuEl);
    }

    btnEl.addEventListener(
      "pointerdown",
      (e) => {
        if (e.button !== 0) return;
        e.preventDefault();
        e.stopPropagation();
        e.stopImmediatePropagation();
        toggleMenu();
      },
      true
    );

    menuEl.querySelectorAll("[data-reports-export-format]").forEach((item) => {
      item.addEventListener("click", (e) => {
        e.preventDefault();
        e.stopPropagation();
        download(
          item.getAttribute("data-reports-export-format") || "xlsx",
          item.getAttribute("data-reports-export-section") || "all"
        );
        closeMenu();
      });
    });

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

    document.addEventListener(
      "pointerdown",
      (e) => {
        if (Date.now() < suppressOutsideCloseUntil) return;
        if (!isOpen) return;
        if (isMenuTarget(e.target)) return;
        closeMenu();
      },
      true
    );

    document.addEventListener("keydown", (e) => {
      if (e.key === "Escape" && isOpen) closeMenu();
    });
  }

  global.WespReportsExport = {
    init,
    buildExportUrl,
    download,
    appendFilterContext,
    close: closeMenu,
  };
})(typeof window !== "undefined" ? window : globalThis);
