/**
 * Общие фильтры /reports — даты, ферма, кормораздатчик, рейс.
 */
(function (global) {
  function parseLocalDate(iso) {
    if (!iso) return null;
    const p = String(iso).split("-");
    if (p.length !== 3) return null;
    const d = new Date(Number(p[0]), Number(p[1]) - 1, Number(p[2]));
    d.setHours(0, 0, 0, 0);
    return d;
  }

  function getDateParams() {
    global.WespReportsDateRange?.commit?.();
    const from = document.getElementById("date-from")?.value || "";
    const to = document.getElementById("date-to")?.value || "";
    return { date_from: from, date_to: to };
  }

  function getMultiValues(selectId) {
    const fromDropdown =
      global.WespReportsFilterDropdown?.getMultiSelectValues?.(selectId);
    if (Array.isArray(fromDropdown)) return fromDropdown.filter(Boolean);
    const value = (document.getElementById(selectId)?.value || "").trim();
    return value ? [value] : [];
  }

  function getSelectedFarmNames() {
    const wrap = document.getElementById("reportsFarmFilterWrap");
    if (wrap?.hidden) return [];
    return getMultiValues("farm-select");
  }

  /** @deprecated используйте getSelectedFarmNames */
  function getSelectedFarm() {
    const names = getSelectedFarmNames();
    return names.length === 1 ? names[0] : "";
  }

  function getSelectedDispenserNames() {
    return getMultiValues("dispenser-select");
  }

  function getEffectiveDispenserNames() {
    const selected = getSelectedDispenserNames();
    if (selected.length) return selected;
    const farms = getSelectedFarmNames();
    if (!farms.length) return [];
    const names = new Set();
    farms.forEach((farm) => {
      (global.reportsDispensersByFarm?.[farm] || []).forEach((name) => names.add(name));
    });
    return Array.from(names);
  }

  function getDispenserName() {
    const names = getSelectedDispenserNames();
    return names.length === 1 ? names[0] : "";
  }

  function getDispenserIdsForNames(names) {
    const map = global.reportsDispenserIdByName || {};
    return (names || []).map((name) => map[name]).filter(Boolean);
  }

  function getDispenserIds() {
    return getDispenserIdsForNames(getEffectiveDispenserNames());
  }

  function getDispenserId() {
    const ids = getDispenserIds();
    return ids.length === 1 ? ids[0] : "";
  }

  function getRecipeIdsForDispensers(names) {
    const map = global.reportsRecipesByDispenserName || {};
    const ids = new Set();
    (names || []).forEach((name) => {
      (map[name] || []).forEach((recipe) => {
        if (recipe?.id) ids.add(String(recipe.id));
      });
    });
    return Array.from(ids);
  }

  function getSelectedRecipeNames() {
    return getMultiValues("recipe-select");
  }

  function getRecipeName() {
    const names = getSelectedRecipeNames();
    return names.length === 1 ? names[0] : "";
  }

  function getRecipeIds() {
    const names = getSelectedRecipeNames();
    if (!names.length) return [];
    const select = document.getElementById("recipe-select");
    if (!select) return [];
    const ids = [];
    names.forEach((name) => {
      const opt = Array.from(select.options).find((o) => o.value === name);
      if (opt?.dataset?.recipeId) ids.push(String(opt.dataset.recipeId));
    });
    return ids;
  }

  function getRecipeId() {
    const ids = getRecipeIds();
    return ids.length === 1 ? ids[0] : "";
  }

  function buildAnalyticsParams() {
    const params = new URLSearchParams(getDateParams());
    const recipeIds = getRecipeIds();
    if (recipeIds.length === 1) {
      params.set("recipe_id", recipeIds[0]);
      return params;
    }
    if (recipeIds.length > 1) {
      params.set("recipe_ids", recipeIds.join(","));
      return params;
    }
    const dispenserNames = getEffectiveDispenserNames();
    if (dispenserNames.length) {
      const fromDispensers = getRecipeIdsForDispensers(dispenserNames);
      if (fromDispensers.length) params.set("recipe_ids", fromDispensers.join(","));
    }
    return params;
  }

  function buildAlertsParams() {
    const params = new URLSearchParams(getDateParams());
    const dispenserIds = getDispenserIds();
    if (dispenserIds.length === 1) {
      params.set("dispenser_id", dispenserIds[0]);
    } else if (dispenserIds.length > 1) {
      params.set("dispenser_id", dispenserIds.join(","));
    }
    return params;
  }

  function clearMultiSelect(selectId) {
    global.WespReportsFilterDropdown?.setMultiSelectValues?.(selectId, []);
    const select = document.getElementById(selectId);
    if (select) select.value = "";
  }

  function clearDispenserSelection() {
    clearMultiSelect("dispenser-select");
  }

  function clearFarmSelection() {
    clearMultiSelect("farm-select");
  }

  function clearRecipeSelection() {
    clearMultiSelect("recipe-select");
  }

  global.WespReportsFilters = {
    parseLocalDate,
    getDateParams,
    getSelectedFarmNames,
    getSelectedFarm,
    getSelectedDispenserNames,
    getEffectiveDispenserNames,
    getDispenserName,
    getDispenserId,
    getDispenserIds,
    getRecipeIdsForDispensers,
    getSelectedRecipeNames,
    getRecipeName,
    getRecipeId,
    getRecipeIds,
    buildAnalyticsParams,
    buildAlertsParams,
    clearDispenserSelection,
    clearFarmSelection,
    clearRecipeSelection,
  };
})(typeof window !== "undefined" ? window : globalThis);
