// Pages: Home, AssetDetail, Strategies, Portfolio, Settings, Onboarding

const { useState: useStateP, useEffect: useEffectP, useMemo: useMemoP, useRef: useRefP } = React;

// ============== HOME ==============
function Home({ go, account, openTicket }) {
  const VD = window.VD;
  const { ICONS, AssetGlyph } = window.VDIcons;
  const { Sparkline } = window.VDChart;
  const fmtUsd = (v) => '$' + v.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
  const upcoming0DTE = [
    { sym: 'BTC',  q: 'BTC > $96K',     price: 38, expiry: '4:00 PM ET' },
    { sym: 'ETH',  q: 'ETH > $3.4K',    price: 56, expiry: '4:00 PM ET' },
    { sym: 'SPX',  q: 'SPX > 5,900',    price: 41, expiry: '4:00 PM ET' },
    { sym: 'NVDA', q: 'NVDA > $144',    price: 47, expiry: '4:00 PM ET' },
  ];

  return (
    <div style={{ maxWidth: 1240, margin: '0 auto', padding: '0 32px 80px' }}>
      {/* Tape ticker */}
      <div className="tape" style={{ marginLeft: -32, marginRight: -32, marginBottom: 28 }}>
        <div className="tape-track">
          {[...VD.VD_ASSETS, ...VD.VD_ASSETS, ...VD.VD_ASSETS].map((a, i) => (
            <div key={i} className="tape-item">
              <span style={{ color: 'var(--text-2)', fontWeight: 600, letterSpacing: '0.05em' }}>{a.sym}</span>
              <span className="num">${a.spot.toLocaleString()}</span>
              <span className="num" style={{ color: a.change >= 0 ? 'var(--mint)' : 'var(--coral)' }}>
                {a.change >= 0 ? '▲' : '▼'} {Math.abs(a.change).toFixed(2)}%
              </span>
            </div>
          ))}
        </div>
      </div>

      {/* Account hero — editorial split layout */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr', gap: 32, padding: '8px 0 28px', borderBottom: '1px solid var(--line-subtle)', marginBottom: 32, alignItems: 'flex-end' }}>
        <div>
          <div className="cap-sm" style={{ marginBottom: 10, color: 'var(--text-3)' }}>↳ Account · 02 May 2026</div>
          <div className="serif" style={{ fontSize: 16, color: 'var(--text-2)', marginBottom: 6, fontStyle: 'italic' }}>Your venue today.</div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 14, flexWrap: 'wrap' }}>
            <span className="num" style={{ fontSize: 72, fontWeight: 500, letterSpacing: '-0.04em', lineHeight: 1 }}>{fmtUsd(account.total)}</span>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginTop: 14 }}>
            <span className="num" style={{ color: account.todayPnl >= 0 ? 'var(--mint)' : 'var(--coral)', fontSize: 14, fontWeight: 600 }}>
              {account.todayPnl >= 0 ? '+' : ''}{fmtUsd(account.todayPnl)} <span style={{ color: 'var(--text-3)' }}>·</span> {account.todayPct >= 0 ? '+' : ''}{account.todayPct.toFixed(2)}%
            </span>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, color: 'var(--text-3)', fontSize: 11 }}>
              <span className="live-dot" /> live · today
            </span>
          </div>
        </div>
        <div>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 12 }}>
            <span className="cap-sm" style={{ color: 'var(--text-3)' }}>↳ Performance</span>
            <button onClick={() => go('portfolio')} style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 10, color: 'var(--text-3)', letterSpacing: '0.14em', textTransform: 'uppercase' }} onMouseEnter={e => e.currentTarget.style.color = 'var(--acid)'} onMouseLeave={e => e.currentTarget.style.color = 'var(--text-3)'}>Portfolio →</button>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', border: '1px solid var(--line-subtle)' }}>
            <div style={{ padding: '14px 16px', borderRight: '1px solid var(--line-subtle)' }}>
              <div className="cap-sm" style={{ marginBottom: 6 }}>Open</div>
              <div className="num" style={{ fontSize: 24, fontWeight: 500, lineHeight: 1, letterSpacing: '-0.02em' }}>{account.positions}</div>
            </div>
            <div style={{ padding: '14px 16px', borderRight: '1px solid var(--line-subtle)' }}>
              <div className="cap-sm" style={{ marginBottom: 6 }}>Win rate</div>
              <div className="num" style={{ fontSize: 24, fontWeight: 500, lineHeight: 1, letterSpacing: '-0.02em' }}>{(account.winRate * 100).toFixed(1)}<span style={{ color: 'var(--text-3)', fontSize: 13, marginLeft: 1 }}>%</span></div>
            </div>
            <div style={{ padding: '14px 16px' }}>
              <div className="cap-sm" style={{ marginBottom: 6 }}>All-time</div>
              <div className="num" style={{ fontSize: 24, fontWeight: 500, color: 'var(--mint)', lineHeight: 1, letterSpacing: '-0.02em', whiteSpace: 'nowrap' }}>+${(account.allTimePnl/1000).toFixed(2)}<span style={{ color: 'var(--mint-dim)', fontSize: 13, marginLeft: 1 }}>k</span></div>
            </div>
          </div>
        </div>
      </div>

      {/* Live Hyperliquid HIP-4 outcome stream — primary action surface */}
      {window.VDLiveBlock && <window.VDLiveBlock.LiveBlock />}

      {/* Watchlist */}
      <Section title="Watchlist" cap="↳ markets you follow">
        <div className="card" style={{ overflow: 'hidden' }}>
          <div className="cap" style={{
            display: 'grid', gridTemplateColumns: '1.4fr 120px 1fr 90px 110px 90px 50px',
            padding: '12px 18px', borderBottom: '1px solid var(--line-subtle)', gap: 12,
          }}>
            <div>Asset</div><div></div><div>30d</div><div style={{textAlign:'right'}}>24h</div><div style={{textAlign:'right'}}>Spot</div><div style={{textAlign:'right'}}>IV</div><div style={{textAlign:'right'}}>Mkts</div>
          </div>
          {VD.VD_ASSETS.map((a, i) => (
            <button key={a.sym} onClick={() => go('asset', a.sym)} className="vd-row" style={{
              width:'100%', display: 'grid', gridTemplateColumns: '1.4fr 120px 1fr 90px 110px 90px 50px', padding: '12px 18px', alignItems: 'center', gap: 12,
              borderBottom: i === VD.VD_ASSETS.length - 1 ? 'none' : '1px solid var(--line-subtle)',
              transition: 'background 120ms var(--ease)', textAlign: 'left',
            }} onMouseEnter={(e) => e.currentTarget.style.background = 'var(--bg-elev-2)'} onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                <AssetGlyph sym={a.sym} size={32} animate />
                <div>
                  <div style={{ fontWeight: 600, fontSize: 14, letterSpacing: '-0.01em', display: 'flex', alignItems: 'center', gap: 6 }}>
                    {a.sym}
                    <span className="vd-rowchev" style={{ color: 'var(--acid)', fontFamily: 'JetBrains Mono, monospace', fontSize: 11 }}>→</span>
                  </div>
                  <div style={{ color: 'var(--text-3)', fontSize: 11 }}>{a.name}</div>
                </div>
              </div>
              <div style={{ color: 'var(--text-3)', fontSize: 10, textTransform:'uppercase', letterSpacing:'0.1em', fontWeight: 600, fontFamily: 'JetBrains Mono, monospace' }}>{a.kind}</div>
              <div className="vd-spark" style={{ color: a.change >= 0 ? '#6BE5C1' : '#FF5C6E' }}>
                <Sparkline data={VD.VD_SPARKS[a.sym]} width={120} height={32} color={a.change >= 0 ? '#6BE5C1' : '#FF5C6E'} />
              </div>
              <div className="num" style={{ textAlign: 'right', color: a.change >= 0 ? 'var(--mint)' : 'var(--coral)', fontSize: 13, fontWeight: 600 }}>
                {a.change >= 0 ? '+' : ''}{a.change.toFixed(2)}%
              </div>
              <div className="num" style={{ textAlign: 'right', fontSize: 14, fontWeight: 600 }}>${a.spot.toLocaleString()}</div>
              <div className="num" style={{ textAlign: 'right', color: 'var(--text-2)', fontSize: 12 }}>{a.iv.toFixed(1)}</div>
              <div className="num" style={{ textAlign: 'right', color: 'var(--text-3)', fontSize: 12 }}>{a.openMkts}</div>
            </button>
          ))}
        </div>
      </Section>

      {/* Catalysts hero + rail (full width) */}
      <div style={{ marginTop: 36 }}>
        {window.VDCatalysts && <window.VDCatalysts.CatalystsBlock go={go} openTicket={openTicket} />}
      </div>

      {/* 0DTE row */}
      <div style={{ marginTop: 32 }}>
        <Section title="Expiring today" cap="0DTE markets" tight small>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 8 }}>
            {upcoming0DTE.map((m, i) => (
              <button key={i} onClick={() => go('asset', m.sym)} className="card lift" style={{
                display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px', textAlign:'left',
              }}>
                <AssetGlyph sym={m.sym} size={28} />
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, fontWeight: 600 }}>{m.q}</div>
                  <div style={{ color: 'var(--text-3)', fontSize: 11, marginTop: 2 }}>Resolves {m.expiry}</div>
                </div>
                <div className="num" style={{ color: 'var(--mint)', fontWeight: 600, fontSize: 18, letterSpacing: '-0.02em' }}>{m.price}<span style={{fontSize: 12, color: 'var(--mint-dim)'}}>¢</span></div>
              </button>
            ))}
          </div>
        </Section>
      </div>

      {/* Leaderboard peek */}
      <div style={{ marginTop: 36 }}>
        <LeaderboardPeek />
      </div>
    </div>
  );
}

