// Home page — hero, featured drop, categories, product grid, lookbook, info

const { useState: useStateH, useEffect: useEffectH, useMemo: useMemoH } = React;

// Spinning vinyl hero kept as an opt-in (Tweaks → Hero style: Vinyl)
function HeroVinyl() {
  return (
    <svg className="hero-vinyl" viewBox="0 0 600 600" aria-hidden="true">
      <defs>
        <radialGradient id="rec-grad" cx="50%" cy="50%" r="50%">
          <stop offset="0%" stopColor="#1a1612"/>
          <stop offset="60%" stopColor="#0a0908"/>
          <stop offset="100%" stopColor="#000"/>
        </radialGradient>
        <radialGradient id="rec-glow" cx="50%" cy="50%" r="50%">
          <stop offset="0%" stopColor="#c69464" stopOpacity="0.45"/>
          <stop offset="60%" stopColor="#c69464" stopOpacity="0"/>
        </radialGradient>
      </defs>
      {/* glow */}
      <circle cx="300" cy="300" r="300" fill="url(#rec-glow)"/>
      {/* vinyl */}
      <g style={{transformOrigin:'300px 300px', animation:'spin 22s linear infinite'}}>
        <circle cx="300" cy="300" r="290" fill="url(#rec-grad)"/>
        {Array.from({length: 80}).map((_, i) => (
          <circle key={i} cx="300" cy="300" r={290 - i * 2.6}
                  fill="none" stroke="#1a1612"
                  strokeWidth={i % 8 === 0 ? 0.6 : 0.25}
                  opacity={i % 8 === 0 ? 0.9 : 0.5}/>
        ))}
        {/* label */}
        <circle cx="300" cy="300" r="80" fill="#c69464"/>
        <circle cx="300" cy="300" r="80" fill="url(#rec-glow)"/>
        <text x="300" y="280" textAnchor="middle" fill="#0a0908" fontFamily="Newsreader" fontSize="22" fontStyle="italic" fontWeight="500">Peripheral</text>
        <text x="300" y="304" textAnchor="middle" fill="#0a0908" fontFamily="JetBrains Mono" fontSize="8" letterSpacing="3">VOLUME 02</text>
        <text x="300" y="322" textAnchor="middle" fill="#0a0908" fontFamily="JetBrains Mono" fontSize="7" letterSpacing="2">@PERIPHERALVINYL</text>
        <text x="300" y="336" textAnchor="middle" fill="#0a0908" fontFamily="JetBrains Mono" fontSize="6" letterSpacing="2" opacity="0.7">33 ⅓ RPM</text>
        {/* center hole */}
        <circle cx="300" cy="300" r="4" fill="#0a0908"/>
      </g>
    </svg>
  );
}

// ── Hero: minimal Studio-Iki style (full-bleed image-slot + thin caption row) ─
function Hero({ onShop }) {
  return (
    <section className="hero-v2">
      <div className="hero-image">
        <img src="assets/yt-banner-no-text.png" alt="Peripheral · turntables" className="hero-bg-img"/>
        <div className="hero-overlay-cta">
          <button className="hero-on-img-cta" onClick={onShop}
                  onMouseEnter={()=>onCursor('hover')} onMouseLeave={()=>onCursor('default')}>
            <span>Shop the collection</span>
            <span className="arrow">→</span>
          </button>
        </div>
      </div>
      <div className="hero-meta-row">
        <div className="hero-meta-left">
          <span className="label-mono">Made in Portugal</span>
          <span className="label-mono hidden-sm">· Worldwide shipping</span>
          <span className="label-mono hidden-sm">· Free returns within 30 days</span>
        </div>
      </div>
    </section>
  );
}

