// Desktop shell — sidebar, topbar, and desktop variants of major screens
function DesktopApp() {
  const { route } = useApp();

  // Auth screens get split-side layout
  if (['splash','register','login'].includes(route)) {
    return <DesktopAuth />;
  }

  return (
    <div className="desktop-app">
      <DesktopSidebar />
      <div style={{ minWidth: 0 }}>
        <DesktopTopbar />
        <div className="desktop-content">
          <DesktopRoute />
        </div>
        <DesktopFooterToggle />
      </div>
    </div>
  );
}

function DesktopSidebar() {
  const { route, go, user, logout, setView } = useApp();
  const items = [
    { id: 'dashboard', label: 'Dashboard', icon: 'home' },
    { id: 'accounts', label: 'Accounts', icon: 'chart' },
    { id: 'deposit', label: 'Deposit', icon: 'arrowDown' },
    { id: 'withdraw', label: 'Withdraw', icon: 'arrowUp' },
    { id: 'transfer', label: 'Transfer', icon: 'swap' },
    { id: 'history', label: 'Transactions', icon: 'wallet' },
    { id: 'promotions', label: 'Promotions', icon: 'gift' },
  ];
  const settings = [
    { id: 'profile', label: 'Profile', icon: 'user' },
    { id: 'security', label: 'Security', icon: 'shield' },
  ];
  const isActive = id => route === id || (id === 'accounts' && ['account','newAccount'].includes(route)) || (id === 'profile' && route === 'settings');

  return (
    <aside className="sidebar">
      <div className="sidebar-brand"><Logo /></div>
      <button className="topbar-cta" onClick={() => alert('AI WebTrader would open in a new tab.')} style={{ width: '100%', height: 44, justifyContent: 'center', marginBottom: 12 }}>
        <I.trade size={18} /> Open WebTrader <I.external size={14} />
      </button>

      <div className="sidebar-section">Main</div>
      {items.map(it => (
        <div key={it.id} className={'nav-item ' + (isActive(it.id) ? 'active' : '')} onClick={() => go(it.id)}>
          {I[it.icon]({ size: 18 })}
          <span>{it.label}</span>
          {isActive(it.id) && <span className="nav-dot"></span>}
        </div>
      ))}

      <div className="sidebar-section">Account</div>
      {settings.map(it => (
        <div key={it.id} className={'nav-item ' + (isActive(it.id) ? 'active' : '')} onClick={() => go(it.id)}>
          {I[it.icon]({ size: 18 })}
          <span>{it.label}</span>
        </div>
      ))}
      <div className="nav-item" onClick={() => { logout(); go('splash'); }}>
        <I.logout size={18} /><span>Sign out</span>
      </div>

      <div style={{ marginTop: 'auto' }}>
        <div className="view-toggle" onClick={() => setView('mobile')}>
          <I.phone size={14} style={{ verticalAlign: 'middle', marginRight: 6 }} />
          View mobile version
        </div>
      </div>
    </aside>
  );
}

