// PRODUCT — Artesanías Chepe — con configurador

const ProductDetail = ({ product, onNav, onAddCart, onProduct }) => {
  if (!product) {
    return (
      <div className="page container" style={{ padding: 24 }} data-screen-label="03 Producto">
        <p>Producto no encontrado.</p>
        <button className="btn btn-primary" onClick={() => onNav("catalog")}>Volver al catálogo</button>
      </div>
    );
  }

  const [material, setMaterial] = useState(product.materials[0]);
  const [finish, setFinish] = useState(product.finishes[0]);
  const [sizeId, setSizeId] = useState(product.sizes[0].id);
  const [qty, setQty] = useState(1);
  const [activeImg, setActiveImg] = useState(0);
  const [addedFlash, setAddedFlash] = useState(false);
  const touchStartX = useRef(null);

  const size = product.sizes.find(s => s.id === sizeId) || product.sizes[0];
  const unitPrice = product.price + (size.delta || 0);
  const total = unitPrice * qty;

  const related = window.PRODUCTS.filter(p => p.cat === product.cat && p.id !== product.id).slice(0, 4);

  // Imágenes reales o placeholders de respaldo
  const images = product.images || [];
  const hasImages = images.length > 0;
  const imgClasses = [product.placeholderClass, "ph-warm", "ph", "ph-dark"];
  const imgCount = hasImages ? images.length : imgClasses.length;

  const onTouchStart = (e) => { touchStartX.current = e.touches[0].clientX; };
  const onTouchEnd = (e) => {
    if (touchStartX.current === null) return;
    const diff = touchStartX.current - e.changedTouches[0].clientX;
    if (Math.abs(diff) > 40) {
      if (diff > 0) setActiveImg(i => Math.min(i + 1, imgCount - 1));
      else setActiveImg(i => Math.max(i - 1, 0));
    }
    touchStartX.current = null;
  };

  const onAdd = (e) => {
    onAddCart({ ...product, finish, material, size: size.label, price: unitPrice }, e, qty);
    setAddedFlash(true);
    setTimeout(() => setAddedFlash(false), 1400);
  };

  return (
    <div className="page" data-screen-label="03 Producto">
      {/* Breadcrumb */}
      <div className="container" style={{ paddingTop: 6, paddingBottom: 12 }}>
        <button onClick={() => onNav("catalog")} className="mono"
          style={{ fontSize: 11, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--ink-60)", display: "inline-flex", alignItems: "center", gap: 6 }}>
          <Icon name="arrow-l" size={14} /> Catálogo · {window.CATEGORIES.find(c => c.id === product.cat)?.name}
        </button>
      </div>

      {/* Main image con swipe */}
      <div style={{ padding: "0 20px" }}>
        <div
          onTouchStart={onTouchStart}
          onTouchEnd={onTouchEnd}
          style={{ aspectRatio: "4/5", borderRadius: 16, position: "relative", overflow: "hidden" }}
        >
          {hasImages ? (
            <img
              src={images[activeImg]}
              alt={`${product.name} — foto ${activeImg + 1}`}
              style={{ width: "100%", height: "100%", objectFit: "cover", display: "block", userSelect: "none" }}
              draggable={false}
            />
          ) : (
            <div className={"ph " + imgClasses[activeImg]} style={{ position: "absolute", inset: 0 }}>
              <span style={{ position: "absolute", bottom: 14, left: 16 }}>{product.placeholderLabel} — vista {activeImg + 1}</span>
            </div>
          )}

          {product.badge && (
            <span style={{
              position: "absolute", top: 12, left: 12, zIndex: 2,
              background: "var(--ink)", color: "var(--bone)",
              padding: "6px 10px", borderRadius: 999,
              fontFamily: "var(--mono)", fontSize: 9, letterSpacing: "0.14em", textTransform: "uppercase",
            }}>{product.badge}</span>
          )}
          <button aria-label="Favorito" style={{
            position: "absolute", top: 12, right: 12, zIndex: 2,
            width: 40, height: 40, borderRadius: 999,
            background: "var(--bone)", color: "var(--ink)",
            display: "grid", placeItems: "center", boxShadow: "var(--shadow-sm)",
          }}><Icon name="heart" size={18} /></button>

          {/* Dots */}
          {imgCount > 1 && (
            <div aria-hidden="true" style={{
              position: "absolute", bottom: 14, left: "50%", transform: "translateX(-50%)",
              display: "flex", gap: 6, zIndex: 2,
            }}>
              {Array.from({ length: imgCount }).map((_, i) => (
                <span key={i} style={{
                  width: i === activeImg ? 18 : 7, height: 7, borderRadius: 999,
                  background: i === activeImg
                    ? "var(--bone)"
                    : "color-mix(in srgb, var(--bone) 55%, transparent)",
                  transition: "width .22s ease",
                }} />
              ))}
            </div>
          )}
        </div>
      </div>

      {/* Thumb rail */}
      <div className="rail" style={{ padding: "12px 20px 0" }} role="group" aria-label="Galería de fotos">
        {Array.from({ length: imgCount }).map((_, i) => (
          <button key={i} onClick={() => setActiveImg(i)} aria-label={`Foto ${i + 1}`} aria-pressed={activeImg === i}
            style={{
              width: 64, height: 64, borderRadius: 10, overflow: "hidden",
              outline: activeImg === i ? "2px solid var(--ink)" : "none",
              outlineOffset: 2, flexShrink: 0,
            }}>
            {hasImages ? (
              <img src={images[i]} alt={`Miniatura ${i + 1}`}
                style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }} />
            ) : (
              <div className={"ph " + imgClasses[i]} style={{ width: "100%", height: "100%" }} />
            )}
          </button>
        ))}
      </div>

      {/* Title + price */}
      <div className="container" style={{ paddingTop: 26 }}>
        <div className="eyebrow">{window.CATEGORIES.find(c => c.id === product.cat)?.name} · Mérida</div>
        <h1 className="display" style={{ fontSize: 36, margin: "6px 0 8px", lineHeight: 1.05 }}>{product.name}</h1>
        <p style={{ color: "var(--ink-80)", fontSize: 15, lineHeight: 1.5, margin: "0 0 14px" }}>{product.blurb}</p>
        <div style={{ display: "flex", alignItems: "baseline", gap: 10 }}>
          <span className="display" style={{ fontSize: 32 }}>{formatMXN(unitPrice)}</span>
          <span className="mono" style={{ fontSize: 11, color: "var(--ink-60)", letterSpacing: "0.12em", textTransform: "uppercase" }}>MXN · IVA inc.</span>
        </div>
      </div>

      {/* ===== CONFIGURADOR ===== */}
      <div className="container" style={{ paddingTop: 28 }}>
        <div className="card hair" style={{ padding: 20, borderRadius: 18 }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 16 }}>
            <div className="eyebrow">Configurar pieza</div>
            <span className="mono" style={{ fontSize: 10, color: "var(--clay)", letterSpacing: "0.14em", textTransform: "uppercase" }}>
              ✦ A tu medida
            </span>
          </div>

          {/* Material */}
          <div style={{ marginBottom: 18 }}>
            <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 8 }}>
              <span className="mono" style={{ fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--ink-60)" }}>Material</span>
              <span className="mono" style={{ fontSize: 11, color: "var(--ink)" }}>{material}</span>
            </div>
            <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
              {product.materials.map(m => (
                <button key={m} onClick={() => setMaterial(m)}
                  className={"chip " + (material === m ? "is-active" : "")}>{m}</button>
              ))}
            </div>
          </div>

          {/* Acabado — swatches */}
          <div style={{ marginBottom: 18 }}>
            <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 8 }}>
              <span className="mono" style={{ fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--ink-60)" }}>Acabado</span>
              <span className="mono" style={{ fontSize: 11 }}>{finish}</span>
            </div>
            <div style={{ display: "flex", gap: 10 }}>
              {product.finishes.map(f => {
                const colorMap = {
                  "Natural": "#d8c39a", "Crudo": "#e3d4b5",
                  "Miel": "#b8843d", "Café tostado": "#5e3a22",
                  "Negro mate": "#1a1410", "Gris piedra": "#7d756b",
                };
                const c = colorMap[f] || "#a89178";
                return (
                  <button key={f} onClick={() => setFinish(f)}
                    aria-label={f}
                    style={{
                      width: 44, height: 44, borderRadius: 999,
                      background: c, position: "relative",
                      outline: finish === f ? "2px solid var(--ink)" : "1px solid var(--hair-strong)",
                      outlineOffset: finish === f ? 2 : 0,
                    }}>
                    {finish === f && <span style={{
                      position: "absolute", inset: 0, display: "grid", placeItems: "center",
                      color: c === "#1a1410" || c === "#5e3a22" || c === "#7d756b" ? "var(--bone)" : "var(--ink)",
                    }}><Icon name="check" size={18} stroke={2.2} /></span>}
                  </button>
                );
              })}
            </div>
          </div>

          {/* Tamaño */}
          <div style={{ marginBottom: 18 }}>
            <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 8 }}>
              <span className="mono" style={{ fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--ink-60)" }}>Tamaño</span>
              {size.delta > 0 && <span className="mono" style={{ fontSize: 11, color: "var(--clay)" }}>+{formatMXN(size.delta)}</span>}
            </div>
            <div style={{ display: "grid", gridTemplateColumns: `repeat(${product.sizes.length}, 1fr)`, gap: 8 }}>
              {product.sizes.map(s => (
                <button key={s.id} onClick={() => setSizeId(s.id)}
                  style={{
                    padding: "12px 8px", borderRadius: 12,
                    border: "1px solid " + (sizeId === s.id ? "var(--ink)" : "var(--hair-strong)"),
                    background: sizeId === s.id ? "var(--ink)" : "transparent",
                    color: sizeId === s.id ? "var(--bone)" : "var(--ink)",
                    fontSize: 13, fontFamily: "var(--sans)", fontWeight: 500,
                    transition: "all .15s ease",
                  }}>
                  {s.label}
                </button>
              ))}
            </div>
          </div>

          {/* Cantidad + agregar */}
          <div style={{ display: "flex", gap: 12, alignItems: "center" }}>
            <div className="hair" style={{ display: "inline-flex", borderRadius: 999, overflow: "hidden", height: 48 }}>
              <button onClick={() => setQty(Math.max(1, qty - 1))} style={{ width: 44, display: "grid", placeItems: "center" }}>
                <Icon name="minus" size={16} />
              </button>
              <span className="mono" style={{ width: 36, display: "grid", placeItems: "center", fontSize: 14 }}>{qty}</span>
              <button onClick={() => setQty(qty + 1)} style={{ width: 44, display: "grid", placeItems: "center" }}>
                <Icon name="plus" size={16} />
              </button>
            </div>
            <button onClick={onAdd} className="btn btn-primary" style={{ flex: 1, height: 48 }}>
              {addedFlash ? (<React.Fragment><Icon name="check" size={16} /> Agregado</React.Fragment>) : (
                <React.Fragment>Agregar — {formatMXN(total)}</React.Fragment>
              )}
            </button>
          </div>
        </div>
      </div>

      {/* Trust badges */}
      <div className="container" style={{ paddingTop: 24 }}>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          {[
            { i: "ship",   t: "Envío MX",      s: "5–9 días" },
            { i: "shield", t: "Garantía 5 años", s: "Estructura" },
            { i: "spark",  t: "100% artesanal",  s: "Hecho a mano" },
            { i: "leaf",   t: "Materia local",  s: "Yucatán" },
          ].map((b, i) => (
            <div key={i} className="hair" style={{ padding: 14, borderRadius: 14, display: "flex", gap: 12, alignItems: "center" }}>
              <Icon name={b.i} size={22} stroke={1.4} />
              <div>
                <div style={{ fontSize: 13, fontWeight: 600 }}>{b.t}</div>
                <div className="mono" style={{ fontSize: 9, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--ink-60)", marginTop: 2 }}>{b.s}</div>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Descripción */}
      <div className="container" style={{ paddingTop: 36 }}>
        <SectionHead eyebrow="Detalles" title="Sobre la pieza" />
        <p style={{ fontSize: 15, lineHeight: 1.65, color: "var(--ink-80)" }}>{product.description}</p>
        <div className="divider" style={{ marginTop: 16, marginBottom: 16 }}></div>
        <div style={{ display: "flex", gap: 12 }}>
          <Icon name="leaf" size={18} stroke={1.4} />
          <div>
            <div className="mono" style={{ fontSize: 10, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--ink-60)" }}>Cuidado</div>
            <p style={{ fontSize: 14, color: "var(--ink-80)", margin: "4px 0 0" }}>{product.care}</p>
          </div>
        </div>
      </div>

      {/* Related */}
      <div style={{ paddingTop: 56 }}>
        <div className="container">
          <SectionHead eyebrow="También te puede gustar" title="Del mismo taller" />
        </div>
        <div className="rail" style={{ padding: "0 20px 8px" }}>
          {related.map(p => (
            <div key={p.id} style={{ width: 200 }}>
              <ProductCard product={p} onClick={onProduct} onAdd={onAddCart} compact />
            </div>
          ))}
        </div>
      </div>

      <Footer onNav={onNav} />
    </div>
  );
};

window.ProductDetail = ProductDetail;
