/* global React, Icon, IMG, NEWS, WEAR_PROOF, PhImg, LoopVideo */
const { createElement: e, useEffect: useEffectH, useRef: useRefH, useState: useStateH } = React;

const CRAFT_SPECS = [
  { t: "Material", d: "Massiver, handpolierter Acetat-Rahmen mit Federscharnieren. Leicht, stabil und für den Alltag ausgelegt." },
  { t: "Schutz", d: "Tiefschwarze Gläser mit 100 % UV400 und Filterkategorie 3 — voller Schutz bei klarem Blick." },
  { t: "Lieferumfang", d: "Signature-Box mit Seiden-Inlay, Leder-Etui und Mikrofasertuch. Bereit zum Verschenken." },
];

/* ---------------- Craft accordion (Prada product-details style) ---------------- */
function CraftAccordion({ items }) {
  const [open, setOpen] = useStateH(-1);
  return e("div", { className: "acc" },
    items.map((item, i) =>
      e("div", { key: i, className: "acc-item" + (open === i ? " open" : "") },
        e("button", {
          type: "button", className: "acc-head",
          onClick: () => setOpen(open === i ? -1 : i),
          "aria-expanded": open === i,
        },
          e("span", null, item.t),
          e("span", { className: "acc-sign", "aria-hidden": true })),
        e("div", { className: "acc-body" },
          e("div", { className: "acc-body-inner" }, item.d)))));
}

/* ---------------- Wear proof carousel (Loox / visual UGC style) ---------------- */
function WearProof() {
  const [idx, setIdx] = useStateH(0);
  const trackRef = useRefH(null);
  const go = (i) => {
    const n = (i + WEAR_PROOF.length) % WEAR_PROOF.length;
    setIdx(n);
    const track = trackRef.current;
    if (!track) return;
    const slide = track.children[n];
    if (!slide) return;
    const pad = parseFloat(getComputedStyle(track).paddingLeft) || 0;
    const maxLeft = track.scrollWidth - track.clientWidth;
    const target = n === WEAR_PROOF.length - 1
      ? maxLeft
      : Math.max(0, slide.offsetLeft - pad);
    track.scrollTo({ left: Math.min(target, maxLeft), behavior: "smooth" });
  };
  useEffectH(() => {
    const track = trackRef.current;
    if (!track) return undefined;
    const onScroll = () => {
      const pad = parseFloat(getComputedStyle(track).paddingLeft) || 0;
      let best = 0;
      let bestDist = Infinity;
      [...track.children].forEach((slide, i) => {
        const d = Math.abs(slide.offsetLeft - pad - track.scrollLeft);
        if (d < bestDist) { bestDist = d; best = i; }
      });
      setIdx(best);
    };
    track.addEventListener("scroll", onScroll, { passive: true });
    return () => track.removeEventListener("scroll", onScroll);
  }, []);
  return e("section", { className: "wear-proof" },
    e("div", { className: "wear-proof__head" },
      e("div", null,
        e("p", { className: "wear-proof__kicker" }, "Getragen · Bewertet"),
        e("h3", { className: "wear-proof__title" }, "Echte Stimmen")),
      e("div", { className: "wear-proof__nav" },
        e("button", { type: "button", onClick: () => go(idx - 1), "aria-label": "Vorherige Bewertung" },
          e(Icon, { name: "arrowL", size: 16 })),
        e("button", { type: "button", onClick: () => go(idx + 1), "aria-label": "Nächste Bewertung" },
          e(Icon, { name: "arrowR", size: 16 })))),
    e("div", { className: "wear-proof__track", ref: trackRef },
      WEAR_PROOF.map((item, i) =>
        e("article", { key: i, className: "wear-proof__slide" + (i === idx ? " is-active" : "") },
          e("img", { src: item.img, alt: "ANAYA Geometric Block — getragen", loading: "lazy", style: { objectPosition: item.pos } }),
          e("div", { className: "wear-proof__overlay" },
            e("div", { className: "wear-proof__stars", "aria-label": "5 von 5 Sternen" }, "★★★★★"),
            e("blockquote", { className: "wear-proof__quote" }, "„", item.quote, "”"),
            e("footer", { className: "wear-proof__by" }, item.name, " · Verifizierter Kauf"))))),
    e("div", { className: "wear-proof__dots" },
      WEAR_PROOF.map((_, i) =>
        e("button", {
          key: i, type: "button", className: i === idx ? "on" : "",
          onClick: () => go(i), "aria-label": "Bewertung " + (i + 1),
        }))));
}

