// Product detail page

const { useState: useStateP, useEffect: useEffectP } = React;

function Stars({ n = 5 }) {
  return (
    <span className="stars">
      {Array.from({ length: 5 }).map((_, i) =>
        <Icon.star key={i} style={{ opacity: i < n ? 1 : 0.2 }}/>
      )}
    </span>
  );
}

function PdpRow({ k, children, open, onToggle }) {
  return (
    <div style={{ borderBottom: '1px solid var(--line)' }}>
      <button onClick={onToggle}
              onMouseEnter={() => onCursor('hover')} onMouseLeave={() => onCursor('default')}
              style={{ width:'100%', padding:'18px 0', display:'flex', justifyContent:'space-between', alignItems:'center', textAlign:'left' }}>
        <span className="label-mono" style={{ color:'var(--fg)', fontSize:12 }}>{k}</span>
        <span className="num" style={{ color:'var(--fg-mute)', transform: open ? 'rotate(45deg)':'none', transition:'transform 300ms' }}>+</span>
      </button>
      <div style={{ display:'grid', gridTemplateRows: open ? '1fr':'0fr', transition:'grid-template-rows 400ms cubic-bezier(.2,.6,.2,1)' }}>
        <div style={{ overflow:'hidden', minHeight:0 }}>
          <div style={{ paddingBottom:18, color:'var(--fg-mute)', fontSize:14, lineHeight:1.6, maxWidth:540 }}>
            {children}
          </div>
        </div>
      </div>
    </div>
  );
}

