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

/* =========================================================================
   HOMEPAGE
   ========================================================================= */

const PathPicker = ({ onPick }) => {
  const paths = [
    { id: 'home',     label: 'Home setup', sub: 'Desktop OBS · capture · multi-monitor', icon: <Icons.tool size={18} /> },
    { id: 'phone',    label: 'Phone',      sub: 'Tethered, single device',               icon: <Icons.mic size={18} /> },
    { id: 'backpack', label: 'Backpack',   sub: 'Bonded LTE, full IRL',                  icon: <Icons.backpack size={18} /> },
    { id: 'hybrid',   label: 'Hybrid',     sub: 'Desktop relay + bonded mobile',         icon: <Icons.router size={18} /> },
    { id: 'car',      label: 'Car',        sub: 'IRL on the move',                       icon: <Icons.car size={18} /> },
    { id: 'event',    label: 'Event',      sub: 'Convention / venue',                    icon: <Icons.zap size={18} /> },
    { id: 'travel',   label: 'Travel',     sub: 'Hotels, airports, abroad',              icon: <Icons.globe size={18} /> },
  ];
  const [active, setActive] = useState('home');
  const a = paths.find(p => p.id === active);
  // Recommendation copy varies by environment. Desktop / hybrid get different
  // tier suggestions than the mobile-first paths.
  const REC = {
    home:     { tier: 'Home Creator',   plat: 'Twitch + YouTube', budget: '$1,200 – $4,000', data: 'Residential gigabit' },
    phone:    { tier: 'Mobile Creator', plat: 'TikTok + Twitch',  budget: '$400 – $1,500',   data: 'Single carrier' },
    backpack: { tier: 'Pro Backpack',   plat: 'Twitch + TikTok',  budget: '$840 – $1,800',   data: 'Multi-carrier' },
    hybrid:   { tier: 'Hybrid Relay',   plat: 'Twitch + TikTok',  budget: '$2,000 – $5,000', data: 'Home + bonded mobile' },
    car:      { tier: 'Mobile Creator', plat: 'Twitch + Kick',    budget: '$1,200 – $3,000', data: 'Multi-carrier' },
    event:    { tier: 'Event Broadcast',plat: 'Twitch + YouTube', budget: '$3,000 – $6,000', data: 'Bonded + venue' },
    travel:   { tier: 'Travel IRL',     plat: 'Twitch + TikTok',  budget: '$2,000 – $4,500', data: 'eSIM + local' },
  };
  const r = REC[active] || REC.backpack;
  return (
    <div className="card card-pad-lg" style={{ background: 'var(--bg-1)' }}>
      <div className="row between mb-5">
        <div>
          <Eyebrow>Start Here · Path Selector</Eyebrow>
          <h3 className="mt-2">Where will you stream from?</h3>
        </div>
        <span className="badge is-beginner">Beginner-safe</span>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 10 }}>
        {paths.map(p => (
          <button key={p.id}
            onClick={() => setActive(p.id)}
            className="card hover"
            style={{
              textAlign: 'left',
              padding: '14px 14px',
              background: active === p.id ? 'var(--bg-3)' : 'var(--bg-2)',
              borderColor: active === p.id ? 'var(--accent)' : 'var(--line)',
              cursor: 'pointer',
              transition: 'all 120ms',
            }}>
            <div className="row between mb-2">
              <span style={{ color: active === p.id ? 'var(--accent)' : 'var(--fg-2)' }}>{p.icon}</span>
              {active === p.id && <Icons.check size={14} style={{ color: 'var(--accent)' }} />}
            </div>
            <div style={{ fontWeight: 500, fontSize: 14 }}>{p.label}</div>
            <div className="text-fg3 fs-12 mt-1">{p.sub}</div>
          </button>
        ))}
      </div>
      <div className="mt-5" style={{
        padding: '16px 18px',
        background: 'var(--bg-0)',
        border: '1px dashed var(--line-2)',
        borderRadius: 'var(--radius)',
      }}>
        <div className="row between mb-3">
          <div className="eyebrow"><span className="dot" />Recommended path · {a.label}</div>
          <span className="kbd">↵ generate</span>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 18 }}>
          <PathStat label="Build tier" value={r.tier} />
          <PathStat label="Platform" value={r.plat} />
          <PathStat label="Budget" value={r.budget} />
          <PathStat label="Data" value={r.data} />
        </div>
        <div className="row gap-2 mt-4">
          <Btn kind="primary" size="sm" onClick={onPick} iconRight={<Icons.arrow size={14} />}>
            Open this build
          </Btn>
          {/* Save as preset requires accounts — Phase 5. Hidden until then. */}
        </div>
      </div>
    </div>
  );
};
const PathStat = ({ label, value }) => (
  <div>
    <div className="stat-label">{label}</div>
    <div style={{ fontSize: 14, color: 'var(--fg)', marginTop: 4, fontWeight: 500 }}>{value}</div>
  </div>
);