// Compact leaderboard module for Home — shows top 3, you, and weekly jackpot
function LeaderboardPeek() {
  const VD = window.VD;
  const lb = VD.VD_LEADERBOARD;
  const p = VD.VD_PLAYER;
  const top3 = lb.filter(r => r.rank <= 3);
  const around = lb.filter(r => r.rank > 3);
  return (
    <section style={{ marginTop: 12 }}>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 18, paddingBottom: 12, borderBottom: '1px solid var(--line-subtle)', gap: 16 }}>
        <h2 className="serif" style={{ fontSize: 26, fontWeight: 400, letterSpacing: '-0.025em', margin: 0, lineHeight: 1 }}>This week's board</h2>
        <span style={{ fontSize: 10, color: 'var(--text-3)', fontFamily: 'JetBrains Mono, monospace', textTransform: 'uppercase', letterSpacing: '0.12em' }}>Top 10 split ${(p.jackpot/1000).toFixed(2)}K · resets {p.jackpotResets}</span>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.4fr', gap: 14 }}>
        {/* Podium */}
        <div className="card" style={{ padding: '20px 18px', display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10, alignItems: 'end' }}>
          {[top3[1], top3[0], top3[2]].map((r, i) => {
            const heights = [78, 110, 60];
            const colors = ['var(--text-2)', 'var(--acid)', 'var(--amber)'];
            const labels = ['2', '1', '3'];
            return (
              <div key={r.rank} style={{ textAlign: 'center' }}>
                <div style={{ fontSize: 12, fontWeight: 600, marginBottom: 4 }}>{r.handle}</div>
                <div className="num" style={{ fontSize: 14, fontWeight: 600, color: 'var(--mint)', marginBottom: 8 }}>+{r.pnlPct.toFixed(1)}%</div>
                <div style={{
                  height: heights[i],
                  background: i === 1 ? 'var(--acid-bg10)' : 'var(--bg-elev-3)',
                  border: `1px solid ${colors[i]}`,
                  borderBottom: 'none',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontFamily: 'Instrument Serif, serif',
                  fontSize: 36, color: colors[i],
                  boxShadow: i === 1 ? '0 0 18px rgba(232,255,82,0.25)' : 'none',
                }}>{labels[i]}</div>
              </div>
            );
          })}
        </div>
        {/* Around-you ladder */}
        <div className="card" style={{ overflow: 'hidden' }}>
          <div className="cap" style={{ padding: '12px 18px', borderBottom: '1px solid var(--line-subtle)', display: 'grid', gridTemplateColumns: '60px 1fr 100px', gap: 12 }}>
            <div>Rank</div><div>Player</div><div style={{ textAlign: 'right' }}>Week P&L</div>
          </div>
          {around.map((r, i) => (
            <div key={r.rank} style={{
              display: 'grid', gridTemplateColumns: '60px 1fr 100px', gap: 12,
              padding: '11px 18px', alignItems: 'center',
              background: r.you ? 'var(--acid-bg10)' : 'transparent',
              borderBottom: i === around.length - 1 ? 'none' : '1px solid var(--line-subtle)',
            }}>
              <span className="num" style={{ fontSize: 12, color: r.you ? 'var(--acid)' : 'var(--text-3)', fontWeight: 600 }}>#{r.rank}</span>
              <span style={{ fontSize: 13, fontWeight: r.you ? 600 : 500, color: r.you ? 'var(--acid)' : 'var(--text)' }}>
                {r.handle}{r.you && <span style={{ marginLeft: 8, fontFamily: 'JetBrains Mono, monospace', fontSize: 9, letterSpacing: '0.12em', color: 'var(--acid-dim)' }}>YOU</span>}
              </span>
              <span className="num" style={{ textAlign: 'right', fontSize: 13, fontWeight: 600, color: 'var(--mint)' }}>+{r.pnlPct.toFixed(1)}%</span>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function Section({ title, cap, children, tight, small }) {
  const titleSize = small ? 26 : 36;
  return (
    <section style={{ marginTop: tight ? 24 : 56 }}>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 18, paddingBottom: 12, borderBottom: '1px solid var(--line-subtle)', gap: 16 }}>
        <h2 className="serif" style={{ fontSize: titleSize, fontWeight: 400, letterSpacing: '-0.025em', margin: 0, lineHeight: 1, whiteSpace: 'nowrap' }}>{title}</h2>
        {cap && <span style={{ fontSize: 10, color: 'var(--text-3)', fontFamily: 'JetBrains Mono, monospace', textTransform: 'uppercase', letterSpacing: '0.12em', textAlign: 'right', lineHeight: 1.4, whiteSpace: 'nowrap' }}>{cap}</span>}
      </div>
      {children}
    </section>
  );
}

// ============== ASSET DETAIL ==============
function AssetDetail({ sym, go, openTicket, holdings, pro }) {
  const VD = window.VD;
  const { ICONS, AssetGlyph } = window.VDIcons;
  const { SpotChart } = window.VDChart;
  const a = VD.VD_ASSETS.find(x => x.sym === sym);
  const [range, setRange] = useStateP('1D');
  const [expiryKey, setExpiryKey] = useStateP('fri');
  const [mode, setMode] = useStateP('std'); // std|pro — controlled by tweak too
  const [chainKey, setChainKey] = useStateP(0);

  // jitter the chain every 4s on asset detail only
  useEffectP(() => {
    const t = setInterval(() => setChainKey(k => k + 1), 4000);
    return () => clearInterval(t);
  }, []);

  const series = useMemoP(() => VD.vdChartSeries(sym, range), [sym, range]);
  const proActive = pro || mode === 'pro';

  return (
    <div style={{ maxWidth: 1240, margin: '0 auto', padding: '20px 32px 80px' }}>
      {/* breadcrumb back */}
      <button onClick={() => go('home')} className="btn-ghost btn" style={{ marginLeft: -8, marginBottom: 12, color: 'var(--text-3)' }}>{ICONS.back} Markets</button>

      {/* Hero */}
      <div style={{ display: 'flex', alignItems: 'flex-end', gap: 18, paddingBottom: 18, borderBottom: '1px solid var(--line-subtle)', marginBottom: 22 }}>
        <AssetGlyph sym={sym} size={52} />
        <div>
          <div className="cap-sm" style={{ marginBottom: 4 }}>{a.name} · {a.kind}</div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 14, flexWrap: 'wrap' }}>
            <span style={{ fontSize: 18, fontWeight: 600, letterSpacing: '-0.01em' }}>{a.sym}</span>
            <span className="num" style={{ fontSize: 88, fontWeight: 500, letterSpacing: '-0.045em', lineHeight: 1 }}>${a.spot.toLocaleString()}</span>
            <span className="num" style={{ color: a.change >= 0 ? 'var(--mint)' : 'var(--coral)', fontSize: 18, fontWeight: 600 }}>
              {a.change >= 0 ? '↑' : '↓'} {Math.abs(a.change).toFixed(2)}%
            </span>
          </div>
          <div className="serif" style={{ marginTop: 8, fontSize: 15, color: 'var(--text-2)', fontStyle: 'italic' }}>
            {a.openMkts} open markets · IV {a.iv.toFixed(1)}%
          </div>
        </div>
        <div style={{ flex: 1 }} />
        <button className="btn">★ Watch</button>
      </div>

      {/* Range bar */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems:'center', marginBottom: 12 }}>
        <div style={{ display: 'flex', gap: 4, padding: 3, background: 'var(--bg-elev-2)', borderRadius: 8, border: '1px solid var(--line-subtle)' }}>
          {['1H','1D','1W','1M','1Y','All'].map(r => (
            <button key={r} onClick={() => setRange(r)} style={{
              padding: '6px 14px', borderRadius: 6, fontSize: 12, fontWeight: 600,
              background: range === r ? 'var(--bg-elev-3)' : 'transparent',
              color: range === r ? 'var(--text)' : 'var(--text-3)',
              fontFamily: 'Geist Mono, monospace',
            }}>{r}</button>
          ))}
        </div>
        <div style={{ display: 'flex', gap: 16, alignItems: 'center', color: 'var(--text-3)', fontSize: 11 }}>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><span className="live-dot" /> live · Pyth aggregate</span>
        </div>
      </div>

      {/* Chart */}
      <div style={{ background: 'var(--bg-elev)', borderRadius: 12, border: '1px solid var(--line-subtle)', padding: '12px 0', marginBottom: 16 }}>
        <SpotChart series={series} color={a.change >= 0 ? '#6BE5C1' : '#FF5C6E'} range={range} height={340} />
      </div>

      {/* Stats strip */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 0, background: 'var(--bg-elev)', border: '1px solid var(--line-subtle)', borderRadius: 12, marginBottom: 28 }}>
        <Stat2 k="24h volume" v={a.vol24} />
        <Stat2 k="Implied vol" v={`${a.iv.toFixed(1)}`} u="%" />
        <Stat2 k="52w high" v={`$${a.hi52.toLocaleString()}`} />
        <Stat2 k="52w low"  v={`$${a.lo52.toLocaleString()}`} />
        <Stat2 k="Open markets" v={a.openMkts} last />
      </div>

      {/* Markets section */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 }}>
        <h2 className="h2">Event markets</h2>
        <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
          <button onClick={() => setMode(mode === 'std' ? 'pro' : 'std')} className="chip" style={{ height: 30 }}>{proActive ? 'Pro' : 'Standard'}</button>
          <button className="btn btn-primary" onClick={() => go('strategies', sym)}>{ICONS.layers} Multi-leg</button>
        </div>
      </div>

      {/* Expiry pills */}
      <div style={{ display: 'flex', gap: 8, marginBottom: 12, flexWrap: 'wrap' }}>
        {VD.VD_EXPIRIES.map(e => (
          <button key={e.key} onClick={() => setExpiryKey(e.key)} className={`chip chip-mint ${expiryKey === e.key ? 'is-active' : ''}`} style={{ height: 32, padding: '0 14px' }}>
            <span style={{ fontWeight: 600 }}>{e.label}</span>
            <span style={{ color: 'var(--text-3)', marginLeft: 4, fontSize: 11 }}>{e.sub}</span>
          </button>
        ))}
      </div>

      {/* Chain */}
      <div style={{ background: 'var(--bg-elev)', borderRadius: 12, border: '1px solid var(--line-subtle)', overflow: 'hidden' }}>
        <window.VDChain.Chain key={chainKey} sym={sym} expiryKey={expiryKey} pro={proActive} holdings={holdings}
          onCellClick={(ctx) => openTicket(ctx)} />
      </div>
    </div>
  );
}