/* ---------------- AnayaSphere News (Pradasphere-style) ---------------- */
function AnayaSphere({ onShop, onFounders }) {
  const [idx, setIdx] = useStateH(0);
  const trackRef = useRefH(null);
  const go = (i) => {
    const n = (i + NEWS.length) % NEWS.length;
    setIdx(n);
    const track = trackRef.current;
    if (!track) return;
    const slide = track.children[n];
    if (!slide) return;
    const pad = parseFloat(getComputedStyle(track).paddingLeft) || 0;
    const maxLeft = track.scrollWidth - track.clientWidth;
    const target = n === NEWS.length - 1
      ? maxLeft
      : Math.max(0, slide.offsetLeft - pad);
    track.scrollTo({ left: Math.min(target, maxLeft), behavior: "smooth" });
  };
  const open = (item) => {
    if (item.tag === "Events") return onFounders();
    return onShop();
  };
  return e("section", { className: "anayasphere" },
    e("div", { className: "anayasphere__head" },
      e("h3", { className: "anayasphere__title" }, "Anaya Journal"),
      e("div", { className: "anayasphere__nav" },
        e("button", { onClick: () => go(idx - 1), "aria-label": "Zurück" }, e(Icon, { name: "arrowL", size: 16 })),
        e("button", { onClick: () => go(idx + 1), "aria-label": "Weiter" }, e(Icon, { name: "arrowR", size: 16 })))),
    e("div", { className: "anayasphere__track", ref: trackRef },
      NEWS.map((item, i) =>
        e("button", {
          key: i, className: "anayasphere__slide", onClick: () => open(item),
          style: { border: 0, padding: 0, cursor: "pointer", textAlign: "left" },
        },
          e("img", { src: item.img, alt: item.title, loading: "lazy" }),
          e("div", { className: "anayasphere__overlay" },
            e("span", { className: "anayasphere__label" }, item.tag),
            e("p", { className: "anayasphere__headline" }, item.title),
            e("span", { className: "anayasphere__discover" }, item.action))))),
    e("div", { className: "anayasphere__dots" },
      NEWS.map((_, i) => e("i", { key: i, className: i === idx ? "on" : "", onClick: () => go(i) }))));
}

/* ---------------- Newsletter / Founders signup ---------------- */
function Subscribe({ onFounders }) {
  const [v, setV] = useStateH("");
  const go = () => onFounders(v);
  return e("div", { style: { display: "flex", border: "1px solid var(--gold)", marginBottom: 30 } },
    e("input", {
      value: v, onChange: (ev) => setV(ev.target.value), type: "email",
      placeholder: "name@email.de", "aria-label": "E-Mail-Adresse",
      onKeyDown: (ev) => { if (ev.key === "Enter") go(); },
      style: { flex: 1, background: "none", border: 0, outline: "none", color: "var(--cream)",
        padding: "12px 14px", fontSize: 13, fontFamily: "var(--sans)" } }),
    e("button", { onClick: go, "aria-label": "Auf die Founders List",
      style: { background: "var(--gold)", border: 0, color: "var(--ink)", padding: "0 16px", fontSize: 14 } }, "→"));
}

