// (continues from src/d1-arena.jsx — separated into a second file to keep individual files manageable)

// ===================== ARENA · DASHBOARD =====================
function ArenaDashboard() {
  const { accounts, setPage } = useApp();
  const totalEquity = accounts.reduce((s, a) => s + a.equity, 0);
  const totalBalance = accounts.reduce((s, a) => s + a.balance, 0);
  const todayPnl = accounts.reduce((s, a) => s + (a.profitToday || 0), 0);
  const funded = accounts.filter(a => a.status === 'funded').length;
  const evalCount = accounts.filter(a => a.status === 'evaluation').length;
  const spark = [98000, 100200, 102100, 104500, 103200, 106800, 109200, 112400, 115800, 118200, 122500, 127100, 134166];

  return (
    <>
      <div className="a-pagehead">
        <div>
          <h1>Hey Yulia. Your <em>arena</em>.</h1>
          <div className="sub">{funded} funded · {evalCount} in challenge · 1 strike across {accounts.length} accounts</div>
        </div>
        <div style={{ display: 'flex', gap: 10 }}>
          <button className="a-btn secondary"><I.refresh size={14}/> Sync</button>
          <button className="a-btn primary"><I.plus size={14}/> New challenge</button>
        </div>
      </div>

      <div className="a-hero">
        <div className="a-hero-card">
          <div className="a-hero-eyebrow"><span className="dot"></span>Total equity · all accounts</div>
          <div className="a-hero-eq">
            <span className="c">$</span>{Math.floor(totalEquity).toLocaleString()}<span className="d">.{(totalEquity.toFixed(2)).split('.')[1]}</span>
          </div>
          <div className="a-hero-delta" style={{
            color: todayPnl >= 0 ? 'var(--positive)' : 'var(--negative)',
            background: todayPnl >= 0 ? 'color-mix(in oklab, var(--positive) 12%, transparent)' : 'color-mix(in oklab, var(--negative) 12%, transparent)',
          }}>
            {todayPnl >= 0 ? <I.arrowUp size={12}/> : <I.arrowDown size={12}/>} {window.fmtMoney(Math.abs(todayPnl))} <span className="label">today · {window.fmtPct(todayPnl/totalEquity)}</span>
          </div>
          <div className="a-hero-acts">
            <button className="a-btn primary" onClick={() => setPage('newAccount')}><I.plus size={13}/> New account</button>
            <button className="a-btn secondary" onClick={() => window.openArenaTrader && window.openArenaTrader()}><I.candles size={13}/> Open ArenaTrader</button>
          </div>
        </div>

        <div className="a-tile glow" onClick={() => setPage('wallet')} style={{ cursor: 'pointer' }}>
          <div className="l"><I.wallet size={11}/> WALLET BALANCE</div>
          <div className="v mono">$1,284<small style={{ fontSize: 14, color: 'var(--text-dim)' }}>.50</small></div>
          <div className="d pos">All-time payouts · $8,043.60</div>
          <div style={{ display: 'flex', gap: 6, marginTop: 12 }}>
            <button className="a-btn primary sm" style={{ flex: 1, justifyContent: 'center' }} onClick={e=>{e.stopPropagation(); setPage('deposit');}}><I.arrowDown size={11}/> Deposit</button>
            <button className="a-btn secondary sm" style={{ flex: 1, justifyContent: 'center' }} onClick={e=>{e.stopPropagation(); setPage('withdraw');}}><I.arrowUp size={11}/> Withdraw</button>
          </div>
        </div>

        <div className="a-tile cyan" onClick={() => setPage('tiers')} style={{ cursor: 'pointer' }}>
          <div className="l"><I.trophy size={11}/> RANK</div>
          <div className="v">#247 <small style={{ fontSize: 14, color: 'var(--text-dim)' }}>/ 18.4k</small></div>
          <div className="d pos">▲ 42 this week · top 1.3%</div>
        </div>
      </div>

      {/* 4-KPI stat grid matching original */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginTop: 4 }}>
        <div className="a-tile"><div className="l">Win rate · 30d</div><div className="v">68.4%</div><div className="d pos">▲ 4.1pp</div></div>
        <div className="a-tile"><div className="l">Profit factor</div><div className="v">2.31×</div><div className="d pos">▲ 0.18</div></div>
        <div className="a-tile"><div className="l">Days traded · May</div><div className="v">12</div><div className="d" style={{ color: 'var(--text-dim)' }}>of 14 active days</div></div>
        <div className="a-tile"><div className="l">Risk score</div><div className="v">82<small style={{ fontSize: 12, color: 'var(--text-dim)' }}>/100</small></div><div className="d" style={{ color: 'var(--text-dim)' }}>Disciplined</div></div>
      </div>

      <div className="a-cols-2">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          {/* Featured accounts */}
          <div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 }}>
              <h3 style={{ margin: 0, fontFamily: 'Space Grotesk', fontSize: 18, fontWeight: 700 }}>Active accounts</h3>
              <button className="a-btn ghost sm" onClick={() => setPage('accounts')}>See all {accounts.length} <I.chevronRight size={11}/></button>
            </div>
            <div className="a-acct-grid">
              {accounts.filter(a => a.status !== 'failed').slice(0, 2).map(a => <ArenaAccountCard key={a.id} a={a}/>)}
            </div>
          </div>
        </div>

        <div className="a-side">
          {/* Leaderboard */}
          <div className="a-leader">
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <div>
                <h3 style={{ marginBottom: 0 }}>Grand Cup · S6</h3>
                <div style={{ fontSize: 11, color: 'var(--text-dim)', marginTop: 2 }}>14d left · $50K prize</div>
              </div>
              <I.trophy size={20} style={{ color: 'var(--gold)' }}/>
            </div>
            <div style={{ marginTop: 14 }}>
              {window.SEED_LEADERBOARD.map((r, i) => (
                <div key={i} className={'a-leader-row ' + (r.self ? 'self' : '')}>
                  <div className={'a-leader-rank ' + (r.rank===1?'top1':r.rank===2?'top2':r.rank===3?'top3':'')}>#{r.rank}</div>
                  <div>
                    <div className="a-leader-name">{r.trader}</div>
                    <div style={{ fontSize: 10, color: 'var(--text-faint)' }}><CountryDot c={r.country}/></div>
                  </div>
                  <div className="a-leader-gain">{window.fmtPct(r.gain, 1)}</div>
                </div>
              ))}
            </div>
            <button className="a-btn secondary sm" style={{ width: '100%', marginTop: 12, justifyContent: 'center' }}>
              View full leaderboard <I.external size={11}/>
            </button>
          </div>

          {/* News / calendar */}
          <div className="a-leader">
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
              <h3 style={{ margin: 0 }}>Today's events</h3>
              <span style={{ fontSize: 10, fontFamily: 'JetBrains Mono', color: 'var(--text-faint)' }}>14:02 UTC</span>
            </div>
            {window.SEED_NEWS.map((n, i) => (
              <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 0', borderBottom: '1px solid var(--line-2)' }}>
                <span className="mono" style={{ fontSize: 11, color: 'var(--text-dim)', minWidth: 38 }}>{n.time}</span>
                <span style={{ width: 6, height: 6, borderRadius: 999, background: n.impact==='high'?'var(--negative)':n.impact==='med'?'var(--gold)':'var(--text-faint)' }}/>
                <span style={{ fontSize: 12, flex: 1 }}>{n.title}</span>
                <CountryDot c={n.country}/>
              </div>
            ))}
          </div>
        </div>
      </div>
    </>
  );
}

function ArenaAccountCard({ a }) {
  const { setPage, setAccountId } = useApp();
  const p = useAccountProgress(a);
  const isFunded = a.status === 'funded';
  const tagClass = a.status === 'funded' ? 'funded' : a.status === 'failed' ? 'failed' : 'eval';
  const tagLabel = a.status === 'funded' ? 'FUNDED' : a.status === 'failed' ? 'FAILED' : window.planLabel(a).toUpperCase();
  const delta = a.balance - a.size;

  return (
    <div className={'a-acct ' + (isFunded ? 'funded' : '')} onClick={() => { setAccountId(a.id); setPage('account'); }}>
      <div className="a-acct-top">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          <div className="a-acct-id">
            <span>{a.login}</span>
            <span style={{ color: 'var(--text-faint)' }}>·</span>
            <span style={{ color: 'var(--text-faint)' }}>{a.server}</span>
          </div>
          <div className="a-acct-size">
            ${window.fmtMoneyCompact(a.size)}
            <small>{a.plan}</small>
          </div>
          <div><span className={'a-acct-tag ' + tagClass}>{tagLabel}</span></div>
        </div>
        <div>
          <div className="a-acct-bal-label">{isFunded ? 'EQUITY' : 'BALANCE'}</div>
          <div className="a-acct-bal mono">${window.fmtMoney(a.equity)}</div>
          <div className={'a-acct-delta mono ' + (delta>=0?'pos':'neg')}>{delta>=0?'+':''}{window.fmtMoney(delta)}</div>
        </div>
      </div>

      <div className="a-acct-stages">
        {a.stages.map((s, i) => {
          const cls = s.status === 'passed' ? 'passed'
                    : s.status === 'in_progress' ? 'active'
                    : s.status === 'active' ? 'active'
                    : s.status === 'failed' ? 'failed' : '';
          return (
            <div key={i} className={'a-stage-node ' + cls}>
              <div className="dot">{s.status==='passed'?'✓':s.status==='failed'?'×':i+1}</div>
              <div className="label">
                {s.type === 'FUNDED' ? 'Funded' : 'Phase ' + (s.type[1])}
                <small>{s.status === 'in_progress' ? 'in progress' : s.status === 'pending' ? 'locked' : s.status === 'active' ? 'live' : s.status}</small>
              </div>
            </div>
          );
        })}
      </div>

      <div className="a-acct-obj">
        <div className="a-obj">
          <div className="a-obj-head"><span>Profit</span><span className="pct">{Math.round(p.profitPct*100)}%</span></div>
          <div className="a-obj-bar"><i style={{ width: Math.min(100, p.profitPct*100) + '%' }}/></div>
          <div className="a-obj-vals"><span className="cur">${window.fmtMoney(p.profit)}</span><span className="tgt">/ ${window.fmtMoney(p.profitTargetUsd)}</span></div>
        </div>
        <div className="a-obj">
          <div className="a-obj-head"><span>Drawdown</span><span className="pct">{Math.round(p.ddPct*100)}%</span></div>
          <div className={'a-obj-bar ' + (p.ddPct>0.7?'danger':p.ddPct>0.4?'warn':'')}><i style={{ width: Math.min(100, p.ddPct*100) + '%' }}/></div>
          <div className="a-obj-vals"><span className="cur">${window.fmtMoney(p.ddSoFar)}</span><span className="tgt">/ ${window.fmtMoney(p.maxLossUsd)}</span></div>
        </div>
        <div className="a-obj">
          <div className="a-obj-head"><span>Daily</span><span className="pct">{Math.round(p.dailyPct*100)}%</span></div>
          <div className={'a-obj-bar ' + (p.dailyPct>0.7?'danger':p.dailyPct>0.4?'warn':'')}><i style={{ width: Math.min(100, p.dailyPct*100) + '%' }}/></div>
          <div className="a-obj-vals"><span className="cur">${window.fmtMoney(p.dailyUsed)}</span><span className="tgt">/ ${window.fmtMoney(p.dailyMaxUsd)}</span></div>
        </div>
      </div>

      <div className="a-acct-foot">
        <div className="creds">
          <I.user size={11}/> {a.login} <span className="sep">·</span> {a.server}
        </div>
        <button className="a-iconbtn" onClick={e=>{e.stopPropagation(); window.alert('Copied credentials');}} title="Copy credentials"><I.copy size={13}/></button>
        <button className="a-iconbtn" onClick={e=>{e.stopPropagation(); window.openArenaTrader && window.openArenaTrader(a.id);}} title="Open ArenaTrader"><I.candles size={13}/></button>
        <AccountMoreMenu a={a}/>
      </div>
    </div>
  );
}

