/* global React, Icon, PayVisa, PayMC, PayPaypal, PayApple, PayKlarna, GALLERY, IMG, PhImg, variantLabel */
const { createElement: c, useState: useStateV, useRef: useRefV, useEffect: useEffectV } = React;

const COLORS = [
  { id: "espresso", label: "Espresso-Schwarz", hex: "#1C1B1A" },
  { id: "cognac", label: "Cognac", hex: "#5b4636" },
  { id: "stone", label: "Stone", hex: "#7c776e" },
];
const LENSES = [
  { id: "dark", label: "Tiefschwarz · Kat. 3" },
  { id: "gradient", label: "Gradient · Kat. 2" },
];

const PDP_LINKS = [
  { id: "store", t: "Im Store finden", b: "Die ANAYA N°1 ist exklusiv online erhältlich. Founders List Mitglieder erhalten 48 h früher Zugang." },
  { id: "details", t: "Produktdetails", b: "Rahmen aus handpoliertem Acetat. Glasbreite 54 mm · Stegbreite 18 mm · Bügellänge 145 mm. 100% UV400, Filterkategorie 3. Signature-Box mit Seiden-Inlay, Leder-Etui & Mikrofasertuch." },
  { id: "shipping", t: "Versand & Rückgabe kostenlos", b: "Kostenloser Versand innerhalb Deutschlands. Lieferzeit 5–9 Werktage, zollfrei über IOSS. 14 Tage Widerrufsrecht." },
];

