/**
 * Экспорт /reports — выбор раздела и формата (Excel / PDF).
 */
(function (global) {
  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 closeMenu() {
    const menu = document.getElementById("reportsExportMenu");
    const btn = document.getElementById("reportsExportBtn");
    if (menu) menu.hidden = true;
    if (btn) btn.setAttribute("aria-expanded", "false");
  }

  function toggleMenu() {
    const menu = document.getElementById("reportsExportMenu");
    const btn = document.getElementById("reportsExportBtn");
    if (!menu || !btn) return;
    const open = menu.hidden;
    menu.hidden = !open;
    btn.setAttribute("aria-expanded", open ? "true" : "false");
  }

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

    btn.addEventListener("click", (e) => {
      e.stopPropagation();
      toggleMenu();
    });

    menu.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();
      });
    });

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

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

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