function Stat2({ k, v, u, last }) {
  return (
    <div style={{ padding: '14px 18px', borderRight: last ? 'none' : '1px solid var(--line-subtle)' }}>
      <div className="cap-sm" style={{ marginBottom: 4 }}>{k}</div>
      <div className="num" style={{ fontSize: 16, fontWeight: 600 }}>{v}{u && <span style={{ color: 'var(--text-3)', fontSize: 12, marginLeft: 2 }}>{u}</span>}</div>
    </div>
  );
}

// ============== STRATEGIES ==============
// Robinhood-style: pick an asset, pick what you think, see the trade.
function Strategies({ initialSym }) {
  const Live    = window.VDLiveStrategy && window.VDLiveStrategy.LiveStrategyBuilder;
  const Scanner = window.VDLiveActivity && window.VDLiveActivity.MispricingScanner;
  return (
    <div style={{ maxWidth: 1240, margin: '0 auto', padding: '24px 32px 80px' }}>
      {Live && (
        <div style={{ marginBottom: 36 }}>
          <Live initialSym={initialSym} />
        </div>
      )}
      {/* Mispricing scanner — sits below the strategy builder as a "trade ideas" rail.
          Below the builder rather than above so the primary CTA leads, ideas follow. */}
      {Scanner && <Scanner />}
    </div>
  );
}

