// Graphite Ledger theme — shared across all screens
const TH = {
  bg: '#13130f',
  bg2: '#0d0d0a',
  panel: '#1c1c17',
  panelHi: '#23231d',
  ink: '#e8e4d6',
  inkSoft: '#9a9485',
  muted: '#5f5a4e',
  mutedHi: '#7a7464',
  rule: '#2a2a22',
  ruleHi: '#363630',
  accent: '#d4a84b',
  accentDim: '#8a6f2e',
  accentHi: '#e8bb5a',
  red: '#c86a5a',
  green: '#7ba15c',
  serif: '"Source Serif 4", "Source Serif Pro", Georgia, serif',
  sans: '"Inter", -apple-system, system-ui, sans-serif',
  mono: '"JetBrains Mono", ui-monospace, monospace',
};

// ── Logos ───────────────────────────────────────────────────
function Logo({ variant = 'bars', size = 24, color }) {
  const c = color || TH.accent;
  if (variant === 'bars') {
    return (
      <svg width={size} height={size} viewBox="0 0 24 24">
        <rect x="2" y="14" width="3" height="8" fill={c}/>
        <rect x="7" y="10" width="3" height="12" fill={c}/>
        <rect x="12" y="6" width="3" height="16" fill={c}/>
        <rect x="17" y="2" width="3" height="20" fill={c}/>
      </svg>
    );
  }
  if (variant === 'arrow') {
    // Forward-stepping arrow — walk-forward metaphor
    return (
      <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="2" strokeLinecap="square">
        <path d="M2 18 L8 14 L14 16 L22 4"/>
        <path d="M16 4 L22 4 L22 10"/>
      </svg>
    );
  }
  if (variant === 'w') {
    // Serif W with an underline tick
    return (
      <svg width={size} height={size} viewBox="0 0 24 24">
        <text x="2" y="17" fontFamily='"Source Serif 4", Georgia, serif' fontSize="16" fontWeight="600" fontStyle="italic" fill={c}>W</text>
        <rect x="2" y="20" width="20" height="1.5" fill={c}/>
      </svg>
    );
  }
  return null;
}

// ── Common button ───────────────────────────────────────────
function Btn({ children, onClick, primary, ghost, small, style = {}, type = 'button' }) {
  const base = {
    padding: small ? '7px 14px' : '12px 20px',
    fontFamily: TH.mono,
    fontSize: small ? 11 : 12,
    fontWeight: primary ? 700 : 500,
    textTransform: 'uppercase',
    letterSpacing: 1.2,
    border: '1px solid',
    cursor: 'pointer',
    textAlign: 'center',
    userSelect: 'none',
    transition: 'all .15s',
    display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
  };
  const styles = primary
    ? { ...base, background: TH.accent, color: TH.bg, borderColor: TH.accent, ...style }
    : ghost
    ? { ...base, background: 'transparent', color: TH.inkSoft, borderColor: TH.rule, ...style }
    : { ...base, background: 'transparent', color: TH.ink, borderColor: TH.ruleHi, ...style };
  return <button type={type} onClick={onClick} style={styles}>{children}</button>;
}