function AccountMoreMenu({ a }) {
  const { setPage, setAccountId } = useApp();
  const [open, setOpen] = useState(false);
  const items = [
    { id: 'wt',    l: 'Open ArenaTrader', i: 'candles',  go: () => window.openArenaTrader && window.openArenaTrader(a.id) },
    { id: 'det',   l: 'Open details',   i: 'external', go: () => { setAccountId(a.id); setPage('account'); } },
    { id: 'creds', l: 'Credentials',    i: 'shield',   go: () => setPage('credentials') },
    { id: 'mt5',   l: 'Download MT5',   i: 'download', go: () => {} , disabled: true },
    { id: 'pay',   l: 'Request payout', i: 'upload',   go: () => setPage('wallet'),  disabled: a.status !== 'funded' },
    { id: 'res',   l: 'Reset challenge',i: 'refresh',  go: () => {}, disabled: true, danger: true },
  ];
  return (
    <div style={{ position: 'relative' }} onClick={e => e.stopPropagation()}>
      <button className="a-iconbtn" onClick={() => setOpen(o => !o)} title="More"><I.dots size={13}/></button>
      {open && (
        <>
          <div onClick={() => setOpen(false)} style={{ position: 'fixed', inset: 0, zIndex: 50 }}/>
          <div style={{
            position: 'absolute', top: 'calc(100% + 6px)', right: 0,
            minWidth: 200, zIndex: 60,
            background: 'var(--surface)',
            border: '1px solid var(--line-3)',
            borderRadius: 12,
            padding: 6,
            boxShadow: '0 20px 50px rgba(0,0,0,0.55)',
          }}>
            {items.map(it => {
              const Ic = I[it.i];
              return (
                <button
                  key={it.id}
                  disabled={it.disabled}
                  onClick={() => { if (!it.disabled) { setOpen(false); it.go(); } }}
                  style={{
                    width: '100%',
                    display: 'flex', alignItems: 'center', gap: 10,
                    padding: '9px 10px',
                    border: 'none', background: 'transparent',
                    color: it.disabled ? 'var(--text-faint)' : it.danger ? 'var(--negative)' : 'var(--text)',
                    font: 'inherit', fontSize: 12,
                    borderRadius: 8, cursor: it.disabled ? 'not-allowed' : 'pointer', textAlign: 'left',
                  }}
                  onMouseEnter={e => !it.disabled && (e.currentTarget.style.background = 'rgba(255,255,255,0.04)')}
                  onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
                >
                  <Ic size={13}/>
                  <span style={{ flex: 1 }}>{it.l}</span>
                  {it.disabled && <span style={{ fontSize: 9, color: 'var(--text-faint)', fontFamily: 'JetBrains Mono' }}>SOON</span>}
                </button>
              );
            })}
          </div>
        </>
      )}
    </div>
  );
}

// ===================== ARENA · ACCOUNTS =====================
function ArenaAccounts() {
  const { accounts, setPage, setAccountId } = useApp();
  const [filter, setFilter] = useState('all');
  const [view, setView] = useState('list');
  const [filtersOpen, setFiltersOpen] = useState(false);
  const [failedOpen, setFailedOpen] = useState(false);
  const failedAccounts = accounts.filter(a => a.status === 'failed');
  const [sortOpen, setSortOpen] = useState(false);
  const [sort, setSort] = useState('newest');
  const [appliedFilters, setAppliedFilters] = useState({ plans: [], sizes: [], stages: [], strikes: 'all' });
  const baseList = filter === 'all' ? accounts
    : filter === 'funded' ? accounts.filter(a => a.status === 'funded')
    : filter === 'failed' ? accounts.filter(a => a.status === 'failed')
    : accounts.filter(a => a.status !== 'funded' && a.status !== 'failed');
  const sortOptions = [
    { id: 'newest',  l: 'Newest first',         i: 'clock' },
    { id: 'oldest',  l: 'Oldest first',         i: 'clock' },
    { id: 'sizeDesc',l: 'Account size: high → low', i: 'chart2' },
    { id: 'sizeAsc', l: 'Account size: low → high', i: 'chart2' },
    { id: 'balDesc', l: 'Balance: high → low',  i: 'wallet' },
    { id: 'balAsc',  l: 'Balance: low → high',  i: 'wallet' },
    { id: 'pnlDesc', l: 'P&L: best first',      i: 'fire' },
    { id: 'pnlAsc',  l: 'P&L: worst first',     i: 'warn' },
    { id: 'status',  l: 'Status (Funded first)', i: 'trophy' },
  ];
  const sortLabel = sortOptions.find(o => o.id === sort)?.l || 'Newest first';
  const filtered = useMemo(() => {
    const arr = [...baseList];
    const pnl = a => a.balance - a.size;
    const statusRank = a => a.status === 'funded' ? 0 : a.status === 'failed' ? 2 : 1;
    switch (sort) {
      case 'oldest':   arr.reverse(); break;
      case 'sizeDesc': arr.sort((a, b) => b.size - a.size); break;
      case 'sizeAsc':  arr.sort((a, b) => a.size - b.size); break;
      case 'balDesc':  arr.sort((a, b) => b.balance - a.balance); break;
      case 'balAsc':   arr.sort((a, b) => a.balance - b.balance); break;
      case 'pnlDesc':  arr.sort((a, b) => pnl(b) - pnl(a)); break;
      case 'pnlAsc':   arr.sort((a, b) => pnl(a) - pnl(b)); break;
      case 'status':   arr.sort((a, b) => statusRank(a) - statusRank(b)); break;
      default: break;
    }
    return arr;
  }, [baseList, sort]);
  const activeFilterCount = appliedFilters.plans.length + appliedFilters.sizes.length + appliedFilters.stages.length + (appliedFilters.strikes !== 'all' ? 1 : 0);

  return (
    <>
      <div className="a-pagehead">
        <div>
          <h1>My <em>accounts</em></h1>
          <div className="sub">{accounts.length} accounts · {accounts.filter(a=>a.status==='funded').length} funded</div>
        </div>
        <div style={{ display: 'flex', gap: 10 }}>
          <button className="a-btn primary" onClick={() => setPage('newAccount')}><I.plus size={13}/> New challenge</button>
        </div>
      </div>

      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12, flexWrap: 'wrap', marginBottom: 18 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
          <div className="a-chips">
            {[
              { id: 'all',    l: 'All',       c: accounts.length },
              { id: 'eval',   l: 'Challenge', c: accounts.filter(a=>a.status!=='funded' && a.status!=='failed').length },
              { id: 'funded', l: 'Funded',    c: accounts.filter(a=>a.status==='funded').length },
              ...(failedAccounts.length > 0 ? [{ id: 'failed', l: 'Failed', c: failedAccounts.length }] : []),
            ].map(x => (
              <button key={x.id} className={filter===x.id?'active':''} onClick={()=>setFilter(x.id)}>
                {x.l} <span className="c">{x.c}</span>
              </button>
            ))}
          </div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <button className="a-btn secondary sm" onClick={() => setFiltersOpen(true)}>
            <I.filter size={11}/> Filters {activeFilterCount > 0 && <span style={{ background: 'var(--magenta)', color: '#fff', borderRadius: 999, padding: '0 6px', fontSize: 10, fontWeight: 700, marginLeft: 4 }}>{activeFilterCount}</span>}
          </button>
          <div style={{ position: 'relative' }}>
            <button className="a-btn secondary sm" onClick={() => setSortOpen(o => !o)}>
              <I.sort size={11}/> Sort: {sortLabel}
            </button>
            {sortOpen && (
              <>
                <div onClick={() => setSortOpen(false)} style={{ position: 'fixed', inset: 0, zIndex: 50 }}/>
                <div style={{
                  position: 'absolute', top: 'calc(100% + 6px)', right: 0,
                  minWidth: 240, zIndex: 60,
                  background: 'var(--surface)',
                  border: '1px solid var(--line-3)',
                  borderRadius: 12,
                  padding: 6,
                  boxShadow: '0 20px 50px rgba(0,0,0,0.55)',
                }}>
                  <div style={{ fontSize: 10, fontWeight: 700, color: 'var(--text-faint)', letterSpacing: '.1em', textTransform: 'uppercase', padding: '6px 10px 8px' }}>Sort accounts</div>
                  {sortOptions.map(o => {
                    const Ic = I[o.i] || I.sort;
                    const active = sort === o.id;
                    return (
                      <button key={o.id} onClick={() => { setSort(o.id); setSortOpen(false); }} style={{
                        width: '100%', display: 'flex', alignItems: 'center', gap: 10,
                        padding: '8px 10px',
                        border: 'none',
                        background: active ? 'rgba(255,92,245,0.08)' : 'transparent',
                        color: 'var(--text)', font: 'inherit', fontSize: 12,
                        borderRadius: 8, cursor: 'pointer', textAlign: 'left',
                      }}
                      onMouseEnter={e => !active && (e.currentTarget.style.background = 'rgba(255,255,255,0.04)')}
                      onMouseLeave={e => (e.currentTarget.style.background = active ? 'rgba(255,92,245,0.08)' : 'transparent')}>
                        <Ic size={13} style={{ color: active ? 'var(--magenta)' : 'var(--text-dim)' }}/>
                        <span style={{ flex: 1 }}>{o.l}</span>
                        {active && <I.check size={12} style={{ color: 'var(--magenta)' }}/>}
                      </button>
                    );
                  })}
                </div>
              </>
            )}
          </div>
          <div className="a-chips" style={{ padding: 2 }}>
            <button className={view==='grid'?'active':''} onClick={()=>setView('grid')} title="Grid"><I.grid size={12}/></button>
            <button className={view==='list'?'active':''} onClick={()=>setView('list')} title="List"><I.list size={12}/></button>
          </div>
        </div>
      </div>

      {view === 'grid' ? (
        <div className="a-acct-grid">
          {filtered.map(a => <ArenaAccountCard key={a.id} a={a}/>)}
          <div className="a-acct" style={{
            background: 'transparent',
            border: '1.5px dashed var(--line-3)',
            alignItems: 'center', justifyContent: 'center',
            minHeight: 280,
            display: 'flex', flexDirection: 'column', gap: 10, cursor: 'pointer',
          }}>
            <div style={{
              width: 56, height: 56, borderRadius: 16,
              background: 'linear-gradient(135deg, var(--magenta), var(--cyan))',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              color: '#06070D',
              boxShadow: '0 0 32px -6px var(--magenta)',
            }}>
              <I.plus size={26}/>
            </div>
            <div style={{ fontFamily: 'Space Grotesk', fontSize: 17, fontWeight: 700 }}>New challenge</div>
            <div style={{ fontSize: 12, color: 'var(--text-dim)' }}>30% OFF with code MAY30</div>
            <button className="a-btn primary sm" style={{ marginTop: 6 }}>Start now <I.arrowRight size={12}/></button>
          </div>
        </div>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {filtered.map(a => <ArenaAccountRow key={a.id} a={a}/>)}
          <div style={{
            background: 'transparent',
            border: '1.5px dashed var(--line-3)',
            borderRadius: 14,
            padding: '16px 20px',
            display: 'flex', alignItems: 'center', gap: 16, cursor: 'pointer',
          }}>
            <div style={{
              width: 40, height: 40, borderRadius: 12,
              background: 'linear-gradient(135deg, var(--magenta), var(--cyan))',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              color: '#06070D',
              flex: 'none',
            }}>
              <I.plus size={20}/>
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontFamily: 'Space Grotesk', fontSize: 15, fontWeight: 700 }}>New challenge</div>
              <div style={{ fontSize: 12, color: 'var(--text-dim)', marginTop: 2 }}>30% OFF with code MAY30</div>
            </div>
            <button className="a-btn primary sm">Start now <I.arrowRight size={12}/></button>
          </div>
        </div>
      )}

      {filtersOpen && <ArenaAccountsFilters onClose={() => setFiltersOpen(false)} applied={appliedFilters} setApplied={setAppliedFilters}/>}
    </>
  );
}

