// storefront-pdp.jsx — Product Detail Page

function PDP({ slug, mobile }) {
  const s = useStore();
  const product = PRODUCTS.find(p => p.slug === slug) || PRODUCTS[0];
  const [colorIdx, setColorIdx] = useState(0);
  const [size, setSize] = useState(null);
  const [galleryIdx, setGalleryIdx] = useState(0);
  const color = product.colors[colorIdx];

  // Hoisted so swipe handlers can read VIEWS.length
  const ALL_VIEWS = ['front','back','detail','backLogo'];
  const availableViews = ALL_VIEWS.filter(v => resolveProductImage(product, color, v));
  const VIEWS = availableViews.length > 0 ? availableViews : ['front','back','detail','backLogo'];

  // Touch swipe for mobile gallery
  const touchStartX = useRef(null);
  const touchStartY = useRef(null);
  const onGalleryTouchStart = (e) => {
    touchStartX.current = e.touches[0].clientX;
    touchStartY.current = e.touches[0].clientY;
  };
  const onGalleryTouchEnd = (e) => {
    if (touchStartX.current == null) return;
    const dx = e.changedTouches[0].clientX - touchStartX.current;
    const dy = e.changedTouches[0].clientY - touchStartY.current;
    touchStartX.current = null;
    touchStartY.current = null;
    // require mostly-horizontal swipe of at least 40px
    if (Math.abs(dx) < 40 || Math.abs(dx) < Math.abs(dy)) return;
    if (dx > 0) setGalleryIdx(i => Math.max(0, i - 1));
    else setGalleryIdx(i => Math.min(VIEWS.length - 1, i + 1));
  };

  const related = PRODUCTS.filter(p => p.category === product.category && p.id !== product.id).slice(0,3);
  if (related.length < 3) {
    PRODUCTS.filter(p => p.id !== product.id).forEach(p => { if (related.length < 3 && !related.includes(p)) related.push(p); });
  }

  const addToCart = () => {
    if (!size) return;
    s.addToCart({
      id: product.id, name: product.name, price: product.price,
      color: color.name, colorHex: color.hex, size, qty: 1,
    });
    s.setCartOpen(true);
  };

  return (
    <main style={{ background: C.bg }}>
      {/* breadcrumb */}
      <div style={{
        padding: mobile ? '12px 16px' : '14px 32px', borderBottom: `1px solid ${C.border}`,
        fontFamily:'JetBrains Mono, monospace', fontSize: 11, letterSpacing:'0.16em', textTransform:'uppercase',
        display:'flex', gap:8, color: C.fgMuted,
      }}>
        <a onClick={() => s.go('home')} style={{ cursor:'pointer', color: C.fg }}>Inicio</a>
        <span>/</span>
        <span>{product.category}</span>
        <span>/</span>
        <span style={{ color: C.fg }}>{product.name}</span>
      </div>

      <section style={{
        display:'grid',
        gridTemplateColumns: mobile ? '1fr' : '1fr 1fr',
        gap: 0,
      }}>
        {/* ─ Gallery ─ */}
        <div style={{
          background: '#fafafa', position:'relative',
          borderRight: mobile ? 'none' : `1px solid ${C.border}`,
        }}>
          {(() => {
            // Product views use only the studio shots — no models in the catalog.
            //   Hoodies: flat front + flat back + MM logo detail + back logo detail (2×2)
            //   MM pieces: flat front + flat back (1×2)
            //   No photos: 4 placeholder views (2×2)
            const viewLabels = {
              front:    '01 · Frente',
              back:     '02 · Espalda',
              detail:   '03 · Detalle bordado',
              backLogo: '04 · Logo en espalda',
            };
            // 4+ views → 2×2 grid · 2 views → 1×2 vertical stack (each photo full-width)
            const cols = VIEWS.length <= 2 ? 1 : 2;
            const rows = Math.ceil(VIEWS.length / cols);
            return mobile ? (
              <div>
                <div style={{ position:'relative' }} onTouchStart={onGalleryTouchStart} onTouchEnd={onGalleryTouchEnd}>
                  <ProductPlaceholder
                    product={product} color={color} mobile={mobile} large
                    view={VIEWS[Math.min(galleryIdx, VIEWS.length - 1)] || 'front'}
                    label={viewLabels[VIEWS[Math.min(galleryIdx, VIEWS.length - 1)]] || `${product.id} · vista ${galleryIdx + 1}/${VIEWS.length}`} />
                  <div style={{
                    position:'absolute', bottom: 12, left: 0, right: 0,
                    display:'flex', justifyContent:'center', gap: 6,
                  }}>
                    {VIEWS.map((_, i) => (
                      <button key={i} onClick={() => setGalleryIdx(i)} style={{
                        width: galleryIdx === i ? 24 : 8, height: 4, borderRadius: 2,
                        background: galleryIdx === i ? '#0A0A0A' : 'rgba(0,0,0,0.25)',
                        border: 0, cursor:'pointer', transition:'width .25s',
                      }}/>
                    ))}
                  </div>
                </div>
              </div>
            ) : (
              <div style={{
                display:'grid',
                gridTemplateColumns: `repeat(${cols}, 1fr)`,
                gridAutoRows: '1fr',
                gap: 0,
              }}>
                {VIEWS.map((v, i) => {
                  const isLastRow = Math.floor(i / cols) === rows - 1;
                  const isRightCol = (i % cols) === cols - 1;
                  return (
                    <div key={i} style={{
                      borderRight: isRightCol ? 'none' : `1px solid ${C.border}`,
                      borderBottom: isLastRow ? 'none' : `1px solid ${C.border}`,
                    }}>
                      <ProductPlaceholder product={product} color={color} mobile={mobile}
                        view={v} label={viewLabels[v]} />
                    </div>
                  );
                })}
              </div>
            );
          })()}
        </div>

        {/* ─ Sticky Info ─ */}
        <div style={{
          padding: mobile ? '24px 16px' : '40px 48px',
          position: mobile ? 'static' : 'sticky', top: mobile ? 'auto' : 70, alignSelf:'start',
        }}>
          <div style={{ display:'flex', alignItems:'baseline', gap: 12, marginBottom: 8 }}>
            <span style={{ fontFamily:'JetBrains Mono, monospace', fontSize: 11, letterSpacing:'0.2em', textTransform:'uppercase', color: C.fgMuted }}>
              {product.id.toUpperCase()} · {product.category}
            </span>
            {product.isNew && (
              <span style={{
                background: C.accent, color:'#fff',
                fontFamily:'JetBrains Mono, monospace', fontSize: 9,
                letterSpacing:'0.18em', padding:'3px 7px', textTransform:'uppercase',
              }}>NEW IN</span>
            )}
          </div>
          <h1 style={{
            margin: 0, fontFamily:'Anton, sans-serif',
            fontSize: mobile ? 44 : 72, lineHeight: 0.95, letterSpacing:'-0.01em',
            textTransform:'uppercase',
          }}>{product.name}</h1>
          <div style={{ marginTop: 10, display:'flex', alignItems:'baseline', gap: 12 }}>
            <span style={{ fontFamily:'Anton, sans-serif', fontSize: mobile ? 28 : 36, letterSpacing:'-0.01em' }}>
              ${product.price.toLocaleString('es-MX')}
            </span>
            <span style={{ fontFamily:'JetBrains Mono, monospace', fontSize: 11, color: C.fgMuted, letterSpacing:'0.18em', textTransform:'uppercase' }}>MXN · 3 MSI</span>
          </div>

          <p style={{
            marginTop: 20, marginBottom: 28,
            fontFamily:'Roboto, sans-serif', fontSize: 14, lineHeight: 1.55, color:'#333',
          }}>{product.description}</p>

          {/* Color selector */}
          <div style={{ marginBottom: 24 }}>
            <div style={{
              display:'flex', justifyContent:'space-between', alignItems:'baseline',
              fontFamily:'JetBrains Mono, monospace', fontSize: 11, letterSpacing:'0.18em', textTransform:'uppercase',
              marginBottom: 10,
            }}>
              <span>Color</span>
              <span style={{ color: C.fgMuted }}>{color.name}</span>
            </div>
            <div style={{ display:'flex', gap: 10 }}>
              {product.colors.map((c, i) => (
                <button key={i} onClick={() => setColorIdx(i)} style={{
                  width: 36, height: 36, padding: 3, borderRadius: '50%',
                  border: colorIdx === i ? `1.5px solid ${C.fg}` : '1.5px solid transparent',
                  background:'transparent', cursor:'pointer',
                }}>
                  <span style={{ display:'block', width:'100%', height:'100%', borderRadius:'50%', background: c.hex, boxShadow:'inset 0 0 0 1px rgba(0,0,0,0.18)' }}/>
                </button>
              ))}
            </div>
          </div>

          {/* Size selector */}
          <div style={{ marginBottom: 28 }}>
            <div style={{
              display:'flex', justifyContent:'space-between', alignItems:'baseline',
              fontFamily:'JetBrains Mono, monospace', fontSize: 11, letterSpacing:'0.18em', textTransform:'uppercase',
              marginBottom: 10,
            }}>
              <span>Talla</span>
              <a style={{ color: C.fgMuted, cursor:'pointer', textDecoration:'underline' }}>Guía de tallas</a>
            </div>
            <div style={{ display:'grid', gridTemplateColumns:`repeat(${product.sizes.length}, 1fr)`, gap: 8 }}>
              {product.sizes.map(sz => (
                <button key={sz} onClick={() => setSize(sz)} style={{
                  padding: '14px 0',
                  border: size === sz ? `1.5px solid ${C.fg}` : `1px solid ${C.border}`,
                  background: size === sz ? C.fg : '#fff',
                  color: size === sz ? '#fff' : C.fg,
                  fontFamily:'JetBrains Mono, monospace', fontSize: 12, letterSpacing:'0.14em',
                  cursor:'pointer', transition: 'all .15s',
                }}>{sz}</button>
              ))}
            </div>
          </div>

          {/* CTAs */}
          <div style={{ display:'flex', flexDirection:'column', gap: 10 }}>
            <button className="cmd-btn-primary" onClick={addToCart} disabled={!size}>
              {size ? 'Comprar' : 'Elige talla'} {size && Icon.arrowR(16)}
            </button>
            <button className="cmd-btn-secondary" onClick={() => s.openReserva(product)}>
              Reservar en estudio {Icon.pin(15)}
            </button>
            {product.tryOnEnabled && (
              <button className="cmd-btn-link" onClick={() => s.openTryOn(product)}>
                {Icon.sparkles(15)} Probar con AI
                <span style={{ marginLeft: 6, fontSize: 9, padding:'2px 5px', background: C.accent, color:'#fff', letterSpacing:'0.16em' }}>BETA</span>
              </button>
            )}
          </div>

          {/* Accordions */}
          <div style={{ marginTop: 32, borderTop: `1px solid ${C.border}` }}>
            <Accordion title="Materiales y construcción" defaultOpen>
              <p style={{ fontFamily:'Roboto, sans-serif', fontSize: 13, lineHeight: 1.55, color:'#333', margin: 0 }}>{product.materials}</p>
            </Accordion>
            <Accordion title="Cuidado de la prenda">
              <p style={{ fontFamily:'Roboto, sans-serif', fontSize: 13, lineHeight: 1.55, color:'#333', margin: 0 }}>Lavado en frío, del revés. Secado al aire. No usar suavizante. No planchar el bordado.</p>
            </Accordion>
            <Accordion title="Envíos y devoluciones">
              <p style={{ fontFamily:'Roboto, sans-serif', fontSize: 13, lineHeight: 1.55, color:'#333', margin: 0 }}>Envío gratis desde $1,499. 30 días para devolver. Cambios sin costo en cualquiera de nuestros 24 estudios.</p>
            </Accordion>
          </div>
        </div>
      </section>

      {/* Related */}
      <section style={{ borderTop: `1px solid ${C.fg}`, padding: mobile ? '24px 16px 40px' : '40px 32px 80px', marginTop: 32 }}>
        <div style={{ display:'flex', alignItems:'baseline', gap: 24, marginBottom: 24 }}>
          <span style={{ fontFamily:'JetBrains Mono, monospace', fontSize:11, letterSpacing:'0.16em' }}>05</span>
          <h2 style={{ margin:0, fontFamily:'Anton, sans-serif', fontSize: mobile ? 32 : 48, textTransform:'uppercase', letterSpacing:'-0.01em', lineHeight: 0.95 }}>
            Combina con
          </h2>
        </div>
        <div style={{ display:'grid', gridTemplateColumns: mobile ? '1fr 1fr' : 'repeat(3, 1fr)', gap: mobile ? 12 : 24 }}>
          {related.map(p => (
            <ProductCard key={p.id} product={p} mobile={mobile} onClick={() => { s.go('pdp', { slug: p.slug }); window.scrollTo?.(0,0); }} />
          ))}
        </div>
      </section>
    </main>
  );
}

function Accordion({ title, children, defaultOpen = false }) {
  const [open, setOpen] = useState(defaultOpen);
  return (
    <div style={{ borderBottom: `1px solid ${C.border}` }}>
      <button onClick={() => setOpen(!open)} style={{
        width:'100%', display:'flex', justifyContent:'space-between', alignItems:'center',
        padding:'16px 0', background:'transparent', border:0, cursor:'pointer',
        fontFamily:'JetBrains Mono, monospace', fontSize: 11, letterSpacing:'0.18em', textTransform:'uppercase',
      }}>
        <span>{title}</span>
        <span style={{ fontFamily:'JetBrains Mono, monospace', fontSize: 14 }}>{open ? '−' : '+'}</span>
      </button>
      {open && <div style={{ paddingBottom: 16 }}>{children}</div>}
    </div>
  );
}

Object.assign(window, { PDP });