function HeroVinylVersion({ onShop }) {
  return (
    <section className="hero">
      <div className="hero-stage" aria-hidden="true"/>
      <HeroVinyl/>
      <div className="hero-runner">
        <span>Side A · 04:32 / 38:14 · Sub-Floor → Long Player → Hypnose</span>
      </div>

      <div className="hero-top">
        <div className="eyebrow-block">
          <div className="eyebrow">Volume 02 — Limited Run</div>
          <div className="eyebrow" style={{color:'var(--accent)'}}>Now Shipping Worldwide</div>
        </div>
        <div className="eyebrow" style={{textAlign:'right'}}>
          Cat. № PVL/02<br/>
          Pressed in Portugal
        </div>
      </div>

      <div className="hero-content">
        <div className="eyebrow">A cinematic capsule for record nights</div>
        <h1 className="h-display">
          <em>Cut</em> for<br/>
          the closing <em>set</em>
        </h1>
        <p style={{ maxWidth: 540, color:'var(--fg-mute)', fontSize:17, lineHeight:1.6 }}>
          Heavyweight cotton, brushed-back fleece, and reinforced canvas —
          finished the way an old record sleeve is finished. Made in Portugal, in limited runs.
        </p>
        <button className="hero-cta" onClick={onShop}
                onMouseEnter={()=>onCursor('hover')} onMouseLeave={()=>onCursor('default')}>
          <span>Shop the Volume</span>
          <span className="arrow">→</span>
        </button>
      </div>
    </section>
  );
}