function ArenaFailedAccountsModal({ accounts, onClose, onOpen, onNew }) {
  return (
    <>
      <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.62)', backdropFilter: 'blur(6px)', zIndex: 200 }}/>
      <div style={{
        position: 'fixed', top: '50%', left: '50%', transform: 'translate(-50%, -50%)',
        width: 760, maxWidth: '94vw', maxHeight: '90vh', zIndex: 201,
        background: 'var(--surface)', border: '1px solid var(--line-3)',
        borderRadius: 22,
        boxShadow: '0 30px 80px rgba(0,0,0,0.6)',
        display: 'flex', flexDirection: 'column', overflow: 'hidden',
      }}>
        <div style={{ padding: '22px 26px 16px', borderBottom: '1px solid var(--line)', display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12 }}>
          <div style={{ display: 'flex', gap: 14 }}>
            <div style={{ width: 36, height: 36, borderRadius: 10, background: 'color-mix(in oklab, var(--negative) 18%, transparent)', border: '1px solid color-mix(in oklab, var(--negative) 35%, transparent)', color: 'var(--negative)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <I.warn size={18}/>
            </div>
            <div>
              <div style={{ fontFamily: 'Space Grotesk', fontSize: 22, fontWeight: 700, letterSpacing: '-0.02em' }}>Failed accounts</div>
              <div style={{ fontSize: 12, color: 'var(--text-dim)', marginTop: 4 }}>{accounts.length} account{accounts.length !== 1 ? 's' : ''} ended without passing. Hidden from your main list — kept here for the record.</div>
            </div>
          </div>
          <button onClick={onClose} style={{
            width: 34, height: 34, borderRadius: 999,
            background: 'rgba(255,255,255,0.04)', border: '1px solid var(--line)',
            color: 'var(--text-dim)', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer',
          }}><I.x size={14}/></button>
        </div>

        <div style={{ flex: 1, overflowY: 'auto', padding: '8px 0' }}>
          {accounts.length === 0 && (
            <div style={{ padding: 40, textAlign: 'center', color: 'var(--text-faint)', fontSize: 13 }}>
              No failed accounts. Keep it clean.
            </div>
          )}
          {accounts.map((a, idx) => {
            const lastStrike = a.strikeLog?.[a.strikeLog.length - 1];
            const failedOn = a.stages?.find(s => s.status === 'failed')?.failedOn || lastStrike?.date || '—';
            const drawdown = a.size - a.equity;
            return (
              <div key={a.id} style={{
                padding: '18px 26px',
                borderBottom: idx < accounts.length - 1 ? '1px solid var(--line-2)' : 'none',
                display: 'grid', gridTemplateColumns: '1fr auto', gap: 16, alignItems: 'center',
              }}>
                <div style={{ minWidth: 0 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10, flexWrap: 'wrap' }}>
                    <span className="a-acct-tag failed">FAILED</span>
                    <span className="mono" style={{ fontSize: 13, fontWeight: 600 }}>#{a.login}</span>
                    <span style={{ fontSize: 12, color: 'var(--text-faint)' }}>·</span>
                    <span style={{ fontSize: 13, color: 'var(--text-dim)' }}>${window.fmtMoneyCompact(a.size)} {a.plan}</span>
                  </div>
                  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, minmax(0, 1fr))', gap: '6px 18px', fontSize: 12, color: 'var(--text-dim)' }}>
                    <span>Failed <b style={{ color: 'var(--text)' }}>{failedOn}</b></span>
                    <span>Days <b style={{ color: 'var(--text)' }}>{a.daysTraded}</b></span>
                    <span>Drawdown <b className="mono" style={{ color: 'var(--negative)' }}>−${window.fmtMoney(Math.abs(drawdown))}</b></span>
                    <span style={{ gridColumn: '1 / -1' }}>Reason <b style={{ color: 'var(--negative)' }}>{lastStrike?.rule || 'Max drawdown'}</b></span>
                  </div>
                  {lastStrike?.detail && (
                    <div style={{
                      marginTop: 10, padding: '8px 12px', fontSize: 12, color: 'var(--text-dim)',
                      background: 'color-mix(in oklab, var(--negative) 6%, var(--surface-2))',
                      borderLeft: '2px solid var(--negative)', borderRadius: '0 8px 8px 0',
                    }}>
                      "{lastStrike.detail}"
                    </div>
                  )}
                </div>
                <div style={{ display: 'flex', gap: 6, flexShrink: 0 }}>
                  <button className="a-btn secondary sm" onClick={() => { onClose(); onOpen(a.id); }}>Review</button>
                  <button className="a-btn secondary sm" title="Download statement"><I.download size={12}/></button>
                </div>
              </div>
            );
          })}
        </div>

        <div style={{
          padding: '16px 26px', borderTop: '1px solid var(--line)', background: 'var(--surface-2)',
          display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12,
        }}>
          <div style={{ fontSize: 12, color: 'var(--text-dim)' }}>
            Failed accounts don't count against your tier. Ready for another shot?
          </div>
          <button className="a-btn primary" onClick={() => { onClose(); onNew(); }}>
            <I.plus size={13}/> New challenge
          </button>
        </div>
      </div>
    </>
  );
}