// ============== PORTFOLIO ==============
function Portfolio({ go, account, openTicket }) {
  const VD = window.VD;
  const { ICONS, AssetGlyph } = window.VDIcons;
  const [tab, setTab] = useStateP('open');
  const fmtUsd = (v) => '$' + Math.abs(v).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });

  const open = VD.VD_POSITIONS_OPEN;
  const pending = VD.VD_POSITIONS_PENDING;
  const history = VD.VD_POSITIONS_HISTORY;

  const LivePositions = window.VDLivePositions && window.VDLivePositions.PositionsPanel;
  const ActivityFeed  = window.VDLiveActivity && window.VDLiveActivity.ActivityFeed;

  return (
    <div style={{ maxWidth: 1240, margin: '0 auto', padding: '24px 32px 80px' }}>
      {/* Live HL account state — primary view of "your stuff" when wallet connects.
          Internal order is: account summary → trading stats → P&L chart → open book →
          open positions, so the open book sits above positions as the user expects. */}
      {LivePositions && (
        <div style={{ marginBottom: 32 }}>
          <LivePositions />
        </div>
      )}

      <div style={{ marginBottom: 28, paddingBottom: 20, borderBottom: '1px solid var(--line-subtle)' }}>
        <div className="cap-sm" style={{ marginBottom: 8, color: 'var(--text-3)' }}>↳ Portfolio · live ledger</div>
        <h1 className="serif" style={{ fontSize: 56, fontWeight: 400, letterSpacing: '-0.035em', margin: 0, lineHeight: 1 }}>
          Your <em style={{ color: 'var(--acid)' }}>open book</em>.
        </h1>
      </div>

      {/* 4 stats */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 0, background: 'var(--bg-elev)', border: '1px solid var(--line-subtle)', borderRadius: 12, marginBottom: 24 }}>
        <Stat2 k="Account value" v={fmtUsd(account.total)} />
        <Stat2 k="Today P&L" v={`${account.todayPnl >= 0 ? '+' : '-'}${fmtUsd(account.todayPnl)}`} />
        <Stat2 k="All-time P&L" v={`+${fmtUsd(account.allTimePnl)}`} />
        <Stat2 k="Win rate" v={`${(account.winRate * 100).toFixed(1)}`} u="%" last />
      </div>

      {/* Tabs */}
      <div style={{ display: 'flex', gap: 4, padding: 3, background: 'var(--bg-elev-2)', borderRadius: 8, border: '1px solid var(--line-subtle)', marginBottom: 16, width: 'fit-content' }}>
        {[['open',`Open · ${open.length}`],['pending',`Pending · ${pending.length}`],['history',`History · ${history.length}`]].map(([k,l]) => (
          <button key={k} onClick={() => setTab(k)} style={{
            padding: '8px 18px', borderRadius: 6, fontSize: 13, fontWeight: 600,
            background: tab === k ? 'var(--bg-elev-3)' : 'transparent',
            color: tab === k ? 'var(--text)' : 'var(--text-3)',
          }}>{l}</button>
        ))}
      </div>

      {tab === 'open' && (
        <div className="card" style={{ overflow: 'hidden' }}>
          <PosHeader />
          {open.map((p, i) => <PosRow key={p.id} p={p} last={i === open.length - 1} onClick={() => openTicket({
            sym: p.sym, side: p.side, action: 'Close', strike: p.strike, expiryKey: 'fri',
            price: p.mark, size: 5800, mid: p.mark,
            holding: { qty: p.qty, avg: p.avg }
          })} />)}
        </div>
      )}

      {tab === 'pending' && <Empty title="No pending positions" sub="Limit orders waiting to fill will show here." cta="Browse markets" onCta={() => go('home')} kind="pending" />}
      {tab === 'history' && (
        <div className="card" style={{ overflow: 'hidden' }}>
          <HistHeader />
          {history.map((p, i) => <HistRow key={p.id} p={p} last={i === history.length - 1} />)}
        </div>
      )}

      {/* Live network activity — last so it doesn't compete with your stuff */}
      {ActivityFeed && (
        <div style={{ marginTop: 32 }}>
          <ActivityFeed />
        </div>
      )}
    </div>
  );
}

