/* global React, useApp, Foto, ProductCard, SectionHead, MOTIFS, GlyphDiamond,
   IconStar, IconHeart, IconTruck, IconRefresh, IconLock, IconChevron, IconPlus, IconMinus, IconArrow,
   PRODUCTS, CATEGORIES, fmt */
const { createElement: p, useState: useStateProd, useEffect: useEffectProd } = React;

function Stars({ r }) {
  return p("span", { style: { display: "inline-flex", gap: 2, color: "var(--marigold)" } },
    [...Array(5)].map((_, i) => p(IconStar, { key: i, size: 15, style: { opacity: i < Math.round(r) ? 1 : .3 } })));
}

function ProductPage() {
  const { route, navigate, addToCart, isFav, toggleFav } = useApp();
  const prod = PRODUCTS.find(x => x.id === (route.params && route.params.id)) || PRODUCTS[0];
  const hasModels = Array.isArray(prod.models) && prod.models.length > 0;
  const hasVideo = !!prod.video;
  const hasAromas = Array.isArray(prod.aromas) && prod.aromas.length > 0;
  const isCustom = !!prod.custom;
  const [size, setSize] = useStateProd(prod.sizes[0]);
  const [color, setColor] = useStateProd(prod.colors[0]);
  const [aroma, setAroma] = useStateProd(hasAromas ? prod.aromas[0] : null);
  const [model, setModel] = useStateProd(hasModels ? prod.models[0].name : null);
  const [modelOpen, setModelOpen] = useStateProd(false);
  const [videoErr, setVideoErr] = useStateProd(false);
  const [qty, setQty] = useStateProd(1);
  const [tab, setTab] = useStateProd("desc");
  const [view, setView] = useStateProd(0);
  const [guide, setGuide] = useStateProd(false);

  useEffectProd(() => { setSize(prod.sizes[0]); setColor(prod.colors[0]); setAroma(hasAromas ? prod.aromas[0] : null); setModel(hasModels ? prod.models[0].name : null); setModelOpen(false); setVideoErr(false); setQty(1); setView(0); window.scrollTo && null; const sc = document.querySelector(".app-scroll"); if (sc) sc.scrollTo({ top: 0 }); }, [prod.id]);

  const activeModel = hasModels ? (prod.models.find(x => x.name === model) || prod.models[0]) : null;
  const sizeP = prod.sizePrice ? prod.sizePrice[size] : undefined;   // precio especial por talla
  const sizeTBD = sizeP === 0;                                       // 0 = precio por definir
  const unitPrice = (typeof sizeP === "number" && sizeP > 0) ? sizeP : (activeModel ? activeModel.price : prod.price);

  const catName = (CATEGORIES.find(c => c.id === prod.cat) || {}).name || prod.cat;
  const related = PRODUCTS.filter(x => x.cat === prod.cat && x.id !== prod.id).slice(0, 4);
  const relatedFill = related.length < 4 ? [...related, ...PRODUCTS.filter(x => x.id !== prod.id && !related.includes(x)).slice(0, 4 - related.length)] : related;
  const motifFallback = [prod.motif, "flor", "obsidiana", "calavera"];
  const galImgs = Array.isArray(prod.images) ? prod.images.filter(Boolean) : [];
  const mainImg = prod.img || galImgs[0] || null;
  const views = [0, 1, 2, 3].map((i) => galImgs[i] || (i === 0 ? mainImg : null));

  return p("div", { style: { background: "var(--bone)" } },
    /* breadcrumb */
    p("div", { className: "wrap", style: { padding: "22px 32px 6px", display: "flex", gap: 10, alignItems: "center", fontSize: 12.5, letterSpacing: ".08em", textTransform: "uppercase", color: "var(--ink-faint)" } },
      p("button", { onClick: () => navigate("home", {}), style: LINKB }, "Inicio"), "/",
      p("button", { onClick: () => navigate("catalog", { cat: prod.cat }), style: LINKB }, catName), "/",
      p("span", { style: { color: "var(--ink-soft)" } }, prod.name)),

    p("div", { className: "wrap pdp-grid", style: { display: "grid", gridTemplateColumns: "1.05fr .95fr", gap: 56, padding: "26px 32px 64px", alignItems: "start" } },
      /* galería */
      p("div", { className: "pdp-gallery", style: { position: "sticky", top: 150 } },
        (view === 0 && hasVideo && !videoErr)
          ? p("video", { src: prod.video, poster: mainImg || undefined, controls: true, autoPlay: true, loop: true, muted: true, playsInline: true, onError: () => setVideoErr(true), style: { height: 540, width: "100%", objectFit: "cover", borderRadius: 10, background: "#000", display: "block" } })
          : p(Foto, { motif: motifFallback[view], color: prod.color, src: views[view], hint: prod.name, style: { height: 540, borderRadius: 10 } }),
        p("div", { style: { display: "flex", gap: 12, marginTop: 14 } },
          [0, 1, 2, 3].map((i) => p("button", { key: i, onClick: () => setView(i), style: { position: "relative", flex: 1, height: 96, border: `2px solid ${i === view ? "var(--oro)" : "transparent"}`, borderRadius: 8, overflow: "hidden", padding: 0, background: "none", cursor: "pointer" } },
            p(Foto, { motif: motifFallback[i], color: prod.color, src: views[i], hint: "", style: { height: "100%" } }),
            (i === 0 && hasVideo) && p("span", { style: { position: "absolute", inset: 0, display: "grid", placeItems: "center", background: "rgba(0,0,0,.35)" } },
              p("span", { style: { width: 30, height: 30, borderRadius: "50%", background: "rgba(0,0,0,.6)", border: "1px solid var(--gold-claro)", display: "grid", placeItems: "center", color: "var(--gold-claro)", fontSize: 12, paddingLeft: 2 } }, "▶"))))
        )
      ),
      /* info */
      p("div", null,
        p("div", { className: "eyebrow", style: { color: "var(--ink-faint)", marginBottom: 14 } }, catName),
        p("h1", { className: "display", style: { fontSize: "clamp(30px,3.4vw,44px)", margin: "0 0 14px", textTransform: "uppercase", letterSpacing: ".03em", lineHeight: 1.05 } }, prod.name),
        p("div", { style: { display: "flex", alignItems: "center", gap: 12, marginBottom: 22 } },
          p(Stars, { r: prod.rating }),
          p("span", { className: "serif", style: { fontSize: 16, color: "var(--ink-soft)" } }, prod.rating, " · ", prod.reviews, " reseñas")),
        p("div", { className: "serif", style: { fontSize: 38, fontWeight: 600, color: "var(--vino)", marginBottom: 6 } }, (prod.draft || sizeTBD) ? "Precio a definir" : fmt(unitPrice)),
        !prod.draft && !sizeTBD && p("div", { style: { fontSize: 13, color: "var(--verde)", fontWeight: 600, letterSpacing: ".04em", marginBottom: 26 } }, "o 3 meses sin intereses de ", fmt(Math.round(unitPrice / 3)), " · Mercado Pago"),
        p("p", { className: "serif", style: { fontSize: 19, lineHeight: 1.55, color: "var(--ink-soft)", marginBottom: 28 } }, prod.desc),

        /* selector de modelo / variante */
        hasModels && p("div", { style: { marginBottom: 24 } },
          p("div", { style: SEL }, (prod.variantLabel || "Modelo") + ": ", p("strong", { style: { color: "var(--ink)" } }, model)),
          p("button", { onClick: () => setModelOpen(o => !o), style: { marginTop: 10, width: "100%", display: "flex", alignItems: "center", justifyContent: "space-between", padding: "13px 16px", background: "rgba(0,0,0,.25)", border: "1px solid var(--amate-line)", borderRadius: 6, color: "var(--ink)", fontFamily: "var(--font-ui)", fontSize: 14, cursor: "pointer", letterSpacing: ".02em" } },
            p("span", null, model, activeModel && activeModel.pieces ? p("span", { style: { color: "var(--ink-faint)", marginLeft: 8 } }, "· " + activeModel.pieces + " pz") : null, p("span", { style: { color: "var(--vino)", marginLeft: 10, fontWeight: 600 } }, fmt(unitPrice))),
            p(IconChevron, { size: 16, style: { transform: modelOpen ? "rotate(180deg)" : "none", transition: "transform .2s", flex: "none" } })),
          modelOpen && p("div", { style: { marginTop: 8, border: "1px solid var(--amate-line)", borderRadius: 6, overflow: "hidden", background: "rgba(0,0,0,.2)" } },
            prod.models.map((mo, i) => p("button", { key: mo.name, onClick: () => { setModel(mo.name); setModelOpen(false); }, style: { width: "100%", display: "flex", alignItems: "center", justifyContent: "space-between", padding: "12px 16px", background: mo.name === model ? "rgba(122,30,42,.25)" : "none", border: "none", borderTop: i ? "1px solid var(--amate-line)" : "none", color: "var(--ink)", fontFamily: "var(--font-ui)", fontSize: 14, cursor: "pointer", textAlign: "left" } },
              p("span", null, mo.name, mo.pieces ? p("span", { style: { color: "var(--ink-faint)", marginLeft: 8 } }, "· " + mo.pieces + " pz") : null),
              p("span", { style: { color: "var(--vino)", fontWeight: 600 } }, fmt(mo.price))))) ),

        /* aroma */
        hasAromas && p("div", { style: { marginBottom: 22 } },
          p("div", { style: SEL }, "Aroma: ", p("strong", { style: { color: "var(--ink)" } }, aroma)),
          p("div", { style: { display: "flex", gap: 10, marginTop: 10, flexWrap: "wrap" } },
            prod.aromas.map(ar => p("button", { key: ar, onClick: () => setAroma(ar), className: "chip", style: aroma === ar ? { background: "var(--ink)", color: "var(--bone)", borderColor: "var(--ink)" } : {} }, ar)))),
        /* color */
        prod.colors.length > 1 && p("div", { style: { marginBottom: 22 } },
          p("div", { style: SEL }, "Color: ", p("strong", { style: { color: "var(--ink)" } }, color)),
          p("div", { style: { display: "flex", gap: 10, marginTop: 10, flexWrap: "wrap" } },
            prod.colors.map(cl => p("button", { key: cl, onClick: () => setColor(cl), className: "chip", style: color === cl ? { background: "var(--ink)", color: "var(--bone)", borderColor: "var(--ink)" } : {} }, cl)))),
        /* talla */
        !hasModels && p("div", { style: { marginBottom: 28 } },
          p("div", { style: { display: "flex", justifyContent: "space-between", alignItems: "center" } },
            p("div", { style: SEL }, "Talla: ", p("strong", { style: { color: "var(--ink)" } }, size)),
            p("button", { onClick: () => setGuide(true), style: { ...LINKB, fontSize: 12, textTransform: "none", letterSpacing: 0, fontFamily: "var(--font-serif)", fontStyle: "italic", fontSize: 14 } }, "Guía de tallas")),
          p("div", { style: { display: "flex", gap: 10, marginTop: 10, flexWrap: "wrap" } },
            prod.sizes.map(s => p("button", { key: s, onClick: () => setSize(s), className: "chip", style: size === s ? { background: "var(--ink)", color: "var(--bone)", borderColor: "var(--ink)", minWidth: 48 } : { minWidth: 48 } }, s)))),

        /* qty + add */
        !prod.draft && !sizeTBD && !isCustom && p("div", { style: { display: "flex", gap: 14, marginBottom: 18 } },
          p("div", { style: { display: "flex", alignItems: "center", border: "1px solid var(--amate-line)", borderRadius: 4, background: "rgba(0,0,0,.25)" } },
            p("button", { onClick: () => setQty(q => Math.max(1, q - 1)), style: QTYB }, p(IconMinus, { size: 16 })),
            p("span", { style: { width: 44, textAlign: "center", fontFamily: "var(--font-display)", fontSize: 18 } }, qty),
            p("button", { onClick: () => setQty(q => q + 1), style: QTYB }, p(IconPlus, { size: 16 }))),
          p("button", { className: "btn btn-ink", style: { flex: 1, fontSize: 14 }, onClick: () => { addToCart(prod, qty, { size, color, aroma, model, vlabel: hasModels ? (prod.variantLabel || "Modelo") : null, price: unitPrice }); navigate("cart", {}); } }, "Agregar al altar · ", fmt(unitPrice * qty)),
          p("button", { className: "btn btn-ghost", style: { width: 54, padding: 0, color: isFav(prod.id) ? "var(--rose)" : undefined, borderColor: isFav(prod.id) ? "var(--rose)" : undefined }, "aria-label": "Favorito", onClick: () => toggleFav(prod.id) }, p(IconHeart, { size: 20, fill: isFav(prod.id) ? "currentColor" : "none" }))),
        !prod.draft && !sizeTBD && !isCustom && p("button", { className: "btn btn-gold btn-full", style: { marginBottom: 26 }, onClick: () => { addToCart(prod, qty, { size, color, aroma, model, vlabel: hasModels ? (prod.variantLabel || "Modelo") : null, price: unitPrice }); navigate("cart", {}); } }, "Comprar ahora"),
        !prod.draft && !sizeTBD && isCustom && p("div", { style: { display: "flex", flexDirection: "column", gap: 12, marginBottom: 26 } },
          p("div", { style: { border: "1px solid var(--amate-line)", borderRadius: 6, padding: "16px 18px", background: "rgba(0,0,0,.2)", color: "var(--ink-soft)", fontFamily: "var(--font-serif)", fontSize: 15.5 } }, "Esta pieza se personaliza con tu imagen. Escríbenos por WhatsApp y mándanos el diseño que quieres; te confirmamos todo al instante."),
          p("a", { href: "https://wa.me/message/CR42U3DQIYNNI1", target: "_blank", rel: "noopener noreferrer", className: "btn btn-gold btn-full", style: { textDecoration: "none" } }, "Personalízalo por WhatsApp")),
        prod.draft && p("div", { style: { display: "flex", flexDirection: "column", gap: 12, marginBottom: 26 } },
          p("div", { style: { border: "1px solid var(--amate-line)", borderRadius: 6, padding: "16px 18px", background: "rgba(0,0,0,.2)", color: "var(--ink-soft)", fontFamily: "var(--font-serif)", fontSize: 15.5 } }, "Esta pieza estará disponible muy pronto. Si te interesa, escríbenos y te avisamos en cuanto salga."),
          p("a", { href: "https://wa.me/message/CR42U3DQIYNNI1", target: "_blank", rel: "noopener noreferrer", className: "btn btn-gold btn-full", style: { textDecoration: "none" } }, "Pregúntanos por WhatsApp")),
        !prod.draft && sizeTBD && p("div", { style: { display: "flex", flexDirection: "column", gap: 12, marginBottom: 26 } },
          p("div", { style: { border: "1px solid var(--amate-line)", borderRadius: 6, padding: "16px 18px", background: "rgba(0,0,0,.2)", color: "var(--ink-soft)", fontFamily: "var(--font-serif)", fontSize: 15.5 } }, "El precio de la talla " + size + " está por definir. Escríbenos y te la cotizamos al instante."),
          p("a", { href: "https://wa.me/message/CR42U3DQIYNNI1", target: "_blank", rel: "noopener noreferrer", className: "btn btn-gold btn-full", style: { textDecoration: "none" } }, "Cotizar talla " + size + " por WhatsApp")),

        /* perks */
        p("div", { style: { display: "grid", gap: 12, borderTop: "1px solid var(--amate-line)", paddingTop: 22 } },
          [[IconTruck, "Envío gratis en compras +$999", "Llega en 3–5 días hábiles a toda la República"],
           [IconRefresh, "Cambios y devoluciones", "30 días para cambios. Tu primera compra es sagrada"],
           [IconLock, "Pago seguro con Mercado Pago", "Tarjetas, OXXO, PayPal y meses sin intereses"]].map((row, i) =>
            p("div", { key: i, style: { display: "flex", gap: 14, alignItems: "flex-start" } },
              p(row[0], { size: 22, style: { color: "var(--oro-deep)", flex: "none", marginTop: 2 } }),
              p("div", null, p("div", { style: { fontWeight: 600, fontSize: 14, letterSpacing: ".02em" } }, row[1]),
                p("div", { style: { fontSize: 13.5, color: "var(--ink-faint)", fontFamily: "var(--font-serif)" } }, row[2])))))
      )
    ),

    /* tabs descripción */
    p("div", { style: { background: "var(--bone-2)", borderTop: "1px solid var(--amate-line)", borderBottom: "1px solid var(--amate-line)", padding: "48px 0" } },
      p("div", { className: "wrap", style: { maxWidth: 900 } },
        p("div", { style: { display: "flex", gap: 28, justifyContent: "center", marginBottom: 28, borderBottom: "1px solid var(--amate-line)" } },
          [["desc", "Descripción"], ["mat", "Materiales y cuidado"], ["env", "Envíos"]].map(([id, l]) =>
            p("button", { key: id, onClick: () => setTab(id), style: { background: "none", border: "none", borderBottom: `2px solid ${tab === id ? "var(--vino)" : "transparent"}`, color: tab === id ? "var(--vino)" : "var(--ink-faint)", fontFamily: "var(--font-ui)", fontWeight: 600, fontSize: 13, letterSpacing: ".12em", textTransform: "uppercase", padding: "0 0 14px" } }, l))),
        p("div", { className: "serif", style: { fontSize: 19, lineHeight: 1.65, color: "var(--ink-soft)", textAlign: "center" } },
          tab === "desc" && prod.desc + " Inspirada en la cosmovisión mexica del inframundo, esta pieza acompaña a quien camina entre la vida y la muerte con elegancia y orgullo.",
          tab === "mat" && "Elaborada con materiales nobles seleccionados a mano. Limpia con paño seco, evita el contacto con agua y perfumes. Guárdala en su bolsa de tela incluida para conservar su brillo.",
          tab === "env" && "Enviamos a toda la República Mexicana en 3–5 días hábiles. Envío gratis en compras superiores a $999 MXN. Empaque ritual de regalo disponible sin costo.")
      )
    ),

    /* relacionados */
    p("div", { className: "wrap", style: { padding: "56px 32px 72px" } },
      p(SectionHead, null, "Almas afines"),
      p("div", { style: { display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 22, marginTop: 36 } },
        relatedFill.map(rp => p(ProductCard, { key: rp.id, p: rp, height: 250 })))
    ),

    /* modal guía de tallas */
    p(Modal, { open: guide, onClose: () => setGuide(false), title: "Guía de tallas", maxWidth: 560 },
      p("p", { className: "serif", style: { fontSize: 17, color: "var(--cream-soft)", marginTop: 0, marginBottom: 16, lineHeight: 1.5 } }, "Medidas de referencia en centímetros. Si dudas entre dos tallas, elige la mayor."),
      p("table", { style: { width: "100%", borderCollapse: "collapse", fontFamily: "var(--font-ui)", fontSize: 14 } },
        p("thead", null, p("tr", null, ["Talla", "Busto", "Cintura", "Cadera"].map((h, i) =>
          p("th", { key: i, style: { textAlign: "left", padding: "9px 10px", borderBottom: "1px solid var(--gold-deep)", color: "var(--gold-claro)", textTransform: "uppercase", letterSpacing: ".08em", fontSize: 11.5 } }, h)))),
        p("tbody", null, [["Chico", "82–86", "62–66", "88–92"], ["Mediano", "87–92", "67–73", "93–98"], ["Grande", "93–99", "74–81", "99–105"], ["Única", "Ajustable", "Ajustable", "Ajustable"]].map((row, i) =>
          p("tr", { key: i }, row.map((cell, j) =>
            p("td", { key: j, style: { padding: "10px 10px", borderBottom: "1px solid var(--green-line)", color: j === 0 ? "var(--gold-claro)" : "var(--cream)", fontWeight: j === 0 ? 600 : 400 } }, cell)))))))
  );
}
const LINKB = { background: "none", border: "none", cursor: "pointer", color: "inherit", fontFamily: "inherit", fontSize: "inherit", letterSpacing: "inherit", textTransform: "inherit", padding: 0 };
const SEL = { fontSize: 13, letterSpacing: ".1em", textTransform: "uppercase", color: "var(--ink-faint)", fontWeight: 600 };
const QTYB = { width: 40, height: 46, background: "none", border: "none", display: "grid", placeItems: "center", color: "var(--ink)" };

Object.assign(window, { ProductPage });