const HeroDiagram = () => (
  <div style={{
    position: 'relative',
    border: '1px solid var(--line-2)',
    borderRadius: 12,
    background: 'var(--bg-1)',
    padding: 24,
    overflow: 'hidden',
  }} className="grid-bg">
    {/* corner ticks */}
    {['tl','tr','bl','br'].map(c => (
      <span key={c} style={{
        position: 'absolute',
        width: 10, height: 10,
        border: '1px solid var(--accent)',
        ...(c.includes('t') ? { top: -1 } : { bottom: -1 }),
        ...(c.includes('l') ? { left: -1, borderRight: 0 } : { right: -1, borderLeft: 0 }),
        ...(c.includes('t') ? { borderBottom: 0 } : { borderTop: 0 }),
      }} />
    ))}
    <div className="row between mb-4">
      <div className="eyebrow"><span className="dot" />Backpack Build · BP-04</div>
      <div className="mono text-fg4 fs-12">UPLINK · 12.8 Mbps · 4 carriers bonded</div>
    </div>

    {/* The diagram */}
    <div style={{ position: 'relative', minHeight: 320 }}>
      {/* central streamer */}
      <DiagramNode x={50} y={50} label="STREAMER" sub="phone @ 1080p60" big />

      {/* gear nodes */}
      <DiagramNode x={18} y={20} label="GIMBAL" sub="DJI RS 4" tone="dim" />
      <DiagramNode x={82} y={20} label="MIC" sub="Rode Wireless GO" tone="dim" />
      <DiagramNode x={12} y={75} label="POWER" sub="20K mAh × 2" tone="dim" />
      <DiagramNode x={88} y={75} label="BONDED RTR" sub="Peplink MAX BR1" tone="accent" pulse />

      {/* Connection lines (SVG) */}
      <svg style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', pointerEvents: 'none' }} viewBox="0 0 100 100" preserveAspectRatio="none">
        <defs>
          <linearGradient id="ln" x1="0" x2="1">
            <stop offset="0" stopColor="rgba(182,255,61,0)" />
            <stop offset="0.5" stopColor="rgba(182,255,61,0.6)" />
            <stop offset="1" stopColor="rgba(182,255,61,0)" />
          </linearGradient>
        </defs>
        {[[50,50,18,22],[50,50,82,22],[50,50,12,73],[50,50,88,73]].map(([x1,y1,x2,y2], i) => (
          <line key={i} x1={x1} y1={y1} x2={x2} y2={y2}
                stroke="rgba(255,255,255,0.12)" strokeWidth="0.2"
                strokeDasharray="0.6 0.4" />
        ))}
        {/* accent line (router → streamer) animated */}
        <line x1="50" y1="50" x2="88" y2="73"
              stroke="var(--accent)" strokeWidth="0.3"
              strokeDasharray="1.5 1" >
          <animate attributeName="stroke-dashoffset" from="0" to="-12" dur="2s" repeatCount="indefinite" />
        </line>
      </svg>

      {/* uplink meters in lower right */}
      <div style={{
        position: 'absolute', right: 8, bottom: 8,
        background: 'var(--bg-0)', border: '1px solid var(--line-2)',
        padding: 12, minWidth: 220, borderRadius: 6,
      }}>
        <div className="row between mb-3">
          <div className="mono fs-12 text-fg3">CARRIER LANES</div>
          <div className="mono fs-12 text-accent">12.8 ↑</div>
        </div>
        <div className="col gap-2">
          {[['VZW','LTE',92,'good'],['T-MO','5G',78,'good'],['ATT','LTE',55,'warn'],['VZW-B','LTE',28,'bad']].map(([n, b, v, t], i) => (
            <div key={i} className="row gap-2" style={{ fontFamily: 'var(--font-mono)', fontSize: 11 }}>
              <span style={{ width: 44, color: 'var(--fg-3)' }}>{n}</span>
              <span style={{ width: 30, color: 'var(--fg-4)' }}>{b}</span>
              <div style={{ flex: 1 }}><Meter value={v} tone={t === 'good' ? '' : t} /></div>
              <span className="num" style={{ width: 36, textAlign: 'right', color: 'var(--fg-2)' }}>{v}%</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  </div>
);

const DiagramNode = ({ x, y, label, sub, big = false, tone, pulse }) => (
  <div style={{
    position: 'absolute',
    left: `${x}%`, top: `${y}%`,
    transform: 'translate(-50%, -50%)',
    zIndex: 2,
    background: big ? 'var(--bg-0)' : 'var(--bg-2)',
    border: `1px solid ${tone === 'accent' ? 'var(--accent)' : 'var(--line-2)'}`,
    borderRadius: 6,
    padding: big ? '14px 16px' : '8px 12px',
    minWidth: big ? 160 : 120,
    textAlign: 'center',
    boxShadow: tone === 'accent' ? '0 0 20px var(--accent-glow)' : 'none',
  }}>
    {pulse && <span style={{
      position: 'absolute', top: -4, right: -4, width: 8, height: 8,
      background: 'var(--accent)', borderRadius: '50%',
      boxShadow: '0 0 8px var(--accent)',
      animation: 'pulse 1.6s infinite',
    }} />}
    <div style={{
      fontFamily: 'var(--font-mono)',
      fontSize: big ? 11 : 10,
      letterSpacing: '0.12em',
      color: tone === 'accent' ? 'var(--accent)' : 'var(--fg-3)',
    }}>{label}</div>
    <div style={{
      fontSize: big ? 14 : 12,
      color: 'var(--fg)',
      marginTop: 2,
    }}>{sub}</div>
  </div>
);

const CategoryCard = ({ icon, label, sub, count, badge, onClick, accent }) => (
  <button onClick={onClick} className="card hover"
    style={{
      background: 'var(--bg-1)',
      padding: '24px 22px',
      textAlign: 'left',
      cursor: 'pointer',
      display: 'flex',
      flexDirection: 'column',
      minHeight: 200,
      position: 'relative',
      overflow: 'hidden',
    }}>
    {accent && <span style={{
      position: 'absolute', inset: 0,
      background: 'radial-gradient(180px 100px at 90% 100%, var(--accent-faint), transparent)',
      pointerEvents: 'none',
    }} />}
    <div className="row between mb-5">
      <div style={{
        width: 36, height: 36, borderRadius: 6,
        display: 'grid', placeItems: 'center',
        background: 'var(--bg-3)',
        color: accent ? 'var(--accent)' : 'var(--fg-2)',
        border: '1px solid var(--line-2)',
      }}>{icon}</div>
      {badge}
    </div>
    <div style={{ marginTop: 'auto' }}>
      <div style={{ fontSize: 18, fontWeight: 600, letterSpacing: '-0.015em' }}>{label}</div>
      <div className="text-fg3 fs-13 mt-1" style={{ maxWidth: '28ch' }}>{sub}</div>
      <div className="row between mt-4">
        <span className="mono fs-12 text-fg4">{count}</span>
        <Icons.arrow size={14} style={{ color: 'var(--fg-3)' }} className="arrow" />
      </div>
    </div>
  </button>
);

const FeatureRow = ({ items }) => (
  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 0,
                border: '1px solid var(--line)', borderRadius: 10, overflow: 'hidden',
                background: 'var(--bg-1)' }}>
    {items.map((it, i) => (
      <div key={i} style={{
        padding: '24px 24px',
        borderRight: i < items.length - 1 ? '1px solid var(--line)' : 'none',
      }}>
        <div style={{ color: 'var(--accent)', marginBottom: 12 }}>{it.icon}</div>
        <div style={{ fontWeight: 600, marginBottom: 6, letterSpacing: '-0.01em' }}>{it.title}</div>
        <div className="text-fg3 fs-13">{it.sub}</div>
      </div>
    ))}
  </div>
);

const HomePage = ({ onNav }) => {
  return (
    <div className="page-fade">
      {/* HERO ============================================================= */}
      <section className="section" style={{ paddingTop: 80, paddingBottom: 80, position: 'relative' }}>
        <div className="container">
          <div style={{ display: 'grid', gridTemplateColumns: '1.05fr 1fr', gap: 64, alignItems: 'center' }}>
            <div>
              <Eyebrow>The field guide & gear lab · 2026 edition</Eyebrow>
              <h1 className="mt-4">
                Streaming,<br />
                <span style={{ color: 'var(--accent)' }}>tested</span> in the real world.
              </h1>
              <p className="lede mt-5">
                Home studios and backpack rigs. Bonded uplinks and home gigabit.
                Platform monetization, creator safety, and the gear logs to back
                every recommendation — for streamers everywhere.
              </p>
              <div className="row gap-3 mt-6">
                <Btn kind="primary" onClick={() => onNav('build')} iconRight={<Icons.arrow size={16} />}>
                  Configure my build
                </Btn>
                <Btn kind="ghost" onClick={() => onNav('bonding')}>
                  <Icons.router size={14} />
                  Compare bonding hardware
                </Btn>
              </div>
              <div className="row gap-5 mt-7">
                <Stat label="Builds tested" value="247" tone="accent" />
                <div style={{ width: 1, height: 32, background: 'var(--line)' }} />
                <Stat label="Carriers tracked" value="34" />
                <div style={{ width: 1, height: 32, background: 'var(--line)' }} />
                <Stat label="Live test hours / Q1" value="1,820" unit="h" />
              </div>
            </div>
            <HeroDiagram />
          </div>
        </div>
      </section>

      <SignalStrip />

      {/* PATH PICKER ====================================================== */}
      <section className="section">
        <div className="container">
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.2fr', gap: 64, alignItems: 'start' }}>
            <div style={{ position: 'sticky', top: 90 }}>
              <Eyebrow>01 · Start Here</Eyebrow>
              <h2 className="mt-3">
                Skip the<br/>overwhelm.<br/>
                <span style={{ color: 'var(--fg-3)' }}>Pick your environment.</span>
              </h2>
              <p className="text-fg2 mt-5" style={{ maxWidth: '34ch' }}>
                A single answer about where you'll stream from generates the right build tier,
                platform mix, budget range, and data-plan strategy. No fluff, no funnel.
              </p>
              <div className="row gap-2 mt-5 wrap">
                <Badge kind="beginner">Beginner-safe</Badge>
                <Badge kind="updated">Quarterly verified</Badge>
              </div>
            </div>
            <PathPicker onPick={() => onNav('build')} />
          </div>
        </div>
      </section>

      {/* CATEGORY GRID ==================================================== */}
      <section className="section">
        <div className="container">
          <div className="section-head">
            <div>
              <Eyebrow>02 · Field guides</Eyebrow>
              <h2 className="mt-3">Ten sections.<br/>One brain trust.</h2>
            </div>
            <Btn kind="line" onClick={() => document.querySelector('.footer')?.scrollIntoView({ behavior: 'smooth' })}>
              See the full site map<Icons.arrow size={14} />
            </Btn>
          </div>

          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14 }}>
            <CategoryCard icon={<Icons.backpack size={18} />} label="IRL Builds"
                          sub="From phone-only to pro backpack. Live BOM, wiring, runtime."
                          count="6 build tiers · BOM downloads"
                          badge={<Badge kind="tested" dot>Live</Badge>}
                          accent onClick={() => onNav('build')} />
            <CategoryCard icon={<Icons.camera size={18} />} label="Gear Lab"
                          sub="Cameras, mics, routers, bonders. Scored on IRL suitability."
                          count="184 reviewed · 12 categories"
                          badge={<Badge kind="updated">Updated</Badge>}
                          onClick={() => onNav('gear')} />
            <CategoryCard icon={<Icons.wifi size={18} />} label="Data & Connectivity"
                          sub="Best plans, deprioritization, multi-SIM, eSIM, travel."
                          count="34 carriers · 78 plans"
                          badge={<Badge kind="updated">Q2 · 26</Badge>}
                          onClick={() => onNav('data')} />
            <CategoryCard icon={<Icons.router size={18} />} label="Cell Bonding"
                          sub="LiveU vs Peplink vs Speedify. Hardware vs software."
                          count="9 systems · 2,100 test runs"
                          badge={<Badge kind="pro">Pro</Badge>}
                          onClick={() => onNav('bonding')} />
            <CategoryCard icon={<Icons.play size={18} />} label="Platform Strategy"
                          sub="Twitch, YouTube, TikTok, Kick. Monetization, vertical, clips."
                          count="6 platforms · live database"
                          onClick={() => onNav('platforms')} />
            <CategoryCard icon={<Icons.shield size={18} />} label="IRL Safety & Legal"
                          sub="Filming rights, harassment, theft, travel risk, insurance."
                          count="9 long-form guides · monthly"
                          badge={<Badge kind="independent">Independent</Badge>}
                          onClick={() => onNav('safety')} />
            <CategoryCard icon={<Icons.user size={18} />} label="Streamer Profiles"
                          sub="Real stacks, real economics. Steal-the-setup cards."
                          count="22 profiles · 4 in lab"
                          onClick={() => onNav('streamer')} />
            <CategoryCard icon={<Icons.tool size={18} />} label="Creator Toolkit"
                          sub="Calculators, checklists, AI prompt packs — affiliate-free."
                          count="9 tools · live"
                          badge={<Badge kind="independent">Independent</Badge>}
                          onClick={() => onNav('toolkit')} />
            <CategoryCard icon={<Icons.tag size={18} />} label="Deals & Buyer Guides"
                          sub="Best-of buying guides. Disclosed affiliates, ranked by use case."
                          count="32 guides · weekly deals"
                          badge={<Badge kind="deal" dot>Live deals</Badge>}
                          onClick={() => onNav('deals')} />
          </div>
        </div>
      </section>

      {/* FLAGSHIP BUILD PREVIEW ============================================ */}
      <section className="section" style={{ background: 'var(--bg-1)', borderTop: '1px solid var(--line)', borderBottom: '1px solid var(--line)' }}>
        <div className="container">
          <div className="section-head">
            <div>
              <Eyebrow>Flagship · Live tool</Eyebrow>
              <h2 className="mt-3">The Build Configurator.</h2>
              <p className="lede mt-3" style={{ maxWidth: '52ch' }}>
                Sliders, filters, live BOM. Tell us your budget, environment and platform mix —
                we return a tested gear stack with wiring, runtime, and data strategy.
              </p>
            </div>
            <Btn kind="primary" onClick={() => onNav('build')} iconRight={<Icons.arrow size={14} />}>
              Open configurator
            </Btn>
          </div>

          <FeatureRow items={[
            { icon: <Icons.tool size={20} />, title: 'Live bill of materials', sub: 'Add, swap, remove. Total updates as you tweak.' },
            { icon: <Icons.battery size={20} />, title: 'Runtime estimator', sub: 'Real draw figures from our lab logs, not specs.' },
            { icon: <Icons.wifi size={20} />, title: 'Data strategy', sub: 'Carrier mix, hotspot fallback, deprioritization model.' },
            { icon: <Icons.download size={20} />, title: 'Exportable build sheet', sub: 'PDF + Notion. Hand to a tech or to yourself.' },
          ]} />
        </div>
      </section>

      {/* MARQUEE: "as used by" =========================================== */}
      <section style={{ padding: '40px 0', borderBottom: '1px solid var(--line)' }}>
        <div className="container">
          <div className="row between mb-4">
            <Eyebrow>As tested in the wild · selected profiles</Eyebrow>
            <a className="mono fs-12 text-fg4" style={{ cursor: 'pointer' }} onClick={() => onNav('streamer')}>BROWSE PROFILES ↗</a>
          </div>
          <div className="marquee-mask">
            <div className="marquee">
              {['StreamerHouse · LA', 'Roady · Pro IRL · 4.2K avg', 'NeonRunner · Tokyo', 'Desk Studio · ATX · twin-PC',
                'Convention-Cam · 3 carriers', 'Glassblower IRL · welding rig',
                'GamerHouse Lab · home rig', 'CitySolo · Berlin handheld',
                'NorthernLights · Reykjavík home OBS', 'Cold Brewer · sim-racing IRL'].concat(
                ['StreamerHouse · LA', 'Roady · Pro IRL · 4.2K avg', 'NeonRunner · Tokyo', 'Desk Studio · ATX · twin-PC',
                'Convention-Cam · 3 carriers', 'Glassblower IRL · welding rig',
                'GamerHouse Lab · home rig', 'CitySolo · Berlin handheld',
                'NorthernLights · Reykjavík home OBS', 'Cold Brewer · sim-racing IRL']
              ).map((n, i) => (
                <span key={i} className="ticker">
                  <span className="k">▌</span>
                  <span style={{ color: 'var(--fg-2)' }}>{n}</span>
                </span>
              ))}
            </div>
          </div>
        </div>
      </section>

      {/* NEWSLETTER ====================================================== */}
      <section className="section">
        <div className="container">
          <div className="card card-pad-lg" style={{
            padding: '56px 64px',
            background: 'linear-gradient(180deg, var(--bg-1), var(--bg-0))',
            border: '1px solid var(--line-2)',
            position: 'relative', overflow: 'hidden',
          }}>
            <div style={{
              position: 'absolute', top: -100, right: -100, width: 400, height: 400,
              background: 'radial-gradient(circle, var(--accent-faint), transparent 60%)',
              pointerEvents: 'none',
            }} />
            <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: 48, alignItems: 'center' }}>
              <div>
                <Eyebrow>The weekly field log</Eyebrow>
                <h2 className="mt-3" style={{ fontSize: 36 }}>Friday signal report.</h2>
                <p className="text-fg2 mt-4" style={{ maxWidth: '46ch' }}>
                  Carrier shifts, new gear in the lab, platform changes, and one streamer
                  profile a week. No course funnels, no AI slop.
                </p>
              </div>
              <div className="col gap-3">
                <div className="row gap-2" style={{
                  border: '1px solid var(--line-2)',
                  borderRadius: 6,
                  padding: '6px 6px 6px 16px',
                  background: 'var(--bg-2)',
                }}>
                  <input placeholder="you@stream.tv" style={{
                    flex: 1, background: 'transparent', border: 0, outline: 0,
                    color: 'var(--fg)', fontSize: 14,
                  }} />
                  <Btn kind="primary" size="sm">Subscribe</Btn>
                </div>
                <div className="row gap-3 fs-12 text-fg4">
                  <span><Icons.check size={12} style={{ display: 'inline', marginRight: 4 }} />4,210 streamers</span>
                  <span><Icons.check size={12} style={{ display: 'inline', marginRight: 4 }} />Free, ad-free</span>
                  <span><Icons.check size={12} style={{ display: 'inline', marginRight: 4 }} />One-click unsub</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>
    </div>
  );
};

window.HomePage = HomePage;