// Row-style account display (list view)
function ArenaAccountRow({ a }) {
  const { setPage, setAccountId } = useApp();
  const p = useAccountProgress(a);
  const isFunded = a.status === 'funded';
  const tagClass = a.status === 'funded' ? 'funded' : a.status === 'failed' ? 'failed' : 'eval';
  const tagLabel = a.status === 'funded' ? 'FUNDED' : a.status === 'failed' ? 'FAILED' : window.planLabel(a).toUpperCase();
  const delta = a.balance - a.size;

  return (
    <div
      className={'a-acct ' + (isFunded ? 'funded' : '')}
      onClick={() => { setAccountId(a.id); setPage('account'); }}
      style={{ padding: '16px 20px', display: 'grid', gridTemplateColumns: '180px 110px 1fr 130px 180px auto', gap: 18, alignItems: 'center' }}
    >
      {/* Login + plan */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
        <span className="mono" style={{ fontSize: 13, fontWeight: 600 }}>{a.login}</span>
        <span style={{ fontSize: 11, color: 'var(--text-faint)' }}>{a.server}</span>
      </div>

      {/* Size + plan */}
      <div>
        <div style={{ fontFamily: 'Space Grotesk', fontWeight: 700, fontSize: 17, letterSpacing: '-0.02em' }}>${window.fmtMoneyCompact(a.size)}</div>
        <div style={{ fontSize: 11, color: 'var(--text-dim)' }}>{a.plan}</div>
      </div>

      {/* Stage chips */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 4, minWidth: 0 }}>
        <span className={'a-acct-tag ' + tagClass} style={{ flex: 'none' }}>{tagLabel}</span>
        <div style={{ display: 'flex', alignItems: 'center', gap: 4, marginLeft: 6, flex: 1, minWidth: 0 }}>
          {a.stages.map((s, i) => {
            const cls = s.status === 'passed' ? 'passed'
                      : s.status === 'in_progress' || s.status === 'active' ? 'active'
                      : s.status === 'failed' ? 'failed' : '';
            return (
              <React.Fragment key={i}>
                <div style={{
                  width: 18, height: 18, borderRadius: 999,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontSize: 9, fontWeight: 700,
                  background: cls === 'passed' ? 'var(--magenta)' : cls === 'active' ? 'var(--cyan)' : 'var(--surface-3)',
                  color: cls === 'passed' || cls === 'active' ? '#06070D' : 'var(--text-faint)',
                  flex: 'none',
                  border: cls === 'failed' ? '1px solid var(--negative)' : 'none',
                }}>
                  {s.status === 'passed' ? '✓' : s.status === 'failed' ? '×' : (i + 1)}
                </div>
                {i < a.stages.length - 1 && <div style={{ flex: 1, minWidth: 6, maxWidth: 18, height: 1, background: a.stages[i+1].status === 'pending' ? 'var(--surface-3)' : 'var(--magenta)' }}/>}
              </React.Fragment>
            );
          })}
        </div>
      </div>

      {/* Progress mini */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 10, color: 'var(--text-faint)' }}>
          <span>Profit</span><span className="mono">{Math.round(p.profitPct*100)}%</span>
        </div>
        <div className="a-obj-bar"><i style={{ width: Math.min(100, p.profitPct*100) + '%' }}/></div>
        <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 10, color: 'var(--text-faint)' }}>
          <span>DD</span><span className="mono">{Math.round(p.ddPct*100)}%</span>
        </div>
        <div className={'a-obj-bar ' + (p.ddPct>0.7?'danger':p.ddPct>0.4?'warn':'')}><i style={{ width: Math.min(100, p.ddPct*100) + '%' }}/></div>
      </div>

      {/* Balance / equity */}
      <div style={{ textAlign: 'right' }}>
        <div className="a-acct-bal-label">{isFunded ? 'EQUITY' : 'BALANCE'}</div>
        <div className="a-acct-bal mono">${window.fmtMoney(a.equity)}</div>
        <div className={'a-acct-delta mono ' + (delta>=0?'pos':'neg')}>{delta>=0?'+':''}{window.fmtMoney(delta)}</div>
      </div>

      {/* Actions */}
      <div style={{ display: 'flex', gap: 6, justifyContent: 'flex-end' }}>
        <button className="a-iconbtn" onClick={e=>{e.stopPropagation(); window.alert('Credentials copied');}} title="Copy credentials"><I.copy size={13}/></button>
        <button className="a-iconbtn" onClick={e=>{e.stopPropagation(); window.openArenaTrader && window.openArenaTrader(a.id);}} title="Open ArenaTrader"><I.candles size={13}/></button>
        <AccountMoreMenu a={a}/>
      </div>
    </div>
  );
}

// Filter drawer
function ArenaAccountsFilters({ onClose, applied, setApplied }) {
  const [local, setLocal] = useState(applied);
  const toggle = (key, val) => {
    const arr = local[key];
    setLocal({ ...local, [key]: arr.includes(val) ? arr.filter(x => x !== val) : [...arr, val] });
  };
  return (
    <>
      <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.55)', backdropFilter: 'blur(4px)', zIndex: 150 }}/>
      <div style={{
        position: 'fixed', top: 0, right: 0, bottom: 0,
        width: 420, maxWidth: '92vw', zIndex: 160,
        background: 'var(--surface)',
        borderLeft: '1px solid var(--line)',
        display: 'flex', flexDirection: 'column',
        boxShadow: '-30px 0 80px rgba(0,0,0,0.4)',
      }}>
        <div style={{ padding: '20px 24px', borderBottom: '1px solid var(--line)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div>
            <div style={{ fontSize: 17, fontWeight: 700, fontFamily: 'Space Grotesk', letterSpacing: '-0.02em' }}>Filters</div>
            <div style={{ fontSize: 12, color: 'var(--text-dim)', marginTop: 2 }}>Narrow your account list</div>
          </div>
          <button className="a-iconbtn" onClick={onClose}><I.x size={13}/></button>
        </div>

        <div style={{ flex: 1, overflowY: 'auto', padding: '20px 24px' }}>
          {/* Plan */}
          <div style={{ marginBottom: 22 }}>
            <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--text-dim)', letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 10 }}>Plan</div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
              {['Signature One', 'Signature', 'Signature Pro'].map(p => (
                <button key={p} onClick={() => toggle('plans', p)} style={{
                  padding: '8px 14px', borderRadius: 10,
                  border: '1.5px solid ' + (local.plans.includes(p) ? 'var(--magenta)' : 'var(--line)'),
                  background: local.plans.includes(p) ? 'rgba(255,92,245,0.10)' : 'var(--surface-2)',
                  color: 'var(--text)', font: 'inherit', fontSize: 12, fontWeight: 500, cursor: 'pointer',
                }}>{p}</button>
              ))}
            </div>
          </div>

          {/* Size */}
          <div style={{ marginBottom: 22 }}>
            <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--text-dim)', letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 10 }}>Account size</div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
              {[25000, 50000, 100000, 200000].map(s => (
                <button key={s} onClick={() => toggle('sizes', s)} style={{
                  padding: '8px 14px', borderRadius: 10,
                  border: '1.5px solid ' + (local.sizes.includes(s) ? 'var(--magenta)' : 'var(--line)'),
                  background: local.sizes.includes(s) ? 'rgba(255,92,245,0.10)' : 'var(--surface-2)',
                  color: 'var(--text)', fontFamily: 'JetBrains Mono', fontSize: 12, fontWeight: 600, cursor: 'pointer',
                }}>${window.fmtMoneyCompact(s)}</button>
              ))}
            </div>
          </div>

          {/* Stage */}
          <div style={{ marginBottom: 22 }}>
            <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--text-dim)', letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 10 }}>Stage</div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
              {['Challenge 1', 'Challenge 2', 'Challenge 3', 'Funded', 'Failed'].map(s => (
                <button key={s} onClick={() => toggle('stages', s)} style={{
                  padding: '8px 14px', borderRadius: 10,
                  border: '1.5px solid ' + (local.stages.includes(s) ? 'var(--magenta)' : 'var(--line)'),
                  background: local.stages.includes(s) ? 'rgba(255,92,245,0.10)' : 'var(--surface-2)',
                  color: 'var(--text)', font: 'inherit', fontSize: 12, fontWeight: 500, cursor: 'pointer',
                }}>{s}</button>
              ))}
            </div>
          </div>

          {/* Strikes */}
          <div style={{ marginBottom: 22 }}>
            <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--text-dim)', letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 10 }}>Strike level</div>
            <div className="a-chips" style={{ width: '100%' }}>
              {[
                { id: 'all', l: 'Any' },
                { id: 'clean', l: '0 strikes' },
                { id: 'warned', l: '1–2 strikes' },
                { id: 'critical', l: '3 strikes' },
              ].map(x => (
                <button key={x.id} className={local.strikes === x.id ? 'active' : ''} onClick={() => setLocal({ ...local, strikes: x.id })} style={{ flex: 1, justifyContent: 'center' }}>{x.l}</button>
              ))}
            </div>
          </div>

          {/* Result preview */}
          <div style={{ padding: 14, background: 'var(--surface-2)', borderRadius: 12, border: '1px solid var(--line)', fontSize: 12, color: 'var(--text-dim)' }}>
            <I.info size={12} style={{ marginRight: 6, verticalAlign: 'middle' }}/>
            {local.plans.length + local.sizes.length + local.stages.length + (local.strikes !== 'all' ? 1 : 0)} filter{(local.plans.length + local.sizes.length + local.stages.length + (local.strikes !== 'all' ? 1 : 0)) === 1 ? '' : 's'} selected. Click Apply to filter.
          </div>
        </div>

        <div style={{ padding: '14px 24px', borderTop: '1px solid var(--line)', background: 'var(--surface-2)', display: 'flex', gap: 10 }}>
          <button className="a-btn ghost" onClick={() => setLocal({ plans: [], sizes: [], stages: [], strikes: 'all' })}>Reset</button>
          <div style={{ flex: 1 }}/>
          <button className="a-btn secondary" onClick={onClose}>Cancel</button>
          <button className="a-btn primary" onClick={() => { setApplied(local); onClose(); }}>Apply filters</button>
        </div>
      </div>
    </>
  );
}

