// PDP.jsx — Product Detail Page
const { useState: usePDPState } = React;

const PDP = ({ params, onNav, onAdd, onFav, favs }) => {
  const p = CATALOG.find(x => x.id === params?.id) || CATALOG[0];
  const [gallery, setGallery] = usePDPState(0);
  const [qty, setQty] = usePDPState(1);
  const [tab, setTab] = usePDPState("descripcion");
  const { isMobile, isTablet } = useViewport();
  const fav = favs.has(p.id);

  const gallerySrc = [p.img, p.img, p.img, p.img];
  const related = CATALOG.filter(x => x.cat === p.cat && x.id !== p.id).slice(0, 4);

  return (
    <div style={{ maxWidth: "var(--container)", margin: "0 auto", padding: isMobile ? "0 16px" : "0 32px" }}>
      <Breadcrumb items={["Inicio", CATEGORIES.find(c => c.id === p.cat)?.label || "Productos", p.brand, p.name.slice(0, 32) + (p.name.length > 32 ? "…" : "")]} />

      {/* main */}
      <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "1fr 1fr", gap: isMobile ? 24 : 48, alignItems: "start" }}>
        {/* gallery */}
        <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "72px 1fr", gap: 14, position: isMobile ? "static" : "sticky", top: 160 }}>
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {gallerySrc.map((src, i) => (
              <button key={i} onClick={() => setGallery(i)}
                style={{
                  width: 72, height: 72, borderRadius: "var(--radius-md)", overflow: "hidden",
                  border: i === gallery ? "2px solid var(--primary)" : "1px solid var(--border)",
                  padding: 0, cursor: "pointer", background: "var(--bg-elev-1)",
                }}>
                <img src={src} alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }} />
              </button>
            ))}
          </div>
          <div style={{ aspectRatio: 1, borderRadius: "var(--radius-lg)", overflow: "hidden", background: "var(--bg-section)", position: "relative" }}>
            <img src={gallerySrc[gallery]} alt={p.name} style={{ width: "100%", height: "100%", objectFit: "cover" }} />
            {p.discount && (
              <span style={{ position: "absolute", top: 16, left: 16, padding: "6px 14px", borderRadius: 10, background: "var(--discount)", color: "#fff", font: "700 13px var(--font-sans)" }}>−{p.discount}% off</span>
            )}
            <button onClick={() => onFav(p)} style={{ position: "absolute", top: 16, right: 16, width: 44, height: 44, borderRadius: 22, background: "rgba(255,255,255,.94)", border: 0, cursor: "pointer", display: "grid", placeItems: "center", boxShadow: "var(--elev-1)", color: fav ? "#B691FF" : "var(--fg-muted)" }}>
              <AllenIcon name="favorite" size={22} fill={fav ? 1 : 0} weight={500} />
            </button>
          </div>
        </div>

        {/* info */}
        <div>
          <div className="label-sm" style={{ color: "var(--primary)" }}>{p.brand}</div>
          <h1 className="headline-lg" style={{ marginTop: 8 }}>{p.name}</h1>
          <div style={{ display: "flex", alignItems: "center", gap: 16, marginTop: 12 }}>
            <RatingStars value={p.rating} count={p.reviews} size={18} />
            <a style={{ color: "var(--primary)", font: "600 13px var(--font-sans)", cursor: "pointer" }}>Lee {p.reviews?.toLocaleString("es-MX")} opiniones</a>
          </div>

          {/* price block */}
          <div style={{ marginTop: 24, padding: "20px 0", borderTop: "1px solid var(--border-soft)", borderBottom: "1px solid var(--border-soft)" }}>
            <div style={{ display: "flex", alignItems: "baseline", gap: 12 }}>
              <span className="price-xl">${p.price.toLocaleString("es-MX")}</span>
              <span style={{ font: "500 16px var(--font-sans)", color: "var(--fg-subtle)" }}>MXN</span>
            </div>
            {p.was && (
              <div style={{ marginTop: 4, display: "flex", alignItems: "baseline", gap: 8 }}>
                <span style={{ font: "500 14px var(--font-sans)", color: "var(--fg-hint)", textDecoration: "line-through" }}>${p.was.toLocaleString("es-MX")}</span>
                <span style={{ font: "700 13px var(--font-sans)", color: "var(--discount)" }}>Ahorras ${(p.was - p.price).toLocaleString("es-MX")}</span>
              </div>
            )}
            <div style={{ marginTop: 12, font: "500 13px var(--font-sans)", color: "var(--fg-muted)" }}>
              en <strong style={{ color: "var(--fg-strong)" }}>12 MSI</strong> de <strong style={{ color: "var(--fg-strong)" }}>${Math.round(p.price / 12).toLocaleString("es-MX")}</strong> sin intereses
            </div>
          </div>

          {/* shipping */}
          <div style={{ display: "flex", flexDirection: "column", gap: 10, marginTop: 20 }}>
            <Row icon="local_shipping" tint="success">
              <strong>Llega el viernes 5 de marzo</strong> a Puerto Vallarta · 48330. <a style={{ color: "var(--primary)", fontWeight: 600, cursor: "pointer" }}>Cambiar</a>
            </Row>
            <Row icon="verified" tint="primary">
              <strong>Compra protegida.</strong> Devolución gratis hasta 30 días.
            </Row>
            <Row icon="storefront" tint="muted">
              Vendido por <strong style={{ color: "var(--fg-strong)" }}>{p.brand} Store</strong> · ★ 4.8 · +2 años en Allen
            </Row>
          </div>

          {/* quantity + buttons */}
          <div style={{ marginTop: 28, display: "flex", alignItems: "center", gap: 16 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 4, padding: 4, border: "1px solid var(--border-strong)", borderRadius: "9999px" }}>
              <button onClick={() => setQty(q => Math.max(1, q - 1))} style={iconBtn}><AllenIcon name="remove" size={18} /></button>
              <span style={{ width: 36, textAlign: "center", font: "700 15px var(--font-sans)" }}>{qty}</span>
              <button onClick={() => setQty(q => q + 1)} style={iconBtn}><AllenIcon name="add" size={18} /></button>
            </div>
            <span className="body-sm">{p.inStock || 12} disponibles</span>
          </div>

          <div style={{ marginTop: 18, display: "flex", gap: 12 }}>
            <button onClick={() => onAdd(p, qty)} style={{
              flex: 1, background: "var(--primary)", color: "#fff", border: 0, padding: "16px 24px",
              borderRadius: "9999px", font: "700 15px var(--font-sans)", cursor: "pointer", boxShadow: "var(--elev-cta-blue)",
            }}>Agregar al carrito</button>
            <button onClick={() => { onAdd(p, qty); onNav("cart"); }} style={{
              flex: 1, background: "var(--hub-black)", color: "#fff", border: 0, padding: "16px 24px",
              borderRadius: "9999px", font: "700 15px var(--font-sans)", cursor: "pointer",
            }}>Comprar ahora</button>
          </div>
        </div>
      </div>

      {/* tabs */}
      <div style={{ marginTop: 64 }}>
        <div style={{ display: "flex", gap: 4, borderBottom: "1px solid var(--border)" }}>
          {[
            { id: "descripcion", label: "Descripción" },
            { id: "specs",       label: "Especificaciones" },
            { id: "reseñas",     label: `Reseñas (${p.reviews?.toLocaleString("es-MX") || 0})` },
            { id: "preguntas",   label: "Preguntas" },
          ].map(t => (
            <button key={t.id} onClick={() => setTab(t.id)} style={{
              background: "transparent", border: 0, borderBottom: tab === t.id ? "3px solid var(--primary)" : "3px solid transparent",
              padding: "14px 18px", font: tab === t.id ? "700 14px var(--font-sans)" : "500 14px var(--font-sans)",
              color: tab === t.id ? "var(--fg-strong)" : "var(--fg-muted)", cursor: "pointer", marginBottom: -1,
            }}>{t.label}</button>
          ))}
        </div>
        <div style={{ padding: "32px 0", maxWidth: "var(--container-narrow)" }}>
          {tab === "descripcion" && (
            <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
              <p className="body-lg">Diseñado para uso diario, este producto combina materiales premium con la facilidad de mantenimiento que esperas. Probado por Allen y avalado por su garantía oficial.</p>
              <ul style={{ paddingLeft: 20, color: "var(--fg)", font: "400 16px/1.7 var(--font-sans)" }}>
                <li>Garantía oficial Allen de 12 meses.</li>
                <li>Envío con seguimiento en tiempo real.</li>
                <li>Empaque seguro: tu producto llega listo para usarse.</li>
                <li>Soporte 24/7 en español.</li>
              </ul>
            </div>
          )}
          {tab === "specs" && (
            <table style={{ width: "100%", borderCollapse: "collapse" }}>
              <tbody>
                {[
                  ["Marca", p.brand], ["Modelo", p.id.toUpperCase()], ["Categoría", CATEGORIES.find(c => c.id === p.cat)?.label || p.cat],
                  ["Garantía", "12 meses"], ["Origen", "México"],
                ].map(([k, v]) => (
                  <tr key={k} style={{ borderBottom: "1px solid var(--border-soft)" }}>
                    <td style={{ padding: "12px 0", font: "500 14px var(--font-sans)", color: "var(--fg-muted)", width: 180 }}>{k}</td>
                    <td style={{ padding: "12px 0", font: "600 14px var(--font-sans)", color: "var(--fg-strong)" }}>{v}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
          {tab === "reseñas" && (
            <div style={{ display: "flex", flexDirection: "column", gap: 24 }}>
              <div style={{ display: "flex", gap: 32, alignItems: "center", padding: 24, background: "var(--bg-elev-1)", borderRadius: "var(--radius-lg)", border: "1px solid var(--border-soft)" }}>
                <div style={{ textAlign: "center" }}>
                  <div className="price-xl">{p.rating.toFixed(1)}</div>
                  <RatingStars value={p.rating} size={16} />
                  <div className="body-sm" style={{ marginTop: 6 }}>{p.reviews?.toLocaleString("es-MX")} opiniones</div>
                </div>
                <div style={{ flex: 1, display: "flex", flexDirection: "column", gap: 6 }}>
                  {[5, 4, 3, 2, 1].map(s => (
                    <div key={s} style={{ display: "flex", alignItems: "center", gap: 10 }}>
                      <span style={{ font: "500 12px var(--font-sans)", color: "var(--fg-muted)", width: 18 }}>{s}★</span>
                      <div style={{ flex: 1, height: 8, borderRadius: 4, background: "var(--bg-section)", overflow: "hidden" }}>
                        <div style={{ width: `${s === 5 ? 72 : s === 4 ? 18 : 4}%`, height: "100%", background: "var(--star)" }} />
                      </div>
                      <span className="body-sm" style={{ width: 40, textAlign: "right" }}>{s === 5 ? 605 : s === 4 ? 150 : 30}</span>
                    </div>
                  ))}
                </div>
              </div>
              {[
                { name: "María G.", date: "12 feb 2026", rating: 5, text: "Cumple totalmente lo prometido. Llegó antes de lo estimado y muy bien empacado." },
                { name: "Carlos R.", date: "5 feb 2026", rating: 4, text: "Buena calidad por el precio. El único detalle es que la batería podría durar más, pero por lo demás recomendado." },
              ].map(rv => (
                <div key={rv.date} style={{ paddingBottom: 20, borderBottom: "1px solid var(--border-soft)" }}>
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                    <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                      <div style={{ width: 36, height: 36, borderRadius: 18, background: "var(--bg-section)", display: "grid", placeItems: "center", font: "700 13px var(--font-sans)", color: "var(--fg-strong)" }}>{rv.name[0]}</div>
                      <div>
                        <div className="title-sm">{rv.name}</div>
                        <RatingStars value={rv.rating} size={12} />
                      </div>
                    </div>
                    <span className="body-sm">{rv.date}</span>
                  </div>
                  <p className="body" style={{ marginTop: 10 }}>{rv.text}</p>
                </div>
              ))}
            </div>
          )}
          {tab === "preguntas" && (
            <div style={{ padding: 32, textAlign: "center", background: "var(--bg-elev-1)", borderRadius: "var(--radius-lg)", border: "1px solid var(--border-soft)" }}>
              <p className="body">Aún no hay preguntas sobre este producto.</p>
              <button style={{ marginTop: 14, background: "transparent", color: "var(--primary)", border: "1.5px solid var(--primary)", padding: "10px 20px", borderRadius: "9999px", font: "700 13px var(--font-sans)", cursor: "pointer" }}>Haz la primera pregunta</button>
            </div>
          )}
        </div>
      </div>

      {/* related */}
      <Section title="Productos relacionados" onSeeAll={() => onNav("plp", { cat: p.cat })}>
        <Grid items={related} onOpen={x => onNav("pdp", { id: x.id })} onAdd={onAdd} onFav={onFav} favs={favs} />
      </Section>
    </div>
  );
};

const iconBtn = {
  width: 36, height: 36, borderRadius: 18, border: 0,
  background: "transparent", display: "grid", placeItems: "center", cursor: "pointer", color: "var(--fg-strong)",
};

const Row = ({ icon, tint, children }) => {
  const colors = {
    success: { bg: "var(--success-bg)", fg: "var(--success)" },
    primary: { bg: "var(--primary-soft)", fg: "var(--primary-press)" },
    muted:   { bg: "var(--bg-section)", fg: "var(--fg-muted)" },
  };
  const c = colors[tint] || colors.muted;
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "10px 14px", background: c.bg, borderRadius: "var(--radius-md)" }}>
      <AllenIcon name={icon} size={20} color={c.fg} />
      <span style={{ font: "500 14px/1.5 var(--font-sans)", color: "var(--fg-strong)" }}>{children}</span>
    </div>
  );
};

window.PDP = PDP;