// ───────────────────────── drop banner ─────────────────────────
function DropBanner({ products, openProduct }) {
  const drop = products.filter(p => p.featured)[0];
  return (
    <section id="drop" className="section" style={{paddingTop: 40}}>
      <div className="section-head">
        <div className="left">
          <div className="eyebrow">The Drop · 03 / 12</div>
          <h2 className="h-1"><em>Volume 02</em> — the capsule</h2>
        </div>
        <div className="right">
          <span className="label-mono">Shipping March 2026</span>
        </div>
      </div>

      <div className="drop-banner">
        <div className="drop-banner-l">
          <div>
            <p style={{color:'var(--fg-mute)', maxWidth: 520, lineHeight:1.7, fontSize:16}}>
              A four-piece capsule that takes its cues from late-night Anjuna sets and
              the kind of record shop you find by accident on a side street in Lisbon.
              Considered cuts, weighty cotton, and one warm accent that ties everything together.
            </p>
          </div>
          <div className="drop-meta">
            <div className="drop-meta-row"><span className="l">Capsule</span><span className="r">04 pieces</span></div>
            <div className="drop-meta-row"><span className="l">Run size</span><span className="r">200 units / piece</span></div>
            <div className="drop-meta-row"><span className="l">Manufacturing</span><span className="r">Porto, Portugal</span></div>
            <div className="drop-meta-row"><span className="l">Designer</span><span className="r">In-house</span></div>
            <div className="drop-meta-row"><span className="l">Catalogue №</span><span className="r">PVL/02</span></div>
          </div>
          <button className="btn-secondary" style={{maxWidth:280, alignSelf:'flex-start'}}
                  onMouseEnter={()=>onCursor('hover')} onMouseLeave={()=>onCursor('default')}>
            View the capsule <Icon.arrow/>
          </button>
        </div>
        <div className="drop-banner-r" onClick={() => openProduct(drop)}
             onMouseEnter={()=>onCursor('hover')} onMouseLeave={()=>onCursor('default')}>
          <div style={{position:'absolute', inset:0, padding:'8% 14%',
                       background:`radial-gradient(60% 50% at 50% 40%, color-mix(in oklab, var(--accent-deep) 35%, transparent), transparent 75%), var(--bg-elev-2)`}}>
            <Garment kind={drop.silhouette} color={drop.colors[0].hex}/>
          </div>
          <div style={{position:'absolute', left:24, bottom:24, right:24,
                       display:'flex', justifyContent:'space-between', alignItems:'flex-end',
                       background:'linear-gradient(to top, color-mix(in oklab, var(--bg) 60%, transparent), transparent)',
                       padding:24, margin:-24}}>
            <div>
              <div className="eyebrow" style={{color:'var(--accent)'}}>Featured · {drop.collection}</div>
              <div className="h-2" style={{fontStyle:'italic', marginTop:8}}>{drop.name}</div>
              <div className="label-mono" style={{marginTop:4}}>{drop.type}</div>
            </div>
            <div className="num" style={{fontSize:14}}>€{drop.price}</div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ───────────────────────── categories ─────────────────────────
function CategoryStrip({ onPick }) {
  const icons = {
    tees: 'tee',
    hoodies: 'hoodie',
    caps: 'cap5',
    totes: 'tote',
  };
  return (
    <section className="section" style={{paddingTop:0, paddingBottom:0}}>
      <div className="cats">
        {CATEGORIES.map((c, i) => (
          <a key={c.id} className="cat" onClick={() => onPick(c.id)}
             onMouseEnter={()=>onCursor('hover')} onMouseLeave={()=>onCursor('default')}>
            <div className="cat-num">0{i+1} / 04</div>
            <div>
              <div className="cat-name">{c.name}</div>
              <div className="cat-count" style={{marginTop: 6}}>{c.count} pieces</div>
            </div>
            <div className="cat-svg">
              <Garment kind={icons[c.id]} color="currentColor" graphic={false}/>
            </div>
          </a>
        ))}
      </div>
    </section>
  );
}

// ───────────────────────── product grid ─────────────────────────
function ProductGrid({ products, openProduct, wish, onWish, filter, setFilter, sort, setSort }) {
  const filtered = useMemoH(() => {
    let arr = filter === 'all' ? products : products.filter(p => p.category === filter);
    if (sort === 'price-asc')  arr = [...arr].sort((a,b) => a.price - b.price);
    if (sort === 'price-desc') arr = [...arr].sort((a,b) => b.price - a.price);
    if (sort === 'alpha')      arr = [...arr].sort((a,b) => a.name.localeCompare(b.name));
    return arr;
  }, [products, filter, sort]);

  return (
    <section id="shop" className="section">
      <div className="section-head">
        <div className="left">
          <div className="eyebrow">The Catalogue · {filtered.length} pieces</div>
          <h2 className="h-1"><em>Shop</em> all</h2>
        </div>
      </div>

      <div className="toolbar">
        <div className="chips">
          <button className={`chip ${filter === 'all' ? 'on':''}`} onClick={() => setFilter('all')}
                  onMouseEnter={()=>onCursor('hover')} onMouseLeave={()=>onCursor('default')}>All</button>
          {CATEGORIES.map(c => (
            <button key={c.id} className={`chip ${filter === c.id ? 'on':''}`} onClick={() => setFilter(c.id)}
                    onMouseEnter={()=>onCursor('hover')} onMouseLeave={()=>onCursor('default')}>
              {c.name}
            </button>
          ))}
        </div>
        <div className="right">
          <span>Sort</span>
          <select className="sort" value={sort} onChange={e => setSort(e.target.value)}>
            <option value="featured">Featured</option>
            <option value="price-asc">Price ↑</option>
            <option value="price-desc">Price ↓</option>
            <option value="alpha">A → Z</option>
          </select>
        </div>
      </div>

      <div className="grid">
        {filtered.map(p => (
          <ProductCard key={p.id} p={p} onOpen={openProduct} wish={wish} onWish={onWish}/>
        ))}
      </div>
    </section>
  );
}

// ───────────────────────── lookbook ─────────────────────────
function LookbookItem({ shape='wide', label, color='#0a0908', kind='tee' }) {
  return (
    <div className={`lk ${shape}`}
         style={{ background: `radial-gradient(65% 55% at 50% 40%, ${color}33, transparent 75%), color-mix(in oklab, ${color} 55%, var(--bg-elev-2) 45%)` }}>
      <div style={{position:'absolute', inset:0, padding:'10% 16%', color:'var(--fg)'}}>
        <Garment kind={kind} color={color}/>
      </div>
      <div className="lk-caption">{label}</div>
    </div>
  );
}

function Lookbook() {
  return (
    <section id="lookbook" className="section" style={{paddingLeft:0, paddingRight:0}}>
      <div style={{padding: '0 var(--pad)'}}>
        <div className="section-head">
          <div className="left">
            <div className="eyebrow">Lookbook — 03 / 12</div>
            <h2 className="h-1"><em>The</em> Closing Set</h2>
          </div>
          <div className="right">
            <span className="label-mono">Photography · Studio 04</span>
          </div>
        </div>
      </div>

      <div className="lookbook">
        <LookbookItem shape="wide" label="01 — Sub-Floor, Black"   color="#1a1612" kind="tee"/>
        <LookbookItem shape="sq"   label="02 — Cartridge, Black"   color="#0a0908" kind="cap5"/>
        <LookbookItem shape="sq"   label="03 — Wax Crate, Natural" color="#a08458" kind="tote"/>
        <LookbookItem shape="tall" label="04 — Closing Set"        color="#c69464" kind="hoodie"/>
        <LookbookItem shape="tall" label="05 — Resident, Cream"    color="#d6cbb4" kind="beanie"/>
        <LookbookItem shape="tall" label="06 — Late Bloom"         color="#7a4a2b" kind="tee"/>
        <LookbookItem shape="tall" label="07 — Long Player"        color="#1a1612" kind="hoodie-zip"/>
      </div>
    </section>
  );
}

// ───────────────────────── size guide + faq accordions ─────────────────────────
function Accordion({ items, defaultOpen = null }) {
  const [open, setOpen] = useStateH(defaultOpen);
  return (
    <div className="acc">
      {items.map((it, i) => (
        <div key={i} className={`acc-item ${open === i ? 'open':''}`}>
          <button className="acc-head" onClick={() => setOpen(open === i ? null : i)}
                  onMouseEnter={()=>onCursor('hover')} onMouseLeave={()=>onCursor('default')}>
            <span className="h-2">{it.q}</span>
            <span className="plus">+</span>
          </button>
          <div className="acc-body">
            <div>
              <div className="acc-body-inner">{it.a}</div>
            </div>
          </div>
        </div>
      ))}
    </div>
  );
}

function SizeGuideSection() {
  const [tab, setTab] = useStateH('tees');
  const data = SIZES[tab];
  return (
    <section id="sizing" className="section">
      <div className="section-head">
        <div className="left">
          <div className="eyebrow">Sizing · in centimetres</div>
          <h2 className="h-1"><em>Size</em> guide</h2>
        </div>
        <div className="right" style={{display:'flex', gap:8}}>
          <button className={`chip ${tab==='tees' ? 'on':''}`} onClick={()=>setTab('tees')}>Tees & LS</button>
          <button className={`chip ${tab==='hoodies' ? 'on':''}`} onClick={()=>setTab('hoodies')}>Hoodies</button>
        </div>
      </div>
      <div style={{display:'grid', gridTemplateColumns:'1fr 1.4fr', gap:48, alignItems:'flex-start'}}>
        <div style={{color:'var(--fg-mute)', lineHeight:1.7, maxWidth:420}}>
          <p style={{marginBottom:14}}>
            Measurements are taken garment-flat. For a true-to-size fit, pick the row closest to your chest
            measurement. For a relaxed oversized look — the way these were cut — size up one.
          </p>
          <p>
            Models are between 5'10"–6'2" and wearing size M / L. If you sit between two sizes,
            we usually recommend the larger.
          </p>
        </div>
        <table className="size-table">
          <thead>
            <tr><th>Size</th><th>Chest (cm)</th><th>Length (cm)</th><th>Sleeve (cm)</th></tr>
          </thead>
          <tbody>
            {data.map(r => (
              <tr key={r.size}>
                <td>{r.size}</td>
                <td>{r.chest}</td>
                <td>{r.length}</td>
                <td>{r.sleeve}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </section>
  );
}

function FAQSection() {
  return (
    <section id="faq" className="section">
      <div className="section-head">
        <div className="left">
          <div className="eyebrow">Information</div>
          <h2 className="h-1"><em>Frequently</em> asked</h2>
        </div>
        <div className="right">
          <a className="section-link">Email us <Icon.arrow/></a>
        </div>
      </div>
      <Accordion items={FAQS.map(f => ({ q: f.q, a: <p>{f.a}</p> }))} defaultOpen={0}/>
    </section>
  );
}

// ───────────────────────── product row (best sellers / new in) ─────────────────────────
function ProductRow({ id, eyebrow, title, products = [], link, onLink, openProduct, wish, onWish }) {
  return (
    <section id={id} className="section">
      <div className="section-head">
        <div className="left">
          <div className="eyebrow">{eyebrow}</div>
          <h2 className="h-1">{title}</h2>
        </div>
        {link && (
          <div className="right">
            <a className="section-link" onClick={onLink}
               onMouseEnter={()=>onCursor('hover')} onMouseLeave={()=>onCursor('default')}>
              {link} <Icon.arrow/>
            </a>
          </div>
        )}
      </div>
      <div className="row-strip">
        {products.map(p => (
          <ProductCard key={p.id} p={p} onOpen={openProduct} wish={wish} onWish={onWish}/>
        ))}
      </div>
    </section>
  );
}

// ───────────────────────── about / press strip ─────────────────────────
function AboutSection() {
  return (
    <section id="about" className="section about">
      <div className="about-grid">
        <div className="about-image">
          <img src="assets/banner-no-text.png" alt="" className="about-bg-img"/>
        </div>
        <div className="about-copy">
          <div className="eyebrow">The label</div>
          <h2 className="h-2">
            Peripheral is a label for the people who still <em>buy records</em>.
          </h2>
          <p>
            Each Volume is a limited run — designed in-house, printed and finished to order.
            Heavyweight cottons, brushed-back fleece, garment-dyed colour, made to wear in.
          </p>
          <p>
            A meaningful share of every order funds the channel — studio time, mastering,
            and the records we play. When you wear it, you're keeping the platter spinning.
          </p>
          <div className="about-press">
            <div className="label-mono" style={{ color: 'var(--fg-dim)' }}>Tune in</div>
            <div className="press-row">
              <a href="https://www.youtube.com/@peripheralvinyl" target="_blank" rel="noreferrer"><span>YouTube</span></a>
              <a><span>Instagram</span></a>
              <a><span>SoundCloud</span></a>
              <a><span>Spotify</span></a>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ────────────────────── collections strip ─────────────────────────
function CollectionsSection({ openCollection }) {
  const silhouettes = { tees: 'tee', knits: 'hoodie', cropped: 'tee-crop', bags: 'tote' };
  return (
    <section id="collections" className="section">
      <div className="section-head">
        <div className="left">
          <div className="eyebrow">Collections · {COLLECTIONS.length}</div>
          <h2 className="h-1"><em>Browse</em> by collection</h2>
        </div>
      </div>
      <div className="collections">
        {COLLECTIONS.map((c, i) => (
          <a key={c.id} className="collection-card" onClick={() => openCollection(c.id)}
             onMouseEnter={()=>onCursor('hover')} onMouseLeave={()=>onCursor('default')}>
            <div className="collection-image">
              <div className="collection-silhouette" aria-hidden="true">
                <Garment kind={silhouettes[c.cat]} color="currentColor" graphic={false}/>
              </div>
            </div>
            <div className="collection-meta">
              <div className="collection-num">0{i+1} / 0{COLLECTIONS.length}</div>
              <div className="collection-name">{c.name}</div>
              <div className="collection-sub">{c.sub}</div>
              <div className="collection-link">View collection →</div>
            </div>
          </a>
        ))}
      </div>
    </section>
  );
}

// ────────────────────── collection page (sub-route) ──────────────────────
function CollectionPage({ id, products = [], openProduct, wish, onWish, onBack, openCollection }) {
  const [sort, setSort] = useStateH('featured');
  const collection = COLLECTIONS.find(c => c.id === id) || COLLECTIONS[0];
  let filtered = products.filter(p => p.category === collection.cat);
  if (sort === 'price-asc')  filtered = [...filtered].sort((a,b)=>a.price-b.price);
  if (sort === 'price-desc') filtered = [...filtered].sort((a,b)=>b.price-a.price);
  if (sort === 'alpha')      filtered = [...filtered].sort((a,b)=>a.name.localeCompare(b.name));
  const products_compat = filtered; // rename for JSX below
  return (
    <main className="fade-in" style={{paddingTop:80}}>
      <section className="section collection-hero">
        <div className="pdp-crumb">
          <a onClick={onBack}
             onMouseEnter={()=>onCursor('hover')} onMouseLeave={()=>onCursor('default')}>Shop</a>
          <span className="sep">/</span>
          <span>Collections</span>
          <span className="sep">/</span>
          <span>{collection.name}</span>
        </div>
        <div className="collection-head">
          <div>
            <div className="eyebrow">{collection.sub}</div>
            <h1 className="h-1" style={{marginTop:8}}><em>{collection.name}</em></h1>
          </div>
          <div className="label-mono">{products_compat.length} pieces · 5 colourways</div>
        </div>
      </section>

      <section className="section" style={{paddingTop:0}}>
        <div className="toolbar">
          <div className="chips">
            {COLLECTIONS.map(c => (
              <button key={c.id}
                      className={`chip ${c.id === id ? 'on':''}`}
                      onClick={() => openCollection(c.id)}
                      onMouseEnter={()=>onCursor('hover')} onMouseLeave={()=>onCursor('default')}>
                {c.name}
              </button>
            ))}
          </div>
          <div className="right">
            <span>Sort</span>
            <select className="sort" value={sort} onChange={e=>setSort(e.target.value)}>
              <option value="featured">Featured</option>
              <option value="price-asc">Price ↑</option>
              <option value="price-desc">Price ↓</option>
              <option value="alpha">A → Z</option>
            </select>
          </div>
        </div>
        <div className="grid">
          {products_compat.map(p => (
            <ProductCard key={p.id} p={p} onOpen={openProduct} wish={wish} onWish={onWish}/>
          ))}
        </div>
      </section>
    </main>
  );
}

// ────────────────────── second hero (bottom of page) ──────────────────────
function BottomHero() {
  return (
    <section className="bottom-hero">
      <img src="assets/profile-cover.png" alt="" className="bottom-hero-img"/>
      <div className="bottom-hero-text">
        <div className="eyebrow" style={{ color: 'rgba(235,227,206,0.7)' }}>The Channel</div>
        <h2 className="h-1" style={{ color: '#ebe3ce' }}>
          Hours of <em>melodic house</em><br/>on vinyl.
        </h2>
        <a className="hero-on-img-cta" href="https://www.youtube.com/@peripheralvinyl" target="_blank" rel="noreferrer"
           onMouseEnter={()=>onCursor('hover')} onMouseLeave={()=>onCursor('default')}
           style={{marginTop: 12}}>
          <span>Tune in on YouTube</span>
          <span className="arrow">→</span>
        </a>
      </div>
    </section>
  );
}

// ───────────────────────── home root ─────────────────────────
function HomePage({ products = [], loading, openProduct, wish, onWish, openCollection, onShop }) {
  const bestSellers = products.filter(p => p.featured).slice(0, 4);
  return (
    <main>
      <Hero onShop={onShop}/>
      <ProductRow id="best" eyebrow="Best sellers · Volume 02" title={<><em>Most</em> ordered this drop</>}
                  products={bestSellers} openProduct={openProduct} wish={wish} onWish={onWish}
                  link="Shop all" onLink={() => openCollection('tees')}/>
      <CollectionsSection openCollection={openCollection}/>
      <AboutSection/>
      <BottomHero/>
    </main>
  );
}

Object.assign(window, { HomePage, Hero, ProductRow, CollectionsSection, CollectionPage, AboutSection, BottomHero, ProductGrid, Accordion, SizeGuideSection, FAQSection });