// ===================== ARENA · ACCOUNT DETAIL =====================
function ArenaAccountDetail() {
  const { account, setPage } = useApp();
  const a = account;
  const p = useAccountProgress(a);
  const isFunded = a.status === 'funded';
  const [tab, setTab] = useState('overview');

  return (
    <>
      <div className="a-pagehead">
        <div>
          <div style={{ fontSize: 12, color: 'var(--text-dim)', display: 'flex', alignItems: 'center', gap: 6 }}>
            <a onClick={() => setPage('accounts')} style={{ cursor: 'pointer', color: 'var(--text-dim)' }}>Accounts</a>
            <I.chevronRight size={10}/>
            <span style={{ color: 'var(--text)', fontWeight: 600 }}>#{a.login}</span>
          </div>
          <h1 style={{ marginTop: 6 }}>
            ${window.fmtMoneyCompact(a.size)} <em>{a.plan}</em>
          </h1>
          <div className="sub">
            <span className={'a-acct-tag ' + (isFunded?'funded':a.status==='failed'?'failed':'eval')}>{isFunded?'FUNDED':a.status==='failed'?'FAILED':window.planLabel(a).toUpperCase()}</span>
            <span style={{ marginLeft: 10 }} className="mono">{a.login} · {a.server}</span>
          </div>
        </div>
        <div style={{ display: 'flex', gap: 10 }}>
          <button className="a-btn secondary"><I.refresh size={13}/> Reset</button>
          {isFunded && <button className="a-btn primary" onClick={() => setPage('wallet')}><I.upload size={13}/> Request payout</button>}
          <button className="a-btn primary" onClick={() => window.openArenaTrader && window.openArenaTrader(a.id)}><I.candles size={13}/> Open ArenaTrader</button>
          <button className="a-btn secondary" onClick={() => window.open('about:blank', '_blank')} title="Pop out"><I.external size={13}/></button>
        </div>
      </div>

      {/* Detail tabs */}
      <div className="a-chips" style={{ marginBottom: 18 }}>
        {[
          { id: 'overview',  l: 'Overview' },
          { id: 'rules',     l: 'Objectives & Rules' },
          { id: 'history',   l: 'Trade history' },
          { id: 'trader',    l: 'ArenaTrader' },
        ].map(t => (
          <button key={t.id} className={tab === t.id ? 'active' : ''} onClick={() => { setTab(t.id); if (t.id === 'trader') window.openArenaTrader && window.openArenaTrader(a.id); }}>{t.l}</button>
        ))}
      </div>

      {tab === 'rules' && <AccountDetailRules account={a} progress={p}/>}
      {tab === 'history' && <AccountDetailHistory account={a}/>}
      {tab === 'overview' && (
      <div className="a-detail-grid">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          {/* Stage hero */}
          <div className="a-stage-hero">
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
              <div>
                <div style={{ fontSize: 11, color: 'var(--text-dim)', textTransform: 'uppercase', letterSpacing: '.12em', fontWeight: 600 }}>
                  <span className="dot" style={{ width: 6, height: 6, borderRadius: 999, background: 'var(--positive)', display: 'inline-block', marginRight: 6, boxShadow: '0 0 6px var(--positive)' }}/>
                  Equity · live
                </div>
                <div className="mono" style={{ fontSize: 48, fontWeight: 600, letterSpacing: '-0.035em', lineHeight: 1, marginTop: 6 }}>
                  ${window.fmtMoney(a.equity)}
                </div>
                <div style={{ fontFamily: 'JetBrains Mono', fontSize: 14, color: a.profitToday>=0?'var(--positive)':'var(--negative)', marginTop: 8 }}>
                  {a.profitToday>=0?'+':''}{window.fmtMoney(a.profitToday)} today
                </div>
              </div>
              <div style={{ width: 200, height: 70 }}>
                <Spark data={a.history} color="url(#a-grad)" strokeWidth={2} fill="url(#a-fill)"/>
              </div>
            </div>

            <div className="a-stage-bar">
              {a.stages.map((s, i) => {
                const passed = s.status === 'passed';
                const active = s.status === 'in_progress' || s.status === 'active';
                const failed = s.status === 'failed';
                const cls = passed ? 'passed' : active ? 'active' : failed ? 'failed' : '';
                return (
                  <React.Fragment key={i}>
                    {i>0 && <span className={'link ' + (passed || a.stages[i-1].status==='passed' ? 'lit' : '')}/>}
                    <div className={'node ' + cls}>
                      <div className="ring">{passed?'✓':failed?'×':i+1}</div>
                      <div className="lbl">{s.type==='FUNDED'?'Funded':'Phase '+s.type[1]}</div>
                    </div>
                  </React.Fragment>
                );
              })}
            </div>

            <div className="a-obj-grid">
              <ArenaObjTile label="PROFIT TARGET" current={p.profit} target={p.profitTargetUsd} pct={p.profitPct}/>
              <ArenaObjTile label="MAX DRAWDOWN" current={p.ddSoFar} target={p.maxLossUsd} pct={p.ddPct} invert/>
              <ArenaObjTile label="DAILY LOSS" current={p.dailyUsed} target={p.dailyMaxUsd} pct={p.dailyPct} invert/>
              <ArenaObjTile label="PROFITABLE DAYS" current={p.profitableDays} target={p.minProfitDays || 'n/a'} pct={p.profitDaysPct} isDays/>
            </div>
          </div>

          {/* Trade log */}
          <div className="a-leader">
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 }}>
              <h3 style={{ margin: 0 }}>Recent trades</h3>
              <button className="a-btn ghost sm">View journal <I.chevronRight size={11}/></button>
            </div>
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
              <thead>
                <tr style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '.08em', color: 'var(--text-faint)', fontWeight: 600 }}>
                  <th style={{ textAlign: 'left', padding: '8px 0' }}>Symbol</th>
                  <th style={{ textAlign: 'left', padding: '8px 0' }}>Side</th>
                  <th style={{ textAlign: 'right', padding: '8px 0' }}>Volume</th>
                  <th style={{ textAlign: 'right', padding: '8px 0' }}>Entry</th>
                  <th style={{ textAlign: 'right', padding: '8px 0' }}>Exit</th>
                  <th style={{ textAlign: 'right', padding: '8px 0' }}>P/L</th>
                </tr>
              </thead>
              <tbody>
                {[
                  { s: 'EURUSD', side: 'BUY',  vol: 1.50, e: 1.08412, x: 1.08540, pl: 192.00 },
                  { s: 'XAUUSD', side: 'SELL', vol: 0.30, e: 2342.10, x: 2335.40, pl: 201.00 },
                  { s: 'NAS100', side: 'BUY',  vol: 0.80, e: 18420, x: 18395, pl: -200.00 },
                  { s: 'GBPJPY', side: 'BUY',  vol: 0.60, e: 192.45, x: 192.92, pl: 188.40 },
                  { s: 'BTCUSD', side: 'SELL', vol: 0.10, e: 67420, x: 67200, pl: 22.00 },
                ].map((t, i) => (
                  <tr key={i} style={{ borderTop: '1px solid var(--line-2)' }}>
                    <td style={{ padding: '10px 0' }}><b>{t.s}</b></td>
                    <td style={{ padding: '10px 0' }}>
                      <span style={{ fontSize: 10, fontWeight: 700, padding: '2px 6px', borderRadius: 4, background: t.side==='BUY'?'color-mix(in oklab, var(--positive) 12%, transparent)':'color-mix(in oklab, var(--negative) 12%, transparent)', color: t.side==='BUY'?'var(--positive)':'var(--negative)' }}>{t.side}</span>
                    </td>
                    <td className="mono" style={{ textAlign: 'right', padding: '10px 0' }}>{t.vol.toFixed(2)}</td>
                    <td className="mono" style={{ textAlign: 'right', padding: '10px 0', color: 'var(--text-dim)' }}>{t.e.toLocaleString()}</td>
                    <td className="mono" style={{ textAlign: 'right', padding: '10px 0', color: 'var(--text-dim)' }}>{t.x.toLocaleString()}</td>
                    <td className={'mono ' + (t.pl>=0?'pos':'neg')} style={{ textAlign: 'right', padding: '10px 0', fontWeight: 600 }}>{t.pl>=0?'+':''}${t.pl.toFixed(2)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>

        <div className="a-side">
          {/* Credentials */}
          <div className="a-leader">
            <h3 style={{ marginBottom: 14 }}>Credentials</h3>
            <ArenaKv label="Login" value={a.login} mono copy/>
            <ArenaKv label="Server" value={a.server} mono/>
            <ArenaKv label="Currency" value={a.currency}/>
            <ArenaKv label="Leverage" value="1:30"/>
            <div style={{ display: 'flex', gap: 6, marginTop: 14 }}>
              <button className="a-btn secondary sm" style={{ flex: 1 }} onClick={() => window.openArenaTrader && window.openArenaTrader(a.id)}><I.candles size={11}/> ArenaTrader</button>
              <button className="a-btn secondary sm" style={{ flex: 1 }} onClick={() => setPage('credentials')}><I.download size={11}/> MT5</button>
            </div>
          </div>

          {/* Strikes */}
          <div className="a-leader">
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 }}>
              <h3 style={{ margin: 0 }}>Rule strikes</h3>
              <div style={{ display: 'flex', gap: 3 }}>
                {Array.from({ length: a.strikeMax }).map((_, i) => (
                  <div key={i} style={{
                    width: 10, height: 10, borderRadius: 3,
                    background: i < a.strikes ? 'var(--negative)' : 'rgba(255,255,255,0.06)',
                    boxShadow: i < a.strikes ? '0 0 8px var(--negative)' : 'none',
                  }}/>
                ))}
              </div>
            </div>
            {a.strikeLog.length === 0 ? (
              <div style={{ fontSize: 13, color: 'var(--text-dim)' }}>No strikes. Keep it clean!</div>
            ) : a.strikeLog.map((s, i) => (
              <div key={i} style={{ paddingBottom: 10, marginBottom: 10, borderBottom: i<a.strikeLog.length-1?'1px solid var(--line-2)':'none' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 4 }}>
                  <span style={{ fontSize: 12, fontWeight: 600 }}>{s.rule}</span>
                  <span className="mono" style={{ fontSize: 10, color: 'var(--text-faint)' }}>{s.date}</span>
                </div>
                <div style={{ fontSize: 12, color: 'var(--text-dim)' }}>{s.detail}</div>
              </div>
            ))}
          </div>

          {/* Payout / actions */}
          {isFunded && (
            <div className="a-stage-hero" style={{ padding: 18 }}>
              <div style={{ fontSize: 11, color: 'var(--text-dim)', textTransform: 'uppercase', letterSpacing: '.1em', fontWeight: 600 }}>Next payout</div>
              <div style={{ fontFamily: 'Space Grotesk', fontSize: 28, fontWeight: 700, marginTop: 6 }}>in {a.nextPayoutInDays} days</div>
              <div style={{ fontSize: 13, color: 'var(--text-dim)', marginTop: 2 }}>Available: ${window.fmtMoney((a.balance - a.size) * 0.8)}</div>
              <button className="a-btn primary" style={{ width: '100%', marginTop: 14, justifyContent: 'center' }}>
                <I.upload size={13}/> Request payout
              </button>
            </div>
          )}
        </div>
      </div>
      )}
    </>
  );
}

