/* CỘI — Wholesale, Verify, Verify-a-bag, Ledger pages */

const { useState: useWS, useMemo: useMWS } = React;
const { Page: WSPage_, PageHero: WSHero_ } = window.SonPage;
const { WholesaleDashboard: _WD, Verify: _Verify } = { ...window.SonSections3, ...window.SonSections1 };

// ============================== WHOLESALE
function WholesalePage() {
  const tiers = window.SON_DATA.WHOLESALE_TIERS;
  const [qty, setQty] = useWS(50);
  const [duration, setDuration] = useWS(12);
  const pricePerKg = qty < 25 ? 264 : qty < 100 ? 228 : qty < 500 ? 196 : 168;
  const total = qty * pricePerKg * duration / 1000;

  return (
    <WSPage_ navDefaultDark={true}>
      <WSHero_
        num="01"
        eyebrow="WHOLESALE"
        title={<>Allocation, <em>at scale.</em></>}
        sub="From 10kg cafe programmes to 9.2-tonne refrigerated container orders. Quarterly futures, harvest-window pre-booking, and full BLT documentation per shipment."
      >
        <div className="crumbs"><a href="index.html">Home</a><span className="sep">/</span><span>Wholesale</span></div>
      </WSHero_>

      {/* TIERS */}
      <section className="section paper" id="cafe" data-screen-label="Wholesale · Tiers">
        <div className="container">
          <div className="section-head reveal">
            <div>
              <div className="head-num">02 — TIERS</div>
              <h2>Four ways<br/>to <em style={{ fontStyle: 'italic', color: 'var(--gold)' }}>scale.</em></h2>
            </div>
            <div className="head-meta">
              <p>The same farms, the same ledger, the same chain of custody — at every scale. Anchor IDs and a delivery cadence to match your operation.</p>
            </div>
          </div>
          <div className="wholesale-grid reveal">
            {tiers.map((w, i) => (
              <div
                className="wholesale-card"
                key={i}
                id={['cafe','distribution','enterprise','container'][i]}
              >
                <div>
                  <div className="moq">{w.moq}<sup>{w.unit}</sup></div>
                  <div className="desc">
                    <strong>{w.desc}</strong>
                    {w.sub}
                  </div>
                </div>
                <div className="price-from">
                  <div className="label">From</div>
                  <div className="price">{w.price}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* MOQ CALCULATOR */}
      <section className="section dark" data-screen-label="Wholesale · Calculator">
        <div className="container">
          <div className="section-head reveal">
            <div>
              <div className="head-num">03 — VOLUME CALCULATOR</div>
              <h2>Estimate <em style={{ fontStyle: 'italic', color: 'var(--gold-2)' }}>your</em> programme.</h2>
            </div>
            <div className="head-meta">
              <p>Volume, frequency, contract length. The estimate updates live; the final price is set at harvest in the contract you sign.</p>
            </div>
          </div>

          <div className="dashboard reveal" style={{ margin: 0 }}>
            <div className="dashboard-head">
              <div className="head-left">
                <div className="title">MOQ ESTIMATE</div>
                <div className="subtitle">DEMO · NON-BINDING</div>
              </div>
              <div className="actions">
                <button>Reset</button>
                <a className="btn gold" href="#book" style={{ padding: '8px 14px' }}>Convert to RFQ</a>
              </div>
            </div>

            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 48, marginBottom: 32 }}>
              <div>
                <div className="eyebrow gold" style={{ marginBottom: 8 }}>VOLUME · KG / MONTH</div>
                <div style={{ fontFamily: 'var(--serif)', fontSize: 56, fontWeight: 300, lineHeight: 1 }}>
                  {qty}<span style={{ fontSize: 18, fontFamily: 'var(--sans)', opacity: 0.5, marginLeft: 4 }}>kg/mo</span>
                </div>
                <input
                  type="range" min="10" max="1000" step="5"
                  value={qty} onChange={e => setQty(+e.target.value)}
                  style={{ width: '100%', marginTop: 24, accentColor: 'var(--gold)' }}
                />
                <div style={{ display: 'flex', justifyContent: 'space-between', fontFamily: 'var(--mono)', fontSize: 10, opacity: 0.55, marginTop: 4 }}>
                  <span>10 kg</span><span>1,000 kg</span>
                </div>
              </div>
              <div>
                <div className="eyebrow gold" style={{ marginBottom: 8 }}>CONTRACT · MONTHS</div>
                <div style={{ fontFamily: 'var(--serif)', fontSize: 56, fontWeight: 300, lineHeight: 1 }}>
                  {duration}<span style={{ fontSize: 18, fontFamily: 'var(--sans)', opacity: 0.5, marginLeft: 4 }}>mo</span>
                </div>
                <input
                  type="range" min="1" max="36" step="1"
                  value={duration} onChange={e => setDuration(+e.target.value)}
                  style={{ width: '100%', marginTop: 24, accentColor: 'var(--gold)' }}
                />
                <div style={{ display: 'flex', justifyContent: 'space-between', fontFamily: 'var(--mono)', fontSize: 10, opacity: 0.55, marginTop: 4 }}>
                  <span>1 mo</span><span>36 mo</span>
                </div>
              </div>
            </div>

            <div className="dashboard-metrics" style={{ marginBottom: 0 }}>
              <div className="metric">
                <div className="label">PRICE · per kg</div>
                <div className="val"><span className="num">${pricePerKg}</span></div>
                <div className="trend">▲ Tier-locked at {qty < 25 ? '10kg' : qty < 100 ? '50kg' : qty < 500 ? '250kg' : 'Container'}</div>
              </div>
              <div className="metric">
                <div className="label">MONTHLY · USD</div>
                <div className="val"><span className="num">${(qty * pricePerKg).toLocaleString()}</span></div>
                <div className="trend">▲ Invoice cycle · net 30</div>
              </div>
              <div className="metric">
                <div className="label">CONTRACT TOTAL</div>
                <div className="val"><span className="num">${total.toFixed(1)}k</span></div>
                <div className="trend">▲ {duration} months</div>
              </div>
              <div className="metric">
                <div className="label">EX-WORKS PORT</div>
                <div className="val" style={{ fontSize: 28 }}>Cát Lái</div>
                <div className="trend">▲ HCMC · weekly cadence</div>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* COMMAND CENTER (reuse) */}
      <_WD />

      {/* RFQ BOOK CALL FORM */}
      <section className="form-section dark" id="book" data-screen-label="Wholesale · RFQ">
        <div className="container">
          <div className="section-head reveal">
            <div>
              <div className="head-num">05 — BOOK A CALL</div>
              <h2>Speak to <em style={{ fontStyle: 'italic', color: 'var(--gold-2)' }}>origin.</em></h2>
            </div>
            <div className="head-meta">
              <p>A member of the export team responds within one business day. For container orders, we coordinate directly with the farm and our HCMC freight partner.</p>
            </div>
          </div>
          <RFQForm />
        </div>
      </section>
    </WSPage_>
  );
}