function DesktopTopbar() {
  const { go, totalEquity, user } = useApp();
  return (
    <div className="topbar">
      <div className="topbar-search">
        <I.search size={16} />
        <input placeholder="Search markets, accounts, transactions…" />
        <span className="mono" style={{ fontSize: 11, color: 'var(--text-faint)', padding: '2px 6px', border: '1px solid var(--line)', borderRadius: 6 }}>⌘K</span>
      </div>
      <div className="topbar-actions">
        <div className="topbar-pill">
          <span style={{ color: 'var(--text-dim)', fontSize: 12 }}>Total equity</span>
          <span className="mono" style={{ fontWeight: 600 }}>${totalEquity.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span>
        </div>
        <button className="topbar-cta" onClick={() => go('deposit')}>
          <I.plus size={16} /> Deposit
        </button>
        <button className="topbar-pill" style={{ width: 40, padding: 0, justifyContent: 'center' }}><I.bell size={16} /></button>
        <ThemeToggle variant="pill" />
        <div onClick={() => go('profile')} style={{ width: 40, height: 40, borderRadius: '50%', background: 'linear-gradient(135deg, var(--green), var(--cyan))', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#0A0B0D', fontWeight: 700, fontSize: 13, cursor: 'pointer' }}>
          {user.name.split(' ').map(s => s[0]).slice(0,2).join('')}
        </div>
      </div>
    </div>
  );
}

function DesktopFooterToggle() {
  return (
    <div className="desktop-footer-toggle">
      AITrader v1.0 · CFDs are complex instruments with high risk of losing money.
    </div>
  );
}

function DesktopRoute() {
  const { route } = useApp();
  switch (route) {
    case 'dashboard': return <DesktopDashboard />;
    case 'accounts': return <DesktopAccounts />;
    case 'account': return <DesktopAccountDetail />;
    case 'newAccount': return <DesktopNewAccount />;
    case 'deposit': return <DesktopDeposit />;
    case 'withdraw': return <DesktopWithdraw />;
    case 'transfer': return <DesktopTransfer />;
    case 'history': return <DesktopHistory />;
    case 'promotions': return <DesktopPromotions />;
    case 'profile': return <DesktopProfile />;
    case 'settings': return <DesktopSettings />;
    case 'security': return <DesktopSecurity />;
    default: return <DesktopDashboard />;
  }
}

// === Desktop Auth ===
function DesktopAuth() {
  const { route, setView } = useApp();
  return (
    <div className="auth-desktop">
      <div className="auth-desktop-side">
        <div className="auth-bg">
          <div className="blob blob-1"></div>
          <div className="blob blob-2"></div>
          <div className="blob blob-3"></div>
        </div>
        <div style={{ position: 'relative', zIndex: 1 }}>
          <Logo size="lg" />
        </div>
        <div style={{ position: 'relative', zIndex: 1 }}>
          <h1 style={{ fontSize: 56, fontWeight: 700, letterSpacing: '-0.03em', lineHeight: 1.05, margin: '0 0 18px' }}>
            Trade everything.<br/>
            <span style={{ background: 'linear-gradient(135deg, var(--green), var(--cyan))', WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent', backgroundClip: 'text' }}>Settled in crypto.</span>
          </h1>
          <p style={{ color: 'var(--text-dim)', fontSize: 17, lineHeight: 1.6, maxWidth: 460, margin: '0 0 36px' }}>
            Forex, indices, stocks and crypto CFDs. Fund instantly with BTC, ETH or USDT — no paperwork, no waiting.
          </p>
          <div style={{ display: 'flex', gap: 32 }}>
            <DStat n="180+" l="Markets" />
            <DStat n="1:500" l="Leverage" />
            <DStat n="0.0s" l="KYC" />
            <DStat n="24/7" l="Crypto deposits" />
          </div>
        </div>
        <div style={{ position: 'relative', zIndex: 1, fontSize: 12, color: 'var(--text-faint)' }}>
          AITrader v1.0 · CFDs carry high risk
        </div>
      </div>
      <div className="auth-desktop-form">
        {route === 'splash' && <DesktopSplash />}
        {route === 'register' && <Register />}
        {route === 'login' && <Login />}
        <div style={{ textAlign: 'center', marginTop: 32, fontSize: 12, color: 'var(--text-dim)' }}>
          <a onClick={() => setView('mobile')} style={{ color: 'var(--green)', cursor: 'pointer' }}>View mobile version</a>
        </div>
      </div>
    </div>
  );
}

function BigStat({ label, value, pct, up }) {
  return (
    <div style={{ background: 'var(--card)', border: '1px solid var(--line)', borderRadius: 12, padding: 14 }}>
      <div style={{ fontSize: 11, color: 'var(--text-dim)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 500 }}>{label}</div>
      <div className="mono" style={{ fontSize: 20, fontWeight: 600, marginTop: 6, color: up ? 'var(--green)' : 'var(--red)' }}>{value}</div>
      <div className="mono" style={{ fontSize: 11, color: 'var(--text-dim)', marginTop: 2 }}>{pct}</div>
    </div>
  );
}

function AccountSnapshot({ acc, onClick }) {
  const change = (Math.random() * 200 - 50);
  const pct = (change / acc.balance) * 100;
  const up = change >= 0;
  return (
    <button onClick={onClick} style={{ background: 'var(--card)', border: '1px solid var(--line)', borderRadius: 12, padding: 14, cursor: 'pointer', textAlign: 'left', color: 'var(--text)', fontFamily: 'inherit' }}>
      <div className="between">
        <span className="pill pill-green">Live · {acc.kind}</span>
        <span className="mono" style={{ fontSize: 11, color: 'var(--text-dim)' }}>#{acc.number}</span>
      </div>
      <div className="mono" style={{ fontSize: 22, fontWeight: 600, marginTop: 10 }}>${acc.balance.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</div>
      <div className="mono" style={{ fontSize: 12, fontWeight: 600, color: up ? 'var(--green)' : 'var(--red)', marginTop: 2 }}>
        {up ? '▲ +' : '▼ '}${Math.abs(change).toFixed(2)} · {pct.toFixed(2)}% today
      </div>
    </button>
  );
}

function DStat({ n, l }) {
  return (
    <div className="col">
      <div className="mono" style={{ fontSize: 26, fontWeight: 600 }}>{n}</div>
      <div style={{ fontSize: 11, color: 'var(--text-dim)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>{l}</div>
    </div>
  );
}

function DStatInline({ n, l, up }) {
  return (
    <div className="col">
      <div className="mono" style={{ fontSize: 16, fontWeight: 600, color: up ? 'var(--green)' : 'var(--red)' }}>{n}</div>
      <div style={{ fontSize: 10, color: 'var(--text-dim)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>{l}</div>
    </div>
  );
}

function MarketTile({ sym, price, pct }) {
  const up = pct >= 0;
  return (
    <button onClick={() => alert('AI WebTrader would open ' + sym)} style={{ background: 'var(--card)', border: '1px solid var(--line)', borderRadius: 12, padding: 12, cursor: 'pointer', textAlign: 'left', color: 'var(--text)', fontFamily: 'inherit' }}>
      <div style={{ fontSize: 11, color: 'var(--text-dim)', fontWeight: 500 }}>{sym}</div>
      <div className="mono" style={{ fontSize: 14, fontWeight: 600, marginTop: 4 }}>{price}</div>
      <div className="mono" style={{ fontSize: 11, fontWeight: 600, color: up ? 'var(--green)' : 'var(--red)', marginTop: 2 }}>{up ? '+' : ''}{pct.toFixed(2)}%</div>
    </button>
  );
}

function DesktopSplash() {
  const { go } = useApp();
  return (
    <div>
      <h2 style={{ fontSize: 32, margin: '0 0 8px', fontWeight: 700, letterSpacing: '-0.02em' }}>Welcome to AITrader</h2>
      <p style={{ color: 'var(--text-dim)', fontSize: 15, margin: '0 0 32px' }}>Crypto-funded trading for forex, indices, stocks and crypto CFDs.</p>
      <div className="stack" style={{ gap: 12 }}>
        <button className="btn btn-primary" onClick={() => go('register')}>Create account</button>
        <button className="btn btn-secondary" onClick={() => go('login')}>Sign in</button>
      </div>
    </div>
  );
}

// === Desktop Dashboard ===
function DesktopDashboard() {
  const { go, accounts, totalEquity, txns, user } = useApp();
  return (
    <div>
      <div className="between" style={{ marginBottom: 24 }}>
        <div>
          <h1 className="desktop-h1">Welcome back, {user.name.split(' ')[0]}</h1>
          <p className="desktop-sub">Here's what's moving in your portfolio today.</p>
        </div>
        <div className="row" style={{ gap: 8 }}>
          <button className="btn btn-secondary btn-sm" onClick={() => go('transfer')} style={{ width: 'auto', padding: '0 18px' }}><I.swap size={16}/> Transfer</button>
          <button className="btn btn-secondary btn-sm" onClick={() => go('withdraw')} style={{ width: 'auto', padding: '0 18px' }}><I.arrowUp size={16}/> Withdraw</button>
          <button className="btn btn-primary btn-sm" onClick={() => go('deposit')} style={{ width: 'auto', padding: '0 22px' }}><I.arrowDown size={16}/> Deposit</button>
        </div>
      </div>

      <div className="grid-12">
        <div>
          <div className="card" style={{ padding: 24, background: 'linear-gradient(135deg, rgba(166,255,61,0.10), rgba(77,224,255,0.06))', borderColor: 'color-mix(in oklab, var(--green) 20%, transparent)', position: 'relative', overflow: 'hidden' }}>
            <div style={{ position: 'absolute', top: -80, right: -80, width: 240, height: 240, borderRadius: '50%', background: 'radial-gradient(circle, rgba(166,255,61,0.2), transparent 70%)' }}></div>
            <div className="between" style={{ position: 'relative' }}>
              <div>
                <div style={{ fontSize: 12, color: 'var(--text-dim)', textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 500 }}>Total equity · USD</div>
                <div className="mono" style={{ fontSize: 48, fontWeight: 600, letterSpacing: '-0.02em', marginTop: 6 }}>${totalEquity.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</div>
                <div className="row" style={{ gap: 10, marginTop: 8 }}>
                  <span className="pill pill-green mono">▲ $482.14 · 2.31%</span>
                  <span style={{ color: 'var(--text-dim)', fontSize: 13 }}>Today</span>
                </div>
              </div>
            </div>
            <div style={{ marginTop: 24, display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12, position: 'relative' }}>
              <BigStat label="Today" value="+$482.14" pct="+2.31%" up />
              <BigStat label="This week" value="+$1,284.50" pct="+6.42%" up />
              <BigStat label="This month" value="+$1,842.50" pct="+9.81%" up />
              <BigStat label="All-time" value="+$3,420.10" pct="+18.20%" up />
            </div>
          </div>

          <div className="between" style={{ marginTop: 28, marginBottom: 12 }}>
            <h3 style={{ fontSize: 18, margin: 0, fontWeight: 600 }}>Open positions</h3>
            <span className="pill pill-green">3 live</span>
          </div>
          <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
            <table className="data-table">
              <thead>
                <tr><th>Symbol</th><th>Side</th><th>Size</th><th>Entry</th><th>Current</th><th style={{ textAlign: 'right' }}>P/L</th></tr>
              </thead>
              <tbody>
                <DTPos symbol="BTC/USD" side="BUY" size={0.42} entry={68420} current={69180} pnl={319.20} />
                <DTPos symbol="EUR/USD" side="SELL" size={2.5} entry={1.0842} current={1.0828} pnl={35.00} />
                <DTPos symbol="NAS100" side="BUY" size={1} entry={19840} current={19792} pnl={-48.00} />
              </tbody>
            </table>
          </div>

          <div className="between" style={{ marginTop: 28, marginBottom: 12 }}>
            <h3 style={{ fontSize: 18, margin: 0, fontWeight: 600 }}>Recent activity</h3>
            <a onClick={() => go('history')} style={{ fontSize: 13, color: 'var(--green)', cursor: 'pointer', fontWeight: 500 }}>View all transactions →</a>
          </div>
          <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
            <table className="data-table">
              <thead><tr><th>Type</th><th>Description</th><th>Date</th><th>Status</th><th style={{ textAlign: 'right' }}>Amount</th></tr></thead>
              <tbody>
                {txns.slice(0,6).map(tx => <DTTx key={tx.id} tx={tx} />)}
              </tbody>
            </table>
          </div>
        </div>

        <div>
          <div className="card" style={{ padding: 18 }}>
            <div className="between" style={{ marginBottom: 14 }}>
              <h3 style={{ fontSize: 14, margin: 0, fontWeight: 600 }}>Margin & risk</h3>
              <span className="pill pill-green">Healthy</span>
            </div>
            <RiskGauge used={18} />
            <div className="stack" style={{ gap: 10, marginTop: 16 }}>
              <KV k="Used margin" v="$3,820.00" />
              <KV k="Free margin" v="$16,872.13" up />
              <KV k="Margin level" v="847.20%" />
              <KV k="Open positions" v="3" />
              <KV k="Max drawdown · 30d" v="−4.20%" />
            </div>
            <div style={{ fontSize: 11, color: 'var(--text-dim)', marginTop: 14, lineHeight: 1.5, paddingTop: 12, borderTop: '1px solid var(--line-2)' }}>
              You're using 18% of available margin. Stop-out triggers at 50% margin level.
            </div>
          </div>

          <div className="between" style={{ marginTop: 20, marginBottom: 12 }}>
            <h3 style={{ fontSize: 14, margin: 0, fontWeight: 600 }}>Trading accounts</h3>
            <a onClick={() => go('accounts')} style={{ fontSize: 12, color: 'var(--green)', cursor: 'pointer' }}>All →</a>
          </div>
          <div className="stack" style={{ gap: 10 }}>
            {accounts.map(a => <DesktopMiniAccount key={a.id} acc={a} />)}
            <button className="card" onClick={() => go('newAccount')} style={{ border: '1px dashed var(--line)', background: 'transparent', padding: 14, color: 'var(--text-dim)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8 }}>
              <I.plus size={16} /> Open new account
            </button>
          </div>

          <div className="card" style={{ marginTop: 20, padding: 18 }}>
            <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 12 }}>Performance · 30d</div>
            <div className="stack" style={{ gap: 10 }}>
              <KV k="P/L" v="+$1,842.50" up />
              <KV k="Win rate" v="62.4%" />
              <KV k="Trades" v="148" />
              <KV k="Best trade" v="+$420.10" up />
              <KV k="Worst trade" v="−$185.30" down />
              <KV k="Avg. hold" v="3h 24m" />
            </div>
          </div>

          <div className="card" style={{ marginTop: 20, padding: 18 }}>
            <div className="between" style={{ marginBottom: 12 }}>
              <div style={{ fontSize: 14, fontWeight: 600 }}>Market news</div>
              <a style={{ fontSize: 12, color: 'var(--green)', cursor: 'pointer' }}>More</a>
            </div>
            <div className="stack" style={{ gap: 12 }}>
              <NewsItem cat="Crypto" t="Bitcoin breaks $69k as ETF inflows hit weekly high" time="12m" />
              <NewsItem cat="FX" t="Dollar index slips ahead of Fed minutes release" time="48m" />
              <NewsItem cat="Stocks" t="Tesla rallies on autonomous robotaxi rumors" time="2h" />
              <NewsItem cat="Commodities" t="Gold steadies near $2,345 amid weaker dollar" time="3h" />
            </div>
          </div>

          <div className="card" style={{ marginTop: 20, padding: 20, background: 'linear-gradient(135deg, rgba(166,255,61,0.12), rgba(255,77,210,0.08))', borderColor: 'transparent', position: 'relative', overflow: 'hidden' }}>
            <span className="pill pill-green">Limited time</span>
            <div style={{ fontSize: 16, fontWeight: 600, marginTop: 12 }}>2× your first deposit</div>
            <div style={{ fontSize: 12, color: 'var(--text-dim)', marginTop: 4 }}>Match up to $5,000 in bonus margin.</div>
            <button className="btn btn-primary btn-sm" onClick={() => go('promotions')} style={{ marginTop: 14 }}>Claim now</button>
          </div>

          <div className="card" style={{ marginTop: 20, padding: 18 }}>
            <div className="between" style={{ marginBottom: 12 }}>
              <div style={{ fontSize: 14, fontWeight: 600 }}>Refer & earn</div>
              <span className="pill pill-green">$120 / referral</span>
            </div>
            <div className="row" style={{ gap: 10 }}>
              <Stat n="3" l="Referred" small />
              <Stat n="$360" l="Earned" small />
              <Stat n="$80" l="Pending" small />
            </div>
            <div className="mono" style={{ background: 'var(--card-2)', border: '1px solid var(--line)', borderRadius: 10, padding: '10px 12px', fontSize: 12, marginTop: 12, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <span>aitrader.io/r/jane8420</span>
              <I.copy size={14} />
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function Spark({ data, up }) {
  const w = 56, h = 22;
  const max = Math.max(...data), min = Math.min(...data);
  const r = max - min || 1;
  const pts = data.map((v, i) => `${(i / (data.length - 1)) * w},${h - ((v - min) / r) * h}`).join(' ');
  return (
    <svg width={w} height={h} style={{ flexShrink: 0 }}>
      <polyline points={pts} fill="none" stroke={up ? 'var(--green)' : 'var(--red)'} strokeWidth="1.5" />
    </svg>
  );
}

function RiskGauge({ used }) {
  // Semicircle gauge — 0 to 100% margin used
  const w = 220, h = 110;
  const cx = w / 2, cy = h, r = 88;
  const angle = Math.PI * (used / 100);
  const ex = cx - r * Math.cos(angle);
  const ey = cy - r * Math.sin(angle);
  const bg = `M ${cx - r} ${cy} A ${r} ${r} 0 0 1 ${cx + r} ${cy}`;
  const fg = `M ${cx - r} ${cy} A ${r} ${r} 0 0 1 ${ex} ${ey}`;
  const color = used < 40 ? 'var(--green)' : used < 70 ? 'var(--amber)' : 'var(--red)';
  return (
    <div style={{ position: 'relative', width: '100%', display: 'flex', justifyContent: 'center' }}>
      <svg viewBox={`0 0 ${w} ${h + 4}`} width="100%" style={{ maxWidth: 220, display: 'block' }}>
        <path d={bg} fill="none" stroke="var(--line)" strokeWidth="10" strokeLinecap="round" />
        <path d={fg} fill="none" stroke={color} strokeWidth="10" strokeLinecap="round" />
      </svg>
      <div style={{ position: 'absolute', bottom: 6, left: 0, right: 0, textAlign: 'center' }}>
        <div className="mono" style={{ fontSize: 28, fontWeight: 600, lineHeight: 1 }}>{used}%</div>
        <div style={{ fontSize: 10, color: 'var(--text-dim)', textTransform: 'uppercase', letterSpacing: '0.06em', marginTop: 2 }}>Margin used</div>
      </div>
    </div>
  );
}

function KV({ k, v, up, down }) {
  return (
    <div className="between">
      <span style={{ fontSize: 12, color: 'var(--text-dim)' }}>{k}</span>
      <span className="mono" style={{ fontSize: 13, fontWeight: 600, color: up ? 'var(--green)' : down ? 'var(--red)' : 'var(--text)' }}>{v}</span>
    </div>
  );
}

function NewsItem({ cat, t, time }) {
  return (
    <div style={{ paddingBottom: 12, borderBottom: '1px solid var(--line-2)' }}>
      <div className="row" style={{ gap: 8, marginBottom: 4 }}>
        <span className="pill" style={{ background: 'var(--card-2)', color: 'var(--text-dim)', fontSize: 10 }}>{cat}</span>
        <span style={{ fontSize: 11, color: 'var(--text-faint)' }}>{time} ago</span>
      </div>
      <div style={{ fontSize: 13, lineHeight: 1.4 }}>{t}</div>
    </div>
  );
}

function Stat({ n, l, small }) {
  return (
    <div className="col" style={{ flex: 1 }}>
      <div className="mono" style={{ fontSize: small ? 18 : 22, fontWeight: 600 }}>{n}</div>
      <div style={{ fontSize: 10, color: 'var(--text-dim)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>{l}</div>
    </div>
  );
}

function DTPos({ symbol, side, size, entry, current, pnl }) {
  const up = pnl >= 0;
  return (
    <tr>
      <td><span style={{ fontWeight: 600 }}>{symbol}</span></td>
      <td><span className={'pill ' + (side === 'BUY' ? 'pill-green' : 'pill-red')}>{side}</span></td>
      <td className="mono">{size}</td>
      <td className="mono">{entry}</td>
      <td className="mono">{current}</td>
      <td className="mono" style={{ textAlign: 'right', fontWeight: 600, color: up ? 'var(--green)' : 'var(--red)' }}>{up ? '+' : ''}${pnl.toFixed(2)}</td>
    </tr>
  );
}

function DTTx({ tx }) {
  const up = tx.amount >= 0;
  const iconMap = { deposit: 'arrowDown', withdraw: 'arrowUp', transfer: 'swap', bonus: 'gift', trade: 'chart' };
  return (
    <tr>
      <td>
        <div className="row" style={{ gap: 10 }}>
          <div style={{ width: 30, height: 30, borderRadius: 8, background: 'var(--card-2)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--text-dim)' }}>
            {I[iconMap[tx.type] || 'swap']({ size: 14 })}
          </div>
          <span style={{ textTransform: 'capitalize' }}>{tx.type}</span>
        </div>
      </td>
      <td>{tx.label}</td>
      <td className="mono" style={{ color: 'var(--text-dim)' }}>{tx.date}</td>
      <td><span className={'pill ' + (tx.status === 'pending' ? 'pill-amber' : tx.status === 'failed' ? 'pill-red' : 'pill-green')}>{tx.status}</span></td>
      <td className="mono" style={{ textAlign: 'right', fontWeight: 600, color: up ? 'var(--green)' : 'var(--text)' }}>{up ? '+' : ''}${Math.abs(tx.amount).toFixed(2)}</td>
    </tr>
  );
}

function DesktopMiniAccount({ acc }) {
  const { go } = useApp();
  const isDemo = acc.type === 'demo';
  return (
    <button onClick={() => go('account', { id: acc.id })} className="card" style={{ padding: 16, textAlign: 'left', cursor: 'pointer', color: 'var(--text)', width: '100%' }}>
      <div className="between">
        <span className={'pill ' + (isDemo ? 'pill-demo' : 'pill-green')}>{isDemo ? 'Demo' : 'Live'} · {acc.platform}</span>
        <I.chevR size={14} />
      </div>
      <div className="mono" style={{ fontSize: 11, color: 'var(--text-dim)', marginTop: 8 }}>#{acc.number}</div>
      <div className="mono" style={{ fontSize: 22, fontWeight: 600, marginTop: 2 }}>${acc.balance.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</div>
      <div style={{ fontSize: 11, color: 'var(--text-dim)' }}>{acc.kind} · {acc.leverage}</div>
    </button>
  );
}

// === Desktop Accounts ===
function DesktopAccounts() {
  const { go, accounts } = useApp();
  return (
    <div>
      <div className="between" style={{ marginBottom: 24 }}>
        <div>
          <h1 className="desktop-h1">Trading accounts</h1>
          <p className="desktop-sub">Live and demo trading accounts on AI WebTrader.</p>
        </div>
        <button className="btn btn-primary btn-sm" onClick={() => go('newAccount')} style={{ width: 'auto', padding: '0 22px' }}><I.plus size={16}/> Open new account</button>
      </div>
      <div className="grid-cols-3">
        {accounts.map(a => <AccountCard key={a.id} acc={a} onClick={() => go('account', { id: a.id })} />)}
        <button className="card" onClick={() => go('newAccount')} style={{ border: '1px dashed var(--line)', background: 'transparent', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 8, padding: 24, cursor: 'pointer', color: 'var(--text-dim)', minHeight: 180 }}>
          <div style={{ width: 44, height: 44, borderRadius: 14, background: 'var(--card)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><I.plus /></div>
          <span style={{ fontSize: 14, fontWeight: 500, color: 'var(--text)' }}>Open new account</span>
          <span style={{ fontSize: 12 }}>Live or demo</span>
        </button>
      </div>
    </div>
  );
}

function DesktopAccountDetail() {
  const { go, params, accounts } = useApp();
  const acc = accounts.find(a => a.id === params.id) || accounts[0];
  const isDemo = acc.type === 'demo';
  return (
    <div>
      <a onClick={() => go('accounts')} style={{ fontSize: 13, color: 'var(--text-dim)', cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 6, marginBottom: 18 }}>
        <I.back size={14} /> Back to accounts
      </a>
      <div className="grid-12">
        <div>
          <div className="card" style={{ padding: 28, background: isDemo ? 'var(--card)' : 'linear-gradient(135deg, rgba(166,255,61,0.10), rgba(77,224,255,0.06))' }}>
            <span className={'pill ' + (isDemo ? 'pill-demo' : 'pill-green')}>{isDemo ? 'Demo' : 'Live'} · {acc.platform}</span>
            <div className="mono" style={{ fontSize: 14, color: 'var(--text-dim)', marginTop: 16 }}>#{acc.number}</div>
            <div className="mono" style={{ fontSize: 48, fontWeight: 600, letterSpacing: '-0.02em', marginTop: 4 }}>${acc.balance.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</div>
            <div style={{ fontSize: 13, color: 'var(--text-dim)' }}>Balance · {acc.currency}</div>
            <div className="row" style={{ gap: 10, marginTop: 24 }}>
              <button className="btn btn-primary btn-sm" onClick={() => alert('AI WebTrader would open in a new tab.')} style={{ width: 'auto', padding: '0 22px' }}><I.trade size={16}/> Open WebTrader</button>
              {!isDemo && <>
                <button className="btn btn-secondary btn-sm" onClick={() => go('deposit')} style={{ width: 'auto', padding: '0 18px' }}><I.arrowDown size={14}/> Deposit</button>
                <button className="btn btn-secondary btn-sm" onClick={() => go('withdraw')} style={{ width: 'auto', padding: '0 18px' }}><I.arrowUp size={14}/> Withdraw</button>
                <button className="btn btn-secondary btn-sm" onClick={() => go('transfer')} style={{ width: 'auto', padding: '0 18px' }}><I.swap size={14}/> Transfer</button>
              </>}
            </div>
          </div>

          <div className="grid-cols-2" style={{ marginTop: 16 }}>
            <div className="card" style={{ padding: 0 }}>
              <div style={{ padding: '14px 18px', fontSize: 13, fontWeight: 600, borderBottom: '1px solid var(--line-2)' }}>Trading details</div>
              <Detail k="Equity" v={`$${acc.equity.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`} />
              <Detail k="Free margin" v={`$${(acc.equity * 0.85).toFixed(2)}`} />
              <Detail k="Margin level" v="847.20%" />
              <Detail k="Leverage" v={acc.leverage} />
              <Detail k="Type" v={acc.kind} last />
            </div>
            <div className="card" style={{ padding: 0 }}>
              <div style={{ padding: '14px 18px', fontSize: 13, fontWeight: 600, borderBottom: '1px solid var(--line-2)' }}>Connection</div>
              <Detail k="Login" v={acc.number} copy />
              <Detail k="Server" v={'AITrader-Live01'} copy />
              <Detail k="Platform" v="AI WebTrader" />
              <Detail k="Investor pw" v="••••••••" last />
            </div>
          </div>
        </div>

        <div>
          <div className="card" style={{ padding: 18 }}>
            <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 12 }}>Quick actions</div>
            <div className="stack" style={{ gap: 8 }}>
              <button className="btn btn-secondary btn-sm" onClick={() => go('deposit')}><I.arrowDown size={14}/> Deposit funds</button>
              <button className="btn btn-secondary btn-sm" onClick={() => go('transfer')}><I.swap size={14}/> Transfer to another account</button>
              <button className="btn btn-secondary btn-sm"><I.lock size={14}/> Reset password</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function DesktopNewAccount() {
  return (
    <div style={{ maxWidth: 720 }}>
      <a onClick={() => useApp().go('accounts')} style={{ fontSize: 13, color: 'var(--text-dim)', cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 6, marginBottom: 18 }}>
        <I.back size={14} /> Back to accounts
      </a>
      <h1 className="desktop-h1">Open new account</h1>
      <p className="desktop-sub">Live or demo · AI WebTrader.</p>
      <NewAccount />
    </div>
  );
}

// === Desktop Wallet ===
function DesktopDeposit() {
  return (
    <div style={{ maxWidth: 760 }}>
      <h1 className="desktop-h1">Deposit funds</h1>
      <p className="desktop-sub">Crypto only. Funds credited after network confirmation.</p>
      <Deposit />
    </div>
  );
}

function DesktopWithdraw() {
  return (
    <div style={{ maxWidth: 720 }}>
      <h1 className="desktop-h1">Withdraw</h1>
      <p className="desktop-sub">Send funds to your external crypto wallet.</p>
      <Withdraw />
    </div>
  );
}

function DesktopTransfer() {
  return (
    <div style={{ maxWidth: 640 }}>
      <h1 className="desktop-h1">Internal transfer</h1>
      <p className="desktop-sub">Move funds between your trading accounts. No fees, instant.</p>
      <Transfer />
    </div>
  );
}

function DesktopHistory() {
  const { txns } = useApp();
  const [filter, setFilter] = useState('all');
  const list = filter === 'all' ? txns : txns.filter(t => t.type === filter);
  return (
    <div>
      <h1 className="desktop-h1">Transactions</h1>
      <p className="desktop-sub">All deposits, withdrawals, transfers, and trade settlements.</p>
      <div className="row" style={{ gap: 8, marginBottom: 16 }}>
        {[['all','All'],['deposit','Deposits'],['withdraw','Withdrawals'],['transfer','Transfers'],['trade','Trades'],['bonus','Bonuses']].map(([id, l]) => (
          <button key={id} onClick={() => setFilter(id)} style={{
            padding: '8px 16px', borderRadius: 999, fontSize: 13, fontWeight: 500,
            background: filter === id ? 'var(--green)' : 'var(--card)',
            color: filter === id ? '#0A0B0D' : 'var(--text-dim)',
            border: '1px solid ' + (filter === id ? 'var(--green)' : 'var(--line)'),
            cursor: 'pointer', fontFamily: 'inherit'
          }}>{l}</button>
        ))}
      </div>
      <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
        <table className="data-table">
          <thead><tr><th>Type</th><th>Description</th><th>Method</th><th>Date</th><th>Status</th><th style={{ textAlign: 'right' }}>Amount</th></tr></thead>
          <tbody>
            {list.map(tx => (
              <tr key={tx.id}>
                <td><span style={{ textTransform: 'capitalize' }}>{tx.type}</span></td>
                <td>{tx.label}</td>
                <td className="mono" style={{ color: 'var(--text-dim)' }}>{tx.method}</td>
                <td className="mono" style={{ color: 'var(--text-dim)' }}>{tx.date}</td>
                <td><span className={'pill ' + (tx.status === 'pending' ? 'pill-amber' : tx.status === 'failed' ? 'pill-red' : 'pill-green')}>{tx.status}</span></td>
                <td className="mono" style={{ textAlign: 'right', fontWeight: 600, color: tx.amount >= 0 ? 'var(--green)' : 'var(--text)' }}>
                  {tx.amount >= 0 ? '+' : ''}${Math.abs(tx.amount).toFixed(2)}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function DesktopPromotions() {
  return (
    <div>
      <h1 className="desktop-h1">Promotions</h1>
      <p className="desktop-sub">Bonuses, cashback and referral rewards.</p>
      <Promotions />
    </div>
  );
}

function DesktopProfile() {
  return (
    <div style={{ maxWidth: 760 }}>
      <h1 className="desktop-h1">Profile</h1>
      <p className="desktop-sub">Manage personal info, preferences and rewards.</p>
      <Profile />
    </div>
  );
}

function DesktopSettings() {
  return (
    <div style={{ maxWidth: 640 }}>
      <h1 className="desktop-h1">Personal info</h1>
      <p className="desktop-sub">Update name, email and contact details.</p>
      <Settings />
    </div>
  );
}

function DesktopSecurity() {
  return (
    <div style={{ maxWidth: 760 }}>
      <h1 className="desktop-h1">Security</h1>
      <p className="desktop-sub">Password, two-factor authentication and active sessions.</p>
      <Security />
    </div>
  );
}

window.DesktopApp = DesktopApp;