function PosHeader() {
  return (
    <div className="cap" style={{ display: 'grid', gridTemplateColumns: '1.4fr 80px 110px 90px 70px 90px 90px 110px 110px', padding: '12px 18px', borderBottom: '1px solid var(--line-subtle)', gap: 10 }}>
      <div>Market</div><div>Side</div><div>Strike</div><div>Expiry</div><div style={{textAlign:'right'}}>Qty</div><div style={{textAlign:'right'}}>Avg</div><div style={{textAlign:'right'}}>Mark</div><div style={{textAlign:'right'}}>P&L</div><div style={{textAlign:'right'}}>Status</div>
    </div>
  );
}
function PosRow({ p, last, onClick }) {
  const { AssetGlyph } = window.VDIcons;
  const VD = window.VD;
  const a = VD.VD_ASSETS.find(x => x.sym === p.sym);
  return (
    <button onClick={onClick} style={{ width:'100%', display: 'grid', gridTemplateColumns: '1.4fr 80px 110px 90px 70px 90px 90px 110px 110px', padding: '14px 18px', alignItems:'center', gap: 10, borderBottom: last ? 'none' : '1px solid var(--line-subtle)', textAlign:'left', transition: 'background 120ms var(--ease)' }}
      onMouseEnter={(e) => e.currentTarget.style.background = 'var(--bg-elev-2)'} onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <AssetGlyph sym={p.sym} size={28} />
        <div>
          <div style={{ fontWeight: 600, fontSize: 13 }}>{p.sym} · {p.side} {p.strike >= 1000 ? p.strike.toLocaleString() : p.strike}</div>
          <div style={{ color: 'var(--text-3)', fontSize: 11 }}>{a.name}</div>
        </div>
      </div>
      <div><span className="cap-sm" style={{ color: p.side === 'YES' ? 'var(--mint)' : 'var(--coral)' }}>{p.side}</span></div>
      <div className="num" style={{ fontSize: 13 }}>{p.strike >= 1000 ? p.strike.toLocaleString() : p.strike}</div>
      <div className="num" style={{ fontSize: 12, color: 'var(--text-2)' }}>{p.expiry}</div>
      <div className="num" style={{ textAlign: 'right', fontSize: 13 }}>{p.qty}</div>
      <div className="num" style={{ textAlign: 'right', color: 'var(--text-2)', fontSize: 13 }}>{p.avg}¢</div>
      <div className="num" style={{ textAlign: 'right', fontSize: 13, fontWeight: 600 }}>{p.mark}¢</div>
      <div className="num" style={{ textAlign: 'right', color: p.pnl >= 0 ? 'var(--mint)' : 'var(--coral)', fontSize: 13, fontWeight: 600 }}>
        {p.pnl >= 0 ? '+' : ''}${Math.abs(p.pnl).toLocaleString()} <span style={{ color: 'var(--text-3)', fontWeight: 400 }}>· {p.pnlPct >= 0 ? '+' : ''}{p.pnlPct.toFixed(1)}%</span>
      </div>
      <div style={{ textAlign: 'right' }}>
        <span style={{ display: 'inline-flex', padding: '3px 8px', borderRadius: 4, fontSize: 10.5, fontWeight: 700, letterSpacing: '0.06em',
          background: p.status === 'ITM' ? 'var(--mint-bg10)' : 'var(--bg-elev-3)',
          color: p.status === 'ITM' ? 'var(--mint)' : 'var(--text-3)',
          border: `1px solid ${p.status === 'ITM' ? 'rgba(151,252,228,0.3)' : 'var(--line-subtle)'}`
        }}>{p.status}</span>
      </div>
    </button>
  );
}

