/* ============ Product Detail page ============ */
function ProductPage({ store, productId, navigate, openSizeGuide }) {
  const p = store.products.find(x => x.id === productId) || store.products[0];
  const cat = store.categories.find(c => c.id === p.category);
  const related = store.products.filter(x => x.category === p.category && x.id !== p.id).slice(0, 4);

  const [activePhoto, setActivePhoto] = useState(0);
  const [size, setSize] = useState(p.sizes[0]);
  const [qty, setQty] = useState(1);
  const [openAcc, setOpenAcc] = useState("desc");

  const waMsg = encodeURIComponent(
    `Hola KIRO Jewelry 👋\nMe interesa esta pieza:\n\n• ${p.name}\n• Talla: ${size}\n• Cantidad: ${qty}\n• Precio: ${fmtPrice(p.price)}\n\n¿Sigue disponible?`
  );
  const waLink = `https://wa.me/51954796222?text=${waMsg}`;

  return (
    <main>
      {/* Breadcrumb */}
      <div className="section" style={{ paddingTop: 32, paddingBottom: 12 }}>
        <div style={{ display: "flex", gap: 8, fontSize: 12,
          letterSpacing: "0.16em", textTransform: "uppercase",
          color: "var(--ink-2)" }}>
          <a onClick={()=>navigate("/")} style={{ cursor: "pointer" }}>Inicio</a>
          <span>/</span>
          <a onClick={()=>navigate("/c/"+p.category)} style={{ cursor: "pointer" }}>{cat?.name}</a>
          <span>/</span>
          <span style={{ color: "var(--burgundy)" }}>{p.name}</span>
        </div>
      </div>

      {/* Main */}
      <section className="section pdp" style={{
        paddingTop: 24,
        display: "grid",
        gridTemplateColumns: "1fr 1fr",
        gap: 80, alignItems: "start",
      }}>
        {/* GALLERY */}
        <div className="pdp-gallery" style={{ display: "grid", gridTemplateColumns: "80px 1fr", gap: 16 }}>
          <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
            {Array.from({length: (p.images && p.images.length) || p.photos || 4}).map((_, i) => (
              <button key={i} onClick={()=>setActivePhoto(i)}
                style={{
                  padding: 0, border: i===activePhoto ? "1px solid var(--burgundy)" : "1px solid transparent",
                  background: "transparent", cursor: "pointer", aspectRatio: "1",
                }}>
                <div style={{ width: "100%", height: "100%" }}>
                  <ProductImg p={p} idx={i}/>
                </div>
              </button>
            ))}
          </div>
          <div style={{
            position: "sticky", top: 100,
            aspectRatio: "4/5", background: "var(--cream)", position: "relative", overflow: "hidden",
          }}>
            <ProductImg p={p} idx={activePhoto} />
            {p.tag && (
              <span className="tag" style={{
                position: "absolute", top: 16, left: 16,
                background: "var(--burgundy)", color: "var(--pink-50)",
                padding: "5px 12px", fontSize: 10, letterSpacing: "0.18em",
                textTransform: "uppercase", fontWeight: 600,
              }}>{p.tag}</span>
            )}
          </div>
        </div>

        {/* INFO */}
        <div className="pdp-info" style={{ position: "sticky", top: 100, paddingTop: 12 }}>
          <div className="eyebrow">{cat?.name}</div>
          <h1 style={{
            fontFamily: "var(--serif)", fontWeight: 400,
            fontSize: "clamp(28px, 5vw, 64px)", lineHeight: 1.05,
            letterSpacing: "-0.01em", color: "var(--burgundy)", margin: "12px 0 16px",
          }}>{p.name}</h1>

          <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 28 }}>
            <span style={{ fontSize: 24, color: "var(--ink)", fontFamily: "var(--serif)" }}>
              {fmtPrice(p.price)}
            </span>
          </div>

          <p style={{ fontSize: 16, lineHeight: 1.7, color: "var(--ink-2)", marginBottom: 32 }}>
            {p.description}
          </p>

          {/* Size selector */}
          <div style={{ marginBottom: 24 }}>
            <div style={{ display: "flex", justifyContent: "space-between",
              fontSize: 11, letterSpacing: "0.2em", textTransform: "uppercase",
              fontWeight: 600, color: "var(--burgundy)", marginBottom: 12 }}>
              <span>Talla · {size}</span>
              {p.category === "anillos" && (
                <a
                  onClick={() => openSizeGuide && openSizeGuide()}
                  style={{ color: "var(--ink-2)", textDecoration: "underline", cursor: "pointer" }}
                >
                  Tabla de tallas
                </a>
              )}
            </div>
            <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
              {p.sizes.map(s => (
                <button key={s} onClick={()=>setSize(s)}
                  style={{
                    padding: "12px 18px",
                    background: size === s ? "var(--burgundy)" : "var(--cream)",
                    color: size === s ? "var(--pink-50)" : "var(--ink)",
                    border: "1px solid " + (size === s ? "var(--burgundy)" : "var(--line)"),
                    fontSize: 13, fontWeight: 600, fontFamily: "var(--sans)",
                    cursor: "pointer", minWidth: 56,
                  }}>{s}</button>
              ))}
            </div>
          </div>

          {/* Quantity */}
          <div style={{ marginBottom: 32 }}>
            <div style={{ fontSize: 11, letterSpacing: "0.2em", textTransform: "uppercase",
              fontWeight: 600, color: "var(--burgundy)", marginBottom: 12 }}>Cantidad</div>
            <div style={{ display: "inline-flex", border: "1px solid var(--line)", background: "var(--cream)" }}>
              <button onClick={()=>setQty(q=>Math.max(1,q-1))}
                style={{ width: 44, height: 44, background: "transparent", border: 0,
                  color: "var(--burgundy)", fontSize: 18 }}>−</button>
              <span style={{ width: 44, height: 44, display: "inline-flex", alignItems: "center", justifyContent: "center",
                fontWeight: 600, fontSize: 14 }}>{qty}</span>
              <button onClick={()=>setQty(q=>q+1)}
                style={{ width: 44, height: 44, background: "transparent", border: 0,
                  color: "var(--burgundy)", fontSize: 18 }}>+</button>
            </div>
          </div>

          {/* Primary CTA */}
          <div style={{ display: "grid", gap: 10, marginBottom: 32 }}>
            <a href={waLink} target="_blank" rel="noopener" className="btn btn-whatsapp btn-lg">
              <Icon name="whatsapp" size={18}/>
              Pedir por WhatsApp · {fmtPrice(p.price * qty)}
            </a>
          </div>

          {/* Accordions */}
          <div>
            {[
              { id: "desc", t: "Detalles", body: p.description + " Cada pieza viene con su certificado de origen y guía de cuidado." },
              { id: "mat",  t: "Material", body: p.material + ". Hipoalergénico, sin níquel ni plomo." },
              { id: "ship", t: "Envíos y devoluciones", body: "Envíos en 2 a 5 días hábiles en todo Perú. Gratis sobre S/ 350. Aceptamos devoluciones sin preguntas durante 30 días." },
              { id: "care", t: "Cuidados", body: "Guarda tu pieza en su bolsita de algodón. Evita el contacto con perfumes, cremas y agua salada. Limpia con un paño suave." },
            ].map(acc => (
              <div key={acc.id} style={{ borderBottom: "1px solid var(--line-2)" }}>
                <button onClick={()=>setOpenAcc(o => o===acc.id ? "" : acc.id)}
                  style={{ background: "transparent", border: 0,
                    width: "100%", padding: "18px 0", display: "flex",
                    justifyContent: "space-between", alignItems: "center",
                    fontSize: 13, letterSpacing: "0.16em", textTransform: "uppercase",
                    fontWeight: 600, color: "var(--burgundy)", cursor: "pointer" }}>
                  {acc.t}
                  <Icon name={openAcc===acc.id ? "chevD" : "chevR"} size={14}/>
                </button>
                {openAcc===acc.id && (
                  <div style={{ paddingBottom: 18, fontSize: 14, color: "var(--ink-2)", lineHeight: 1.7 }}>
                    {acc.body}
                  </div>
                )}
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* RELATED */}
      <section className="section" style={{ paddingTop: 64 }}>
        <div className="section-header">
          <div>
            <div className="eyebrow">Te puede gustar</div>
            <h2 className="section-title" style={{ marginTop: 12 }}>
              Más en <em>{cat?.name}</em>
            </h2>
          </div>
        </div>
        <div className="prod-grid" style={{
          display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: "32px 24px",
        }}>
          {related.map(rp => (
            <ProductCard key={rp.id} p={rp} onClick={()=>{ navigate("/p/"+rp.id); window.scrollTo({top:0}); }}/>
          ))}
        </div>
      </section>
    </main>
  );
}

window.ProductPage = ProductPage;
