/* ============================================================
   UVD CLUB — Página de Produto (interativa)
   ============================================================ */

function Accordion({ title, children, open: openInit }) {
  const [open, setOpen] = useState(!!openInit);
  return (
    <div style={{ borderTop: "1px solid var(--line)" }}>
      <button onClick={() => setOpen(!open)} style={{ width: "100%", background: "none", border: "none", display: "flex", justifyContent: "space-between", alignItems: "center", padding: "18px 0", textAlign: "left" }}>
        <span className="ui-label" style={{ fontSize: 13, color: "var(--ink)" }}>{title}</span>
        <span style={{ fontSize: 20, color: "var(--wine)", transition: "transform .2s", transform: open ? "rotate(45deg)" : "none" }}>+</span>
      </button>
      <div style={{ maxHeight: open ? 400 : 0, overflow: "hidden", transition: "max-height .35s ease" }}>
        <div style={{ paddingBottom: 20 }}>{children}</div>
      </div>
    </div>
  );
}

function ProductPage({ product, products, onOpen, onAdd, onNav }) {
  const p = product;
  const isMobile = useIsMobile();
  const [color, setColor] = useState(p.colors[0].name);
  const [size, setSize] = useState(p.sizes.length === 1 ? p.sizes[0] : null);
  const [qty, setQty] = useState(1);
  const [activeImg, setActiveImg] = useState(0);
  const [added, setAdded] = useState(false);

  // reset ao trocar de produto
  useEffect(() => {
    setColor(p.colors[0].name);
    setSize(p.sizes.length === 1 ? p.sizes[0] : null);
    setQty(1);
    setActiveImg(0);
    setAdded(false);
    const sr = document.querySelector("#scrollroot");
    if (sr) sr.scrollTo({ top: 0 }); else window.scrollTo({ top: 0 });
  }, [p.id]);

  const sizeLabel = p.sizeLabel || (p.sizes[0] === "Único" ? "Tamanho" : "Tamanho");
  const needsSize = p.sizes.length > 1;
  const canAdd = !needsSize || size;

  const handleAdd = () => {
    if (!canAdd) return;
    onAdd(p, { color, size: size || p.sizes[0], qty });
    setAdded(true);
    setTimeout(() => setAdded(false), 1800);
  };

  const related = products.filter((x) => x.id !== p.id && x.cat === p.cat).concat(products.filter((x) => x.id !== p.id && x.cat !== p.cat)).slice(0, 4);

  return (
    <div>
      {/* breadcrumb */}
      <div className="wrap" style={{ padding: isMobile ? "18px 20px 0" : "26px 32px 0" }}>
        <div className="ui-label" style={{ fontSize: 11, color: "var(--muted)", display: "flex", gap: 8 }}>
          <span style={{ cursor: "pointer" }} onClick={() => onNav("home")}>Início</span><span>/</span>
          <span style={{ cursor: "pointer" }} onClick={() => onNav(p.cat)}>{p.cat}</span><span>/</span>
          <span style={{ color: "var(--ink)" }}>{p.name}</span>
        </div>
      </div>

      {/* corpo */}
      <section className="wrap" style={{ padding: isMobile ? "20px 20px 56px" : "30px 32px 80px", display: "grid", gridTemplateColumns: isMobile ? "1fr" : "1.05fr 0.95fr", gap: isMobile ? 30 : 56, alignItems: "start" }}>
        {/* galeria */}
        <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "72px 1fr", gap: 16, position: isMobile ? "static" : "sticky", top: 96 }}>
          <div style={{ display: "flex", flexDirection: isMobile ? "row" : "column", gap: isMobile ? 10 : 12, order: isMobile ? 2 : 1, overflowX: isMobile ? "auto" : "visible" }}>
            {p.gallery.map((g, idx) => (
              <button key={idx} onClick={() => setActiveImg(idx)} style={{ padding: 0, border: idx === activeImg ? "1.5px solid var(--wine)" : "1px solid var(--line)", background: "none", borderRadius: 3, overflow: "hidden", flex: isMobile ? "0 0 64px" : undefined }}>
                <Img src={g.src} label={`#${idx + 1}`} pos={g.pos} ratio="3/4" style={{ fontSize: 8 }} />
              </button>
            ))}
          </div>
          <div style={{ order: isMobile ? 1 : 2 }}>
            <Img src={p.gallery[activeImg].src} label={p.gallery[activeImg].ph} pos={p.gallery[activeImg].pos} ratio="3/4" />
          </div>
        </div>

        {/* infos */}
        <div>
          <span className="kicker">{p.cat}</span>
          <h1 style={{ fontSize: "clamp(32px,3.4vw,46px)", lineHeight: 1.12, margin: "10px 0 18px" }}>{p.name}</h1>
          <div style={{ display: "flex", alignItems: "baseline", gap: 12, marginBottom: 8 }}>
            <span style={{ fontFamily: "var(--sans-ui)", fontSize: 22, color: "var(--wine)" }}>{fmtBRL(p.price)}</span>
            {p.compareAt && <span style={{ fontFamily: "var(--sans-ui)", fontSize: 15, color: "var(--muted)", textDecoration: "line-through" }}>{fmtBRL(p.compareAt)}</span>}
          </div>
          <p style={{ fontFamily: "var(--sans-ui)", fontSize: 12.5, color: "var(--muted)", marginTop: 0 }}>ou 6x de {fmtBRL(p.price / 6)} sem juros</p>

          <p style={{ fontSize: 18, lineHeight: 1.6, margin: "20px 0 28px", maxWidth: 460 }}>{p.blurb}</p>

          {/* cor */}
          <div style={{ marginBottom: 24 }}>
            <div className="ui-label" style={{ fontSize: 11, color: "var(--muted)", marginBottom: 12 }}>Cor — <span style={{ color: "var(--ink)" }}>{color}</span></div>
            <div style={{ display: "flex", gap: 12 }}>
              {p.colors.map((c) => <ColorDot key={c.name} hex={c.hex} title={c.name} active={color === c.name} onClick={() => setColor(c.name)} />)}
            </div>
          </div>

          {/* tamanho/variação */}
          <div style={{ marginBottom: 24 }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 12 }}>
              <span className="ui-label" style={{ fontSize: 11, color: "var(--muted)" }}>{sizeLabel}{needsSize && !size && <span style={{ color: "var(--wine)", marginLeft: 8 }}>· selecione</span>}</span>
              {needsSize && <span className="ui-label" style={{ fontSize: 11, color: "var(--wine)", cursor: "pointer", borderBottom: "1px solid var(--wine)" }}>Tabela de medidas</span>}
            </div>
            <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
              {p.sizes.map((s) => {
                const sel = size === s;
                return (
                  <button key={s} onClick={() => setSize(s)} className="ui-label" style={{
                    minWidth: 52, padding: "12px 16px", fontSize: 12,
                    border: sel ? "1.5px solid var(--wine)" : "1px solid var(--line)",
                    background: sel ? "var(--wine)" : "transparent",
                    color: sel ? "var(--cream)" : "var(--ink)",
                    borderRadius: 2, transition: "all .18s",
                  }}>{s}</button>
                );
              })}
            </div>
          </div>

          {/* qty + add */}
          <div style={{ display: "flex", gap: 14, marginBottom: 16 }}>
            <div style={{ display: "flex", alignItems: "center", border: "1px solid var(--line)", borderRadius: 2 }}>
              <button onClick={() => setQty(Math.max(1, qty - 1))} style={qtyBtn}>−</button>
              <span style={{ width: 38, textAlign: "center", fontFamily: "var(--sans-ui)", fontSize: 14 }}>{qty}</span>
              <button onClick={() => setQty(qty + 1)} style={qtyBtn}>+</button>
            </div>
            <button className="btn" style={{ flex: 1, background: added ? "var(--wine-deep)" : "var(--wine)" }} disabled={!canAdd} onClick={handleAdd}>
              {added ? "✓ Adicionado à sacola" : canAdd ? "Adicionar à sacola" : "Selecione um tamanho"}
            </button>
          </div>
          <button className="btn btn--ghost" style={{ width: "100%", marginBottom: 30 }}>Comprar agora</button>

          {/* perks */}
          <div style={{ display: "flex", gap: 24, marginBottom: 18, flexWrap: "wrap" }}>
            {["Frete grátis +R$199", "Troca em 30 dias", "Até 6x sem juros"].map((t) => (
              <span key={t} style={{ fontFamily: "var(--sans-ui)", fontSize: 11.5, color: "var(--muted)", display: "flex", alignItems: "center", gap: 6 }}>
                <span style={{ color: "var(--wine)" }}>✶</span>{t}
              </span>
            ))}
          </div>

          {/* acordeões */}
          <div style={{ marginTop: 10 }}>
            <Accordion title="Descrição" open>
              <p style={{ fontSize: 16.5, lineHeight: 1.65, color: "var(--ink)", margin: 0 }}>{p.desc}</p>
            </Accordion>
            <Accordion title="Detalhes & composição">
              <ul style={{ margin: 0, paddingLeft: 18, fontSize: 16, lineHeight: 1.8 }}>
                {p.details.map((d) => <li key={d}>{d}</li>)}
              </ul>
            </Accordion>
            <Accordion title="Envio & trocas">
              <p style={{ fontSize: 16, lineHeight: 1.65, margin: 0 }}>Enviamos para todo o Brasil em 2–8 dias úteis. Frete grátis em compras acima de R$ 199. Trocas e devoluções gratuitas em até 30 dias.</p>
            </Accordion>
          </div>
        </div>
      </section>

      {/* relacionados */}
      <section style={{ background: "var(--cream-2)", padding: isMobile ? "56px 0" : "76px 0" }}>
        <div className="wrap">
          <div style={{ textAlign: "center", marginBottom: isMobile ? 28 : 40 }}>
            <span className="kicker">Combina com</span>
            <h2 style={{ fontSize: isMobile ? "clamp(28px,8vw,38px)" : "clamp(30px,3.6vw,46px)", marginTop: 8 }}>Você também vai amar</h2>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: isMobile ? "repeat(2,1fr)" : "repeat(4,1fr)", gap: isMobile ? 14 : 28, rowGap: isMobile ? 28 : 28 }}>
            {related.map((r) => <ProductCard key={r.id} p={r} onOpen={onOpen} onAdd={(prod) => onAdd(prod, { color: prod.colors[0].name, size: prod.sizes[0], qty: 1 })} variant="editorial" />)}
          </div>
        </div>
      </section>
    </div>
  );
}
const qtyBtn = { width: 40, height: 46, background: "none", border: "none", fontSize: 18, color: "var(--ink)" };

Object.assign(window, { ProductPage, Accordion });