// ===== Account detail · Trade history tab =====
function AccountDetailHistory({ account }) {
  const a = account;
  const [side, setSide] = useState('all');
  const [outcome, setOutcome] = useState('all');
  const [range, setRange] = useState('30');
  const trades = [
    { d: 'May 19 14:01', s: 'EURUSD', side: 'BUY',  vol: 1.50, e: 1.08412, x: 1.08540, dur: '38m', pip: 12.8, rr: 2.1, pl: 192.00,  tag: 'Trend' },
    { d: 'May 19 13:42', s: 'XAUUSD', side: 'SELL', vol: 0.30, e: 2342.10, x: 2335.40, dur: '1h 4m', pip: 67.0, rr: 1.8, pl: 201.00,  tag: 'Reversal' },
    { d: 'May 19 12:22', s: 'NAS100', side: 'BUY',  vol: 0.80, e: 18420, x: 18395, dur: '12m', pip: -25.0, rr: -1.0, pl: -200.00, tag: 'Breakout' },
    { d: 'May 19 11:08', s: 'GBPJPY', side: 'BUY',  vol: 0.60, e: 192.45, x: 192.92, dur: '52m', pip: 47.0, rr: 2.5, pl: 188.40,  tag: 'Trend' },
    { d: 'May 19 10:32', s: 'BTCUSD', side: 'SELL', vol: 0.10, e: 67420, x: 67200, dur: '2h 18m', pip: 22.0, rr: 1.4, pl: 22.00,   tag: 'Range' },
    { d: 'May 19 09:18', s: 'EURJPY', side: 'BUY',  vol: 1.00, e: 169.42, x: 169.81, dur: '44m', pip: 39.0, rr: 1.9, pl: 248.20,  tag: 'Trend' },
    { d: 'May 18 16:44', s: 'XAUUSD', side: 'BUY',  vol: 0.40, e: 2330.00,x: 2342.00,dur: '3h 06m',pip: 120.0,rr: 3.0, pl: 480.00,  tag: 'High-conviction' },
    { d: 'May 18 14:11', s: 'USDJPY', side: 'SELL', vol: 0.80, e: 156.85, x: 156.42, dur: '1h 18m', pip: 43.0, rr: 2.0, pl: 215.00,  tag: 'Reversal' },
    { d: 'May 18 11:35', s: 'GBPUSD', side: 'BUY',  vol: 1.20, e: 1.27050,x: 1.27120,dur: '22m', pip: 7.0,  rr: 0.9, pl: 84.00,   tag: 'Range' },
    { d: 'May 17 15:02', s: 'WTI',    side: 'BUY',  vol: 0.50, e: 77.92,  x: 78.42,  dur: '4h 11m', pip: 50.0, rr: 2.2, pl: 250.00,  tag: 'Trend' },
  ];
  const filtered = trades.filter(t => {
    if (side !== 'all' && t.side.toLowerCase() !== side) return false;
    if (outcome === 'win' && t.pl < 0) return false;
    if (outcome === 'loss' && t.pl >= 0) return false;
    return true;
  });
  const wins = filtered.filter(t => t.pl > 0).length;
  const winRate = filtered.length ? Math.round((wins / filtered.length) * 100) : 0;
  const total = filtered.reduce((s, t) => s + t.pl, 0);

  return (
    <>
      {/* Summary tiles */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 18 }}>
        <div className="a-tile">
          <div className="l">TRADES</div>
          <div className="v">{filtered.length}</div>
          <div className="d" style={{ color: 'var(--text-dim)' }}>last {range} days</div>
        </div>
        <div className="a-tile">
          <div className="l">WIN RATE</div>
          <div className="v">{winRate}%</div>
          <div className="d pos">{wins} wins · {filtered.length - wins} losses</div>
        </div>
        <div className="a-tile">
          <div className="l">NET P&L</div>
          <div className={'v ' + (total >= 0 ? 'pos' : 'neg')}>{total >= 0 ? '+' : '−'}${window.fmtMoney(Math.abs(total))}</div>
          <div className="d" style={{ color: 'var(--text-dim)' }}>across selected filters</div>
        </div>
        <div className="a-tile">
          <div className="l">AVG TRADE</div>
          <div className="v mono">{filtered.length ? (total / filtered.length >= 0 ? '+' : '−') : ''}${filtered.length ? window.fmtMoney(Math.abs(total / filtered.length)) : '—'}</div>
          <div className="d" style={{ color: 'var(--text-dim)' }}>per trade</div>
        </div>
      </div>

      {/* Filter bar */}
      <div style={{ display: 'flex', gap: 10, alignItems: 'center', marginBottom: 14, flexWrap: 'wrap' }}>
        <div className="a-chips">
          {[{ id: 'all', l: 'All sides' }, { id: 'buy', l: 'Long' }, { id: 'sell', l: 'Short' }].map(o =>
            <button key={o.id} className={side === o.id ? 'active' : ''} onClick={() => setSide(o.id)}>{o.l}</button>
          )}
        </div>
        <div className="a-chips">
          {[{ id: 'all', l: 'All' }, { id: 'win', l: 'Wins' }, { id: 'loss', l: 'Losses' }].map(o =>
            <button key={o.id} className={outcome === o.id ? 'active' : ''} onClick={() => setOutcome(o.id)}>{o.l}</button>
          )}
        </div>
        <div className="a-chips">
          {[{ id: '7', l: '7d' }, { id: '30', l: '30d' }, { id: '90', l: '90d' }, { id: 'all', l: 'All' }].map(o =>
            <button key={o.id} className={range === o.id ? 'active' : ''} onClick={() => setRange(o.id)}>{o.l}</button>
          )}
        </div>
        <div style={{ flex: 1 }}/>
        <button className="a-btn secondary sm"><I.download size={11}/> Export CSV</button>
      </div>

      {/* Trade table */}
      <div className="a-section" style={{ padding: 0 }}>
        <table className="a-table">
          <thead>
            <tr>
              <th>Date</th><th>Symbol</th><th>Side</th>
              <th className="r">Volume</th><th className="r">Entry</th><th className="r">Exit</th>
              <th>Duration</th><th>Tag</th>
              <th className="r">Pips</th><th className="r">R:R</th><th className="r">P/L</th>
            </tr>
          </thead>
          <tbody>
            {filtered.map((t, i) => (
              <tr key={i}>
                <td className="mono" style={{ color: 'var(--text-dim)', fontSize: 11 }}>{t.d}</td>
                <td style={{ fontWeight: 600 }}>{t.s}</td>
                <td>
                  <span className="a-tag" style={{
                    background: t.side === 'BUY' ? 'color-mix(in oklab, var(--positive) 14%, transparent)' : 'color-mix(in oklab, var(--negative) 14%, transparent)',
                    color: t.side === 'BUY' ? 'var(--positive)' : 'var(--negative)',
                  }}>{t.side}</span>
                </td>
                <td className="mono r">{t.vol.toFixed(2)}</td>
                <td className="mono r" style={{ color: 'var(--text-dim)' }}>{t.e.toLocaleString()}</td>
                <td className="mono r" style={{ color: 'var(--text-dim)' }}>{t.x.toLocaleString()}</td>
                <td className="mono" style={{ color: 'var(--text-dim)', fontSize: 11 }}>{t.dur}</td>
                <td><span className="a-tag muted" style={{ fontSize: 9 }}>{t.tag.toUpperCase()}</span></td>
                <td className={'mono r ' + (t.pip >= 0 ? 'pos' : 'neg')}>{t.pip >= 0 ? '+' : ''}{t.pip.toFixed(1)}</td>
                <td className={'mono r ' + (t.rr >= 1.5 ? 'pos' : '')} style={{ color: t.rr < 0 ? 'var(--negative)' : t.rr >= 1.5 ? 'var(--positive)' : 'var(--text-dim)' }}>{t.rr.toFixed(1)}R</td>
                <td className={'mono r ' + (t.pl >= 0 ? 'pos' : 'neg')} style={{ fontWeight: 600 }}>{t.pl >= 0 ? '+' : '−'}${Math.abs(t.pl).toFixed(2)}</td>
              </tr>
            ))}
            {filtered.length === 0 && (
              <tr><td colSpan={11} style={{ padding: '40px 20px', textAlign: 'center', color: 'var(--text-dim)', fontSize: 13 }}>No trades match the current filters.</td></tr>
            )}
          </tbody>
        </table>
      </div>
    </>
  );
}

// ===== Account detail · Rules tab =====
function AccountDetailRules({ account, progress }) {
  const a = account;
  const rules = [
    { l: 'Profit target', v: `$${window.fmtMoney(progress.profitTargetUsd)}`, sub: 'Phase target before promotion', ok: progress.profitPct >= 1 },
    { l: 'Max overall drawdown', v: `$${window.fmtMoney(progress.maxLossUsd)}`, sub: 'Trailing equity from peak' },
    { l: 'Max daily loss', v: `$${window.fmtMoney(progress.dailyMaxUsd)}`, sub: 'Resets each trading day' },
    { l: 'Min profitable days', v: progress.minProfitDays || '—', sub: 'Days with net positive P&L' },
    { l: 'Consistency rule', v: '≤ 40% on a single day', sub: 'No day > 40% of total profit' },
    { l: 'News trading', v: a.status === 'funded' ? 'Not allowed during high-impact' : 'Allowed', sub: 'Applies to funded accounts only' },
    { l: 'Weekend hold', v: 'Closed by Friday 22:00 UTC', sub: 'Auto-flatten on remaining positions' },
    { l: 'Min hold time', v: '60 seconds', sub: 'Per-position guard' },
  ];
  return (
    <div className="a-section">
      <h3 style={{ margin: '0 0 14px', fontFamily: 'Space Grotesk', fontSize: 16 }}>Objectives & rules</h3>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 0 }}>
        {rules.map((r, i) => (
          <div key={i} style={{ padding: '14px 16px', borderBottom: i < rules.length - 2 ? '1px solid var(--line-2)' : 'none', borderRight: i % 2 === 0 ? '1px solid var(--line-2)' : 'none', display: 'flex', alignItems: 'flex-start', gap: 12 }}>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 14, fontWeight: 600 }}>{r.l}</div>
              <div style={{ fontSize: 11, color: 'var(--text-dim)', marginTop: 2 }}>{r.sub}</div>
            </div>
            <div className="mono" style={{ fontSize: 13, fontWeight: 600, color: 'var(--text)' }}>{r.v}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

function ArenaObjTile({ label, current, target, pct, invert, isDays }) {
  const bar = invert ? (pct>0.7?'danger':pct>0.4?'warn':'') : '';
  return (
    <div className="a-obj-tile">
      <div style={{ fontSize: 10, color: 'var(--text-faint)', letterSpacing: '.08em', textTransform: 'uppercase', fontWeight: 600 }}>{label}</div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginTop: 8 }}>
        <span className="mono" style={{ fontSize: 22, fontWeight: 600, letterSpacing: '-0.025em' }}>
          {isDays ? current : '$' + window.fmtMoney(current)}
        </span>
        <span className="mono" style={{ fontSize: 11, color: 'var(--text-faint)' }}>
          / {isDays ? target : '$' + (typeof target === 'number' ? window.fmtMoney(target) : target)}
        </span>
      </div>
      <div className={'a-obj-bar ' + bar} style={{ marginTop: 10 }}>
        <i style={{ width: Math.min(100, pct*100) + '%' }}/>
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 6, fontSize: 11, color: 'var(--text-dim)' }}>
        <span>{Math.round(pct*100)}%</span>
        <span className="mono">{invert ? 'used' : 'reached'}</span>
      </div>
    </div>
  );
}

function ArenaKv({ label, value, mono, copy }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '10px 0', borderBottom: '1px solid var(--line-2)' }}>
      <span style={{ fontSize: 11, color: 'var(--text-dim)', textTransform: 'uppercase', letterSpacing: '.08em', fontWeight: 600 }}>{label}</span>
      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
        <span className={mono?'mono':''} style={{ fontSize: 13 }}>{value}</span>
        {copy && <button className="a-iconbtn" style={{ width: 26, height: 26 }}><I.copy size={11}/></button>}
      </span>
    </div>
  );
}

