/* CỘI — sections 1: Nav, Hero, BrandPillars, ProductFeature, Process, Verify */

const { useState, useEffect, useRef } = React;

// ============================== NAV (slide-down luxury menu)
function Nav({ scrolled, overDark }) {
  const [cartCount, setCartCount] = useState(() => window.CoiCart ? window.CoiCart.count() : 0);
  const [open, setOpen] = useState(false);

  useEffect(() => {
    const update = () => setCartCount(window.CoiCart ? window.CoiCart.count() : 0);
    update();
    window.addEventListener('coi-cart-changed', update);
    window.addEventListener('storage', update);
    return () => {
      window.removeEventListener('coi-cart-changed', update);
      window.removeEventListener('storage', update);
    };
  }, []);

  useEffect(() => {
    document.body.style.overflow = open ? 'hidden' : '';
    const onKey = (e) => { if (e.key === 'Escape') setOpen(false); };
    window.addEventListener('keydown', onKey);
    return () => {
      document.body.style.overflow = '';
      window.removeEventListener('keydown', onKey);
    };
  }, [open]);

  return (
    <>
      <nav className={`nav ${scrolled ? 'scrolled' : ''} ${overDark ? 'over-dark' : ''} ${open ? 'menu-open' : ''}`}>
        <div className="nav-left">
          <button className="nav-trigger" onClick={() => setOpen(!open)} aria-label="Menu">
            <span className="trigger-icon">
              <span className={`bar ${open ? 'a' : ''}`} />
              <span className={`bar ${open ? 'b' : ''}`} />
            </span>
            <span className="trigger-label">{open ? 'Close' : 'Menu'}</span>
          </button>
        </div>
        <a href="index.html" className="nav-logo">
          CỘI
          <span className="mark-sub">ROOTED IN VIETNAM</span>
        </a>
        <div className="nav-right">
          <a className="nav-link nav-link-hide" href="verify-bag.html">Verify a bag</a>
          <a className="nav-cart" href="cart.html">
            <span>Cart</span>
            <span className="nav-cart-count">[ {cartCount} ]</span>
          </a>
        </div>
      </nav>

      {/* Backdrop */}
      <div className={`nav-backdrop ${open ? 'open' : ''}`} onClick={() => setOpen(false)} />

      {/* Slide-down drawer */}
      <div className={`nav-drawer ${open ? 'open' : ''}`} aria-hidden={!open}>
        <div className="drawer-inner">
          <div className="drawer-col">
            <div className="drawer-eyebrow">/ 01 — SHOP</div>
            <a href="shop.html" className="drawer-link">All Coffee</a>
            <a href="product.html?id=reserve" className="drawer-link">Reserve <span className="drawer-link-meta">$49 · 100g</span></a>
            <a href="product.html?id=grand-reserve" className="drawer-link">Grand Reserve <span className="drawer-link-meta">$79 · 100g</span></a>
            <a href="product.html?id=founder" className="drawer-link">Founder Collection <span className="drawer-link-meta">$149 · 100g</span></a>
            <a href="heritage.html" className="drawer-link gold">Heritage Series <span className="drawer-link-meta">$299 · 25g</span></a>
            <a href="vault.html" className="drawer-link gold">Collector Vault <span className="drawer-link-meta">$799–1,200 · 10g</span></a>
            <a href="pods.html" className="drawer-link">Coffee Pods</a>
            <a href="product.html?id=family" className="drawer-link">The Family Trio</a>
          </div>

          <div className="drawer-col">
            <div className="drawer-eyebrow">/ 02 — DISCOVER</div>
            <a href="farms.html" className="drawer-link">Farms</a>
            <a href="process.html" className="drawer-link">Process</a>
            <a href="sustainability.html" className="drawer-link">Sustainability</a>
            <a href="packaging.html" className="drawer-link">Packaging</a>
            <a href="export.html" className="drawer-link">Global Export</a>
            <a href="about.html" className="drawer-link">About CỘI</a>
            <a href="press.html" className="drawer-link">Press</a>
          </div>

          <div className="drawer-col">
            <div className="drawer-eyebrow">/ 03 — VERIFY</div>
            <a href="verify.html" className="drawer-link">Verify a batch</a>
            <a href="verify-bag.html" className="drawer-link">Verify a bag</a>
            <a href="ledger.html" className="drawer-link">Public ledger</a>
            <a href="docs.html" className="drawer-link">BLT · FloraChain docs</a>

            <div className="drawer-eyebrow" style={{ marginTop: 32 }}>/ 04 — TRADE</div>
            <a href="wholesale.html" className="drawer-link">Wholesale</a>
            <a href="wholesale.html#book" className="drawer-link">Book a call</a>
            <a href="contact.html" className="drawer-link">Contact</a>
          </div>

          <div className="drawer-feature">
            <a href="vault.html" className="drawer-feature-card">
              <div className="drawer-feature-img" style={{ backgroundImage: 'url(assets/coi-vault.png)' }} />
              <div className="drawer-feature-eyebrow">FEATURED · 88 WORLDWIDE</div>
              <div className="drawer-feature-title">Collector Vault</div>
              <div className="drawer-feature-sub">A legacy in every grain. 10g · numbered.</div>
              <div className="drawer-feature-cta">View vault <span>→</span></div>
            </a>
          </div>
        </div>

        <div className="drawer-foot">
          <div className="mono">CỘI · ROOTED IN VIETNAM</div>
          <div className="drawer-foot-meta">
            <a href="verify-bag.html">Verify a bag</a>
            <span>·</span>
            <a href="cart.html">Cart [ {cartCount} ]</a>
            <span>·</span>
            <a href="contact.html">Contact</a>
          </div>
        </div>
      </div>
    </>
  );
}