// ── Ticker strip ────────────────────────────────────────────
function Ticker() {
  const SYMBOLS = ['BTCUSDT','ETHUSDT','SOLUSDT','AVAXUSDT','ARBUSDT','LINKUSDT','DOGEUSDT'];
  const LABELS  = { BTCUSDT:'BTC', ETHUSDT:'ETH', SOLUSDT:'SOL', AVAXUSDT:'AVAX', ARBUSDT:'ARB', LINKUSDT:'LINK', DOGEUSDT:'DOGE' };
  const [ticks, setTicks] = React.useState([]);

  const fetchPrices = React.useCallback(() => {
    fetch(`https://api.binance.com/api/v3/ticker/24hr?symbols=${JSON.stringify(SYMBOLS)}`)
      .then(r => r.json())
      .then(data => setTicks(data.map(d => ({
        label: LABELS[d.symbol],
        price: parseFloat(d.lastPrice),
        pct:   parseFloat(d.priceChangePercent),
      }))))
      .catch(() => {});
  }, []);

  React.useEffect(() => {
    fetchPrices();
    const id = setInterval(fetchPrices, 10000);
    return () => clearInterval(id);
  }, [fetchPrices]);

  const fmt = (v) => v >= 1000 ? v.toLocaleString(undefined, { maximumFractionDigits: 0 })
                   : v >= 1    ? v.toFixed(2)
                   :             v.toFixed(4);

  if (!ticks.length) return (
    <div style={{ height: 37, borderBottom: `1px solid ${TH.rule}`, background: TH.panel,
                  display: 'flex', alignItems: 'center', padding: '0 18px',
                  fontFamily: TH.mono, fontSize: 11, color: TH.muted, letterSpacing: 1 }}>
      LOADING PRICES…
    </div>
  );

  return (
    <div style={{
      display: 'flex', padding: '8px 0', borderBottom: `1px solid ${TH.rule}`,
      fontFamily: TH.mono, fontSize: 11, color: TH.inkSoft, background: TH.panel,
      overflow: 'hidden', whiteSpace: 'nowrap',
    }}>
      {ticks.map((tk, i) => (
        <div key={i} style={{ padding: '0 18px', borderRight: i < ticks.length - 1 ? `1px solid ${TH.rule}` : 'none', display: 'inline-flex', gap: 8, flexShrink: 0 }}>
          <span style={{ color: TH.muted }}>{tk.label}</span>
          <span style={{ color: TH.ink }}>{fmt(tk.price)}</span>
          <span style={{ color: tk.pct >= 0 ? TH.green : TH.red }}>
            {tk.pct >= 0 ? '+' : ''}{tk.pct.toFixed(2)}%
          </span>
        </div>
      ))}
    </div>
  );
}

// ── Nav ─────────────────────────────────────────────────────
function Nav({ route, go, user, logoVariant = 'bars' }) {
  const [mobileOpen, setMobileOpen] = React.useState(false);
  const isWide = useWide();
  const items = user
    ? [['home', 'Dashboard'], ['backtester', 'Backtest'], ['videos', 'Videos'], ['telegram', 'Community']]
    : [['landing', 'Home'], ['pricing', 'Pricing'], ['videos', 'Preview']];
  return (
    <div style={{ borderBottom: `1px solid ${TH.rule}`, background: TH.bg, position: 'sticky', top: 0, zIndex: 50 }}>
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: isWide ? '14px 32px' : '14px 20px', fontFamily: TH.sans,
        maxWidth: 1480, margin: '0 auto',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, cursor: 'pointer' }} onClick={() => go(user ? 'home' : 'landing')}>
          <Logo variant={logoVariant} size={24} />
          <div style={{ fontFamily: TH.serif, fontSize: 19, fontWeight: 600, color: TH.ink, letterSpacing: -0.3 }}>
            Walkforward<span style={{ color: TH.accent }}>.</span>
          </div>
        </div>
        {isWide && (
          <div style={{ display: 'flex', gap: 28, fontSize: 12, fontFamily: TH.mono, textTransform: 'uppercase', letterSpacing: 1 }}>
            {items.map(([k, label]) => (
              <span key={k} onClick={() => go(k)} style={{
                cursor: 'pointer',
                color: route === k ? TH.accent : TH.inkSoft,
                borderBottom: route === k ? `1px solid ${TH.accent}` : '1px solid transparent',
                paddingBottom: 3,
              }}>{label}</span>
            ))}
          </div>
        )}
        <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
          {user ? (
            <>
              {isWide && <span onClick={() => go('billing')} style={{ fontSize: 12, color: TH.inkSoft, cursor: 'pointer', fontFamily: TH.mono, textTransform: 'uppercase', letterSpacing: 1 }}>Billing</span>}
              <div onClick={() => go('home')} style={{
                width: 32, height: 32, borderRadius: '50%', background: TH.panelHi,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontFamily: TH.mono, fontSize: 12, color: TH.accent, cursor: 'pointer',
                border: `1px solid ${TH.rule}`,
              }}>{(user.name || 'U')[0].toUpperCase()}</div>
            </>
          ) : (
            <>
              {isWide && <span onClick={() => go('login')} style={{ fontSize: 13, color: TH.inkSoft, cursor: 'pointer' }}>Log in</span>}
              <Btn primary small onClick={() => go('signup')}>Join →</Btn>
            </>
          )}
          {!isWide && (
            <div onClick={() => setMobileOpen(v => !v)} style={{ padding: 6, color: TH.ink, cursor: 'pointer' }}>
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <line x1="3" y1="7" x2="21" y2="7"/><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="17" x2="21" y2="17"/>
              </svg>
            </div>
          )}
        </div>
      </div>
      {!isWide && mobileOpen && (
        <div style={{ borderTop: `1px solid ${TH.rule}`, padding: '10px 20px', fontFamily: TH.mono, fontSize: 12, textTransform: 'uppercase', letterSpacing: 1 }}>
          {items.map(([k, label]) => (
            <div key={k} onClick={() => { go(k); setMobileOpen(false); }} style={{
              padding: '12px 0', color: route === k ? TH.accent : TH.inkSoft,
              borderBottom: `1px solid ${TH.rule}`, cursor: 'pointer',
            }}>{label}</div>
          ))}
          {user && (
            <div onClick={() => { go('billing'); setMobileOpen(false); }} style={{ padding: '12px 0', color: TH.inkSoft, cursor: 'pointer' }}>Billing</div>
          )}
        </div>
      )}
    </div>
  );
}

