/* global React, Icons, PlugBot, Wordmark */
const { useState } = React;

/* =========================================================================
   Shared atomic components
   ========================================================================= */

const Badge = ({ kind, children, dot = false }) => (
  <span className={`badge is-${kind}`}>
    {dot && <span className="pulse" />}
    {children}
  </span>
);

const Pill = ({ on, onClick, children }) => (
  <button className={`pill ${on ? 'is-on' : ''}`} onClick={onClick}>
    {children}
  </button>
);

const Btn = ({ kind = 'ghost', size, onClick, children, href, icon, iconRight }) => {
  const cls = `btn btn-${kind} ${size === 'sm' ? 'btn-sm' : ''}`;
  const inner = (
    <>
      {icon}
      {children}
      {iconRight}
    </>
  );
  if (href) return <a className={cls} href={href}>{inner}</a>;
  return <button className={cls} onClick={onClick}>{inner}</button>;
};

const Meter = ({ value, max = 100, tone = '' }) => (
  <div className={`meter ${tone}`}>
    <i style={{ width: `${(value / max) * 100}%` }} />
  </div>
);

const Score = ({ value }) => (
  <span className="score"><span className="n">{value.toFixed(1)}</span><span className="d">/ 10</span></span>
);

const Stat = ({ label, value, unit, tone }) => (
  <div>
    <div className="stat-num" style={{ color: tone === 'accent' ? 'var(--accent)' : undefined }}>
      {value}{unit && <span style={{ fontSize: 16, color: 'var(--fg-3)', marginLeft: 3 }}>{unit}</span>}
    </div>
    <div className="stat-label mt-2">{label}</div>
  </div>
);

const Eyebrow = ({ children, dot = true }) => (
  <div className="eyebrow">
    {dot && <span className="dot" />}
    {children}
  </div>
);

// LastVerified — appears on every perishable surface (plans, gear, policy).
// Pass a date string and an optional `staleAfterDays` (default 120) to flip
// the stamp into warn-mode when content drifts past the threshold.
const LastVerified = ({ date, staleAfterDays = 120, prefix = 'Last verified' }) => {
  const d = new Date(date);
  const ageDays = Number.isFinite(d.getTime())
    ? Math.floor((Date.now() - d.getTime()) / 86400000)
    : null;
  const stale = ageDays !== null && ageDays > staleAfterDays;
  return (
    <span className={`last-verified ${stale ? 'is-stale' : ''}`} title={stale ? `Stale by ${ageDays - staleAfterDays}d — pending re-verify` : ''}>
      <span className="dot" />
      {prefix} · {date}{stale ? ' · STALE' : ''}
    </span>
  );
};

/* =========================================================================
   Top navigation
   ========================================================================= */

const NAV = [
  { id: 'home',      label: 'Start' },
  { id: 'build',     label: 'Builds' },
  { id: 'gear',      label: 'Gear Lab' },
  { id: 'data',      label: 'Data' },
  { id: 'bonding',   label: 'Bonding' },
  { id: 'platforms', label: 'Platforms' },
  { id: 'safety',    label: 'Safety' },
  { id: 'streamer',  label: 'Streamers' },
  { id: 'toolkit',   label: 'Toolkit' },
  { id: 'deals',     label: 'Deals' },
];

const TopNav = ({ page, onNav }) => (
  <header className="topnav">
    <div className="container topnav-inner">
      <a onClick={() => onNav('home')} style={{ cursor: 'pointer' }}>
        <Wordmark />
      </a>
      <nav className="nav-links">
        {NAV.map((n) => (
          <a key={n.id}
             className={`nav-link ${page === n.id ? 'is-active' : ''}`}
             onClick={() => onNav(n.id)}>
            {n.label}
          </a>
        ))}
      </nav>
      <div className="nav-tools">
        {/* Search button removed for Phase 1 — search lands in Phase 2 once
            content collections exist to search over. Keeping the button
            visible without a destination would just be more dead UI. */}
        <Btn kind="primary" size="sm" onClick={() => onNav('build')}>
          Build mine
          <Icons.arrow size={14} />
        </Btn>
      </div>
    </div>
  </header>
);

/* =========================================================================
   Footer

   Every link is now honest:
   - In-site nav uses <a href="#" onClick> with preventDefault so keyboard
     focus + screen-reader semantics work; onNav is passed in from app.jsx.
   - mailto: for actionable email surfaces (Contact, early-list newsletter,
     Submit a setup).
   - Soon tag on items that don't have a destination yet — visibly tagged
     instead of silently dead.
   ========================================================================= */

const Soon = () => <span className="soon-tag" aria-label="coming soon">soon</span>;

