/* global React, Icons, Badge, Btn, Pill, Meter, Score, Stat, Eyebrow */
const { useState, useMemo } = React;

/* =========================================================================
   DATA & CONNECTIVITY HUB — plan finder
   ========================================================================= */

// Plan database. Verified May 12 2026. Calyx Sprout is the sleeper —
// 501(c)(3) membership tier on T-Mo backbone, no deprioritization, $500/yr
// ≈ $42/mo. Nearly nobody publishes a clean guide to it; we lead with it.
const PLANS = [
  { id: 1, carrier: 'Calyx',   name: 'Sprout (membership · $500/yr)', price: 42, deprio: 9999, hotspot: 9999, type: 'Membership', up: '10-30',  score: 9.4, notes: 'Best-kept secret. T-Mo SIM, no deprioritization. 501(c)(3) membership.', highlight: true },
  { id: 2, carrier: 'T-Mobile',name: 'Business 5G Unlimited Adv.',    price: 70, deprio: 100,  hotspot: 50,   type: 'Post',       up: '20-100', score: 9.2, notes: 'Best uplink in mid-density US markets.' },
  { id: 3, carrier: 'Verizon', name: 'Business 5G Unlimited Plus',    price: 70, deprio: 100,  hotspot: 100,  type: 'Post',       up: '15-50',  score: 9.0, notes: 'Strong urban uplink, weak rural.' },
  { id: 4, carrier: 'US Mobile',name: 'Unlimited Premium (Warp)',     price: 50, deprio: 100,  hotspot: 50,   type: 'MVNO',       up: '10-40',  score: 8.4, notes: 'Best dollar-per-Mbps in the postpaid tier.' },
  { id: 5, carrier: 'AT&T',    name: 'Business Unl. Premium',         price: 85, deprio: 60,   hotspot: 60,   type: 'Post',       up: '10-25',  score: 7.8, notes: 'Inconsistent uplink; useful as third carrier only.' },
  { id: 6, carrier: 'Google Fi',name: 'Unlimited Plus',                price: 65, deprio: 50,   hotspot: 50,   type: 'MVNO',       up: '8-20',   score: 7.6, notes: 'Solid travel default — eSIM-clean across most countries.' },
  { id: 7, carrier: 'Visible', name: 'Plus (by Verizon)',             price: 45, deprio: 50,   hotspot: 0,    type: 'MVNO',       up: '5-15',   score: 7.4, notes: 'Cheap soft-priority; no native hotspot allotment.' },
];