/* ---------------- Search (Prada Algolia-style) ---------------- */
const SEARCH_INDEX = [
  { label: "Geometric Block", sub: "Sonnenbrille · Handpoliertes Acetat", tags: ["geometric", "block", "sonnenbrille", "brille", "acetat", "n°1"], action: "shop", thumb: IMG.thumb, kind: "Produkt" },
  { label: "Sonnenbrillen", sub: "Erste Edition · 200 nummerierte Stücke", tags: ["sonnenbrille", "eyewear", "brille", "kollektion", "sunglasses"], action: "shop", kind: "Kollektion" },
  { label: "Founders List", sub: "Pre-Launch · Gründerpreis sichern", tags: ["founders", "warteliste", "pre-launch", "gründerpreis", "liste", "platz"], action: "founders", kind: "Service" },
  { label: "Bold Reflections", sub: "Campaign · Editorial Sommer '26", tags: ["bold", "reflections", "campaign", "editorial", "sommer"], action: "shop", thumb: IMG.editorialRed, kind: "Editorial" },
  { label: "Versand & Rückgabe", sub: "Kostenloser Versand · IOSS inklusive", tags: ["versand", "lieferung", "rückgabe", "ioss", "kostenlos", "shipping"], action: "service", kind: "Service" },
  { label: "UV400 · Kat. 3", sub: "Vollschutz · Premium-Gläser", tags: ["uv", "schutz", "linsen", "kategorie", "gläser"], action: "shop", kind: "Details" },
  { label: "Signature Box", sub: "Geschenkverpackung inklusive", tags: ["box", "verpackung", "geschenk", "signature"], action: "shop", kind: "Details" },
  { label: "FAQ & Kontakt", sub: "Fragen vor dem Launch", tags: ["faq", "kontakt", "hilfe", "service"], action: "service", kind: "Service" },
];
const SEARCH_COLLECTIONS = [
  { label: "Sonnenbrillen", action: "shop" },
  { label: "Geometric Block", action: "shop" },
  { label: "Founders List", action: "founders" },
];
const SEARCH_HIGHLIGHTS = [
  { label: "Bold Reflections", action: "shop" },
  { label: "Pre-Launch · Erste Edition", action: "founders" },
  { label: "Geometric Block · Sommer '26", action: "shop" },
  { label: "Signature Box", action: "shop" },
];

function matchQuery(q, item) {
  const s = q.trim().toLowerCase();
  if (!s) return false;
  if (item.label.toLowerCase().includes(s)) return true;
  if ((item.sub || "").toLowerCase().includes(s)) return true;
  return (item.tags || []).some((t) => t.includes(s));
}

function highlightLabel(label, q) {
  const s = q.trim();
  if (!s) return label;
  const low = label.toLowerCase();
  const idx = low.indexOf(s.toLowerCase());
  if (idx < 0) return label;
  return [
    label.slice(0, idx),
    e("mark", { className: "search-hit", key: "m" }, label.slice(idx, idx + s.length)),
    label.slice(idx + s.length),
  ];
}

function Search({ open, onClose, onAction }) {
  const [q, setQ] = useStateH("");
  const inputRef = useRefH(null);

  useEffectH(() => {
    if (!open) return undefined;
    setQ("");
    const t = setTimeout(() => inputRef.current && inputRef.current.focus(), 100);
    const onKey = (ev) => { if (ev.key === "Escape") onClose(); };
    document.addEventListener("keydown", onKey);
    return () => { clearTimeout(t); document.removeEventListener("keydown", onKey); };
  }, [open, onClose]);

  const trimmed = q.trim();
  const results = trimmed ? SEARCH_INDEX.filter((item) => matchQuery(q, item)) : [];
  const pick = (action) => () => { onAction(action); onClose(); };

  const saNews = (title, items) =>
    e("div", { className: "sa-news" },
      e("h4", { className: "sa-news__title" }, title),
      e("ul", { className: "sa-news__list" },
        items.map((item, i) =>
          e("li", { key: i },
            e("button", { className: "sa-news__link", onClick: pick(item.action) }, item.label)))));

  const resultRow = (item, i) =>
    e("li", { key: i },
      e("button", { className: "search-results__item", onClick: pick(item.action) },
        item.thumb && e("img", { className: "search-results__thumb", src: item.thumb, alt: "", loading: "lazy" }),
        e("span", { className: "search-results__copy" },
          e("span", { className: "search-results__label" }, highlightLabel(item.label, q)),
          item.sub && e("span", { className: "search-results__sub" }, item.sub),
          item.kind && e("span", { className: "search-results__kind" }, item.kind))));

  return e("div", {
    className: "search-panel" + (open ? " show" : ""),
    role: "dialog",
    "aria-modal": true,
    "aria-label": "Suche",
    "aria-hidden": !open,
  },
    e("div", { className: "search-algolia__top" },
      e("div", { className: "search-algolia__field" },
        e("input", {
          ref: inputRef,
          className: "search-algolia__input",
          placeholder: "Auf anaya.com suchen",
          value: q,
          onChange: (ev) => setQ(ev.target.value),
          "aria-label": "Suchbegriff",
          autoComplete: "off",
          autoCorrect: "off",
          spellCheck: false,
        }),
        trimmed && e("button", {
          className: "search-algolia__clear",
          onClick: () => { setQ(""); inputRef.current && inputRef.current.focus(); },
          "aria-label": "Eingabe löschen",
        }, e(Icon, { name: "close", size: 14 }))),
      e("button", { className: "search-algolia__close", onClick: onClose, "aria-label": "Suche schließen" }, "Schließen")),
    e("section", { className: "search-algolia__body" },
      trimmed
        ? results.length
          ? e("div", { className: "search-algolia__results" },
              e("p", { className: "search-algolia__count" }, results.length, " Ergebnis", results.length === 1 ? "" : "se"),
              e("ul", { className: "search-results" }, results.map(resultRow)))
          : e("p", { className: "search-empty" }, "Keine Ergebnisse für „", trimmed, "“")
        : e("div", { className: "search-algolia__suggest" },
            saNews("Kollektionen", SEARCH_COLLECTIONS),
            saNews("Highlights", SEARCH_HIGHLIGHTS))));
}

