// Dashboard
function Dashboard() {
  const { go, user, accounts, totalEquity, txns } = useApp();
  const [hidden, setHidden] = useState(false);
  const change = +482.14;
  const changePct = 2.31;

  const fmt = n => hidden ? '••••••' : n.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });

  return (
    <div className="screen with-tabs page-enter">
      <StatusBar />
      <div className="appbar">
        <div className="row" style={{ gap: 10, flex: 1, minWidth: 0 }}>
          <div style={{ width: 38, height: 38, borderRadius: '50%', background: 'linear-gradient(135deg, var(--green), var(--cyan))', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#0A0B0D', fontWeight: 700, fontSize: 14, flexShrink: 0 }}>
            {user.name.split(' ').map(s => s[0]).slice(0,2).join('')}
          </div>
          <div className="col" style={{ minWidth: 0 }}>
            <div style={{ fontSize: 11, color: 'var(--text-dim)', textTransform: 'uppercase', letterSpacing: '0.06em', whiteSpace: 'nowrap' }}>Welcome back</div>
            <div style={{ fontSize: 15, fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{user.name.split(' ')[0]}</div>
          </div>
        </div>
        <div className="appbar-actions">
          <ThemeToggle />
          <button className="icon-btn" onClick={() => go('promotions')}><I.gift size={18} /></button>
          <button className="icon-btn"><I.bell size={18} /></button>
        </div>
      </div>

      <div style={{ padding: '0 16px' }}>
        {/* Balance hero */}
        <div className="card" style={{
          background: 'linear-gradient(135deg, rgba(166,255,61,0.12), rgba(77,224,255,0.08))',
          borderColor: 'color-mix(in oklab, var(--green) 25%, transparent)',
          padding: 22,
          position: 'relative',
          overflow: 'hidden'
        }}>
          <div style={{ position: 'absolute', top: -40, right: -40, width: 160, height: 160, borderRadius: '50%', background: 'radial-gradient(circle, rgba(166,255,61,0.25), transparent 70%)' }}></div>
          <div className="between" style={{ position: 'relative' }}>
            <div style={{ fontSize: 12, color: 'var(--text-dim)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 500 }}>Total equity</div>
            <button onClick={() => setHidden(h => !h)} style={{ background: 'none', border: 'none', color: 'var(--text-dim)', cursor: 'pointer', padding: 4 }}>
              {hidden ? <I.eyeOff size={16} /> : <I.eye size={16} />}
            </button>
          </div>
          <div className="row" style={{ alignItems: 'baseline', gap: 6, marginTop: 8, position: 'relative' }}>
            <span className="mono" style={{ fontSize: 36, fontWeight: 600, letterSpacing: '-0.02em' }}>${fmt(totalEquity)}</span>
          </div>
          <div className="row" style={{ gap: 8, marginTop: 6, position: 'relative' }}>
            <span className="pill pill-green mono">▲ ${fmt(change)} · {changePct}%</span>
            <span style={{ fontSize: 12, color: 'var(--text-dim)' }}>Today</span>
          </div>

          <div className="row" style={{ gap: 8, marginTop: 18, position: 'relative' }}>
            <QuickAction icon="arrowDown" label="Deposit" onClick={() => go('deposit')} primary />
            <QuickAction icon="arrowUp" label="Withdraw" onClick={() => go('withdraw')} />
            <QuickAction icon="swap" label="Transfer" onClick={() => go('transfer')} />
          </div>
        </div>

        {/* Stats grid (replaces equity chart on mobile) */}
        <div className="grid-cols-2" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginTop: 12 }}>
          <StatTile label="Today" value="+$482.14" pct="+2.31%" up />
          <StatTile label="This week" value="+$1,284.50" pct="+6.42%" up />
          <StatTile label="This month" value="+$1,842.50" pct="+9.81%" up />
          <StatTile label="All-time" value="+$3,420.10" pct="+18.2%" up />
        </div>

        {/* Accounts strip */}
        <div className="between" style={{ marginTop: 22, marginBottom: 10 }}>
          <h3 style={{ fontSize: 16, margin: 0, fontWeight: 600 }}>Trading accounts</h3>
          <a onClick={() => go('accounts')} style={{ fontSize: 13, color: 'var(--green)', cursor: 'pointer', fontWeight: 500 }}>See all</a>
        </div>
        <div style={{ display: 'flex', gap: 10, overflowX: 'auto', margin: '0 -16px', padding: '0 16px 4px', scrollbarWidth: 'none' }}>
          {accounts.slice(0,3).map(a => (
            <MiniAccountCard key={a.id} acc={a} onClick={() => go('account', { id: a.id })} />
          ))}
          <button className="card" onClick={() => go('newAccount')} style={{
            minWidth: 96, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
            border: '1px dashed var(--line)', background: 'transparent', cursor: 'pointer', color: 'var(--text-dim)', gap: 6
          }}>
            <I.plus size={22} />
            <span style={{ fontSize: 12 }}>New</span>
          </button>
        </div>

        {/* Open positions preview */}
        <div className="between" style={{ marginTop: 22, marginBottom: 10 }}>
          <h3 style={{ fontSize: 16, margin: 0, fontWeight: 600 }}>Open positions</h3>
          <span className="pill pill-green">3 live</span>
        </div>
        <div className="stack" style={{ gap: 8 }}>
          <Position symbol="BTC/USD" side="BUY" size={0.42} entry={68420} current={69180} pnl={319.20} />
          <Position symbol="EUR/USD" side="SELL" size={2.5} entry={1.0842} current={1.0828} pnl={35.00} />
          <Position symbol="NAS100" side="BUY" size={1} entry={19840} current={19792} pnl={-48.00} />
        </div>

        {/* Recent activity */}
        <div className="between" style={{ marginTop: 22, marginBottom: 10 }}>
          <h3 style={{ fontSize: 16, margin: 0, fontWeight: 600 }}>Recent activity</h3>
          <a onClick={() => go('history')} style={{ fontSize: 13, color: 'var(--green)', cursor: 'pointer', fontWeight: 500 }}>History</a>
        </div>
        <div className="card" style={{ padding: 4 }}>
          {txns.slice(0,3).map((tx, i, arr) => (
            <TxRow key={tx.id} tx={tx} last={i === arr.length - 1} />
          ))}
        </div>
      </div>

      <TabBar />
    </div>
  );
}

function QuickAction({ icon, label, onClick, primary }) {
  return (
    <button onClick={onClick} style={{
      flex: 1, height: 64, borderRadius: 16,
      background: primary ? 'linear-gradient(135deg, var(--green), var(--green-2))' : 'var(--card)',
      color: primary ? '#0A0B0D' : 'var(--text)',
      border: primary ? 'none' : '1px solid var(--line)',
      display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 4,
      fontFamily: 'inherit', fontSize: 12, fontWeight: 600, cursor: 'pointer'
    }}>
      {I[icon]({ size: 18 })}
      <span>{label}</span>
    </button>
  );
}

function StatTile({ label, value, pct, up }) {
  return (
    <div className="card" style={{ padding: 14 }}>
      <div style={{ fontSize: 11, color: 'var(--text-dim)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 500 }}>{label}</div>
      <div className="mono" style={{ fontSize: 18, fontWeight: 600, marginTop: 4, color: up ? 'var(--green)' : 'var(--red)' }}>{value}</div>
      <div className="mono" style={{ fontSize: 11, color: 'var(--text-dim)', marginTop: 2 }}>{pct}</div>
    </div>
  );
}

function EquityChart() {
  // Generate a smooth-ish line
  const points = [40, 38, 45, 42, 50, 48, 55, 52, 60, 58, 65, 62, 68, 64, 72, 70, 75, 73, 78, 80, 77, 82, 85];
  const w = 360, h = 80;
  const max = Math.max(...points), min = Math.min(...points);
  const sx = i => (i / (points.length - 1)) * w;
  const sy = v => h - ((v - min) / (max - min)) * h;
  const path = points.map((v, i) => `${i === 0 ? 'M' : 'L'} ${sx(i)} ${sy(v)}`).join(' ');
  const area = path + ` L ${w} ${h} L 0 ${h} Z`;
  return (
    <svg viewBox={`0 0 ${w} ${h}`} width="100%" height={h} preserveAspectRatio="none" style={{ marginTop: 10, display: 'block' }}>
      <defs>
        <linearGradient id="eqGrad" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="var(--green)" stopOpacity="0.35"/>
          <stop offset="100%" stopColor="var(--green)" stopOpacity="0"/>
        </linearGradient>
      </defs>
      <path d={area} fill="url(#eqGrad)"/>
      <path d={path} fill="none" stroke="var(--green)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  );
}

function MiniAccountCard({ acc, onClick }) {
  const isDemo = acc.type === 'demo';
  return (
    <button className="card" onClick={onClick} style={{
      minWidth: 200, padding: 16, textAlign: 'left', cursor: 'pointer', color: 'var(--text)',
      background: isDemo ? 'var(--card)' : 'linear-gradient(135deg, var(--card) 0%, color-mix(in oklab, var(--green) 6%, var(--card)) 100%)'
    }}>
      <div className="between">
        <span className={'pill ' + (isDemo ? 'pill-demo' : 'pill-green')}>{isDemo ? 'Demo' : 'Live'} · {acc.platform}</span>
        <I.chevR size={16} />
      </div>
      <div className="mono" style={{ fontSize: 11, color: 'var(--text-dim)', marginTop: 10 }}>#{acc.number}</div>
      <div className="mono" style={{ fontSize: 22, fontWeight: 600, marginTop: 4 }}>${acc.balance.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</div>
      <div style={{ fontSize: 11, color: 'var(--text-dim)' }}>{acc.leverage} · {acc.currency}</div>
    </button>
  );
}

function Position({ symbol, side, size, entry, current, pnl }) {
  const up = pnl >= 0;
  return (
    <div className="card" style={{ padding: 14 }}>
      <div className="between">
        <div className="row" style={{ gap: 10 }}>
          <div style={{ width: 36, height: 36, borderRadius: 10, background: 'var(--card-2)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 11, fontWeight: 700 }} className="mono">{symbol.slice(0,3)}</div>
          <div className="col">
            <div className="row" style={{ gap: 6 }}>
              <span style={{ fontWeight: 600, fontSize: 14 }}>{symbol}</span>
              <span className={'pill ' + (side === 'BUY' ? 'pill-green' : 'pill-red')}>{side}</span>
            </div>
            <div style={{ fontSize: 11, color: 'var(--text-dim)' }} className="mono">{size} lots @ {entry}</div>
          </div>
        </div>
        <div className="col" style={{ alignItems: 'flex-end' }}>
          <div className="mono" style={{ fontWeight: 600, fontSize: 14, color: up ? 'var(--green)' : 'var(--red)' }}>
            {up ? '+' : ''}${pnl.toFixed(2)}
          </div>
          <div className="mono" style={{ fontSize: 11, color: 'var(--text-dim)' }}>{current}</div>
        </div>
      </div>
    </div>
  );
}

function TxRow({ tx, last }) {
  const up = tx.amount >= 0;
  const iconMap = { deposit: 'arrowDown', withdraw: 'arrowUp', transfer: 'swap', bonus: 'gift', trade: 'chart' };
  return (
    <div style={{ padding: 14, borderBottom: last ? 'none' : '1px solid var(--line-2)' }}>
      <div className="between">
        <div className="row" style={{ gap: 12 }}>
          <div style={{ width: 36, height: 36, borderRadius: 10, background: 'var(--card-2)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--text-dim)' }}>
            {I[iconMap[tx.type] || 'swap']({ size: 16 })}
          </div>
          <div className="col">
            <div style={{ fontSize: 14, fontWeight: 500 }}>{tx.label}</div>
            <div style={{ fontSize: 11, color: 'var(--text-dim)' }} className="mono">{tx.date} · {tx.method}</div>
          </div>
        </div>
        <div className="col" style={{ alignItems: 'flex-end' }}>
          <div className="mono" style={{ fontWeight: 600, fontSize: 14, color: up ? 'var(--green)' : 'var(--text)' }}>
            {up ? '+' : ''}${Math.abs(tx.amount).toFixed(2)}
          </div>
          <div className="mono" style={{ fontSize: 10, color: 'var(--text-faint)' }}>
            {tx.status === 'pending' ? <span style={{ color: 'var(--amber)' }}>Pending</span> : tx.status === 'failed' ? <span style={{ color: 'var(--red)' }}>Failed</span> : 'Completed'}
          </div>
        </div>
      </div>
    </div>
  );
}

window.Dashboard = Dashboard;
window.TxRow = TxRow;
window.Position = Position;
