/* CỘI — Shop, Product, Subscriptions, Gift pages */

const { useState: useShopState } = React;
const { Page: ShopPage_, PageHero: ShopHero_ } = window.SonPage;

// ============================== SHOP COLLECTION
function ShopCollectionPage() {
  const retail = window.SON_DATA.RETAIL_PRODUCTS;
  const [filter, setFilter] = useShopState('all');
  const filters = [
    { id: 'all', label: 'All' },
    { id: 'flagship', label: 'Reserve' },
    { id: 'limited', label: 'Grand Reserve' },
    { id: 'no.', label: 'Founder' },
    { id: 'serialized', label: 'Heritage' },
    { id: 'worldwide', label: 'Vault' },
    { id: 'gifted', label: 'Gift' }
  ];
  const filtered = filter === 'all' ? retail : retail.filter(p => p.badge.toLowerCase().includes(filter));

  return (
    <ShopPage_ navDefaultDark={true}>
      <ShopHero_
        num="01"
        eyebrow="THE COLLECTION"
        title={<>Six farms, one <em>collection.</em></>}
        sub="Single-origin pouches, heritage tins, gift boxes and tasting sets — every item linked to its own BLT batch and FloraChain anchor."
      >
        <div className="crumbs"><a href="index.html">Home</a><span className="sep">/</span><span>Shop</span></div>
        <div className="mono" style={{ fontSize: 11, opacity: 0.6, letterSpacing: '0.1em' }}>
          {retail.length} products · 6 farms · Q1 2025 harvest
        </div>
      </ShopHero_>

      <section className="section paper" id="single-origin" data-screen-label="Shop · All">
        <div className="container">
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', borderBottom: '1px solid var(--line)', paddingBottom: 24, marginBottom: 32 }}>
            <div>
              <div className="eyebrow gold">/ FILTER</div>
              <div style={{ display: 'flex', gap: 24, marginTop: 12 }}>
                {filters.map(f => (
                  <button
                    key={f.id}
                    onClick={() => setFilter(f.id)}
                    style={{
                      fontSize: 14,
                      fontFamily: 'var(--serif)',
                      fontStyle: filter === f.id ? 'italic' : 'normal',
                      color: filter === f.id ? 'var(--gold)' : 'inherit',
                      opacity: filter === f.id ? 1 : 0.6,
                      borderBottom: filter === f.id ? '1px solid var(--gold)' : 'none',
                      paddingBottom: 2
                    }}
                  >{f.label}</button>
                ))}
              </div>
            </div>
            <div className="mono" style={{ fontSize: 11, opacity: 0.55 }}>
              SORT BY · NEWEST
            </div>
          </div>

          <div>
            {filtered.map((p, i) => (
              <a className="collection-row" key={i} href={`product.html?id=${p.id}`}>
                <div className="thumb" style={{ backgroundImage: `url(${p.img})`, backgroundSize: 'contain', backgroundColor: '#0d0a07', backgroundRepeat: 'no-repeat' }} />
                <div>
                  <div className="name">{p.name}</div>
                  <div className="sub">{p.sub}</div>
                </div>
                <div className="meta">{p.region}</div>
                <div className="meta">{p.badge} · BLT-tagged</div>
                <div className="price">{p.price}</div>
              </a>
            ))}
          </div>
        </div>
      </section>

      <section className="section dark" id="reserves" data-screen-label="Shop · Reserve">
        <div className="container">
          <div className="section-head reveal">
            <div>
              <div className="head-num">02 — RESERVE COLLECTION</div>
              <h2>The <em style={{ fontStyle: 'italic', color: 'var(--gold-2)' }}>numbered</em> pouches.</h2>
            </div>
            <div className="head-meta">
              <p>The Reserve Collection is our highest-altitude microlot, harvest-numbered, hand-finished, limited to 850 pouches per harvest window.</p>
            </div>
          </div>
          <div className="products-grid reveal" style={{ gridTemplateColumns: 'repeat(3, 1fr)' }}>
            {retail.slice(0, 3).map((p, i) => (
              <a className="product-card" href={`product.html?id=${p.id}`} key={i}>
                <div className="product-img" style={{ backgroundImage: `url(${p.img})`, backgroundSize: 'contain', backgroundColor: '#0d0a07', backgroundRepeat: 'no-repeat' }}>
                  <div className="product-badge">{p.badge}</div>
                </div>
                <div className="product-meta">/ {String(i + 1).padStart(2, '0')} · {p.region}</div>
                <div className="product-name">{p.name}</div>
                <div className="product-price">
                  <span className="price">{p.price}</span>
                  <span className="weight">{p.weight}</span>
                </div>
              </a>
            ))}
          </div>
        </div>
      </section>

      <SubscriptionsSection />
      <TastingSection />
      <GiftSection />
    </ShopPage_>
  );
}