// ===================== ARENA · MOBILE =====================
function ArenaMobile({ routes }) {
  const { page } = useApp();
  const PageComponent = routes[page] || routes.dashboard;
  return (
    <div className="am">
      <div className="phone-notch"></div>
      <PageComponent/>
      <ArenaMobileTabbar/>
    </div>
  );
}

function ArenaMobileTabbar() {
  const { page, setPage } = useApp();
  return (
    <div className="am-tabbar">
      <div className={'am-tab ' + (page==='dashboard'?'active':'')} onClick={()=>setPage('dashboard')}>
        <I.home size={18}/> Arena
      </div>
      <div className={'am-tab ' + (page==='accounts'?'active':'')} onClick={()=>setPage('accounts')}>
        <I.grid size={18}/> Accounts
      </div>
      <div className="am-tab cta" onClick={()=>window.openArenaTrader && window.openArenaTrader()} title="Trade"><I.candles size={20}/></div>
      <div className={'am-tab ' + (page==='journal'?'active':'')} onClick={()=>setPage('journal')}>
        <I.list size={18}/> Journal
      </div>
      <div className={'am-tab ' + (page==='profile'?'active':'')} onClick={()=>setPage('profile')}>
        <I.user size={18}/> Profile
      </div>
    </div>
  );
}

function ArenaMobileDash() {
  const { accounts, setPage } = useApp();
  const totalEquity = accounts.reduce((s, a) => s + a.equity, 0);
  const todayPnl = accounts.reduce((s, a) => s + (a.profitToday || 0), 0);
  return (
    <>
      <div className="am-header">
        <PropArenaLockup size={26}/>
        <div style={{ display: 'flex', gap: 8 }}>
          <button onClick={() => setPage('inbox')} className="icon-btn" style={{
            width: 38, height: 38, borderRadius: 12,
            background: 'rgba(255,255,255,0.04)', border: '1px solid var(--line)',
            color: 'var(--text-dim)', display: 'flex', alignItems: 'center', justifyContent: 'center',
          }} title="Inbox"><I.mail size={16}/></button>
          <button onClick={() => setPage('notifications')} className="icon-btn" style={{
            width: 38, height: 38, borderRadius: 12,
            background: 'rgba(255,255,255,0.04)', border: '1px solid var(--line)',
            color: 'var(--text-dim)', display: 'flex', alignItems: 'center', justifyContent: 'center',
            position: 'relative',
          }} title="Notifications">
            <I.bell size={16}/>
            <span style={{ position: 'absolute', top: 6, right: 6, width: 7, height: 7, borderRadius: 999, background: 'var(--magenta)' }}/>
          </button>
        </div>
      </div>
      <div className="am-hero">
        <div className="am-rankbar">
          <div className="b">G</div>
          <div className="meta">
            <b>Gold tier</b>
            <div>2,840 / 3,500 XP · 660 to Platinum</div>
            <div style={{ marginTop: 6, height: 5, background: 'rgba(255,255,255,0.08)', borderRadius: 999, overflow: 'hidden' }}>
              <div style={{ width: '78%', height: '100%', background: 'linear-gradient(90deg, var(--magenta), var(--cyan))' }}/>
            </div>
          </div>
        </div>
        <div style={{ fontSize: 10, color: 'var(--text-dim)', textTransform: 'uppercase', letterSpacing: '.1em', fontWeight: 700 }}>TOTAL EQUITY</div>
        <div className="am-eq" style={{ marginTop: 4 }}>
          <span className="c">$</span>{Math.floor(totalEquity).toLocaleString()}<span className="d">.{totalEquity.toFixed(2).split('.')[1]}</span>
        </div>
        <div className="am-delta" style={{ color: todayPnl<0?'var(--negative)':'var(--positive)' }}>
          {todayPnl>=0?<I.arrowUp size={11}/>:<I.arrowDown size={11}/>} {window.fmtMoney(Math.abs(todayPnl))} today
        </div>
        <div className="am-actions">
          <button className="a-btn primary" style={{ justifyContent: 'center' }} onClick={() => setPage('newAccount')}><I.plus size={13}/> New account</button>
          <button className="a-btn secondary" style={{ justifyContent: 'center' }} onClick={() => window.openArenaTrader && window.openArenaTrader()}><I.candles size={13}/> ArenaTrader</button>
        </div>
      </div>

      <div className="am-acts-row">
        {[
          { i: 'candles', l: 'Trade' },
          { i: 'wallet', l: 'Billing' },
          { i: 'trophy', l: 'Cup' },
          { i: 'gift', l: 'Rewards' },
        ].map(x => (
          <div key={x.l} className="am-act">
            <div className="ico">{I[x.i]({ size: 16 })}</div>
            <b>{x.l}</b>
          </div>
        ))}
      </div>

      <div className="am-section-head">
        <h3>Active accounts</h3>
        <a onClick={() => setPage('accounts')}>See all <I.chevronRight size={11}/></a>
      </div>
      {accounts.filter(a => a.status!=='failed').slice(0,2).map(a => <ArenaMobileAcctRow key={a.id} a={a}/>)}

      <div className="am-section-head"><h3>Today's events</h3></div>
      {window.SEED_NEWS.slice(0,3).map((n, i) => (
        <div key={i} className="am-acct" style={{ padding: 12, marginBottom: 8, display: 'flex', alignItems: 'center', gap: 10 }}>
          <span className="mono" style={{ fontSize: 12, color: 'var(--text-dim)', minWidth: 40 }}>{n.time}</span>
          <span style={{ width: 6, height: 6, borderRadius: 999, background: n.impact==='high'?'var(--negative)':'var(--gold)' }}/>
          <span style={{ flex: 1, fontSize: 12 }}>{n.title}</span>
          <CountryDot c={n.country}/>
        </div>
      ))}
    </>
  );
}

function ArenaMobileAcctRow({ a }) {
  const { setAccountId, setPage } = useApp();
  const p = useAccountProgress(a);
  return (
    <div className={'am-acct ' + (a.status==='funded'?'funded':'')} onClick={()=>{setAccountId(a.id); setPage('account');}}>
      <div className="am-acct-row1">
        <div style={{ minWidth: 0, flex: 1 }}>
          <div className="am-acct-id" style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{a.login} · {a.plan}</div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 4, flexWrap: 'wrap' }}>
            <span className="am-acct-size" style={{ marginLeft: 0 }}>${window.fmtMoneyCompact(a.size)}</span>
            <span className={'a-acct-tag ' + (a.status==='funded'?'funded':a.status==='failed'?'failed':'eval')}>
              {a.status==='funded'?'FUNDED':a.status==='failed'?'FAILED':window.planLabel(a).toUpperCase()}
            </span>
          </div>
        </div>
        <div style={{ flex: 'none', textAlign: 'right' }}>
          <div className="am-acct-bal mono">${window.fmtMoney(a.equity)}</div>
          <div className="mono" style={{ fontSize: 11, color: (a.balance-a.size)>=0?'var(--positive)':'var(--negative)', textAlign: 'right' }}>
            {(a.balance-a.size)>=0?'+':''}{window.fmtMoney(a.balance-a.size)}
          </div>
        </div>
      </div>
      <div className="am-acct-bar">
        {a.stages.map((s, i) => (
          <div key={i} className={'seg ' + (s.status==='passed'?'lit':'')}>
            {s.status==='in_progress' && <div className="ind" style={{ width: Math.min(100, p.profitPct*100) + '%' }}/>}
          </div>
        ))}
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 8, fontSize: 11, color: 'var(--text-dim)' }}>
        <span>Profit {Math.round(p.profitPct*100)}%</span>
        <span>DD {Math.round(p.ddPct*100)}%</span>
        <span>Daily {Math.round(p.dailyPct*100)}%</span>
      </div>
    </div>
  );
}

function ArenaMobileAccounts() {
  const { accounts, setPage } = useApp();
  const [f, setF] = useState('all');
  const filtered = f==='all'?accounts:accounts.filter(a => f==='funded'?a.status==='funded':a.status!=='funded');
  return (
    <>
      <div className="am-header">
        <div className="am-greet">Accounts <small>{accounts.length} total · {accounts.filter(a=>a.status==='funded').length} funded</small></div>
        <button onClick={() => setPage('newAccount')} className="icon-btn" style={{
          width: 38, height: 38, borderRadius: 12,
          background: 'linear-gradient(135deg, var(--magenta), var(--magenta-2))',
          color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', border: 'none', cursor: 'pointer',
        }}><I.plus size={16}/></button>
      </div>
      <div className="a-chips" style={{ marginBottom: 14, width: '100%', display: 'flex' }}>
        {[
          { id: 'all', l: 'All', c: accounts.length },
          { id: 'eval', l: 'Challenge', c: accounts.filter(a=>a.status!=='funded').length },
          { id: 'funded', l: 'Funded', c: accounts.filter(a=>a.status==='funded').length },
        ].map(x => (
          <button key={x.id} className={f===x.id?'active':''} onClick={()=>setF(x.id)} style={{ flex: 1, justifyContent: 'center' }}>
            {x.l} <span className="c">{x.c}</span>
          </button>
        ))}
      </div>
      {filtered.map(a => <ArenaMobileAcctRow key={a.id} a={a}/>)}
    </>
  );
}