/* ---------------- PDP (Prada layout) ---------------- */
function PDP({ onAdd, onBack, onFounders, colorIdx, lensIdx, onColorIdx, onLensIdx }) {
  const [idx, setIdx] = useStateV(0);
  const [expanded, setExpanded] = useStateV(false);
  const [linkOpen, setLinkOpen] = useStateV("");
  const galleryRef = useRefV(null);
  const slideRefs = useRefV([]);
  const jumpRef = useRefV(false);

  const goToSlide = (i) => {
    const el = slideRefs.current[i];
    if (!el) return;
    jumpRef.current = true;
    setIdx(i);
    el.scrollIntoView({ behavior: "smooth", block: "start" });
    setTimeout(() => { jumpRef.current = false; }, 480);
  };

  useEffectV(() => {
    const root = galleryRef.current;
    if (!root) return;
    const io = new IntersectionObserver((ents) => {
      if (jumpRef.current) return;
      ents.forEach((en) => {
        if (!en.isIntersecting || en.intersectionRatio < 0.58) return;
        const i = Number(en.target.dataset.index);
        if (!Number.isNaN(i)) setIdx(i);
      });
    }, { root, threshold: [0.58, 0.85] });
    slideRefs.current.forEach((el) => el && io.observe(el));
    return () => io.disconnect();
  }, []);

  return c("div", { className: "pdp-screen" },
    /* gallery — scroll-snap; dots fix am Rand (außerhalb Scroll) */
    c("div", { className: "pdp-gallery-wrap" },
      c("section", { className: "pdp-gallery", ref: galleryRef },
        GALLERY.map((item, i) =>
          c("div", {
            key: i,
            className: "pdp-gallery__slide",
            "data-index": i,
            ref: (el) => { slideRefs.current[i] = el; },
          }, c("img", { src: item.src, alt: item.label, loading: i === 0 ? "eager" : "lazy" })))),
      c("nav", {
        className: "pdp-dots",
        "aria-label": "Produktgalerie",
        style: { "--dot-active": idx },
      },
        c("span", { className: "pdp-dots__indicator", "aria-hidden": true }),
        c("div", { className: "pdp-dots__track" },
          GALLERY.map((_, i) =>
            c("button", {
              key: i,
              className: i === idx ? "on" : "",
              onClick: () => goToSlide(i),
              "aria-label": `Karussell, zur Folie ${i + 1}`,
              "aria-current": i === idx ? "true" : undefined,
            }))))),

    /* bottom sheet — product info */
    c("div", { className: "pdp-sheet-wrap" },
      c("div", { className: "pdp-sheet" + (expanded ? " expanded" : "") },
        c("button", {
          className: "pdp-sheet__handle",
          onClick: () => setExpanded((v) => !v),
          "aria-label": expanded ? "Produktinfo einklappen" : "Produktinfo ausklappen",
        }),
        c("div", { className: "pdp-sheet__scroll" },
          c("div", { className: "pdp-cat" }, "Sonnenbrillen"),
          c("h1", { className: "pdp-name" }, "Geometric Block"),
          c("div", { className: "pdp-price-row" },
            c("span", { className: "pdp-price" }, "34,90 €"),
            c("span", { className: "pdp-price-note" }, "Gründerpreis · inkl. MwSt.")),
          c("p", { className: "pdp-prelaunch-note" },
            "Erste Edition · limitiert auf 200 nummerierte Stücke. Gründerpreis 34,90 € inkl. MwSt."),
          c("button", { className: "btn", onClick: () => onAdd && onAdd(1, { colorIdx, lensIdx }) },
            "In den Warenkorb", c(Icon, { name: "bag", size: 15 })),
          c("button", { className: "btn ghost", style: { marginTop: 10 }, onClick: () => onFounders && onFounders() },
            "Auf die Founders List", c(Icon, { name: "arrowR", size: 15 })),

          c("div", { className: "pdp-options" },
            c("div", { className: "pdp-options__row" },
              c("span", { className: "pdp-options__label" }, "Farbe"),
              c("div", { className: "pdp-options__values" },
                COLORS.map((col, i) =>
                  c("button", {
                    key: col.id,
                    className: "pdp-swatch" + (i === colorIdx ? " on" : ""),
                    style: { background: col.hex },
                    onClick: () => onColorIdx && onColorIdx(i),
                    "aria-label": col.label,
                    title: col.label,
                  })))),
            c("div", { className: "pdp-options__row" },
              c("span", { className: "pdp-options__label" }, "Linsen"),
              c("div", { className: "pdp-options__values" },
                LENSES.map((lens, i) =>
                  c("button", {
                    key: lens.id,
                    className: "pdp-lens" + (i === lensIdx ? " on" : ""),
                    onClick: () => onLensIdx && onLensIdx(i),
                  }, lens.label))))),

          c("div", { className: "pdp-links" },
            PDP_LINKS.map((link) =>
              c("div", { key: link.id },
                c("button", {
                  className: "pdp-link",
                  onClick: () => setLinkOpen(linkOpen === link.id ? "" : link.id),
                }, link.t),
                linkOpen === link.id && c("p", { className: "pdp-link-body" }, link.b)))),

          c("div", { className: "pdp-related" },
            c("div", { className: "pdp-related__title" }, "Das könnte Ihnen auch gefallen"),
            c("button", { className: "pdp-related__card", onClick: () => onFounders && onFounders() },
              c("img", { src: IMG.model, alt: "Founders List", loading: "lazy" }),
              c("div", { className: "pdp-related__meta" },
                c("div", { className: "serif", style: { fontSize: 14, marginBottom: 4 } }, "Founders List"),
                c("span", null, "Nummerierte erste Edition · 200 Stück"))))))));
}

const CART_PICKS = [
  { id: "geometric-espresso", name: "Geometric Block", sub: "Espresso-Schwarz · Kat. 3", price: "34,90 €", img: IMG.product, colorIdx: 0 },
  { id: "geometric-cognac", name: "Geometric Block", sub: "Cognac · Kat. 3", price: "34,90 €", img: IMG.angleLeft, colorIdx: 1 },
  { id: "geometric-side", name: "Geometric Block", sub: "Stone · Kat. 3", price: "34,90 €", img: IMG.side, colorIdx: 2 },
];