// ============================== HERO
function Hero() {
  return (
    <section className="hero hero-art" id="top" data-screen-label="01 Hero">
      <div className="hero-bg" style={{ backgroundImage: `url(assets/coi-hero.png)` }} />

      <div className="hero-ticker">
        <div className="hero-ticker-inner">
          {Array.from({length: 2}).map((_, i) => (
            <React.Fragment key={i}>
              <span>BATCH COI-240S-LD-01227 · ANCHORED 03:41 UTC</span>
              <span className="dot">◆</span>
              <span>SUỐI NHIÊU ESTATE · LÂM ĐỒNG · 1,200–1,500M</span>
              <span className="dot">◆</span>
              <span>EX. ĐÀ NẴNG → ROTTERDAM · ETA 11D</span>
              <span className="dot">◆</span>
              <span>FOUNDER COLLECTION · NUMBERED 0001/1888</span>
              <span className="dot">◆</span>
              <span>FLORACHAIN BLOCK 5,048,216 CONFIRMED</span>
              <span className="dot">◆</span>
              <span>AUTHENTICATED THROUGH BLT · ANCHORED TO FLORACHAIN</span>
              <span className="dot">◆</span>
            </React.Fragment>
          ))}
        </div>
      </div>

      <div className="hero-content hero-content-art">
        <div className="hero-meta hero-meta-overlay">
          <div className="hero-meta-item">
            <div className="label">Origin</div>
            <div className="val">Lâm Đồng, Vietnam</div>
          </div>
          <div className="hero-meta-item">
            <div className="label">Verification</div>
            <div className="val">BLT · FloraChain</div>
          </div>
          <div className="hero-meta-item">
            <div className="label">Collection</div>
            <div className="val">Reserve · Grand · Founder</div>
          </div>
          <div className="hero-meta-item">
            <div className="label">Latest batch</div>
            <div className="val mono">COI-240S-LD-01227</div>
          </div>
        </div>
        <div className="hero-actions hero-actions-overlay">
          <a href="shop.html" className="btn gold">Explore Collection <span className="arrow">→</span></a>
          <a href="verify-bag.html" className="btn">Verify a bag</a>
        </div>
      </div>
    </section>
  );
}

