// HOME page — second by second per brief §5
const { useState: useS_H, useEffect: useE_H } = React;

// Live API endpoint. The /v1/score lookup is @Public + rate-limited 60 rpm.
// CORS allows https://plassic.com (configured in SSM CORS_ORIGINS).
const PLASSIC_API = 'https://api.plassic.com';

function HomePage({ onNav, tweaks }) {
  const heroScore = tweaks.heroScore ?? 73;
  const headline = tweaks.headline ?? "We scanned 14,328 products this week. Here's what's in yours.";
  const dasharray = 2 * Math.PI * 130; // r=130
  const dashoffset = dasharray * (1 - heroScore / 100);

  const [scanInput, setScanInput] = useS_H('');
  const [scanResult, setScanResult] = useS_H(null);
  const [scanLoading, setScanLoading] = useS_H(false);

  const exampleProducts = [
    { brand: 'OAT MILK', sub: 'Carton · Major label · 1L', score: 94, note: 'No plastic film.' },
    { brand: 'CRUNCH BAR', sub: 'Multipack · 12 × 35g', score: 62, note: 'Foil + tray.' },
    { brand: 'MASCARA TUBE', sub: 'Drugstore brand · 8ml', score: 23, note: '7 different polymers.' },
  ];

  // Hits the live API at https://api.plassic.com/v1/score?gtin=… or
  // ?brand=…&product=…  Public, rate-limited (60 rpm). CORS-allowed for
  // https://plassic.com. Falls back to a "not found yet" card on 404.
  async function lookup(e) {
    e?.preventDefault?.();
    const q = scanInput.trim();
    if (!q) return;
    setScanLoading(true);
    setScanResult(null);

    const isGtin = /^\d{8,14}$/.test(q);
    const params = isGtin
      ? `gtin=${encodeURIComponent(q)}`
      // Single-word inputs only get a brand search; the lookup endpoint
      // requires both `brand` and `product` together, so we send the same
      // token twice and let the fuzzy matcher decide.
      : `brand=${encodeURIComponent(q)}&product=${encodeURIComponent(q)}`;

    try {
      const res = await fetch(`${PLASSIC_API}/v1/score?${params}`, {
        method: 'GET',
        headers: { Accept: 'application/json' },
      });
      const json = await res.json().catch(() => ({}));
      if (res.ok && json && (json.data?.score ?? json.score) != null) {
        const payload = json.data ?? json;
        setScanResult({
          ok: true,
          brand: (payload.brand ?? q).toUpperCase(),
          score: payload.score,
          live: true,
        });
      } else {
        // 404 SkuNotFound or any other miss → "we don't have this yet"
        setScanResult({ ok: false, brand: q.toUpperCase(), live: true });
      }
    } catch (err) {
      // Network/CORS error — show a non-scary fallback.
      setScanResult({ ok: false, brand: q.toUpperCase(), live: false });
    } finally {
      setScanLoading(false);
    }
  }

  return (
    <div className="page">
      <SmartBanner visible={tweaks.showBanner} onDismiss={() => window.parent.postMessage({type:'__edit_mode_set_keys', edits: { showBanner: false }}, '*')} />
      <DocBar onNav={onNav} crumb="HOME · 2026" />
      <Subnav page="/" onNav={onNav} />

      {/* 0–1s : BIG NUMBER */}
      {/* What Plassic actually IS — first thing on the page so a Gen Z
          visitor swiping in from TikTok knows in <2 seconds.
          Polarity (higher = cleaner) taught by concrete example, not by
          definition: 94 = good carton, 12 = Coca-Cola. Punchy by design. */}
      <section className="brand-pitch">
        <div className="mono mute" style={{ marginBottom: 10, letterSpacing: 2 }}>WHAT THIS IS</div>
        <h1 className="pitch-headline">
          Find out how much plastic is in your stuff.
        </h1>
        <p className="pitch-sub">
          Plassic gives every product you buy a 0&ndash;100 score &mdash; <strong>higher is cleaner.</strong>
          {' '}94 is oat milk in a carton. 12 is Coca-Cola. Scan the barcode, snap the label, or paste the brand. Free.
        </p>
      </section>

      <section className="hero-block">
        <div className="top-cap">
          <span>SCANNED THIS WEEK</span>
          <span>14,328</span>
        </div>
        <div className="ring-wrap">
          <svg className="ring" viewBox="0 0 280 280" aria-hidden="true">
            <circle className="bg" cx="140" cy="140" r="130" />
            <circle className="fg" cx="140" cy="140" r="130"
                    strokeDasharray={dasharray} strokeDashoffset={dashoffset}
                    style={{ transition: 'stroke-dashoffset 600ms var(--plassic-ease-out)' }} />
          </svg>
          <div className="ring-num">
            <CountUp to={heroScore} dur={600} />
          </div>
        </div>
        <div className="ring-cap">PLASSIC SCORE · {verdictFor(heroScore)}</div>
        <p className="hero-headline">{headline}</p>
      </section>

      {/* 1–3s : SCAN-IT widget */}
      <section style={{ padding: '0 20px 8px' }}>
        <div className="mono mute" style={{ marginBottom: 8 }}>SCAN A BRAND OR BARCODE</div>
        <form className="input-row" onSubmit={lookup}>
          <input
            value={scanInput}
            onChange={(e) => setScanInput(e.target.value)}
            placeholder="e.g. NESTLE or 9300605119703"
            autoComplete="off"
          />
          <button type="submit" aria-label="Look up" disabled={scanLoading}><Icon.search /></button>
        </form>
        {scanLoading && (
          <div className="mono mute" style={{ marginTop: 12, fontSize: 11, letterSpacing: 2 }}>
            LIVE · ASKING API.PLASSIC.COM…
          </div>
        )}
        {scanResult && (
          <div style={{ marginTop: 12 }}>
            {scanResult.ok ? (
              <div className={'example-card ' + bandFor(scanResult.score)}>
                <div className="swatch"><CountUp to={scanResult.score} dur={500}/></div>
                <div className="body">
                  <div className="title">{scanResult.brand}</div>
                  <div className="sub">CACHED 5 MIN · 1.4M SCANS</div>
                  <div className="verdict">{verdictFor(scanResult.score)} · TAP TO SHARE</div>
                </div>
                <button className="share-btn" aria-label="Share this score" onClick={() => onNav('/scan/' + scanResult.brand.toLowerCase().replace(/[^a-z0-9]/g, ''))}>
                  <Icon.share />
                </button>
              </div>
            ) : (
              <div style={{
                padding: '14px 16px', border: '1.5px dashed var(--plassic-jungle-950)',
                borderRadius: 16, marginTop: 4
              }}>
                <div className="mono" style={{ marginBottom: 4 }}>UNKNOWN · {scanResult.brand}</div>
                <div style={{ fontSize: 13, lineHeight: 1.4 }}>
                  We haven't scanned this yet. Open the app to add it — your scan goes into the public dataset.
                </div>
              </div>
            )}
          </div>
        )}
        <div className="mono mute" style={{ marginTop: 10, fontSize: 10 }}>
          LIVE · API.PLASSIC.COM · 5-MIN EDGE CACHE
        </div>
      </section>

      {/* 3–8s : Three example cards with share */}
      <div className="section-h" style={{ marginTop: 24 }}>
        <span>WHAT IT LOOKS LIKE</span>
        <span>3 EXAMPLES</span>
      </div>
      <div className="example-grid">
        {exampleProducts.map((p, i) => (
          <div key={i} className={'example-card ' + bandFor(p.score)}>
            <div className="swatch">{p.score}</div>
            <div className="body">
              <div className="title">{p.brand}</div>
              <div className="sub">{p.sub}</div>
              <div className="verdict">{verdictFor(p.score)} · {p.note}</div>
            </div>
            <button className="share-btn" aria-label="Share" onClick={() => onNav('/scan/' + p.brand.toLowerCase().replace(/[^a-z0-9]/g, ''))}>
              <Icon.share />
            </button>
          </div>
        ))}
      </div>

      {/* 8–15s : Install row */}
      <div className="section-h" style={{ marginTop: 32 }}>
        <span>GET THE APP</span>
        <span>FREE · NO ADS</span>
      </div>
      <section className="install-row">
        <div className="stores">
          <a className="store-btn" href="#" onClick={(e) => e.preventDefault()}>
            <Icon.apple />
            <div className="label-stack">
              <span className="small">Download on</span>
              <span className="big">App Store</span>
            </div>
          </a>
          <a className="store-btn" href="#" onClick={(e) => e.preventDefault()}>
            <Icon.android />
            <div className="label-stack">
              <span className="small">Get it on</span>
              <span className="big">Google Play</span>
            </div>
          </a>
        </div>
        <div className="sms-row">
          <div className="label">OR · TEXT THE LINK TO YOURSELF</div>
          <div className="sms-input">
            <div className="country">+61</div>
            <input type="tel" placeholder="412 345 678" />
            <button aria-label="Send link"><Icon.send /></button>
          </div>
        </div>
      </section>

      {/* 15s+ : Brand wall sneak peek */}
      <div className="section-h" style={{ marginTop: 16 }}>
        <span>WORST OF THE WEEK</span>
        <a className="mono" style={{ color: 'var(--plassic-jungle-950)', textDecoration: 'underline' }}
           href="#/wall" onClick={(e) => { e.preventDefault(); onNav('/wall'); }}>
          SEE ALL 1,200 →
        </a>
      </div>
      <div className="marquee" aria-hidden="true">
        <div className="marquee-track">
          <span>COCA-COLA · 12</span><span className="dot">·</span>
          <span>NESTLE · 19</span><span className="dot">·</span>
          <span>PEPSI · 14</span><span className="dot">·</span>
          <span>P&G · 18</span><span className="dot">·</span>
          <span>L'OREAL · 21</span><span className="dot">·</span>
          <span>UNILEVER · 26</span><span className="dot">·</span>
          {/* duplicate for seamless loop */}
          <span>COCA-COLA · 12</span><span className="dot">·</span>
          <span>NESTLE · 19</span><span className="dot">·</span>
          <span>PEPSI · 14</span><span className="dot">·</span>
          <span>P&G · 18</span><span className="dot">·</span>
          <span>L'OREAL · 21</span><span className="dot">·</span>
          <span>UNILEVER · 26</span><span className="dot">·</span>
        </div>
      </div>

      {/* email row (only if not installed) */}
      <div className="section-h" style={{ marginTop: 32 }}>
        <span>NOT READY TO INSTALL?</span>
        <span>WE'LL EMAIL ONCE</span>
      </div>
      <section style={{ padding: '0 20px 0' }}>
        <form className="input-row" onSubmit={(e) => e.preventDefault()}>
          <input type="email" placeholder="you@example.com" />
          <button type="submit" aria-label="Subscribe"><Icon.arrow /></button>
        </form>
        <div className="mono mute" style={{ marginTop: 8, fontSize: 10 }}>
          ONE EMAIL · WHEN APP HITS YOUR APP STORE · NO LIST · NO CRM
        </div>
      </section>

      <Foot onNav={onNav} />
    </div>
  );
}

window.HomePage = HomePage;