/* ---------------- Cart Drawer ---------------- */
function CartDrawer({ open, qty, colorIdx, lensIdx, onClose, onQty, onCheckout, onAdd }) {
  const total = (34.9 * qty);
  const variantSub = typeof variantLabel === "function" ? variantLabel(colorIdx, lensIdx) : "Espresso-Schwarz · Tiefschwarz";
  return c(React.Fragment, null,
    c("div", { className: "overlay" + (open ? " show" : ""), onClick: onClose }),
    c("aside", { className: "drawer" + (open ? " show" : "") },
      c("div", { style: { display: "flex", alignItems: "center", justifyContent: "space-between", padding: "18px 18px 16px", borderBottom: "1px solid var(--line-soft)" } },
        c("div", { className: "eyebrow" }, `Warenkorb (${qty})`),
        c("button", { className: "tb-btn", onClick: onClose, "aria-label": "Schließen" }, c(Icon, { name: "close", size: 20 }))),

      qty > 0
        ? c("div", { style: { flex: 1, overflowY: "auto" } },
            c("div", { style: { display: "flex", gap: 14, padding: 18, borderBottom: "1px solid var(--line-soft)" } },
              c("div", { className: "ph has-img", style: { width: 84, height: 84, flex: "0 0 auto" } },
                c(PhImg, { src: IMG.thumb, alt: "Geometric Block" })),
              c("div", { style: { flex: 1 } },
                c("div", { className: "eyebrow", style: { fontSize: 8.5, marginBottom: 5 } }, "ANAYA N°1"),
                c("div", { className: "serif", style: { fontSize: 15, marginBottom: 3 } }, "Geometric Block"),
                c("div", { className: "muted", style: { fontSize: 11, marginBottom: 10 } }, variantSub),
                c("div", { style: { display: "flex", alignItems: "center", justifyContent: "space-between" } },
                  c("div", { className: "qty" },
                    c("button", { onClick: () => onQty(Math.max(0, qty - 1)) }, c(Icon, { name: "minus", size: 13 })),
                    c("span", null, qty),
                    c("button", { onClick: () => onQty(qty + 1) }, c(Icon, { name: "plus", size: 13 }))),
                  c("span", { className: "price", style: { fontSize: 15 } }, total.toFixed(2).replace(".", ",") + " €")))),
            c("div", { style: { padding: "18px" } },
              c("div", { style: { display: "flex", alignItems: "center", gap: 8, color: "var(--gold-deep)", fontSize: 11, letterSpacing: ".06em" } },
                c(Icon, { name: "truck", size: 16 }), "Kostenloser Versand · 5–9 Werktage")))
        : c("div", { className: "cart-empty" },
            c("div", { className: "cart-empty__msg" },
              c(Icon, { name: "bag", size: 30, color: "var(--ink-mute)" }),
              c("p", { className: "muted", style: { fontSize: 13, margin: 0 } }, "Ihr Warenkorb ist noch leer."),
              c("button", { className: "btn ghost sm", onClick: onClose }, "Weiter shoppen")),
            c("div", { className: "cart-suggest" },
              c("div", { className: "cart-suggest__title" }, "Das könnte Ihnen auch gefallen"),
              CART_PICKS.map((item) =>
                c("div", { key: item.id, className: "cart-suggest__item" },
                  c("img", { src: item.img, alt: item.name, loading: "lazy" }),
                  c("div", { className: "cart-suggest__info" },
                    c("div", { className: "eyebrow", style: { fontSize: 8.5, marginBottom: 4 } }, "ANAYA N°1"),
                    c("div", { className: "serif", style: { fontSize: 14, marginBottom: 2 } }, item.name),
                    c("div", { className: "muted", style: { fontSize: 11, marginBottom: 4 } }, item.sub),
                    c("div", { className: "price", style: { fontSize: 13 } }, item.price)),
                  c("button", {
                    className: "cart-suggest__add",
                    onClick: () => onAdd && onAdd(1, { colorIdx: item.colorIdx, lensIdx: 0 }),
                    "aria-label": `${item.name} hinzufügen`,
                  }, c(Icon, { name: "plus", size: 16 })))))),

      qty > 0 && c("div", { style: { borderTop: "1px solid var(--line)", padding: 18 } },
        c("div", { style: rowS }, c("span", { className: "muted", style: { fontSize: 13 } }, "Zwischensumme"), c("span", { style: { fontSize: 13 } }, total.toFixed(2).replace(".", ",") + " €")),
        c("div", { style: rowS }, c("span", { className: "muted", style: { fontSize: 13 } }, "Versand"), c("span", { style: { fontSize: 13 } }, "Kostenlos")),
        c("div", { className: "rule gold", style: { margin: "12px 0" } }),
        c("div", { style: { ...rowS, marginBottom: 16 } }, c("span", { className: "serif", style: { fontSize: 15 } }, "Gesamt"), c("span", { className: "price", style: { fontSize: 17 } }, total.toFixed(2).replace(".", ",") + " €")),
        c("button", { className: "btn", onClick: onCheckout }, "Zur Kasse", c(Icon, { name: "lock", size: 14 })),
        c("div", { className: "paymarks", style: { justifyContent: "center", marginTop: 16 } },
          c(PayApple), c(PayPaypal), c(PayVisa), c(PayMC), c(PayKlarna)))));
}
const rowS = { display: "flex", justifyContent: "space-between", alignItems: "center", padding: "4px 0" };