const DataPage = ({ onNav }) => {
  const [usage, setUsage] = useState(120); // GB/mo
  const [travel, setTravel] = useState(false);
  const [budget, setBudget] = useState(200);

  const sorted = PLANS
    .filter(p => p.price <= budget)
    .filter(p => p.deprio >= Math.min(usage / 2, 100))
    .sort((a, b) => b.score - a.score);

  return (
    <div className="page-fade">
      {/* HEADER */}
      <section style={{ padding: '40px 0 24px', borderBottom: '1px solid var(--line)' }}>
        <div className="container">
          <div className="row between" style={{ alignItems: 'flex-end' }}>
            <div style={{ maxWidth: '70%' }}>
              <Eyebrow>Connectivity · 34 carriers tracked</Eyebrow>
              <h1 className="mt-3" style={{ fontSize: 56 }}>Data plans, decoded.</h1>
              <p className="lede mt-3" style={{ maxWidth: '60ch' }}>
                Real uplink speeds, real deprioritization thresholds. No marketing-page numbers.
                We re-test every plan quarterly and timestamp the page.
              </p>
            </div>
            <div className="col gap-2" style={{ alignItems: 'flex-end' }}>
              <div className="row gap-2">
                <Badge kind="independent">Non-affiliated rankings</Badge>
                <Badge kind="tested" dot>Live tests</Badge>
              </div>
              <LastVerified date="2026-05-12" />
            </div>
          </div>
        </div>
      </section>

      {/* FINDER */}
      <section style={{ padding: '48px 0', background: 'var(--bg-1)', borderBottom: '1px solid var(--line)' }}>
        <div className="container">
          <div style={{ display: 'grid', gridTemplateColumns: '380px 1fr', gap: 32 }}>
            <div>
              <Eyebrow>Plan finder</Eyebrow>
              <h2 className="mt-3" style={{ fontSize: 32 }}>Tell us what you stream.</h2>
              <p className="text-fg2 mt-3 fs-14">We rank the ~78 tracked plans by your actual usage envelope.</p>

              <div className="col gap-5 mt-6">
                <SliderControl label="Monthly upload" value={usage} setValue={setUsage} min={20} max={500} step={10} unit="GB" hint={`~${(usage / 30).toFixed(1)} GB/day`} />
                <SliderControl label="Monthly budget" value={budget} setValue={setBudget} min={20} max={400} step={10} unit="$" hint="combined" />
                <div>
                  <div className="row between mb-2">
                    <span className="mono fs-12 text-fg3" style={{ letterSpacing: '0.1em', textTransform: 'uppercase' }}>Travel abroad</span>
                  </div>
                  <div className="row gap-2">
                    <button className={`pill ${!travel ? 'is-on' : ''}`} onClick={() => setTravel(false)}>Domestic only</button>
                    <button className={`pill ${travel ? 'is-on' : ''}`} onClick={() => setTravel(true)}>Travel often</button>
                  </div>
                </div>
              </div>

              <div className="card card-pad mt-6" style={{ background: 'var(--bg-0)' }}>
                <Eyebrow>Recommendation</Eyebrow>
                <div className="mt-3" style={{ fontSize: 20, fontWeight: 600 }}>
                  {sorted.length === 0 ? 'No match — raise your budget' : `${sorted[0].carrier} · ${sorted[0].name}`}
                </div>
                <p className="text-fg3 fs-13 mt-2">{sorted[0]?.notes || '—'}</p>
                <div className="row gap-2 mt-4">
                  {/* Save lands with accounts in Phase 5. See-bonding-kit goes to /bonding. */}
                  <Btn kind="primary" size="sm" onClick={() => onNav?.('bonding')}>
                    See bonding kit<Icons.arrow size={12} />
                  </Btn>
                </div>
              </div>
            </div>

            <div>
              <div className="row between mb-3">
                <Eyebrow>Ranked · {sorted.length} matching</Eyebrow>
                <span className="mono fs-12 text-fg4">UPLINK SPEEDS · MEDIAN OF 18 TESTS</span>
              </div>
              <div className="col gap-2">
                {sorted.map((p, i) => (
                  <div key={p.id} className="card" style={{ padding: '14px 18px' }}>
                    <div className="row between">
                      <div className="row gap-4">
                        <div style={{
                          width: 36, height: 36, borderRadius: 4,
                          background: i === 0 ? 'var(--accent)' : 'var(--bg-3)',
                          color: i === 0 ? 'var(--accent-ink)' : 'var(--fg-3)',
                          fontFamily: 'var(--font-mono)', fontSize: 13,
                          display: 'grid', placeItems: 'center', fontWeight: 600,
                        }}>{(i + 1).toString().padStart(2, '0')}</div>
                        <div>
                          <div className="row gap-2">
                            <span style={{ fontWeight: 500 }}>{p.carrier}</span>
                            <Badge kind={p.type === 'Post' ? 'pro' : p.type === 'Membership' ? 'independent' : 'beginner'}>{p.type}</Badge>
                            {p.highlight && <Badge kind="tested" dot>Sleeper pick</Badge>}
                            {i === 0 && !p.highlight && <Badge kind="tested" dot>Top pick</Badge>}
                          </div>
                          <div className="text-fg3 fs-13 mt-1">{p.name}</div>
                        </div>
                      </div>
                      <div className="row gap-5">
                        <SmallStat label="Uplink" value={`${p.up} ↑`} mono accent />
                        <SmallStat label="Deprio" value={`${p.deprio}GB`} mono />
                        <SmallStat label="Hotspot" value={p.hotspot ? `${p.hotspot}GB` : '—'} mono />
                        <SmallStat label="Price" value={`$${p.price}`} mono big />
                        <Score value={p.score} />
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* USAGE CALCULATOR */}
      <section className="section">
        <div className="container">
          <div className="section-head">
            <div>
              <Eyebrow>Tools · Usage calculator</Eyebrow>
              <h2 className="mt-3">How much data do you actually need?</h2>
            </div>
          </div>

          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16 }}>
            {[
              { tier: '720p · 4 Mbps',  hr: 1.8,  mo: 54 },
              { tier: '1080p · 6 Mbps', hr: 2.7,  mo: 81 },
              { tier: '1080p60 · 8',    hr: 3.6,  mo: 108 },
              { tier: '1440p · 12',     hr: 5.4,  mo: 162 },
            ].map((b, i) => (
              <div key={i} className="card card-pad">
                <div className="mono fs-12 text-fg4" style={{ letterSpacing: '0.1em', textTransform: 'uppercase' }}>Tier {i + 1}</div>
                <div style={{ fontSize: 16, fontWeight: 600, marginTop: 4 }}>{b.tier}</div>
                <div className="mt-4">
                  <div className="row between mb-1"><span className="fs-12 text-fg3">Per hour</span><span className="mono">{b.hr} GB</span></div>
                  <div className="row between"><span className="fs-12 text-fg3">Per month (1h/day)</span><span className="mono text-accent">{b.mo} GB</span></div>
                </div>
                <div className="mt-3" style={{ paddingTop: 12, borderTop: '1px solid var(--line)' }}>
                  <Meter value={(b.mo / 162) * 100} tone={i >= 3 ? 'warn' : ''} />
                </div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* GUIDE GRID */}
      <section className="section" style={{ background: 'var(--bg-1)', borderTop: '1px solid var(--line)' }}>
        <div className="container">
          <div className="section-head">
            <div>
              <Eyebrow>Deep guides — coming Phase 4</Eyebrow>
              <h2 className="mt-3">When the obvious answer isn’t.</h2>
            </div>
            {/* "All connectivity guides" lands once we have an MDX content
                collection (Phase 4). For now: card list is a preview — not interactive. */}
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14 }}>
            {[
              { t: 'Deprioritization, explained', s: 'Why your stream tanks at the convention center even though you have 5 bars.', b: 'updated' },
              { t: 'Hotspot vs phone tethering', s: 'Why your dedicated hotspot can be slower than the phone in your pocket.', b: null },
              { t: 'Multi-carrier strategy', s: 'Picking 2, 3, or 4 SIMs. The diminishing-returns curve and when to stop.', b: 'tested' },
              { t: 'Travel SIM / eSIM guide', s: 'What to swap in before Tokyo, Berlin, or São Paulo. With actual upload tests.', b: 'updated' },
              { t: 'Venue & event checklist', s: 'The 8-step survey to run before you commit to a venue uplink.', b: null },
              { t: 'When your stream drops', s: 'A 4-minute recovery playbook. Print it, tape it to the inside of your pack.', b: 'beginner' },
            ].map((g, i) => (
              <div key={i} className="card card-pad" style={{ display: 'block' }}>
                <div className="row between mb-3">
                  <Eyebrow dot={false}>Guide · drafting</Eyebrow>
                  {g.b && <Badge kind={g.b}>{g.b}</Badge>}
                </div>
                <h4 style={{ fontSize: 17 }}>{g.t}</h4>
                <p className="text-fg3 fs-13 mt-2">{g.s}</p>
                <div className="row between mt-4 fs-12 mono text-fg4">
                  <span>SOON</span>
                </div>
              </div>
            ))}
          </div>
        </div>
      </section>
    </div>
  );
};

const SliderControl = ({ label, value, setValue, min, max, step, unit, hint }) => (
  <div>
    <div className="row between mb-2">
      <span className="mono fs-12 text-fg3" style={{ letterSpacing: '0.1em', textTransform: 'uppercase' }}>{label}</span>
      <span className="mono fs-13" style={{ color: 'var(--accent)' }}>{unit === '$' ? `$${value}` : `${value} ${unit}`}</span>
    </div>
    <input type="range" className="slider"
           min={min} max={max} step={step} value={value}
           onChange={e => setValue(parseFloat(e.target.value))} />
    {hint && <div className="mono fs-12 text-fg4 mt-1">{hint}</div>}
  </div>
);

const SmallStat = ({ label, value, mono, big, accent }) => (
  <div style={{ textAlign: 'right' }}>
    <div className="mono fs-12 text-fg4" style={{ letterSpacing: '0.05em' }}>{label}</div>
    <div style={{
      fontFamily: mono ? 'var(--font-mono)' : 'inherit',
      fontSize: big ? 18 : 14,
      marginTop: 2,
      color: accent ? 'var(--accent)' : 'var(--fg)',
    }}>{value}</div>
  </div>
);

window.DataPage = DataPage;
