// Collection / shop — Inga's 3-layer structure (site notes 2026-06-12):
//
//   Layer 1  Anlass          horizontal bar at the top (Apéro/Essen/Cocktails/Feiern)
//   Layer 2  Geschmackswelten round boxes (Frisch & Leicht, Fruchtig & Lebendig, …)
//   Layer 3  Getränkeart     filter chips, derived live from Shopify Produkttyp
//
// Which products belong where is decided ENTIRELY in Shopify: Layer 1 + 2 via
// prefixed tags ("Anlass:Apéro", "Geschmack:Frisch & Leicht"), Layer 3 via the
// Produkttyp field. The taxonomy lists (order, translations, circle colors)
// are the site's information architecture and live in i18n.js.
//
// The mega menu (and any /shop?anlass=… deep link) can preset any layer via
// the `filter` prop; `onFilterChange` mirrors chip clicks back into the URL.
function Collection({ onOpen, onAdd, filter, onFilterChange }) {
  const [anlass, setAnlass] = useState("Alle");
  const [geschmack, setGeschmack] = useState(null);   // null = all
  const [art, setArt] = useState("Alle");
  const [sort, setSort] = useState("featured");

  // Sync preset filters coming from the mega/mobile menu or the URL.
  // `_ts` changes on every nav click so clicking the same entry twice
  // still resets cleanly.
  useEffect(() => {
    if (!filter) return;
    setAnlass(filter.anlass || "Alle");
    setGeschmack(filter.geschmack || null);
    setArt(filter.art || "Alle");
  }, [filter && filter._ts]);

  // Mirror the current filter state into the URL (history.replaceState in
  // App.jsx) so filtered views are shareable and survive a reload.
  useEffect(() => {
    if (onFilterChange) onFilterChange({ anlass, geschmack, art });
  }, [anlass, geschmack, art]);

  // Layer 2: the fixed 4 worlds, plus any extra Geschmack: values Inga
  // invents in Shopify later (appended at the end, untranslated).
  const knownWorlds = TAXONOMY.geschmack.map((g) => g.key);
  const extraWorlds = Array.from(new Set(
    PRODUCTS.flatMap((p) => p.geschmack || [])
      .filter((g) => !knownWorlds.some((k) => k.toLowerCase() === g.toLowerCase()))
  ));
  const worlds = [
    ...TAXONOMY.geschmack,
    ...extraWorlds.map((key) => ({ key, de: key, en: key, wash: "gw--extra" })),
  ];

  // Layer 3: live from the catalog ("Sets" sorted last).
  const drinkTypes = ["Alle", ...Array.from(new Set(PRODUCTS.map((p) => p.category).filter(Boolean)))
    .sort((a, b) => (a === "Sets") - (b === "Sets") || a.localeCompare(b, "de"))];

  const matchTag = (list, val) =>
    (list || []).some((x) => String(x).toLowerCase() === String(val).toLowerCase());

  let items = PRODUCTS.filter((p) =>
    (anlass === "Alle" || matchTag(p.anlass, anlass)) &&
    (!geschmack || matchTag(p.geschmack, geschmack)) &&
    (art === "Alle" || p.category === art)
  );
  if (sort === "low")  items = [...items].sort((a, b) => a.price - b.price);
  if (sort === "high") items = [...items].sort((a, b) => b.price - a.price);

  const hasFilter = anlass !== "Alle" || geschmack || art !== "Alle";
  const reset = () => { setAnlass("Alle"); setGeschmack(null); setArt("Alle"); };

  return (
    <section className="section" style={{ paddingTop: 48 }}>
      <div className="wrap">
        <div className="collection__head">
          <span className="eyebrow">{t("collection.eyebrow")}</span>
          <h2>{anlass !== "Alle" ? taxLabel("anlass", anlass) : t("collection.h2")}</h2>
          <p>{t("collection.lead")}</p>
        </div>

        {/* Layer 1 — Anlass. The primary dimension, styled as the page's
            tab navigation. */}
        <div className="anlass-bar" role="tablist" aria-label={t("collection.anlass")}>
          {["Alle", ...TAXONOMY.anlass.map((a) => a.key)].map((a) => (
            <button
              key={a}
              role="tab"
              aria-selected={anlass === a}
              className={`anlass-tab${anlass === a ? " on" : ""}`}
              onClick={() => setAnlass(a)}
            >
              {a === "Alle" ? t("collection.all") : taxLabel("anlass", a)}
            </button>
          ))}
        </div>

        {/* Layers 2 + 3 — one unified filter panel: two labelled rows of
            identical pills. Geschmack pills carry a small colored dot for
            their world; sort closes off the second row. (The playful round
            Geschmackswelten circles live on the home page as navigation —
            here in the shop, filtering stays quiet and uniform.) */}
        <div className="filters">
          <div className="filter-row">
            <span className="filter-row__label">{t("collection.geschmack")}</span>
            <div className="filter-row__chips">
              {worlds.map((g) => {
                const on = geschmack && geschmack.toLowerCase() === g.key.toLowerCase();
                return (
                  <button
                    key={g.key}
                    className={`chip chip--dot${on ? " chip--on" : ""}`}
                    aria-pressed={!!on}
                    onClick={() => setGeschmack(on ? null : g.key)}
                  >
                    <span className={`dot ${g.wash}`} aria-hidden="true"></span>
                    {taxLabel("geschmack", g.key)}
                  </button>
                );
              })}
            </div>
          </div>
          <div className="filter-row">
            <span className="filter-row__label">{t("collection.art")}</span>
            <div className="filter-row__chips">
              {drinkTypes.map((c) => (
                <button key={c} className={`chip${art === c ? " chip--on" : ""}`} onClick={() => setArt(c)}>
                  {c === "Alle" ? t("collection.all") : c}
                </button>
              ))}
            </div>
            <div className="collection__sort">
              <span className="collection__sort-label">{t("collection.sort")}</span>
              <select className="collection__sort-select" value={sort} onChange={(e) => setSort(e.target.value)} aria-label={t("collection.sort")}>
                <option value="featured">{t("collection.sort.featured")}</option>
                <option value="low">{t("collection.sort.low")}</option>
                <option value="high">{t("collection.sort.high")}</option>
              </select>
            </div>
          </div>
        </div>

        {items.length > 0 ? (
          <div className="grid grid--4">
            {items.map((p) => <ProductCard key={p.id} p={p} onOpen={onOpen} onAdd={onAdd} />)}
          </div>
        ) : (
          <div className="collection__empty">
            <Icon name="sprout" size={28} />
            <p>{t("collection.empty")}</p>
            {hasFilter && (
              <Button variant="secondary" size="md" onClick={reset}>{t("collection.reset")}</Button>
            )}
          </div>
        )}
      </div>
    </section>
  );
}
Object.assign(window, { Collection });