function PDP({ product, products, onClose, onAdd, wish, onWish, recentlyViewed, openProduct }) {
  // Variant type: printed or embroidered
  const initType = product.printed?.length > 0 ? 'printed' : 'embroidered';
  const [variantType, setVariantType] = useStateP(initType);
  const [cwIdx,       setCwIdx]       = useStateP(0);
  const [imgIdx,      setImgIdx]      = useStateP(0);
  const [openSection, setOpenSection] = useStateP('description');

  const colorways    = product[variantType] || [];
  const cw           = colorways[cwIdx] || colorways[0];
  const shirtColors  = cw?.shirtColors || [];
  const [shirtColor, setShirtColor] = useStateP(shirtColors[0]);

  // When colorway changes, preserve thread selection if new colorway has the same option
  useEffectP(() => {
    const newColors = cw?.shirtColors || [];
    const preserved = newColors.find(sc => sc.name === shirtColor?.name);
    setShirtColor(preserved || newColors[0] || null);
    setImgIdx(0);
  }, [cwIdx, variantType]); // intentional stale read of shirtColor

  // Reset image index when shirt color changes
  useEffectP(() => { setImgIdx(0); }, [shirtColor?.name]);

  // Reset colorway index when switching variant type
  const switchVariantType = (type) => {
    setVariantType(type);
    setCwIdx(0);
    setImgIdx(0);
  };

  const size0 = cw?.sizes?.[0] || '';
  const [size, setSize] = useStateP(size0);
  // Preserve size selection if new colorway still has it, otherwise reset
  useEffectP(() => {
    const newSizes = cw?.sizes || [];
    if (!newSizes.includes(size)) setSize(newSizes[0] || '');
  }, [cwIdx, variantType]); // intentional stale read of size

  // Size table for size guide accordion
  const sizeTableKey = product.category === 'knits' ? 'hoodies' : (product.category === 'bags' ? null : 'tees');
  const sizeTable    = sizeTableKey ? (SIZES?.[sizeTableKey] || null) : null;

  const isWished = wish.has(product.id);
  const reviews  = REVIEWS[product.id] || REVIEWS._default;
  const avgScore = (reviews.reduce((a, r) => a + r.rating, 0) / reviews.length).toFixed(1);

  const related = (products || []).filter(p => p.category === product.category && p.id !== product.id).slice(0, 4);
  const recent  = recentlyViewed
    .filter(id => id !== product.id)
    .map(id => (products || []).find(p => p.id === id))
    .filter(Boolean).slice(0, 4);

  // Gallery — use per-shirt-color images when available, else colorway images
  const images  = (shirtColor?.images?.length ? shirtColor.images : cw?.images) || [];
  const mainImg = images[imgIdx] || null;
  const total   = images.length;
  const bgColor = cw?.hex || '#e8dfc8';

  const prevImg = () => setImgIdx(i => (i - 1 + total) % total);
  const nextImg = () => setImgIdx(i => (i + 1) % total);

  const handleBuy = () => {
    if (!cw) return;
    const variantId = shirtColor?.variants?.[size];
    const url = variantId
      ? `https://peripheralvinyl-shop.fourthwall.com/cart/checkout?products=${variantId}:1`
      : cw.url;
    onAdd(product, cw, shirtColor, size);
    window.location.href = url; // same-tab navigation — browser back returns to this page
  };

  return (
    <main className="fade-in" style={{ paddingTop: 80 }}>
      <div className="pdp">

        {/* ── gallery ── */}
        <div className="pdp-gallery">
          <div className="pdp-main"
               style={{ background: `radial-gradient(70% 55% at 50% 38%, color-mix(in oklab, ${bgColor} 22%, #1a1612), #0a0908)`, color:'#ebe3ce' }}>
            {mainImg ? (
              <img src={mainImg} alt={product.name}
                   style={{ position:'absolute', inset:0, width:'100%', height:'100%', objectFit:'contain', padding:'8% 10%' }}/>
            ) : (
              <div style={{ position:'absolute', inset:0, padding:'14% 22%' }}>
                <Garment kind={product.silhouette} color={bgColor}/>
              </div>
            )}
            <div style={{ position:'absolute', top:20, left:20, color:'rgba(235,227,206,0.7)' }} className="eyebrow">
              {product.category}
            </div>
            {total > 1 && (
              <div style={{ position:'absolute', top:20, right:20, color:'rgba(235,227,206,0.7)' }} className="eyebrow">
                {String(imgIdx + 1).padStart(2,'0')} / {String(total).padStart(2,'0')}
              </div>
            )}
            {total > 1 && (
              <>
                <button className="gallery-arrow gallery-prev" onClick={prevImg}
                        onMouseEnter={() => onCursor('hover')} onMouseLeave={() => onCursor('default')}>‹</button>
                <button className="gallery-arrow gallery-next" onClick={nextImg}
                        onMouseEnter={() => onCursor('hover')} onMouseLeave={() => onCursor('default')}>›</button>
              </>
            )}
          </div>
        </div>

        {/* ── info panel ── */}
        <div className="pdp-info">
          <div className="pdp-crumb">
            <a onClick={onClose} onMouseEnter={() => onCursor('hover')} onMouseLeave={() => onCursor('default')}>Shop</a>
            <span className="sep">/</span>
            <a>{CATEGORIES.find(c => c.id === product.category)?.name}</a>
            <span className="sep">/</span>
            <span>{product.name}</span>
          </div>

          <div className="pdp-title">
            <h1 className="h-1" style={{ fontStyle:'italic' }}>{product.name}</h1>
            <div className="label-mono">{variantType === 'embroidered' ? 'Embroidered' : 'Back print'}</div>
          </div>

          <div className="pdp-price">
            <span className="num">€{cw?.price || product.price}.00</span>
            <span className="ship">Tax incl. · Ships in 2–3 days</span>
          </div>

          <p className="pdp-desc">{product.description}</p>

          {/* ── Printed / Embroidered tiles ── */}
          {product.hasEmbroidered && product.printed?.length > 0 && (
            <div className="pdp-section">
              <div className="h"><h5>Style</h5></div>
              <div style={{ display:'flex', gap:8 }}>
                {[['printed','Back print'],['embroidered','Embroidered']].map(([type, label]) => (
                  <button key={type}
                          onClick={() => switchVariantType(type)}
                          onMouseEnter={() => onCursor('hover')} onMouseLeave={() => onCursor('default')}
                          style={{
                            flex:1, padding:'12px 8px', border:'1px solid',
                            borderColor: variantType === type ? 'var(--fg)' : 'var(--line)',
                            background: variantType === type ? 'var(--fg)' : 'transparent',
                            color: variantType === type ? 'var(--bg)' : 'var(--fg)',
                            fontFamily:'var(--mono)', fontSize:11, letterSpacing:'0.1em',
                            textTransform:'uppercase', cursor:'none', transition:'all 200ms',
                          }}>
                    {label}
                  </button>
                ))}
              </div>
            </div>
          )}

          {/* ── Colorway swatches ── */}
          <div className="pdp-section">
            <div className="h">
              <h5>Colour — {cw?.name}</h5>
            </div>
            <div className="opts">
              {colorways.map((c, i) => (
                <button key={c.name}
                        className={`opt-color ${cwIdx === i ? 'on' : ''}`}
                        style={{ background: c.hex }}
                        onClick={() => setCwIdx(i)}
                        aria-label={c.name}
                        onMouseEnter={() => onCursor('hover')} onMouseLeave={() => onCursor('default')}/>
              ))}
            </div>
          </div>

          {/* ── Shirt colour (Black / White thread) ── */}
          {shirtColors.length > 0 && (
            <div className="pdp-section">
              <div className="h">
                <h5>Thread — {shirtColor?.name}</h5>
              </div>
              <div className="opts">
                {shirtColors.map(sc => (
                  <button key={sc.name}
                          className={`opt ${shirtColor?.name === sc.name ? 'on' : ''}`}
                          onClick={() => setShirtColor(sc)}
                          onMouseEnter={() => onCursor('hover')} onMouseLeave={() => onCursor('default')}
                          style={{ fontFamily:'var(--mono)', fontSize:11 }}>
                    {sc.name}
                  </button>
                ))}
              </div>
            </div>
          )}

          {/* ── Size ── */}
          <div className="pdp-section">
            <div className="h">
              <h5>Size — {size}</h5>
              {sizeTable && (
                <a onClick={() => { setOpenSection('sizing'); setTimeout(() => scrollToId('pdp-sizing'), 50); }}
                   onMouseEnter={() => onCursor('hover')} onMouseLeave={() => onCursor('default')}>Size guide ↓</a>
              )}
            </div>
            <div className="opts">
              {(cw?.sizes || product.sizes || []).map(s => (
                <button key={s} className={`opt ${size === s ? 'on' : ''}`}
                        onClick={() => setSize(s)}
                        onMouseEnter={() => onCursor('hover')} onMouseLeave={() => onCursor('default')}>
                  {s}
                </button>
              ))}
            </div>
          </div>

          {/* ── Buy CTA ── */}
          <div className="pdp-actions">
            <div className="pdp-pair">
              <button className="btn-primary" onClick={handleBuy}
                      onMouseEnter={() => onCursor('hover')} onMouseLeave={() => onCursor('default')}>
                <span>Buy on Fourthwall</span>
                <span className="num">— €{cw?.price || product.price}.00</span>
              </button>
              <button className={`pdp-wish ${isWished ? 'on' : ''}`} onClick={() => onWish(product.id)}
                      onMouseEnter={() => onCursor('hover')} onMouseLeave={() => onCursor('default')}>
                {isWished ? <Icon.heartFill/> : <Icon.heart/>}
              </button>
            </div>
            <div className="label-mono" style={{ textAlign:'center', color:'var(--fg-dim)', paddingTop:4 }}>
              Opens in a new tab — secure checkout &amp; shipping handled by Fourthwall
            </div>
          </div>

          {/* ── Accordion ── */}
          <div className="pdp-meta-list" style={{ marginTop:8 }}>
            <PdpRow open={openSection === 'materials'} onToggle={() => setOpenSection(openSection === 'materials' ? null : 'materials')} k="Materials & Construction">
              <p>{product.materials}</p>
              <p style={{ marginTop:8 }}>{product.fit}</p>
            </PdpRow>
            <PdpRow open={openSection === 'care'} onToggle={() => setOpenSection(openSection === 'care' ? null : 'care')} k="Care">
              <p>{product.care}</p>
            </PdpRow>
            <PdpRow open={openSection === 'origin'} onToggle={() => setOpenSection(openSection === 'origin' ? null : 'origin')} k="Origin">
              <p>{product.origin}</p>
            </PdpRow>
            <PdpRow open={openSection === 'ship'} onToggle={() => setOpenSection(openSection === 'ship' ? null : 'ship')} k="Shipping & Returns">
              <p>Ships within 2–3 business days. Delivery 3–7 days in EU / UK / US, 7–14 days elsewhere. Free returns within 30 days on unworn items.</p>
            </PdpRow>
            {sizeTable && (
              <div id="pdp-sizing">
                <PdpRow open={openSection === 'sizing'} onToggle={() => setOpenSection(openSection === 'sizing' ? null : 'sizing')} k="Size Guide — cm (measured flat)">
                  <table style={{ width:'100%', borderCollapse:'collapse' }}>
                    <thead>
                      <tr style={{ fontFamily:'var(--mono)', fontSize:10, letterSpacing:'0.12em', textTransform:'uppercase', color:'var(--fg-mute)' }}>
                        <th style={{ textAlign:'left',  paddingBottom:10, fontWeight:400 }}>Size</th>
                        <th style={{ textAlign:'right', paddingBottom:10, fontWeight:400 }}>Chest</th>
                        <th style={{ textAlign:'right', paddingBottom:10, fontWeight:400 }}>Length</th>
                        <th style={{ textAlign:'right', paddingBottom:10, fontWeight:400 }}>Sleeve</th>
                      </tr>
                    </thead>
                    <tbody>
                      {sizeTable.map(row => (
                        <tr key={row.size} style={{ borderTop:'1px solid var(--line)' }}>
                          <td style={{ padding:'7px 0', fontFamily:'var(--mono)', fontSize:12 }}>{row.size}</td>
                          <td style={{ padding:'7px 0', fontFamily:'var(--mono)', fontSize:12, textAlign:'right' }}>{row.chest}</td>
                          <td style={{ padding:'7px 0', fontFamily:'var(--mono)', fontSize:12, textAlign:'right' }}>{row.length}</td>
                          <td style={{ padding:'7px 0', fontFamily:'var(--mono)', fontSize:12, textAlign:'right' }}>{row.sleeve}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </PdpRow>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* ── Reviews ── */}
      <section className="section">
        <div className="section-head">
          <div className="left">
            <div className="eyebrow">Verified — {reviews.length} reviews</div>
            <h2 className="h-2"><em>What</em> people are saying</h2>
          </div>
        </div>
        <div className="reviews">
          <div className="review-summary">
            <div className="score">{avgScore}</div>
            <div>
              <Stars n={Math.round(avgScore)}/>
              <div className="label-mono" style={{ marginTop:4 }}>Based on {reviews.length} verified buyers</div>
            </div>
          </div>
          {reviews.map((r, i) => (
            <div key={i} className="review">
              <div className="review-head">
                <span className="who">{r.who}</span>
                <span className="when">{r.when} · <Stars n={r.rating}/></span>
              </div>
              <div className="body">{r.body}</div>
            </div>
          ))}
        </div>
      </section>

      {/* ── Related ── */}
      {related.length > 0 && (
        <section className="section">
          <div className="section-head">
            <div className="left">
              <div className="eyebrow">More from this category</div>
              <h2 className="h-2"><em>You</em> might also like</h2>
            </div>
          </div>
          <div className="strip">
            {related.map(p => (
              <ProductCard key={p.id} p={p} onOpen={openProduct} wish={wish} onWish={onWish}/>
            ))}
          </div>
        </section>
      )}

      {/* ── Recently viewed ── */}
      {recent.length > 0 && (
        <section className="section">
          <div className="section-head">
            <div className="left">
              <div className="eyebrow">Recently viewed</div>
              <h2 className="h-2"><em>Pick up</em> where you left off</h2>
            </div>
          </div>
          <div className="strip">
            {recent.map(p => (
              <ProductCard key={p.id} p={p} onOpen={openProduct} wish={wish} onWish={onWish}/>
            ))}
          </div>
        </section>
      )}
    </main>
  );
}

Object.assign(window, { PDP });