/* ---------------- Top Bar ---------------- */
function TopBar({ dark, count, onMenu, onCart, onLogo, onSearch }) {
  return e("header", { className: "topbar" + (dark ? " on-dark" : "") },
    e("div", { className: "tb-side" },
      e("button", { className: "tb-btn", "aria-label": "Menü", onClick: onMenu },
        e("span", { className: "glyph" }))),
    e("button", { className: "tb-logo", onClick: onLogo, style: { background: "none", border: 0 } },
      "ANAYA", e("sup", null, "N°1")),
    e("div", { className: "tb-side right" },
      e("button", { className: "tb-btn", "aria-label": "Suche", onClick: onSearch },
        e(Icon, { name: "search", size: 19 })),
      e("button", { className: "tb-btn", "aria-label": "Warenkorb", onClick: onCart },
        e(Icon, { name: "bag", size: 20 }),
        count > 0 && e("span", { className: "cart-count" }, count))));
}

/* ---------------- Reveal-on-scroll helper ---------------- */
function Reveal({ children, delay = 0, tag = "div", className = "" }) {
  const ref = useRefH(null);
  useEffectH(() => {
    const el = ref.current;
    const io = new IntersectionObserver((ents) => {
      ents.forEach((en) => { if (en.isIntersecting) { setTimeout(() => el.classList.add("in"), delay); io.unobserve(el); } });
    }, { threshold: 0.16 });
    io.observe(el);
    return () => io.disconnect();
  }, []);
  return e(tag, { ref, className: "fade-up " + className }, children);
}