function HistHeader() {
  return (
    <div className="cap" style={{ display: 'grid', gridTemplateColumns: '1.4fr 80px 110px 90px 70px 90px 90px 110px 90px', padding: '12px 18px', borderBottom: '1px solid var(--line-subtle)', gap: 10 }}>
      <div>Market</div><div>Side</div><div>Strike</div><div>Expiry</div><div style={{textAlign:'right'}}>Qty</div><div style={{textAlign:'right'}}>Avg</div><div style={{textAlign:'right'}}>Settle</div><div style={{textAlign:'right'}}>P&L</div><div style={{textAlign:'right'}}>Result</div>
    </div>
  );
}
function HistRow({ p, last }) {
  const { AssetGlyph } = window.VDIcons;
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 80px 110px 90px 70px 90px 90px 110px 90px', padding: '14px 18px', alignItems:'center', gap: 10, borderBottom: last ? 'none' : '1px solid var(--line-subtle)' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <AssetGlyph sym={p.sym} size={28} />
        <div style={{ fontWeight: 600, fontSize: 13 }}>{p.sym} · {p.side} {p.strike >= 1000 ? p.strike.toLocaleString() : p.strike}</div>
      </div>
      <div><span className="cap-sm" style={{ color: p.side === 'YES' ? 'var(--mint)' : 'var(--coral)' }}>{p.side}</span></div>
      <div className="num" style={{ fontSize: 13 }}>{p.strike >= 1000 ? p.strike.toLocaleString() : p.strike}</div>
      <div className="num" style={{ fontSize: 12, color: 'var(--text-2)' }}>{p.expiry}</div>
      <div className="num" style={{ textAlign: 'right', fontSize: 13 }}>{p.qty}</div>
      <div className="num" style={{ textAlign: 'right', color: 'var(--text-2)', fontSize: 13 }}>{p.avg}¢</div>
      <div className="num" style={{ textAlign: 'right', fontSize: 13, color: p.settled === 100 ? 'var(--mint)' : 'var(--coral)' }}>{p.settled}¢</div>
      <div className="num" style={{ textAlign: 'right', color: p.pnl >= 0 ? 'var(--mint)' : 'var(--coral)', fontSize: 13, fontWeight: 600 }}>
        {p.pnl >= 0 ? '+' : '-'}${Math.abs(p.pnl).toLocaleString()}
      </div>
      <div style={{ textAlign: 'right' }}>
        <span style={{ display: 'inline-flex', padding: '3px 8px', borderRadius: 4, fontSize: 10.5, fontWeight: 700, letterSpacing: '0.06em',
          background: p.status === 'WON' ? 'var(--mint-bg10)' : 'var(--coral-bg10)',
          color: p.status === 'WON' ? 'var(--mint)' : 'var(--coral)',
          border: `1px solid ${p.status === 'WON' ? 'rgba(151,252,228,0.3)' : 'rgba(237,112,136,0.3)'}`
        }}>{p.status}</span>
      </div>
    </div>
  );
}