/* ---------------- Menu (Prada-style, nur Pre-Launch-relevant) ---------------- */
const MENU_L1 = [
  { id: "sunglasses", label: "Sonnenbrillen", sub: true },
  { id: "founders", label: "Founders List", action: "founders", highlight: true },
  { id: "service", label: "Service", sub: true },
];
const MENU_SERVICE = [
  { id: "shipping", label: "Versand & Rückgabe", text: "Kostenloser Versand in Deutschland. Lieferzeit 5–9 Werktage, zollfrei über IOSS. 14 Tage Widerrufsrecht." },
  { id: "faq", label: "FAQ", text: "Aktuell nur Pre-Launch: Über die Founders List sicherst du dir Gründerpreis und frühen Zugang. Kein Kauf nötig." },
  { id: "contact", label: "Kontakt", text: "hallo@anaya-no1.com — wir antworten innerhalb von 48 Stunden." },
];

function Menu({ open, onClose, onShop, onFounders }) {
  const [panel, setPanel] = useStateV(null);
  const [serviceOpen, setServiceOpen] = useStateV("");

  useEffectV(() => {
    if (!open) { setPanel(null); setServiceOpen(""); }
  }, [open]);

  const panelTitle = panel === "sunglasses" ? "Sonnenbrillen" : panel === "service" ? "Service" : "";

  const run = (action) => {
    if (action === "shop") { onClose(); onShop(); return; }
    if (action === "founders") { onClose(); onFounders(); }
  };

  return c("div", { className: "route anaya-menu" + (open ? " show" : "") },
    c("div", { className: "menu-head" },
      panel
        ? c("button", { className: "menu-crumb", onClick: () => setPanel(null) },
            c(Icon, { name: "arrowL", size: 18 }), panelTitle)
        : c("div", { className: "tb-logo" }, "ANAYA", c("sup", null, "N°1")),
      c("button", { className: "tb-btn", onClick: onClose, "aria-label": "Menü schließen" },
        c(Icon, { name: "close", size: 22 }))),

    c("div", { className: "menu-body" },
      !panel && c("ul", { className: "menu-l1" },
        MENU_L1.map((item) =>
          c("li", { key: item.id, className: item.highlight ? "highlight" : "" },
            c("button", {
              className: "menu-l1__btn",
              onClick: () => item.action ? run(item.action) : setPanel(item.id),
            },
              c("span", null, item.label),
              item.sub && c(Icon, { name: "arrowR", size: 18 }))))),

      panel === "sunglasses" && c("div", { className: "menu-l2" },
        c("div", { className: "menu-mosaic" },
          c("button", { className: "menu-mosaic__item", onClick: () => run("shop") },
            c("img", { src: IMG.product, alt: "Geometric Block", loading: "lazy" }),
            c("span", { className: "menu-mosaic__name" }, "Geometric Block"))),
        c("div", { className: "menu-l2__section" },
          c("h4", { className: "menu-l2__title" }, "Kollektion Sommer '26"),
          c("button", { className: "menu-l2__link", onClick: () => run("shop") }, "Geometric Block"),
          c("p", { className: "menu-l2__note" }, "Erste Edition · limitiert auf 200 · Pre-Launch"))),

      panel === "service" && c("div", { className: "menu-l2" },
        c("ul", { className: "menu-service" },
          MENU_SERVICE.map((item) =>
            c("li", { key: item.id },
              c("button", {
                className: "menu-service__btn" + (serviceOpen === item.id ? " open" : ""),
                onClick: () => setServiceOpen(serviceOpen === item.id ? "" : item.id),
              }, item.label, c("span", { className: "menu-service__sign" })),
              serviceOpen === item.id && c("p", { className: "menu-service__text" }, item.text)))))),

    c("div", { className: "menu-foot" },
      c("div", { className: "menu-foot__social" },
        c("span", null, "Instagram"), c("span", null, "TikTok")),
      c("button", { className: "menu-foot__locale", type: "button" }, "Deutschland / Deutsch")));
}

Object.assign(window, { PDP, CartDrawer, Menu });