function RFQForm() {
  const [submitted, setSubmitted] = useWS(false);
  if (submitted) {
    return (
      <div className="reveal" style={{ padding: '64px 0', textAlign: 'center', border: '1px solid var(--line-d)' }}>
        <div className="eyebrow gold" style={{ color: 'var(--gold-2)' }}>◆ RFQ RECEIVED</div>
        <h3 style={{ fontFamily: 'var(--serif)', fontWeight: 300, fontSize: 48, margin: '16px 0' }}>
          Reference <em style={{ fontStyle: 'italic', color: 'var(--gold-2)' }}>RFQ-{Math.floor(Math.random()*900000+100000)}</em>
        </h3>
        <p style={{ opacity: 0.75, maxWidth: 480, margin: '0 auto' }}>
          A member of the export team will respond within one business day. Watch your inbox for a Calendly link and a preliminary harvest allocation.
        </p>
      </div>
    );
  }
  return (
    <form className="form reveal" onSubmit={(e) => { e.preventDefault(); setSubmitted(true); }}>
      <div className="form-grid-2">
        <div className="form-row">
          <div className="lbl">FULL NAME</div>
          <input required placeholder="Maria Bernardi" />
        </div>
        <div className="form-row">
          <div className="lbl">TITLE</div>
          <input placeholder="Head of Procurement" />
        </div>
      </div>
      <div className="form-grid-2">
        <div className="form-row">
          <div className="lbl">COMPANY</div>
          <input required placeholder="Maison Héritage Group" />
        </div>
        <div className="form-row">
          <div className="lbl">EMAIL</div>
          <input required type="email" placeholder="m.bernardi@maison.com" />
        </div>
      </div>
      <div className="form-grid-2">
        <div className="form-row">
          <div className="lbl">TIER</div>
          <select>
            <option>Cafe & specialty · 10 kg</option>
            <option>Distribution · 50 kg</option>
            <option>Enterprise · 250 kg</option>
            <option>Container · 9,200 kg</option>
          </select>
        </div>
        <div className="form-row">
          <div className="lbl">DESTINATION PORT</div>
          <input placeholder="Genova, IT" />
        </div>
      </div>
      <div className="form-row">
        <div className="lbl">PROGRAMME DETAIL</div>
        <textarea placeholder="Outlet count, expected monthly volume, target start date, packaging preferences (co-brand or Cội default)…" />
      </div>
      <div style={{ display: 'flex', gap: 12, marginTop: 16 }}>
        <button type="submit" className="btn gold">Submit RFQ <span className="arrow">→</span></button>
        <a href="contact.html" className="btn" style={{ color: 'var(--paper)', borderColor: 'var(--paper)' }}>General enquiry instead</a>
      </div>
    </form>
  );
}