function Empty({ title, sub, cta, onCta, kind }) {
  // SVG illustration — minimal, hairline, mint accent
  const Glyph = () => kind === 'pending' ? (
    <svg width="120" height="120" viewBox="0 0 120 120" fill="none" stroke="#3A4D55" strokeWidth="1.4">
      <circle cx="60" cy="60" r="38" />
      <path d="M60 38v22l14 9" stroke="#5FBFA8" />
      <circle cx="60" cy="60" r="2" fill="#97FCE4" stroke="none" />
    </svg>
  ) : (
    <svg width="120" height="120" viewBox="0 0 120 120" fill="none" stroke="#3A4D55" strokeWidth="1.4">
      <rect x="22" y="34" width="76" height="56" rx="6" />
      <path d="M22 50h76M36 66h32M36 76h22" />
      <circle cx="84" cy="42" r="3" fill="#97FCE4" stroke="none" />
    </svg>
  );
  return (
    <div className="card" style={{ padding: 60, display: 'flex', flexDirection:'column', alignItems: 'center', gap: 14, textAlign: 'center' }}>
      <Glyph />
      <div className="h2">{title}</div>
      <div style={{ color: 'var(--text-3)', fontSize: 13, maxWidth: 320 }}>{sub}</div>
      {cta && <button className="btn btn-primary" onClick={onCta}>{cta}</button>}
    </div>
  );
}

window.VDPages = { Home, AssetDetail, Strategies, Portfolio, Empty };