const Footer = ({ onNav }) => {
  const link = (id) => (e) => { e.preventDefault(); onNav?.(id); };
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer-grid">
          <div>
            <Wordmark live={false} />
            <p className="text-fg3 mt-4" style={{ fontSize: 13.5, maxWidth: '32ch' }}>
              The field guide and gear lab for streamers everywhere — home studios and
              IRL rigs, tested in the real world.
            </p>
            <div className="row gap-2 mt-5">
              <Badge kind="updated">Updated Q2 · 2026</Badge>
              <Badge kind="tested" dot>Live signal</Badge>
            </div>
          </div>
          <div className="footer-col">
            <h5>Field guides</h5>
            <a href="#" onClick={link('build')}>IRL Builds</a>
            <a href="#" onClick={link('gear')}>Gear Lab</a>
            <a href="#" onClick={link('data')}>Data plans</a>
            <a href="#" onClick={link('bonding')}>Cell bonding</a>
            <a href="#" onClick={link('platforms')}>Platforms</a>
            <a href="#" onClick={link('safety')}>Safety &amp; legal</a>
          </div>
          <div className="footer-col">
            <h5>Tools</h5>
            <a href="#" onClick={link('toolkit')}>Toolkit overview</a>
            <a href="#" onClick={link('build')}>Build configurator</a>
            <a href="#" onClick={link('toolkit')}>Data usage calc</a>
            <a href="#" onClick={link('toolkit')}>Battery runtime <Soon /></a>
            <a href="#" onClick={link('toolkit')}>Bitrate calc <Soon /></a>
            <a href="#" onClick={link('toolkit')}>Stream checklist <Soon /></a>
          </div>
          <div className="footer-col">
            <h5>Community</h5>
            <a href="#" onClick={link('streamer')}>Streamer profiles</a>
            <a href="mailto:hello@livestreamers.org?subject=Submit%20my%20setup">Submit a setup</a>
            <a href="mailto:hello@livestreamers.org?subject=Newsletter%20early%20list">Newsletter <Soon /></a>
            <a href="mailto:hello@livestreamers.org?subject=Discord%20invite">Discord <Soon /></a>
            <a href="mailto:hello@livestreamers.org?subject=Editorial%20standards">Editorial standards <Soon /></a>
          </div>
          <div className="footer-col">
            <h5>Site</h5>
            <a href="mailto:hello@livestreamers.org?subject=About">About <Soon /></a>
            <a href="mailto:hello@livestreamers.org">Contact</a>
            <a href="mailto:hello@livestreamers.org?subject=Affiliate%20disclosure">Affiliate disclosure <Soon /></a>
            <a href="mailto:hello@livestreamers.org?subject=Privacy">Privacy <Soon /></a>
            <a href="mailto:hello@livestreamers.org?subject=Terms">Terms <Soon /></a>
          </div>
        </div>
        <div className="footer-bottom">
          <span>© 2026 LIVESTREAMERS.ORG — TESTED, INDEPENDENT, READER-SUPPORTED.</span>
          <span>BUILD 26.02.14 / NODE STATUS: NOMINAL</span>
        </div>
      </div>
    </footer>
  );
};

/* =========================================================================
   Live signal strip (data ticker)
   ========================================================================= */
// SignalStrip — single live data ticker across the top of the home page.
// Numbers reflect Streams Charts Q1 2026 (hours-watched basis); Twitch +4.46%
// QoQ vs TikTok Live -11.92% — narrative is no-longer-Twitch-in-decline.
const SignalStrip = () => (
  <div style={{ borderTop: '1px solid var(--line)', borderBottom: '1px solid var(--line)', background: 'var(--bg-1)' }}>
    <div className="container">
      <div className="row" style={{ height: 38, gap: 32, fontFamily: 'var(--font-mono)', fontSize: 11.5, color: 'var(--fg-3)', letterSpacing: '0.04em' }}>
        <span style={{ color: 'var(--accent)' }}>● LIVE</span>
        <span><span className="k">TWITCH Q1·26</span><span className="v good">+4.46% QoQ</span></span>
        <span><span className="k">TIKTOK LIVE Q1·26</span><span className="v warn">−11.92% QoQ</span></span>
        <span><span className="k">TWITCH MONETIZATION-FOR-ALL</span><span className="v" style={{ color: 'var(--fg)' }}>live · May 26</span></span>
        <span><span className="k">VERIFIED BUILDS</span><span className="v" style={{ color: 'var(--fg)' }}>247</span></span>
        <span><span className="k">PLANS TRACKED</span><span className="v" style={{ color: 'var(--fg)' }}>34 carriers</span></span>
        <span className="text-fg4" style={{ marginLeft: 'auto' }}>SOURCE · STREAMS CHARTS Q1 ’26</span>
      </div>
    </div>
  </div>
);

/* =========================================================================
   Mobile frame (for paired view)
   ========================================================================= */

const PhoneFrame = ({ children, page }) => (
  <div className="phone">
    <div className="phone-notch" />
    <div className="phone-statusbar">
      <span>9:41</span>
      <span style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
        <Icons.signal size={12} />
        <Icons.wifi size={12} sw={2} />
        <span style={{ fontFamily: 'var(--font-mono)' }}>78</span>
        <Icons.battery size={14} />
      </span>
    </div>
    <div className="phone-body">{children}</div>
  </div>
);

window.Badge = Badge;
window.Pill = Pill;
window.Btn = Btn;
window.Meter = Meter;
window.Score = Score;
window.Stat = Stat;
window.Eyebrow = Eyebrow;
window.LastVerified = LastVerified;
window.TopNav = TopNav;
window.Footer = Footer;
window.SignalStrip = SignalStrip;
window.PhoneFrame = PhoneFrame;