// ============================== VERIFY (full page)
function VerifyPage() {
  return (
    <WSPage_ navDefaultDark={true}>
      <WSHero_
        num="01"
        eyebrow="TRACEABILITY ENGINE"
        title={<>One ID. <em>One farm.</em></>}
        sub="Enter the batch identifier from your pouch hangtag, paste a QR payload, or scan a tin serial. The ledger returns the full passport in under three seconds."
      >
        <div className="crumbs"><a href="index.html">Home</a><span className="sep">/</span><span>Verify a batch</span></div>
      </WSHero_>
      <_Verify />

      <section className="section paper" data-screen-label="Verify · Recent">
        <div className="container">
          <div className="section-head reveal">
            <div>
              <div className="head-num">02 — RECENT ANCHORS</div>
              <h2>Latest <em style={{ fontStyle: 'italic', color: 'var(--gold)' }}>anchors.</em></h2>
            </div>
            <div className="head-meta">
              <p>Six most recent batches anchored to FloraChain. Click to open the public ledger record.</p>
              <a className="btn" href="ledger.html">Full ledger <span className="arrow">→</span></a>
            </div>
          </div>
          <RecentAnchors />
        </div>
      </section>
    </WSPage_>
  );
}

function RecentAnchors() {
  const rows = [
    { id: 'COI-240S-LD-01227', farm: 'Suối Nhiêu Estate', block: 4847291, anchored: '2024.12.04 03:41 UTC', weight: '12.4 kg' },
    { id: 'COI-240H-BMT-09431', farm: 'Hoà Khê Cooperative', block: 4912038, anchored: '2024.12.19 11:08 UTC', weight: '9.8 kg' },
    { id: 'COI-250Q-QN-00214', farm: 'Đà Đèo Cloud Forest', block: 5048216, anchored: '2025.02.14 22:17 UTC', weight: '5.2 kg' },
    { id: 'COI-241G-KT-00518', farm: 'Pleiku Ridge', block: 5102994, anchored: '2025.03.02 06:22 UTC', weight: '8.1 kg' },
    { id: 'COI-241B-DL-12009', farm: 'Sông Lâm Heritage', block: 5188174, anchored: '2025.03.18 14:51 UTC', weight: '6.7 kg' },
    { id: 'COI-242M-GL-00873', farm: 'Tây Nguyên', block: 5234908, anchored: '2025.04.07 09:18 UTC', weight: '10.2 kg' }
  ];
  return (
    <table className="ledger-table reveal" style={{ background: 'var(--paper)' }}>
      <thead>
        <tr>
          <th>BATCH ID</th><th>FARM</th><th>BLOCK</th><th>ANCHORED</th><th>WEIGHT</th><th></th>
        </tr>
      </thead>
      <tbody>
        {rows.map(r => (
          <tr key={r.id}>
            <td className="tx-hash">{r.id}</td>
            <td style={{ fontFamily: 'var(--serif)', fontSize: 16 }}>{r.farm}</td>
            <td className="ledger-block-num">#{r.block.toLocaleString()}</td>
            <td>{r.anchored}</td>
            <td>{r.weight}</td>
            <td><a href="verify.html" style={{ color: 'var(--gold)' }}>view →</a></td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}

// ============================== VERIFY A BAG (mobile-style scan)
function VerifyBagPage() {
  const [scanning, setScanning] = useWS(false);
  const [result, setResult] = useWS(null);

  const onScan = () => {
    setScanning(true);
    setTimeout(() => {
      setScanning(false);
      setResult(window.SON_DATA.SAMPLE_BATCHES['COI-240S-LD-01227']);
    }, 2200);
  };

  return (
    <WSPage_ navDefaultDark={true}>
      <div className="vb-page" data-screen-label="Verify a Bag">
        <div className="container">
          <div className="vb-stage">
            <div className="crumbs" style={{ alignSelf: 'flex-start', marginBottom: 32 }}>
              <a href="index.html">Home</a><span className="sep">/</span>
              <span>Verify a bag</span>
            </div>

            <div className="eyebrow gold" style={{ color: 'var(--gold-2)', textAlign: 'center' }}>
              ◆ VERIFY YOUR POUCH HANGTAG
            </div>
            <h1 style={{
              fontFamily: 'var(--serif)', fontWeight: 300,
              fontSize: 'clamp(40px, 6vw, 72px)', lineHeight: 0.95,
              letterSpacing: '-0.02em', textAlign: 'center', margin: '24px 0 16px'
            }}>
              Point camera <em style={{ fontStyle: 'italic', color: 'var(--gold-2)' }}>here.</em>
            </h1>
            <p style={{ textAlign: 'center', opacity: 0.7, maxWidth: 400, marginBottom: 48 }}>
              Hold the BLT QR on the inside of your pouch within the frame below. We resolve the ledger record on-device.
            </p>

            <div className="vb-frame">
              <span style={{ position: 'absolute', top: 16, left: 16, width: 32, height: 32, borderLeft: '2px solid var(--gold)', borderTop: '2px solid var(--gold)' }} />
              <span style={{ position: 'absolute', top: 16, right: 16, width: 32, height: 32, borderRight: '2px solid var(--gold)', borderTop: '2px solid var(--gold)' }} />
              <span style={{ position: 'absolute', bottom: 16, left: 16, width: 32, height: 32, borderLeft: '2px solid var(--gold)', borderBottom: '2px solid var(--gold)' }} />
              <span style={{ position: 'absolute', bottom: 16, right: 16, width: 32, height: 32, borderRight: '2px solid var(--gold)', borderBottom: '2px solid var(--gold)' }} />
              {scanning && (
                <div style={{
                  position: 'absolute', left: 16, right: 16, top: '50%',
                  height: 1, background: 'var(--gold)',
                  boxShadow: '0 0 24px var(--gold)',
                  animation: 'scan 2.2s ease-in-out'
                }} />
              )}
              {result ? (
                <div style={{ padding: 32, textAlign: 'center' }}>
                  <div className="passport-status" style={{ justifyContent: 'center', marginBottom: 16 }}>
                    <span className="dot" />
                    VERIFIED · FLORACHAIN ANCHORED
                  </div>
                  <h2 style={{ fontFamily: 'var(--serif)', fontWeight: 300, fontSize: 36, margin: '8px 0' }}>{result.farm}</h2>
                  <div className="mono" style={{ fontSize: 12, opacity: 0.7 }}>{result.region}</div>
                  <div style={{ marginTop: 24, fontStyle: 'italic', fontFamily: 'var(--serif)', fontSize: 18, color: 'var(--gold-2)' }}>
                    {result.notes}
                  </div>
                  <a className="btn gold" href="verify.html" style={{ marginTop: 32 }}>Open full passport <span className="arrow">→</span></a>
                </div>
              ) : !scanning && (
                <div style={{ textAlign: 'center', opacity: 0.5 }}>
                  <div style={{ fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '0.2em', marginBottom: 12 }}>QR READY</div>
                  <div style={{ fontSize: 13, maxWidth: 240, margin: '0 auto' }}>Tap the button below to simulate a scan.</div>
                </div>
              )}
            </div>

            <button
              className="btn gold"
              style={{ marginTop: 32 }}
              onClick={onScan}
              disabled={scanning}
            >
              {scanning ? 'Reading…' : result ? 'Scan another' : 'Scan now'} <span className="arrow">→</span>
            </button>

            <div style={{ marginTop: 48, padding: 24, border: '1px solid var(--line-d)', maxWidth: 400, fontSize: 12, opacity: 0.8 }}>
              <div className="eyebrow gold" style={{ marginBottom: 8 }}>◆ NO POUCH?</div>
              Use the manual entry at <a href="verify.html" style={{ color: 'var(--gold)' }}>verify.html</a> with one of the sample batch IDs (e.g. <span className="mono">COI-240S-LD-01227</span>).
            </div>
          </div>
        </div>
      </div>
    </WSPage_>
  );
}

// ============================== LEDGER VIEWER
function LedgerPage() {
  const allRows = useMWS(() => {
    const farms = ['Suối Nhiêu Estate', 'Hoà Khê Cooperative', 'Đà Đèo Cloud Forest', 'Pleiku Ridge', 'Sông Lâm Heritage', 'Tây Nguyên'];
    const out = [];
    let block = 5234908;
    for (let i = 0; i < 30; i++) {
      const f = farms[i % farms.length];
      const id = `COI-${240 + i % 8}${'SHGMBCDLQK'[i % 10]}-${'LD,BMT,QN,KT,GL'.split(',')[i % 5]}-${String(13000 + i * 137 % 8000).padStart(5,'0')}`;
      block -= Math.floor(Math.random() * 800 + 200);
      out.push({
        id, farm: f, block,
        tx: 'flora1tx' + (Math.random().toString(36).slice(2, 10)),
        weight: (4 + Math.random() * 12).toFixed(1) + ' kg',
        time: `${24 - Math.floor(i / 4)}h ago`
      });
    }
    return out;
  }, []);

  const [search, setSearch] = useWS('');
  const filtered = allRows.filter(r => !search || r.id.toLowerCase().includes(search.toLowerCase()) || r.farm.toLowerCase().includes(search.toLowerCase()));

  return (
    <WSPage_ navDefaultDark={true}>
      <WSHero_
        num="01"
        eyebrow="PUBLIC LEDGER"
        title={<>Every batch, <em>inspectable.</em></>}
        sub="Every CỘI batch from 2019 forward is anchored to FloraChain and publicly inspectable. Search by batch ID, farm name, or block height."
      >
        <div className="crumbs"><a href="index.html">Home</a><span className="sep">/</span><span>Public ledger</span></div>
      </WSHero_>

      <section className="section dark" data-screen-label="Ledger">
        <div className="container">
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 32 }}>
            <input
              placeholder="Search batch ID, farm…"
              value={search}
              onChange={e => setSearch(e.target.value)}
              style={{
                background: 'transparent',
                border: 'none',
                borderBottom: '1px solid var(--line-d)',
                color: 'var(--paper)',
                padding: '12px 0',
                fontFamily: 'var(--mono)',
                fontSize: 14,
                width: 360,
                outline: 'none'
              }}
            />
            <div className="mono" style={{ fontSize: 11, opacity: 0.6, letterSpacing: '0.1em' }}>
              {filtered.length} of {allRows.length} entries · flora-1
            </div>
          </div>

          <table className="ledger-table">
            <thead>
              <tr>
                <th>BATCH ID</th><th>FARM</th><th>BLOCK</th><th>TX</th><th>WEIGHT</th><th>TIME</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map((r, i) => (
                <tr key={i}>
                  <td className="tx-hash">{r.id}</td>
                  <td style={{ fontFamily: 'var(--serif)', fontSize: 14 }}>{r.farm}</td>
                  <td className="ledger-block-num">#{r.block.toLocaleString()}</td>
                  <td className="blt-hash">{r.tx}…</td>
                  <td>{r.weight}</td>
                  <td style={{ opacity: 0.6 }}>{r.time}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </section>
    </WSPage_>
  );
}

window.SonWholesalePages = { WholesalePage, VerifyPage, VerifyBagPage, LedgerPage };