function ArenaMobileAccount() {
  const { account, setPage } = useApp();
  const a = account;
  const p = useAccountProgress(a);
  const isFunded = a.status==='funded';
  const [tab, setTab] = useState('overview');
  return (
    <>
      <div className="am-header">
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <button onClick={()=>setPage('accounts')} style={{
            width: 36, height: 36, borderRadius: 10,
            background: 'rgba(255,255,255,0.04)', border: '1px solid var(--line)',
            color: 'var(--text)', display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}><I.chevronLeft size={16}/></button>
          <div className="am-greet" style={{ fontSize: 18 }}>${window.fmtMoneyCompact(a.size)} {a.plan}<small>{a.login} · {a.server}</small></div>
        </div>
        <button className="icon-btn" style={{
          width: 38, height: 38, borderRadius: 12,
          background: 'rgba(255,255,255,0.04)', border: '1px solid var(--line)',
          color: 'var(--text-dim)', display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}><I.dots size={16}/></button>
      </div>

      <div className="a-chips" style={{ marginBottom: 14, width: '100%' }}>
        {[
          { id: 'overview', l: 'Overview' },
          { id: 'rules',    l: 'Rules' },
          { id: 'history',  l: 'Trades' },
        ].map(t => (
          <button key={t.id} className={tab === t.id ? 'active' : ''} onClick={() => setTab(t.id)} style={{ flex: 1, justifyContent: 'center', fontSize: 12 }}>{t.l}</button>
        ))}
        <button onClick={() => window.openArenaTrader && window.openArenaTrader(a.id)} style={{ flex: 1, justifyContent: 'center', fontSize: 12, display: 'inline-flex', alignItems: 'center', gap: 4, padding: '7px 10px', background: 'linear-gradient(135deg, var(--magenta), var(--cyan))', color: '#06070D', border: 'none', borderRadius: 7, fontWeight: 600, cursor: 'pointer' }}>
          <I.candles size={12}/> Trade
        </button>
      </div>

      {tab === 'overview' && <ArenaMobileAccountOverview a={a} p={p} isFunded={isFunded} setPage={setPage}/>}
      {tab === 'rules'    && <ArenaMobileAccountRules a={a} p={p}/>}
      {tab === 'history'  && <ArenaMobileAccountHistory a={a}/>}
    </>
  );
}

function ArenaMobileAccountOverview({ a, p, isFunded, setPage }) {
  return (
    <>
      <div className="am-hero">
        <div style={{ fontSize: 10, color: 'var(--text-dim)', textTransform: 'uppercase', letterSpacing: '.1em', fontWeight: 700 }}>
          {isFunded?'EQUITY · live':'BALANCE'}
        </div>
        <div className="am-eq" style={{ marginTop: 4 }}>
          <span className="c">$</span>{Math.floor(a.equity).toLocaleString()}<span className="d">.{a.equity.toFixed(2).split('.')[1]}</span>
        </div>
        <div className="am-delta" style={{ color: a.profitToday>=0?'var(--positive)':'var(--negative)' }}>
          {a.profitToday>=0?'+':''}{window.fmtMoney(a.profitToday)} today
        </div>
        <div style={{ height: 60, marginTop: 12 }}>
          <Spark data={a.history} color="url(#a-grad)" strokeWidth={2} fill="url(#a-fill)"/>
        </div>
        <div className="am-actions">
          {isFunded
            ? <button className="a-btn primary" style={{ justifyContent: 'center' }} onClick={() => setPage('wallet')}><I.upload size={13}/> Payout</button>
            : <button className="a-btn primary" style={{ justifyContent: 'center' }} onClick={() => window.openArenaTrader && window.openArenaTrader(a.id)}><I.candles size={13}/> ArenaTrader</button>}
          <button className="a-btn secondary" style={{ justifyContent: 'center' }} onClick={() => window.openArenaTrader && window.openArenaTrader(a.id)}>
            {isFunded ? <><I.candles size={13}/> ArenaTrader</> : <><I.copy size={13}/> Credentials</>}
          </button>
        </div>
      </div>

      <div className="am-section-head"><h3>Objectives</h3></div>
      {[
        { l: 'Profit', cur: '$'+window.fmtMoney(p.profit), tgt: '$'+window.fmtMoney(p.profitTargetUsd), pct: p.profitPct },
        { l: 'Drawdown', cur: '$'+window.fmtMoney(p.ddSoFar), tgt: '$'+window.fmtMoney(p.maxLossUsd), pct: p.ddPct, invert: true },
        { l: 'Daily loss', cur: '$'+window.fmtMoney(p.dailyUsed), tgt: '$'+window.fmtMoney(p.dailyMaxUsd), pct: p.dailyPct, invert: true },
      ].map((o, i) => (
        <div key={i} className="am-acct" style={{ padding: 14 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 6 }}>
            <span style={{ fontSize: 12, color: 'var(--text-dim)' }}>{o.l}</span>
            <span className="mono" style={{ fontSize: 11, color: 'var(--text)' }}>{Math.round(o.pct*100)}%</span>
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 8 }}>
            <span className="mono" style={{ fontSize: 16, fontWeight: 600 }}>{o.cur}</span>
            <span className="mono" style={{ fontSize: 11, color: 'var(--text-faint)' }}>/ {o.tgt}</span>
          </div>
          <div className={'a-obj-bar ' + (o.invert && o.pct>0.7?'danger':o.invert && o.pct>0.4?'warn':'')}>
            <i style={{ width: Math.min(100, o.pct*100) + '%' }}/>
          </div>
        </div>
      ))}

      <div className="am-section-head"><h3>Credentials</h3></div>
      <div className="am-acct" style={{ padding: 14 }}>
        <ArenaKv label="Login" value={a.login} mono copy/>
        <ArenaKv label="Server" value={a.server} mono/>
        <ArenaKv label="Leverage" value="1:30"/>
      </div>
    </>
  );
}

function ArenaMobileAccountRules({ a, p }) {
  const rules = [
    { l: 'Profit target', v: `$${window.fmtMoney(p.profitTargetUsd)}`, sub: 'Phase target before promotion' },
    { l: 'Max overall drawdown', v: `$${window.fmtMoney(p.maxLossUsd)}`, sub: 'Trailing equity from peak' },
    { l: 'Max daily loss', v: `$${window.fmtMoney(p.dailyMaxUsd)}`, sub: 'Resets each trading day' },
    { l: 'Consistency rule', v: '≤ 40% on a single day', sub: 'No day > 40% of total profit' },
    { l: 'News trading', v: a.status === 'funded' ? 'Not allowed high-impact' : 'Allowed', sub: 'Funded only' },
    { l: 'Min hold time', v: '60 seconds', sub: 'Per-position guard' },
  ];
  return (
    <div className="am-acct" style={{ padding: 0 }}>
      {rules.map((r, i) => (
        <div key={i} style={{ padding: '12px 14px', borderBottom: i < rules.length - 1 ? '1px solid var(--line-2)' : 'none' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 10 }}>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 13, fontWeight: 600 }}>{r.l}</div>
              <div style={{ fontSize: 11, color: 'var(--text-dim)', marginTop: 2 }}>{r.sub}</div>
            </div>
            <div className="mono" style={{ fontSize: 12, fontWeight: 600, textAlign: 'right' }}>{r.v}</div>
          </div>
        </div>
      ))}
    </div>
  );
}

function ArenaMobileAccountHistory({ a }) {
  const [side, setSide] = useState('all');
  const trades = [
    { d: 'May 19 14:01', s: 'EURUSD', side: 'BUY',  vol: 1.50, pl: 192.00 },
    { d: 'May 19 13:42', s: 'XAUUSD', side: 'SELL', vol: 0.30, pl: 201.00 },
    { d: 'May 19 12:22', s: 'NAS100', side: 'BUY',  vol: 0.80, pl: -200.00 },
    { d: 'May 19 11:08', s: 'GBPJPY', side: 'BUY',  vol: 0.60, pl: 188.40 },
    { d: 'May 19 10:32', s: 'BTCUSD', side: 'SELL', vol: 0.10, pl: 22.00 },
    { d: 'May 19 09:18', s: 'EURJPY', side: 'BUY',  vol: 1.00, pl: 248.20 },
    { d: 'May 18 16:44', s: 'XAUUSD', side: 'BUY',  vol: 0.40, pl: 480.00 },
    { d: 'May 18 14:11', s: 'USDJPY', side: 'SELL', vol: 0.80, pl: 215.00 },
  ];
  const filtered = trades.filter(t => side === 'all' ? true : t.side.toLowerCase() === side);
  const wins = filtered.filter(t => t.pl > 0).length;
  const winRate = filtered.length ? Math.round(wins / filtered.length * 100) : 0;
  const total = filtered.reduce((s, t) => s + t.pl, 0);
  return (
    <>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 6, marginBottom: 12 }}>
        <div className="am-card" style={{ padding: 10, marginBottom: 0 }}>
          <div style={{ fontSize: 9, color: 'var(--text-dim)', textTransform: 'uppercase', letterSpacing: '.06em', fontWeight: 600 }}>Trades</div>
          <div className="mono" style={{ fontSize: 18, fontWeight: 700, marginTop: 2 }}>{filtered.length}</div>
        </div>
        <div className="am-card" style={{ padding: 10, marginBottom: 0 }}>
          <div style={{ fontSize: 9, color: 'var(--text-dim)', textTransform: 'uppercase', letterSpacing: '.06em', fontWeight: 600 }}>Win rate</div>
          <div className="mono" style={{ fontSize: 18, fontWeight: 700, marginTop: 2 }}>{winRate}%</div>
        </div>
        <div className="am-card" style={{ padding: 10, marginBottom: 0 }}>
          <div style={{ fontSize: 9, color: 'var(--text-dim)', textTransform: 'uppercase', letterSpacing: '.06em', fontWeight: 600 }}>Net P&L</div>
          <div className={'mono ' + (total >= 0 ? 'pos' : 'neg')} style={{ fontSize: 16, fontWeight: 700, marginTop: 2 }}>{total >= 0 ? '+' : '−'}${window.fmtMoney(Math.abs(total))}</div>
        </div>
      </div>
      <div className="a-chips" style={{ marginBottom: 10, width: '100%' }}>
        {[{ id: 'all', l: 'All' }, { id: 'buy', l: 'Long' }, { id: 'sell', l: 'Short' }].map(o =>
          <button key={o.id} className={side === o.id ? 'active' : ''} onClick={() => setSide(o.id)} style={{ flex: 1, justifyContent: 'center', fontSize: 11 }}>{o.l}</button>
        )}
      </div>
      <div className="am-card" style={{ padding: 0 }}>
        {filtered.map((t, i) => (
          <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '11px 14px', borderBottom: i < filtered.length - 1 ? '1px solid var(--line-2)' : 'none' }}>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontWeight: 600, fontSize: 13 }}>{t.s}</div>
              <div className="mono" style={{ fontSize: 10, color: 'var(--text-faint)', marginTop: 2 }}>{t.d} · {t.vol.toFixed(2)} lots</div>
            </div>
            <span className="a-tag" style={{ background: t.side==='BUY'?'color-mix(in oklab, var(--positive) 14%, transparent)':'color-mix(in oklab, var(--negative) 14%, transparent)', color: t.side==='BUY'?'var(--positive)':'var(--negative)', fontSize: 9 }}>{t.side}</span>
            <span className={'mono ' + (t.pl >= 0 ? 'pos' : 'neg')} style={{ fontWeight: 700, fontSize: 13, minWidth: 70, textAlign: 'right' }}>{t.pl >= 0 ? '+' : '−'}${Math.abs(t.pl).toFixed(2)}</span>
          </div>
        ))}
      </div>
    </>
  );
}

// Export
Object.assign(window, { ArenaApp });