function SubscriptionsSection() {
  const plans = [
    { freq: 'MONTHLY', name: 'Origin Letter', price: '$124', per: '/ month', desc: 'One 250g Reserve pouch from a new estate each month. Curated card insert with farmer biography and harvest notes.', featured: false },
    { freq: 'QUARTERLY', name: 'Harvest Pair', price: '$268', per: '/ quarter', desc: 'Two 250g pouches, paired by altitude — one Reserve, one Heritage. Selected to mirror the harvest window.', featured: true },
    { freq: 'ANNUAL', name: 'The Atlas', price: '$1,440', per: '/ year', desc: 'A 250g pouch every month for twelve months, plus the year-end Atlas — a leather portfolio of every farmer signature.', featured: false }
  ];
  return (
    <section className="section paper" id="subscriptions" data-screen-label="Shop · Subscriptions">
      <div className="container">
        <div className="section-head reveal">
          <div>
            <div className="head-num">03 — SUBSCRIPTIONS</div>
            <h2>The <em style={{ fontStyle: 'italic', color: 'var(--gold)' }}>continuing</em> bag.</h2>
          </div>
          <div className="head-meta">
            <p>Three plans, each anchored to the harvest cycle. Pause, gift, or change altitude at any time.</p>
          </div>
        </div>
        <div className="sub-grid reveal">
          {plans.map(p => (
            <div key={p.name} className={`sub-card ${p.featured ? 'featured' : ''}`}>
              <div className="freq">{p.freq}</div>
              <div className="title">{p.name}</div>
              <div className="desc">{p.desc}</div>
              <div className="sub-price">{p.price} <span className="per">{p.per}</span></div>
              <button className={`btn ${p.featured ? 'gold' : 'solid'}`}>Subscribe <span className="arrow">→</span></button>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function TastingSection() {
  return (
    <section className="section dark" id="tasting" data-screen-label="Shop · Tasting">
      <div className="container">
        <div className="section-head reveal">
          <div>
            <div className="head-num">04 — TASTING SETS</div>
            <h2>Four farms, <em style={{ fontStyle: 'italic', color: 'var(--gold-2)' }}>one flight.</em></h2>
          </div>
          <div className="head-meta">
            <p>Four 60g vacuum-sealed pouches in a numbered keepsake box. Each pouch carries its own BLT tag and tasting card.</p>
          </div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: 64, alignItems: 'center' }} className="reveal">
          <div style={{ aspectRatio: '4/3', background: '#000', backgroundImage: 'url(assets/coi-giftbox.png)', backgroundSize: 'contain', backgroundRepeat: 'no-repeat', backgroundPosition: 'center', border: '1px solid var(--line-d)' }} />
          <div>
            <div className="eyebrow gold">/ TASTING FLIGHT — 4 × 60G</div>
            <h3 style={{ fontFamily: 'var(--serif)', fontWeight: 300, fontSize: 48, margin: '16px 0 24px', lineHeight: 1 }}>
              The <em style={{ fontStyle: 'italic', color: 'var(--gold-2)' }}>Atlas</em> Flight
            </h3>
            <p style={{ fontSize: 14, opacity: 0.78, lineHeight: 1.6, maxWidth: 460 }}>
              Suối Nhiêu · Hoà Khê · Sông Lâm · Đà Đèo. Four altitudes, four processes, four cups. Hand-numbered to 1,200.
            </p>
            <div style={{ marginTop: 32, fontFamily: 'var(--mono)', fontSize: 22 }}>$148</div>
            <div style={{ marginTop: 24, display: 'flex', gap: 12 }}>
              <button className="btn gold">Add to cart <span className="arrow">→</span></button>
              <a className="btn" href="verify.html" style={{ color: 'var(--paper)', borderColor: 'var(--paper)' }}>Sample batches</a>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function GiftSection() {
  return (
    <section className="section paper" id="gift" data-screen-label="Shop · Gift">
      <div className="container">
        <div className="section-head reveal">
          <div>
            <div className="head-num">05 — GIFT</div>
            <h2>The <em style={{ fontStyle: 'italic', color: 'var(--gold)' }}>boxed</em> story.</h2>
          </div>
          <div className="head-meta">
            <p>Hand-finished gift boxes for events, corporate, and personal gifting. Letterpress card included. Custom monogramming available on annual orders.</p>
          </div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 64 }} className="reveal">
          <div>
            <div style={{ aspectRatio: '4/3', background: '#000', backgroundImage: 'url(assets/coi-giftbox.png)', backgroundSize: 'contain', backgroundRepeat: 'no-repeat', backgroundPosition: 'center', marginBottom: 16 }} />
            <div className="eyebrow gold">/ THE RESERVE GIFT</div>
            <h3 style={{ fontFamily: 'var(--serif)', fontSize: 32, fontWeight: 300, margin: '12px 0' }}>Reserve Pouch + Passport Card</h3>
            <p style={{ fontSize: 13, opacity: 0.75, lineHeight: 1.55 }}>
              One 250g Reserve pouch, letterpress card from The Cội Team, and a personalized digital passport hangtag. $226.
            </p>
            <button className="btn solid" style={{ marginTop: 16 }}>Add to cart <span className="arrow">→</span></button>
          </div>
          <div>
            <div style={{ aspectRatio: '4/3', background: '#000', backgroundImage: 'url(assets/product-bag.png)', backgroundSize: 'contain', backgroundRepeat: 'no-repeat', backgroundPosition: 'center', marginBottom: 16 }} />
            <div className="eyebrow gold">/ CORPORATE</div>
            <h3 style={{ fontFamily: 'var(--serif)', fontSize: 32, fontWeight: 300, margin: '12px 0' }}>Carry Bag · Bulk Order</h3>
            <p style={{ fontSize: 13, opacity: 0.75, lineHeight: 1.55 }}>
              Day-bag retail packs in custom counts from 24 to 240. Monogramming and dedication card available. From $112 / bag.
            </p>
            <a className="btn" href="wholesale.html#cafe" style={{ marginTop: 16, display: 'inline-flex' }}>Bulk inquiry <span className="arrow">→</span></a>
          </div>
        </div>
      </div>
    </section>
  );
}

// ============================== PRODUCT DETAIL (dynamic)
function ProductDetailPage() {
  const id = new URLSearchParams(location.search).get('id') || 'reserve';
  const product = window.SON_DATA.RETAIL_PRODUCTS.find(p => p.id === id) || window.SON_DATA.RETAIL_PRODUCTS[0];

  const [thumb, setThumb] = useShopState(0);
  const [qty, setQty] = useShopState(1);
  const [added, setAdded] = useShopState(false);

  // Gallery: primary image + the other 3 family bags as auxiliary thumbnails
  const all = window.SON_DATA.RETAIL_PRODUCTS;
  const others = all.filter(p => p.id !== product.id).slice(0, 3);
  const gallery = [product.img, ...others.map(o => o.img)];

  const onAdd = () => {
    window.CoiCart.add(product, qty);
    setAdded(true);
    setTimeout(() => setAdded(false), 2200);
  };

  const accent = id === 'grand-reserve' ? '#3d5240' : id === 'founder' ? '#6e1f24' : id === 'family' ? '#2a221a' : '#0d0a07';

  return (
    <ShopPage_ navDefaultDark={true}>
      <section className="product-detail" data-screen-label="Product Detail" style={{ background: '#0a0805' }}>
        <div className="container">
          <div className="crumbs">
            <a href="index.html">Home</a><span className="sep">/</span>
            <a href="shop.html">Shop</a><span className="sep">/</span>
            <span>{product.name}</span>
          </div>

          <div className="product-detail-grid">
            <div>
              <div className="pd-img" style={{ backgroundImage: `url(${gallery[thumb]})`, backgroundColor: accent }} />
              <div className="pd-thumbs">
                {gallery.map((img, i) => (
                  <div key={i} className={i === thumb ? 'active' : ''}
                    style={{ backgroundImage: `url(${img})` }}
                    onClick={() => setThumb(i)} />
                ))}
              </div>
            </div>

            <div>
              <div className="eyebrow gold">{product.badge} · VIETNAMESE CIVET COFFEE</div>
              <h1 className="pd-title">{renderProductTitle(product.name)}</h1>
              <div style={{ fontFamily: 'var(--mono)', fontSize: 12, opacity: 0.6, letterSpacing: '0.1em', marginTop: 4 }}>
                {product.region.toUpperCase()} · {product.weight.toUpperCase()}
              </div>
              {product.tagline && (
                <p style={{ fontFamily: 'var(--serif)', fontStyle: 'italic', fontSize: 20, color: 'var(--gold-2)', marginTop: 24 }}>
                  {product.tagline}
                </p>
              )}

              <p style={{ fontSize: 15, lineHeight: 1.65, opacity: 0.85, marginTop: 24, maxWidth: 480 }}>
                {product.longDesc}
              </p>

              <div className="pd-price">
                <span>{product.price}</span>
                <span className="small">PER {product.weight.toUpperCase()}</span>
              </div>

              {product.notes && (
                <div style={{ marginTop: 24 }}>
                  <div className="eyebrow gold" style={{ marginBottom: 12 }}>TASTING NOTES</div>
                  <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                    {product.notes.map((n, i) => (
                      <span key={i} style={{
                        padding: '6px 12px',
                        border: '1px solid var(--line-d)',
                        fontFamily: 'var(--serif)',
                        fontStyle: 'italic',
                        fontSize: 13,
                        color: 'var(--gold-2)'
                      }}>{n}</span>
                    ))}
                  </div>
                </div>
              )}

              <div className="pf-spec" style={{ marginTop: 32 }}>
                {product.specs.map((s, i) => (
                  <div key={i} className="row" style={i === product.specs.length - 1 ? { borderBottom: 'none' } : {}}>
                    <span className="k">{s.k}</span>
                    <span className="v" style={s.k === 'NUMBERED' || s.k === 'AUTHENTICATED' ? { color: 'var(--gold-2)' } : {}}>{s.v}</span>
                  </div>
                ))}
              </div>

              <div className="pd-buy">
                <div className="qty">
                  <button onClick={() => setQty(Math.max(1, qty - 1))}>−</button>
                  <span>{qty}</span>
                  <button onClick={() => setQty(qty + 1)}>+</button>
                </div>
                <button className="btn gold" style={{ flex: 1 }} onClick={onAdd}>
                  {added ? <>◆ Added to bag</> : <>Add to bag · ${qty * product.priceN} <span className="arrow">→</span></>}
                </button>
              </div>

              <div style={{ marginTop: 16, display: 'flex', gap: 12, alignItems: 'center' }}>
                <a href="cart.html" className="btn" style={{ color: 'var(--paper)', borderColor: 'var(--paper)', flex: 1, justifyContent: 'center' }}>
                  View bag <span className="arrow">→</span>
                </a>
                <a href="verify.html" className="btn" style={{ color: 'var(--gold)', borderColor: 'var(--gold)', flex: 1, justifyContent: 'center' }}>
                  Verify batch
                </a>
              </div>

              <div style={{ marginTop: 24, fontSize: 11, letterSpacing: '0.12em', textTransform: 'uppercase', opacity: 0.55 }}>
                ◆ Free shipping over $200 · Worldwide · Anchored receipt
              </div>
            </div>
          </div>

          {/* Other tiers */}
          <div style={{ marginTop: 128 }}>
            <div className="eyebrow gold" style={{ marginBottom: 24 }}>/ ALSO IN THE FAMILY</div>
            <div className="products-grid" style={{ gridTemplateColumns: 'repeat(3, 1fr)' }}>
              {others.map(p => (
                <a className="product-card" href={`product.html?id=${p.id}`} key={p.id}>
                  <div className="product-img" style={{ backgroundImage: `url(${p.img})`, backgroundSize: 'contain', backgroundColor: '#0d0a07', backgroundRepeat: 'no-repeat' }}>
                    <div className="product-badge">{p.badge}</div>
                  </div>
                  <div className="product-meta">{p.region}</div>
                  <div className="product-name">{p.name}</div>
                  <div className="product-price">
                    <span className="price">{p.price}</span>
                    <span className="weight">{p.weight}</span>
                  </div>
                </a>
              ))}
            </div>
          </div>
        </div>
      </section>
    </ShopPage_>
  );
}

function renderProductTitle(name) {
  // "CỘI Founder Collection" -> CỘI + italic 'Founder Collection'
  if (name.startsWith('CỘI ')) {
    const rest = name.slice(4);
    return <>CỘI <em>{rest}.</em></>;
  }
  if (name.includes('·')) {
    const [a, b] = name.split('·').map(s => s.trim());
    return <>{a} <em>· {b}.</em></>;
  }
  return <>{name}<em>.</em></>;
}

window.SonShopPages = { ShopCollectionPage, ProductDetailPage };