// ============================== BRAND PILLARS
function BrandPillars() {
  const pillars = [
    {
      name: "ORIGIN",
      desc: "Farm-mapped, GPS-anchored, single-estate by design.",
      icon: (
        <svg viewBox="0 0 32 32" fill="none" stroke="currentColor" strokeWidth="1.2">
          <path d="M4 24 L11 14 L16 19 L21 11 L28 24 Z" />
          <line x1="2" y1="24" x2="30" y2="24" />
          <path d="M8 17 L10 15 L12 17" strokeWidth="0.8" opacity="0.6" />
        </svg>
      )
    },
    {
      name: "AUTHENTICITY",
      desc: "Producer-signed, lab-verified, never blended.",
      icon: (
        <svg viewBox="0 0 32 32" fill="none" stroke="currentColor" strokeWidth="1.2">
          <path d="M16 6 C11 6 7 10 7 16 C7 22 11 28 16 28" />
          <path d="M16 9 C12.5 9 10 12 10 16 C10 21 13 26 16 27" />
          <path d="M16 12 C14 12 13 14 13 16 C13 19 14 23 16 25" />
          <path d="M16 15 C15.5 15 15 15.5 15 16 C15 18 15.5 21 16 23" />
        </svg>
      )
    },
    {
      name: "TRACEABILITY",
      desc: "Every batch, anchored to FloraChain. Inspectable forever.",
      icon: (
        <svg viewBox="0 0 32 32" fill="none" stroke="currentColor" strokeWidth="1.2">
          <path d="M16 22 L16 12" />
          <path d="M16 12 C14 11 11 11 9 13 C11 14 13 14 16 12" />
          <path d="M16 12 C18 11 21 11 23 13 C21 14 19 14 16 12" />
          <path d="M16 16 C15 15.3 13.5 15.3 12 16.3 C13.5 17 14.5 17 16 16" />
          <path d="M16 16 C17 15.3 18.5 15.3 20 16.3 C18.5 17 17.5 17 16 16" />
          <path d="M14 24 C13 26 12 27 10 28" />
          <path d="M18 24 C19 26 20 27 22 28" />
          <path d="M16 24 L16 28" />
        </svg>
      )
    },
    {
      name: "STORY",
      desc: "Farmer biography, harvest narrative, hands you can name.",
      icon: (
        <svg viewBox="0 0 32 32" fill="none" stroke="currentColor" strokeWidth="1.2">
          <path d="M5 8 L5 25 L15 25 L16 26 L17 25 L27 25 L27 8 L17 8 L16 9 L15 8 Z" />
          <line x1="16" y1="9" x2="16" y2="26" />
          <line x1="8" y1="13" x2="13" y2="13" opacity="0.6" />
          <line x1="8" y1="16" x2="13" y2="16" opacity="0.6" />
          <line x1="8" y1="19" x2="13" y2="19" opacity="0.6" />
          <line x1="19" y1="13" x2="24" y2="13" opacity="0.6" />
          <line x1="19" y1="16" x2="24" y2="16" opacity="0.6" />
          <line x1="19" y1="19" x2="24" y2="19" opacity="0.6" />
        </svg>
      )
    }
  ];
  return (
    <section className="pillars" data-screen-label="01b Pillars">
      <div className="container">
        <div className="pillars-grid">
          {pillars.map((p, i) => (
            <div className="pillar reveal" key={p.name} style={{ transitionDelay: `${i * 0.08}s` }}>
              <div className="pillar-icon">{p.icon}</div>
              <div>
                <div className="pillar-name">/ {String(i + 1).padStart(2, '0')} — {p.name}</div>
                <div className="pillar-desc" style={{ marginTop: 8 }}>{p.desc}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ============================== PRODUCT FEATURE (the three-tier family)
function ProductFeature() {
  return (
    <section className="product-feature" data-screen-label="01c Family">
      <div className="container">
        <div className="pf-grid">
          <div
            className="pf-img contain reveal"
            style={{ backgroundImage: 'url(assets/coi-family.png)' }}
          />
          <div className="reveal">
            <div className="eyebrow gold">THE FAMILY · THREE TIERS</div>
            <h3>One estate.<br/><em>Three</em> expressions.</h3>
            <p style={{ fontSize: 15, lineHeight: 1.6, opacity: 0.78, maxWidth: 460 }}>
              The same farms, the same wild-foraged process — finished in three altitudes, three roast profiles, three commitments to scarcity. From the everyday Reserve to the numbered Founder Collection.
            </p>

            <div className="pf-spec">
              <div className="row">
                <span className="k" style={{ color: 'var(--gold-2)' }}>CỘI RESERVE</span>
                <span className="v">
                  Vietnamese Civet Coffee · Flagship
                  <div style={{ fontFamily: 'var(--mono)', fontSize: 12, opacity: 0.65, marginTop: 4 }}>
                    $49 / 100g · ex-stock
                  </div>
                </span>
              </div>
              <div className="row">
                <span className="k" style={{ color: 'var(--gold-2)' }}>GRAND RESERVE</span>
                <span className="v">
                  Higher altitude · Limited
                  <div style={{ fontFamily: 'var(--mono)', fontSize: 12, opacity: 0.65, marginTop: 4 }}>
                    $79 / 100g · 480 pouches per harvest
                  </div>
                </span>
              </div>
              <div className="row" style={{ borderBottom: 'none' }}>
                <span className="k" style={{ color: 'var(--gold-2)' }}>FOUNDER</span>
                <span className="v">
                  Numbered estate lot · Digital passport
                  <div style={{ fontFamily: 'var(--mono)', fontSize: 12, opacity: 0.65, marginTop: 4 }}>
                    $149 / 100g · No. 0001 / 1888
                  </div>
                </span>
              </div>
            </div>

            <div className="pf-foot">
              <a className="btn gold" href="shop.html">Explore the family <span className="arrow">→</span></a>
              <a className="btn" href="verify.html">Verify a batch</a>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ============================== PROCESS
function Process() {
  const [active, setActive] = useState(0);
  const steps = window.SON_DATA.PROCESS_STEPS;
  const detail = steps[active].detail;

  return (
    <section className="section tall" id="process" data-screen-label="02 Process">
      <div className="container">
        <div className="section-head reveal">
          <div>
            <div className="head-num">02 — PROCESS</div>
            <h2>From <em style={{ fontStyle: 'italic', color: 'var(--gold)' }}>cherry</em><br/>to cup.</h2>
          </div>
          <div className="head-meta">
            <p>Eight stages, each independently recorded. Click any stage below to read its protocol, its actors, and the data it commits to the ledger.</p>
            <p style={{ opacity: 0.55 }}>No stage is invisible. No batch enters the chain without all eight.</p>
          </div>
        </div>

        <div className="process-timeline reveal">
          {steps.map((s, i) => (
            <div
              key={s.name}
              className={`process-step ${active === i ? 'active' : ''}`}
              onClick={() => setActive(i)}
            >
              <div className="step-dot" />
              <div className="step-num">0{i + 1}</div>
              <div className="step-name">{s.name}</div>
              <div className="step-meta">{s.sub}</div>
            </div>
          ))}
        </div>

        <div className="process-detail reveal">
          <div className="detail-img" style={{ backgroundImage: `url(${detail.img})` }} key={active + '-img'} />
          <div className="detail-text" key={active + '-txt'}>
            <div className="eyebrow gold">STAGE {String(active + 1).padStart(2, '0')} · {steps[active].name.toUpperCase()}</div>
            <h3>{detail.title}</h3>
            <p>{detail.copy}</p>
            <div className="detail-facts">
              {detail.facts.map((f, i) => (
                <div className="fact" key={i}>
                  <div className="label">{f.label}</div>
                  <div className="val">{f.val}</div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ============================== VERIFY ENGINE
function Verify() {
  const [query, setQuery] = useState("");
  const [tab, setTab] = useState("batch");
  const [state, setState] = useState("idle");
  const [result, setResult] = useState(null);

  const sampleIds = Object.keys(window.SON_DATA.SAMPLE_BATCHES);

  const onVerify = (id) => {
    const target = id || query;
    if (!target) return;
    setState("loading");
    setTimeout(() => {
      const match = window.SON_DATA.SAMPLE_BATCHES[target.toUpperCase()];
      if (match) {
        setQuery(target.toUpperCase());
        setResult(match);
        setState("result");
      } else {
        setState("error");
      }
    }, 1200);
  };

  return (
    <section className="section tall dark" id="verify" data-screen-label="03 Verify">
      <div className="container">
        <div className="section-head reveal">
          <div>
            <div className="head-num">03 — TRACEABILITY ENGINE</div>
            <h2>From farm <em style={{ fontStyle: 'italic', color: 'var(--gold-2)' }}>to cup.</em></h2>
          </div>
          <div className="head-meta">
            <p>Enter a batch ID, scan the QR on your pouch hangtag, or paste a tin serial. The ledger returns farm, farmer, processing record, sensory profile, and the FloraChain anchor in under three seconds.</p>
            <p style={{ opacity: 0.55 }}>Try one of the sample batches below.</p>
          </div>
        </div>

        <div className="verify-card reveal">
          <div className="verify-input-pane">
            <div className="eyebrow gold">INPUT</div>
            <h3>Verify a batch</h3>
            <p>One ID, one farm, one ledger entry, one cup.</p>

            <div className="verify-tabs">
              <div className={`verify-tab ${tab === 'batch' ? 'active' : ''}`} onClick={() => setTab('batch')}>Batch ID</div>
              <div className={`verify-tab ${tab === 'qr' ? 'active' : ''}`} onClick={() => setTab('qr')}>QR</div>
              <div className={`verify-tab ${tab === 'serial' ? 'active' : ''}`} onClick={() => setTab('serial')}>Serial</div>
            </div>

            <input
              className="verify-input"
              placeholder={tab === 'batch' ? 'COI-XXXX-XX-NNNNN' : tab === 'qr' ? 'Paste QR payload…' : 'Tin / case serial…'}
              value={query}
              onChange={(e) => setQuery(e.target.value)}
              onKeyDown={(e) => e.key === 'Enter' && onVerify()}
            />
            <div style={{ display: 'flex', gap: 12, marginTop: 24 }}>
              <button className="btn gold" onClick={() => onVerify()}>Verify <span className="arrow">→</span></button>
            </div>

            <div className="verify-suggestions">
              {sampleIds.map(id => (
                <div className="verify-chip" key={id} onClick={() => onVerify(id)}>{id}</div>
              ))}
            </div>
          </div>

          <div className="verify-result">
            {state === "idle" && (
              <div className="verify-empty">
                <div className="qr-frame" />
                <div className="eyebrow" style={{ color: 'rgba(246,241,231,0.5)' }}>
                  AWAITING INPUT
                </div>
              </div>
            )}
            {state === "loading" && (
              <div className="verify-loading">
                <div className="mono" style={{ fontSize: 11, letterSpacing: '0.15em', opacity: 0.6 }}>
                  QUERYING FLORACHAIN…
                </div>
                <div className="verify-loading-bar" />
                <div className="mono" style={{ fontSize: 10, opacity: 0.4 }}>
                  flora-1 · testnet-gateway.metaflora.xyz
                </div>
              </div>
            )}
            {state === "error" && (
              <div className="verify-empty">
                <div className="eyebrow" style={{ color: '#d18671' }}>NOT FOUND</div>
                <p style={{ marginTop: 12, fontSize: 13, maxWidth: 280 }}>
                  Batch identifier did not resolve. Confirm the ID on your hangtag or use one of the sample batches.
                </p>
              </div>
            )}
            {state === "result" && result && (
              <PassportResult data={result} id={query} />
            )}
          </div>
        </div>
      </div>
    </section>
  );
}

function PassportResult({ data, id }) {
  return (
    <div className="verify-passport">
      <div className="passport-header">
        <div>
          <div className="passport-status">
            <span className="dot" />
            VERIFIED · FLORACHAIN ANCHORED
          </div>
          <div className="passport-id" style={{ marginTop: 6 }}>{id}</div>
        </div>
        <div style={{ textAlign: 'right' }}>
          <div className="eyebrow" style={{ color: 'rgba(246,241,231,0.5)' }}>BLOCK</div>
          <div className="mono" style={{ fontSize: 14 }}>#{data.block.toLocaleString()}</div>
        </div>
      </div>

      <div className="passport-field">
        <div className="label">Farm</div>
        <div className="val">{data.farm}</div>
        <div className="mono" style={{ fontSize: 11, opacity: 0.55, marginTop: 4 }}>{data.region}</div>
      </div>
      <div className="passport-field">
        <div className="label">Farmer</div>
        <div className="val">{data.farmer}</div>
        <div className="mono" style={{ fontSize: 11, opacity: 0.55, marginTop: 4 }}>{data.coords} · {data.altitude}</div>
      </div>
      <div className="passport-field">
        <div className="label">Harvest date</div>
        <div className="val mono" style={{ fontSize: 16 }}>{data.harvest}</div>
      </div>
      <div className="passport-field">
        <div className="label">Batch weight</div>
        <div className="val">{data.weight}</div>
      </div>
      <div className="passport-field" style={{ gridColumn: '1 / -1' }}>
        <div className="label">Processing</div>
        <div className="val" style={{ fontSize: 16 }}>{data.process}</div>
      </div>
      <div className="passport-field" style={{ gridColumn: '1 / -1' }}>
        <div className="label">Roast & cupping</div>
        <div className="val" style={{ fontSize: 16 }}>{data.roast}</div>
      </div>
      <div className="passport-field" style={{ gridColumn: '1 / -1' }}>
        <div className="label">Tasting notes</div>
        <div className="val italic" style={{ fontStyle: 'italic', fontSize: 18 }}>{data.notes}</div>
      </div>

      <div className="passport-chain">
        <h4>VERIFICATION CHAIN</h4>
        <div className="chain-flow">
          <div className="chain-node">
            <div className="stage">01 FARM</div>
            <div>{data.farmId}</div>
          </div>
          <div className="chain-arrow">→</div>
          <div className="chain-node">
            <div className="stage">02 BLT HASH</div>
            <div style={{ fontSize: 10 }}>{data.bltHash.slice(0, 16)}…</div>
          </div>
          <div className="chain-arrow">→</div>
          <div className="chain-node verified">
            <div className="stage">03 FLORACHAIN</div>
            <div style={{ fontSize: 10 }}>{data.floraTx.slice(0, 16)}…</div>
          </div>
          <div className="chain-arrow">→</div>
          <div className="chain-node verified">
            <div className="stage">04 ANCHORED</div>
            <div style={{ fontSize: 10 }}>{data.anchored.split(' · ')[0]}</div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ============================== LEGEND (civet mascot)
function Legend() {
  return (
    <section className="legend" data-screen-label="03b Legend">
      <div className="container">
        <div className="legend-grid">
          <div className="legend-text reveal">
            <div className="eyebrow gold" style={{ color: 'var(--gold-2)' }}>THE LEGEND</div>
            <h2>Nature's <em>rare</em><br/>masterpiece.</h2>
            <p>
              Civet coffee is nature's rare masterpiece. The Asian palm civet selects only the ripest cherries from the forest canopy, and through a natural digestive process unique to its species, develops the cherry's body and removes its bitterness.
            </p>
            <p>
              No two harvests are alike. No farm can force the cycle. The civet decides — and we record what the civet decided.
            </p>
            <div className="legend-stats">
              <div className="legend-stat">
                <div className="label">YIELD · per hectare</div>
                <div className="val">≤ <em>4.2</em>%</div>
              </div>
              <div className="legend-stat">
                <div className="label">CONFINED PRODUCTION</div>
                <div className="val"><em>0</em></div>
              </div>
              <div className="legend-stat">
                <div className="label">HARVEST WINDOW</div>
                <div className="val">Nov — <em>Mar</em></div>
              </div>
            </div>
          </div>
          <div />
        </div>
      </div>
    </section>
  );
}

window.SonSections1 = { Nav, Hero, BrandPillars, ProductFeature, Legend, Process, Verify };