/* ---------------- Home ---------------- */
function Home({ onShop, onFounders, joined, scrollRef, onScroll }) {
  const heroVid = useRefH(null);
  useEffectH(() => {
    const v = heroVid.current;
    if (!v) return;
    v.muted = true;
    v.setAttribute("playsinline", "");
    v.setAttribute("webkit-playsinline", "");
    v.play().catch(() => {});
  }, []);

  return e("div", { className: "screen", ref: scrollRef, onScroll },
    /* HERO — nur Video im Header */
    e("section", { className: "hero-campaign" },
      e("video", {
        ref: heroVid,
        className: "hero-campaign__video",
        src: IMG.heroVideo,
        "aria-label": "ANAYA N°1 — Bold Reflections Campaign",
        autoPlay: true,
        muted: true,
        loop: true,
        playsInline: true,
        controls: false,
        preload: "auto",
      }),
      e("div", { className: "hero-campaign__overlay" },
        e("div", { className: "eyebrow", style: { color: "var(--gold)", marginBottom: 16 } }, "Sonnenbrillen · Erste Edition · 200 Stück"),
        e("h1", { className: "display", style: { color: "var(--cream)", fontSize: 46, margin: "0 0 18px" } },
          "Bold", e("br"), e("em", { style: { fontStyle: "italic" } }, "Reflections.")),
        e("p", { style: { color: "rgba(248,246,240,.78)", fontSize: 13.5, lineHeight: 1.6, maxWidth: 300, margin: "0 0 26px", letterSpacing: ".01em" } },
          "Eine architektonische Sonnenbrille aus handpoliertem Acetat. Sichere dir deinen nummerierten Platz zum Gründerpreis — bevor wir öffnen."),
        e("button", { className: "btn", style: { background: "var(--cream)", color: "var(--ink)", borderColor: "var(--cream)", maxWidth: 280 }, onClick: () => onFounders() },
          joined ? "Dein Platz ist gesichert" : "Auf die Founders List", e(Icon, { name: "arrowR", size: 15 })),
        e("button", { onClick: onShop, style: {
          marginTop: 14, background: "none", border: 0, color: "rgba(248,246,240,.82)",
          fontSize: 11, letterSpacing: ".22em", textTransform: "uppercase",
          display: "flex", alignItems: "center", gap: 8, alignSelf: "flex-start" } },
          "Kollektion ansehen", e(Icon, { name: "arrowR", size: 13 })))),

    /* MARQUEE trust */
    e("div", { className: "marquee" },
      e("div", { className: "marquee-track" },
        [0, 1].map((k) => e("span", { key: k },
          e("span", null, "Lieferung ", e("b", null, "5–9 Werktage")),
          e("span", null, "Zollfrei · ", e("b", null, "IOSS")),
          e("span", null, "100% ", e("b", null, "UV400")),
          e("span", null, "Versand ", e("b", null, "kostenlos")),
          e("span", null, "Signature ", e("b", null, "Box")))))),

    /* SONNENBRILLEN FRAME — Prada divided: Text + Model-Bild | Video-Loop */
    e("section", { className: "sunglasses-frame" },
      e(Reveal, null,
        e("div", { className: "frame-divided" },
          e("div", { className: "frame-text" },
            e("div", { className: "frame-text__inner" },
              e("div", { className: "frame-text__kicker" }, "Sonnenbrillen"),
              e("h2", { className: "frame-text__title" }, "Bold Reflections"),
              e("p", { className: "frame-text__copy" },
                "Essentielle Volumen, natürliche Materialien und funktionale Details definieren die neue Saison — neu interpretiert für symmetrische Vision."),
              e(PhImg, {
                className: "frame-text__small-img",
                src: IMG.model,
                alt: "Modell trägt Geometric Block",
                pos: "center 20%",
              })),
            e("button", { className: "frame-cta", onClick: onShop }, "Entdecken")),
          e(LoopVideo, {
            src: IMG.video,
            poster: IMG.editorialRed,
            label: "ANAYA Sonnenbrillen Editorial",
          })))),

    /* PRODUCT — Katalog-Ansicht */
    e("section", { className: "product-hero" },
      e(Reveal, null,
        e(PhImg, { src: IMG.product, alt: "Geometric Block — Produktansicht", pos: "center" }),
        e("div", { className: "pad", style: { padding: "28px 24px 40px", textAlign: "center" } },
          e("div", { className: "eyebrow gold", style: { marginBottom: 12 } }, "ANAYA Eyewear Collection"),
          e("h2", { className: "display", style: { fontSize: 30, margin: "0 0 8px" } }, "Geometric Block"),
          e("p", { className: "muted", style: { fontSize: 12.5, letterSpacing: ".04em", margin: "0 0 14px" } }, "Handpoliertes Acetat · UV400 · Kat. 3"),
          e("div", { className: "price", style: { fontSize: 19, marginBottom: 22 } }, "34,90 €"),
          e("button", { className: "btn", onClick: onShop }, "Ansehen")))),

    /* EDITORIAL MOSAIC — duo + statement + hero */
    e("section", { className: "editorial-mosaic" },
      e("div", { className: "editorial-mosaic__duo" },
        e(PhImg, { src: IMG.editorialStudio, alt: "ANAYA — Studio Editorial", pos: "center 20%" }),
        e(PhImg, { src: IMG.lifestyle, alt: "ANAYA — Outdoor Editorial", pos: "center 15%" })),
      e(Reveal, null,
        e("div", { className: "editorial-mosaic__statement" },
          e("p", { className: "editorial-mosaic__kicker" }, "Geometric Block · N°1"),
          e("h2", { className: "editorial-mosaic__title" }, "Essential volumes.", e("br"), "Functional details."),
          e("p", { className: "editorial-mosaic__copy" },
            "Handpoliertes Acetat · UV400 · Kat. 3 · inkl. Etui & Signature-Box. Limitiert auf 200 Stücke."))),
      e(PhImg, {
        className: "editorial-mosaic__hero",
        src: IMG.lookbookEditorial,
        alt: "ANAYA — Lookbook Editorial",
        pos: "center 25%",
      })),

    /* MANIFESTO — editorial quote block */
    e("section", { className: "manifesto" },
      e(Reveal, null,
        e("div", { className: "manifesto__inner" },
          e("p", { className: "manifesto__kicker" }, "Philosophie"),
          e("blockquote", { className: "manifesto__quote" },
            "„The Art of", e("br"), "Symmetric Vision."),
          e("p", { className: "manifesto__copy" },
            "Symmetrie ist kein Detail — sie ist Haltung. Jede ANAYA wird auf das Gesicht der Trägerin hin gedacht, nicht auf den Trend."),
          e("footer", { className: "manifesto__by" }, "— Anaya, Gründerin")))),

    /* CRAFT — product details accordion */
    e("section", { className: "craft" },
      e(Reveal, null,
        e("div", { className: "craft__head" },
          e("h3", { className: "craft__title" }, "Produktdetails"),
          e("p", { className: "craft__sub" }, "Handpoliertes Acetat · UV400 · Kat. 3")),
        e(CraftAccordion, { items: CRAFT_SPECS }),
        e("div", { className: "craft__ship" },
          e(Icon, { name: "truck", size: 15, stroke: 1.3 }),
          e("span", null, "Kostenloser Versand · 5–9 Werktage · IOSS inklusive")))),

    /* NEWS — Anaya Journal (Pradasphere) */
    e(AnayaSphere, { onShop, onFounders }),

    /* WEAR PROOF — model UGC testimonial carousel */
    e(WearProof),

    /* NEWSLETTER FOOTER */
    e("footer", { style: { background: "var(--ink)", color: "var(--cream)", padding: "10px 24px 40px" } },
      e("div", { className: "rule", style: { background: "rgba(248,246,240,.14)", marginBottom: 34 } }),
      e("div", { className: "serif", style: { fontSize: 22, fontStyle: "italic", marginBottom: 8 } }, "Werde Teil der Founders List."),
      e("p", { style: { fontSize: 12, lineHeight: 1.6, opacity: .7, margin: "0 0 16px", maxWidth: 300 } },
        "Gründerpreis, 48 h früher Zugang und deine nummerierte Edition von 200."),
      e(Subscribe, { onFounders }),
      e("div", { style: { display: "grid", gridTemplateColumns: "1fr 1fr", gap: 26, marginBottom: 30 } },
        e("div", null,
          e("div", { className: "eyebrow", style: { color: "var(--gold)", marginBottom: 12 } }, "Shop"),
          ["Sonnenbrillen", "Geometric Block", "Versand & Lieferung", "FAQ"].map((x, i) =>
            e("div", { key: i, style: { fontSize: 12, opacity: .72, padding: "5px 0", letterSpacing: ".02em" } }, x))),
        e("div", null,
          e("div", { className: "eyebrow", style: { color: "var(--gold)", marginBottom: 12 } }, "Marke"),
          ["Die Gründerin", "Journal", "Kontakt", "Nachhaltigkeit"].map((x, i) =>
            e("div", { key: i, style: { fontSize: 12, opacity: .72, padding: "5px 0", letterSpacing: ".02em" } }, x)))),
      e("div", { className: "rule", style: { background: "rgba(248,246,240,.14)", marginBottom: 18 } }),
      e("div", { style: { display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 10 } },
        e("div", { className: "tb-logo", style: { fontSize: 16, color: "var(--cream)" } }, "ANAYA", e("sup", null, "N°1")),
        e("div", { className: "eyebrow", style: { fontSize: 8.5, color: "rgba(248,246,240,.5)" } }, "© 2026 · Made in EU")),
      e("div", { className: "eyebrow", style: { fontSize: 8.5, color: "rgba(248,246,240,.5)", marginTop: 14 } },
        "Impressum · AGB · Datenschutz · Widerruf")));
}

Object.assign(window, { TopBar, Home, Reveal, AnayaSphere, Search });