// ── Footer ──────────────────────────────────────────────────
function Footer() {
  const wide = useWide();
  return (
    <div style={{ borderTop: `1px solid ${TH.rule}`, padding: wide ? '40px 32px 28px' : '28px 20px 20px', background: TH.bg2, marginTop: 48 }}>
      <div style={{ maxWidth: 1480, margin: '0 auto' }}>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: wide ? 60 : 24, marginBottom: 28 }}>
          <div style={{ maxWidth: 260 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
              <Logo size={22}/>
              <div style={{ fontFamily: TH.serif, fontSize: 18, color: TH.ink, fontWeight: 600 }}>
                Walkforward<span style={{ color: TH.accent }}>.</span>
              </div>
            </div>
            <div style={{ fontFamily: TH.serif, fontSize: 14, color: TH.inkSoft, lineHeight: 1.55 }}>
              A journal & workbench for systematic crypto traders. Built by quants, open to anyone willing to read the data.
            </div>
          </div>
          {[
            ['Product', ['Backtester', 'Research memos', 'Video library', 'Telegram']],
            ['Company', ['Methodology', 'Changelog', 'Press', 'Contact']],
            ['Legal', ['Terms', 'Privacy', 'Risk disclosure', 'Not advice']],
          ].map(([title, links]) => (
            <div key={title}>
              <div style={{ fontFamily: TH.mono, fontSize: 10, color: TH.muted, letterSpacing: 2, marginBottom: 12 }}>{title.toUpperCase()}</div>
              {links.map(l => <div key={l} style={{ fontFamily: TH.sans, fontSize: 13, color: TH.inkSoft, padding: '4px 0', cursor: 'pointer' }}>{l}</div>)}
            </div>
          ))}
        </div>
        <div style={{ borderTop: `1px solid ${TH.rule}`, paddingTop: 16, display: 'flex', flexWrap: 'wrap', justifyContent: 'space-between', gap: 10, fontFamily: TH.mono, fontSize: 10, color: TH.muted, letterSpacing: 1.5 }}>
          <span>© 2026 WALKFORWARD RESEARCH</span>
          <span>NOT INVESTMENT ADVICE · TRADE AT YOUR OWN RISK</span>
          <span>BILLING VIA WHOP</span>
        </div>
      </div>
    </div>
  );
}

// Hook — viewport width >= 820
function useWide() {
  const [w, setW] = React.useState(typeof window !== 'undefined' ? window.innerWidth >= 820 : true);
  React.useEffect(() => {
    const h = () => setW(window.innerWidth >= 820);
    window.addEventListener('resize', h);
    return () => window.removeEventListener('resize', h);
  }, []);
  return w;
}

Object.assign(window, { TH, Logo, Btn, Ticker, Nav, Footer, useWide });
