// ============================================================
// PROP ARENA — extra screens (round 2, matches spec)
// WebTrader · Inbox · Profile · ProfileEdit · Security
// Deposit (3 sub) · Withdraw (4 sub) · ForgotPassword
// ============================================================

// ============ WEBTRADER ============
function ArenaWebtrader() {
  const { accounts, accountId, setAccountId, setPage } = useApp();
  const [state, setState] = useState('loading'); // loading | ok | error
  const [acc, setAcc] = useState(accountId);
  const current = accounts.find(a => a.id === acc) || accounts[0];

  useEffect(() => {
    setState('loading');
    const t = setTimeout(() => setState('ok'), 1100);
    return () => clearTimeout(t);
  }, [acc]);

  function retry() { setState('loading'); setTimeout(() => setState('ok'), 800); }
  function simulateError() { setState('error'); }

  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 }}>WebTrader</span>
          </div>
          <h1 style={{ marginTop: 6 }}>Web<em>Trader</em>.</h1>
          <div className="sub">Embedded trading terminal · SSO from your support account</div>
        </div>
        <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
          <select className="a-input" style={{ minWidth: 240, height: 40 }} value={acc} onChange={e => { setAcc(e.target.value); setAccountId(e.target.value); }}>
            {accounts.map(a => (
              <option key={a.id} value={a.id}>{a.login} · ${window.fmtMoneyCompact(a.size)} {a.plan} {a.status === 'funded' ? '· FUNDED' : ''}</option>
            ))}
          </select>
          <button className="a-btn secondary" onClick={() => window.open('about:blank', '_blank')}><I.external size={13}/> Pop out</button>
          <button className="a-btn secondary" onClick={() => window.open('about:blank', '_blank')}><I.external size={13}/> New tab</button>
          <button className="a-btn secondary" onClick={() => setPage('credentials')}><I.download size={13}/> Open MT5</button>
        </div>
      </div>

      <div style={{
        height: 'calc(100vh - 320px)', minHeight: 540,
        background: 'var(--surface)',
        border: '1px solid var(--line)',
        borderRadius: 16,
        overflow: 'hidden',
        position: 'relative',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
      }}>
        {/* simulated chart placeholder */}
        <svg viewBox="0 0 1200 600" preserveAspectRatio="none" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', opacity: state === 'ok' ? 0.6 : 0.2, transition: 'opacity .5s' }}>
          <defs>
            <linearGradient id="wt-fill" x1="0" x2="0" y1="0" y2="1">
              <stop offset="0%" stopColor="oklch(72% 0.27 330)" stopOpacity="0.3"/>
              <stop offset="100%" stopColor="oklch(72% 0.27 330)" stopOpacity="0"/>
            </linearGradient>
          </defs>
          <path d="M 0 400 Q 200 300 350 350 T 700 250 T 1050 200 T 1200 220 L 1200 600 L 0 600 Z" fill="url(#wt-fill)"/>
          <path d="M 0 400 Q 200 300 350 350 T 700 250 T 1050 200 T 1200 220" fill="none" stroke="oklch(72% 0.27 330)" strokeWidth="2"/>
        </svg>

        {state === 'loading' && (
          <div style={{ position: 'relative', textAlign: 'center', zIndex: 2 }}>
            <div style={{ width: 48, height: 48, borderRadius: 999, border: '3px solid var(--line)', borderTopColor: 'var(--magenta)', margin: '0 auto', animation: 'spin 0.8s linear infinite' }}/>
            <div style={{ marginTop: 18, fontSize: 13, color: 'var(--text-dim)' }}>Loading WebTrader for <b style={{ color: 'var(--text)' }} className="mono">{current.login}</b>…</div>
            <div style={{ marginTop: 4, fontSize: 11, color: 'var(--text-faint)' }}>Negotiating SSO with support broker</div>
          </div>
        )}

        {state === 'ok' && (
          <div style={{ position: 'relative', textAlign: 'center', zIndex: 2 }}>
            <div style={{
              width: 64, height: 64, borderRadius: 18,
              background: 'linear-gradient(135deg, var(--magenta), var(--cyan))',
              color: '#06070D',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              margin: '0 auto',
              boxShadow: '0 0 40px -6px var(--magenta)',
            }}>
              <I.candles size={28}/>
            </div>
            <div style={{ fontFamily: 'Space Grotesk', fontSize: 24, fontWeight: 700, marginTop: 18 }}>WebTrader iframe slot</div>
            <div style={{ fontSize: 13, color: 'var(--text-dim)', marginTop: 6, maxWidth: 420 }}>
              The real <span className="mono">&lt;iframe&gt;</span> mounts here once you wire up the support WebTrader SSO URL.
            </div>
            <div style={{ marginTop: 18, display: 'inline-flex', gap: 8 }}>
              <button className="a-btn ghost sm" onClick={simulateError}><I.warn size={11}/> Simulate error</button>
              <button className="a-btn ghost sm" onClick={retry}><I.refresh size={11}/> Reload</button>
            </div>
          </div>
        )}

        {state === 'error' && (
          <div style={{ position: 'relative', textAlign: 'center', zIndex: 2, maxWidth: 440, padding: 20 }}>
            <div style={{
              width: 64, height: 64, borderRadius: 18,
              background: 'color-mix(in oklab, var(--negative) 20%, transparent)',
              border: '1px solid color-mix(in oklab, var(--negative) 40%, transparent)',
              color: 'var(--negative)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              margin: '0 auto',
            }}>
              <I.warn size={28}/>
            </div>
            <div style={{ fontFamily: 'Space Grotesk', fontSize: 22, fontWeight: 700, marginTop: 18 }}>Trading session unavailable</div>
            <div style={{ fontSize: 13, color: 'var(--text-dim)', marginTop: 8 }}>
              SSO cooldown active. Wait ~10 seconds and try again, or return to your accounts.
            </div>
            <div style={{ marginTop: 18, display: 'inline-flex', gap: 8 }}>
              <button className="a-btn primary sm" onClick={retry}><I.refresh size={11}/> Retry</button>
              <button className="a-btn secondary sm" onClick={() => setPage('accounts')}><I.chevronLeft size={11}/> Back to accounts</button>
            </div>
          </div>
        )}
      </div>

      <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
    </>
  );
}

// ============ INBOX ============
function ArenaInbox() {
  const [filter, setFilter] = useState('all');
  const [openId, setOpenId] = useState('m1');
  const messages = [
    { id: 'm1', from: 'Support · Maya', subj: 'Your KYC documents are approved', preview: 'Hi Yulia, your identity and address documents have been reviewed and approved…', tm: '2h', cat: 'support', unread: true },
    { id: 'm2', from: 'Risk team', subj: 'Reminder: Consistency rule applies to all funded accounts', preview: 'A friendly reminder that no single trading day should exceed 40% of total profit…', tm: '1d', cat: 'risk', unread: true },
    { id: 'm3', from: 'Payouts', subj: 'Payout #PT-19 dispatched to USDT TRC-20', preview: 'Your payout of $4,283.50 has been dispatched. TX hash will appear within 6h…', tm: '6d', cat: 'payouts', unread: false },
    { id: 'm4', from: 'Prop Arena', subj: 'Season 6 Grand Cup — 14 days remain', preview: 'You are currently ranked #247 in the Grand Cup. The prize pool is $50,000…', tm: '8d', cat: 'announce', unread: false },
    { id: 'm5', from: 'Affiliates', subj: 'May commission statement ready', preview: 'Your May commissions total $240.05 across 6 conversions. Detailed breakdown attached…', tm: '12d', cat: 'affil', unread: false },
  ];
  const filtered = filter === 'all' ? messages : filter === 'unread' ? messages.filter(m => m.unread) : messages.filter(m => m.cat === filter);
  const opened = messages.find(m => m.id === openId) || messages[0];

  return (
    <>
      <div className="a-pagehead">
        <div>
          <h1><em>Inbox</em>.</h1>
          <div className="sub">{messages.filter(m => m.unread).length} unread · {messages.length} total · last fetched 14:02 UTC</div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <button className="a-btn secondary"><I.check size={13}/> Mark all read</button>
          <button className="a-btn secondary"><I.refresh size={13}/> Refresh</button>
        </div>
      </div>

      <div className="a-chips" style={{ marginBottom: 18 }}>
        {[
          { id: 'all', l: 'All', c: messages.length },
          { id: 'unread', l: 'Unread', c: messages.filter(m => m.unread).length },
          { id: 'support', l: 'Support' },
          { id: 'risk', l: 'Risk' },
          { id: 'payouts', l: 'Payouts' },
          { id: 'announce', l: 'Announcements' },
        ].map(x => (
          <button key={x.id} className={filter === x.id ? 'active' : ''} onClick={() => setFilter(x.id)}>
            {x.l} {x.c != null && <span className="c">{x.c}</span>}
          </button>
        ))}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '380px 1fr', gap: 18 }}>
        <div className="a-section" style={{ padding: 0, maxHeight: 'calc(100vh - 360px)', overflowY: 'auto' }}>
          {filtered.map((m, i) => (
            <div key={m.id} onClick={() => setOpenId(m.id)} style={{
              display: 'flex', flexDirection: 'column', gap: 4,
              padding: '14px 16px',
              cursor: 'pointer',
              borderBottom: i < filtered.length - 1 ? '1px solid var(--line-2)' : 'none',
              background: openId === m.id ? 'rgba(255,92,245,0.06)' : m.unread ? 'rgba(92,217,255,0.03)' : 'transparent',
              borderLeft: openId === m.id ? '2px solid var(--magenta)' : '2px solid transparent',
            }}>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <span style={{ fontSize: 12, fontWeight: m.unread ? 700 : 500, color: m.unread ? 'var(--text)' : 'var(--text-dim)' }}>{m.from}</span>
                <span className="mono" style={{ fontSize: 10, color: 'var(--text-faint)' }}>{m.tm}</span>
              </div>
              <div style={{ fontSize: 13, fontWeight: m.unread ? 600 : 500, color: 'var(--text)' }}>{m.subj}</div>
              <div style={{ fontSize: 11, color: 'var(--text-dim)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{m.preview}</div>
            </div>
          ))}
        </div>

        <div className="a-section" style={{ padding: 24 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 14 }}>
            <div>
              <div style={{ fontFamily: 'Space Grotesk', fontSize: 22, fontWeight: 700, letterSpacing: '-0.02em' }}>{opened.subj}</div>
              <div style={{ fontSize: 12, color: 'var(--text-dim)', marginTop: 4 }}>From <b style={{ color: 'var(--text)' }}>{opened.from}</b> · {opened.tm} ago</div>
            </div>
            <div style={{ display: 'flex', gap: 6 }}>
              <button className="a-iconbtn"><I.bookmark size={13}/></button>
              <button className="a-iconbtn"><I.trash size={13}/></button>
              <button className="a-iconbtn"><I.dots size={13}/></button>
            </div>
          </div>
          <div style={{ fontSize: 14, lineHeight: 1.6, color: 'var(--text-dim)' }}>
            <p>{opened.preview}</p>
            <p>Read-only display — replies route to support@proparena.io or the live chat from the Help page.</p>
          </div>
          <div style={{ marginTop: 18, display: 'flex', gap: 8 }}>
            <button className="a-btn secondary"><I.speak size={13}/> Open live chat</button>
            <button className="a-btn ghost"><I.check size={13}/> Mark unread</button>
          </div>
        </div>
      </div>
    </>
  );
}

// ============ PROFILE (read-only summary) ============
function ArenaProfile() {
  const { setPage } = useApp();
  return (
    <>
      <div className="a-pagehead">
        <div>
          <h1>My <em>profile</em>.</h1>
          <div className="sub">Personal · billing · bank · KYC · security</div>
        </div>
        <div style={{ display: 'flex', gap: 10 }}>
          <button className="a-btn secondary" onClick={() => setPage('security')}><I.shield size={13}/> Security</button>
          <button className="a-btn primary" onClick={() => setPage('profileEdit')}><I.edit size={13}/> Edit profile</button>
        </div>
      </div>

      <div className="a-section" style={{ marginBottom: 18, background: 'linear-gradient(135deg, rgba(255,92,245,0.06), rgba(92,217,255,0.04)), var(--surface)' }}>
        <div style={{ display: 'flex', gap: 22, alignItems: 'center' }}>
          <div style={{ width: 86, height: 86, borderRadius: 22, background: 'linear-gradient(135deg, var(--magenta), var(--cyan))', color: '#06070D', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 800, fontSize: 32, fontFamily: 'Space Grotesk' }}>YL</div>
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: 'Space Grotesk', fontSize: 28, fontWeight: 700, letterSpacing: '-0.025em' }}>Yulia Larssen</div>
            <div style={{ fontSize: 13, color: 'var(--text-dim)', marginTop: 4 }}>yulia@example.com · Italy · trader since April 2024</div>
            <div style={{ display: 'flex', gap: 6, marginTop: 10 }}>
              <span className="a-tag success">KYC VERIFIED</span>
              <span className="a-tag" style={{ background: 'color-mix(in oklab, var(--cyan) 14%, transparent)', color: 'var(--cyan)' }}>GOLD TIER</span>
              <span className="a-tag muted">12 PAYOUTS</span>
            </div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <div className="mono" style={{ fontSize: 32, fontWeight: 700, letterSpacing: '-0.03em' }}>$8,043</div>
            <div style={{ fontSize: 11, color: 'var(--text-dim)', textTransform: 'uppercase', letterSpacing: '.1em' }}>Lifetime payouts</div>
          </div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18, marginBottom: 18 }}>
        <div className="a-section">
          <h3 style={{ margin: '0 0 14px', fontFamily: 'Space Grotesk', fontSize: 16 }}>Personal</h3>
          <ArenaKv label="Full name" value="Yulia Larssen"/>
          <ArenaKv label="Date of birth" value="1991-03-14"/>
          <ArenaKv label="Country" value="Italy"/>
          <ArenaKv label="Address" value="Via Roma 42, Rome 00184" copy/>
          <ArenaKv label="Phone" value="+39 ••• ••• 4112"/>
          <ArenaKv label="Tax ID" value="LRSYLI91C54H501Z" mono copy/>
        </div>
        <div className="a-section">
          <h3 style={{ margin: '0 0 14px', fontFamily: 'Space Grotesk', fontSize: 16 }}>Billing</h3>
          <ArenaKv label="Default method" value="Wallet balance"/>
          <ArenaKv label="Billing email" value="yulia@example.com" copy/>
          <ArenaKv label="Currency" value="USD"/>
          <ArenaKv label="VAT number" value="—"/>
          <ArenaKv label="Invoices" value="12 issued"/>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18 }}>
        <div className="a-section">
          <h3 style={{ margin: '0 0 14px', fontFamily: 'Space Grotesk', fontSize: 16 }}>Bank / Payout destinations</h3>
          <ArenaKv label="USDT TRC-20" value="TR3z…9F2A" mono copy/>
          <ArenaKv label="USDT ERC-20" value="0xa1…c7Bd" mono copy/>
          <ArenaKv label="Wire · IT" value="IBAN ••••3344" mono copy/>
          <div style={{ marginTop: 12, fontSize: 12, color: 'var(--text-dim)' }}>
            <I.info size={12} style={{ marginRight: 6, verticalAlign: 'middle' }}/>
            Adding or editing destinations requires 2FA — visit <a onClick={() => setPage('security')} style={{ color: 'var(--cyan)', cursor: 'pointer' }}>Security</a>.
          </div>
        </div>
        <div className="a-section">
          <h3 style={{ margin: '0 0 14px', fontFamily: 'Space Grotesk', fontSize: 16 }}>KYC / Verification</h3>
          {[
            { l: 'Identity', sub: 'Sumsub · Apr 14, 2026', state: 'ok' },
            { l: 'Address', sub: 'Utility bill · Apr 14, 2026', state: 'ok' },
            { l: 'Source of funds', sub: 'Required at $50K cumulative', state: 'warn' },
          ].map((k, i) => (
            <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 0', borderTop: i > 0 ? '1px solid var(--line-2)' : 'none' }}>
              <div style={{
                width: 32, height: 32, borderRadius: 999,
                background: k.state === 'ok' ? 'color-mix(in oklab, var(--positive) 18%, transparent)' : 'color-mix(in oklab, var(--gold) 18%, transparent)',
                color: k.state === 'ok' ? 'var(--positive)' : 'var(--gold)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>{k.state === 'ok' ? <I.check size={14}/> : <I.warn size={14}/>}</div>
              <div style={{ flex: 1 }}>
                <div style={{ fontWeight: 500, fontSize: 14 }}>{k.l}</div>
                <div style={{ fontSize: 11, color: 'var(--text-dim)' }}>{k.sub}</div>
              </div>
              {k.state === 'warn' ? <button className="a-btn secondary sm">Verify</button> : <span className="a-tag success">OK</span>}
            </div>
          ))}
          <button className="a-btn primary" style={{ width: '100%', marginTop: 14, justifyContent: 'center' }}><I.shield size={13}/> Start KYC verification</button>
        </div>
      </div>
    </>
  );
}

// ============ PROFILE EDIT ============
function ArenaProfileEdit() {
  const { setPage } = useApp();
  const [form, setForm] = useState({
    name: 'Yulia Larssen',
    email: 'yulia@example.com',
    dob: '1991-03-14',
    country: 'Italy',
    phonePrefix: '+39',
    phone: '••• ••• 4112',
    address: 'Via Roma 42',
    city: 'Rome',
    zip: '00184',
    iban: 'IT60 X054 2811 1010 0000 0123 456',
  });
  function set(k, v) { setForm(f => ({ ...f, [k]: v })); }

  return (
    <>
      <div className="a-pagehead">
        <div>
          <div style={{ fontSize: 12, color: 'var(--text-dim)', display: 'flex', alignItems: 'center', gap: 6 }}>
            <a onClick={() => setPage('profile')} style={{ cursor: 'pointer', color: 'var(--text-dim)' }}>Profile</a>
            <I.chevronRight size={10}/>
            <span style={{ color: 'var(--text)', fontWeight: 600 }}>Edit</span>
          </div>
          <h1 style={{ marginTop: 6 }}>Edit <em>profile</em>.</h1>
          <div className="sub">Save will only post when the profile-update endpoint is wired up</div>
        </div>
        <div style={{ display: 'flex', gap: 10 }}>
          <button className="a-btn ghost" onClick={() => setPage('profile')}>Cancel</button>
          <button className="a-btn primary" onClick={() => setPage('profile')}><I.check size={13}/> Save profile</button>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18 }}>
        <div className="a-section">
          <h3 style={{ margin: '0 0 14px', fontFamily: 'Space Grotesk', fontSize: 16 }}>Personal</h3>
          <ArenaInputField label="Full name" v={form.name} onChange={v => set('name', v)}/>
          <ArenaInputField label="Email" v={form.email} onChange={v => set('email', v)}/>
          <ArenaInputField label="Date of birth" v={form.dob} onChange={v => set('dob', v)} type="date"/>
          <div style={{ marginBottom: 12 }}>
            <label style={{ fontSize: 11, color: 'var(--text-dim)', textTransform: 'uppercase', letterSpacing: '.08em', fontWeight: 600, display: 'block', marginBottom: 6 }}>Country</label>
            <select className="a-input" value={form.country} onChange={e => set('country', e.target.value)}>
              {['Italy','Germany','France','United Kingdom','United States','India','UAE','Other'].map(c => <option key={c}>{c}</option>)}
            </select>
          </div>
          <div style={{ marginBottom: 12 }}>
            <label style={{ fontSize: 11, color: 'var(--text-dim)', textTransform: 'uppercase', letterSpacing: '.08em', fontWeight: 600, display: 'block', marginBottom: 6 }}>Phone</label>
            <div style={{ display: 'grid', gridTemplateColumns: '90px 1fr', gap: 8 }}>
              <select className="a-input" value={form.phonePrefix} onChange={e => set('phonePrefix', e.target.value)}>
                {['+1','+39','+44','+49','+33','+91','+971'].map(p => <option key={p}>{p}</option>)}
              </select>
              <input className="a-input" value={form.phone} onChange={e => set('phone', e.target.value)}/>
            </div>
          </div>
        </div>

        <div className="a-section">
          <h3 style={{ margin: '0 0 14px', fontFamily: 'Space Grotesk', fontSize: 16 }}>Billing address</h3>
          <ArenaInputField label="Street address" v={form.address} onChange={v => set('address', v)}/>
          <ArenaInputField label="City" v={form.city} onChange={v => set('city', v)}/>
          <ArenaInputField label="ZIP / Postal" v={form.zip} onChange={v => set('zip', v)}/>

          <h3 style={{ margin: '22px 0 14px', fontFamily: 'Space Grotesk', fontSize: 16 }}>Bank · primary wire</h3>
          <ArenaInputField label="IBAN" v={form.iban} onChange={v => set('iban', v)} mono/>
          <div style={{ marginTop: 4, fontSize: 12, color: 'var(--text-dim)' }}>
            <I.info size={12} style={{ marginRight: 6, verticalAlign: 'middle' }}/>
            Changes to bank details require 2FA confirmation on save.
          </div>
        </div>
      </div>
    </>
  );
}

function ArenaInputField({ label, v, onChange, type = 'text', mono }) {
  return (
    <div style={{ marginBottom: 12 }}>
      <label style={{ fontSize: 11, color: 'var(--text-dim)', textTransform: 'uppercase', letterSpacing: '.08em', fontWeight: 600, display: 'block', marginBottom: 6 }}>{label}</label>
      <input className="a-input" type={type} value={v} onChange={e => onChange(e.target.value)} style={mono ? { fontFamily: 'JetBrains Mono', fontSize: 13 } : {}}/>
    </div>
  );
}

// ============ SECURITY (dedicated) ============
function ArenaSecurity() {
  const { setPage } = useApp();
  const [twoFa, setTwoFa] = useState(true);
  const [pwModal, setPwModal] = useState(false);
  const [setupModal, setSetupModal] = useState(null); // null | 'intro' | 'qr' | 'verify' | 'done'
  const [disableModal, setDisableModal] = useState(false);
  const [alerts, setAlerts] = useState({ login: true, payout: true, withdraw: true, marketing: false });

  return (
    <>
      <div className="a-pagehead">
        <div>
          <h1><em>Security</em>.</h1>
          <div className="sub">2FA · password · sessions · alerts · KYC</div>
        </div>
        <button className="a-btn secondary" onClick={() => setPage('profile')}><I.chevronLeft size={13}/> Profile</button>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1.3fr 1fr', gap: 18 }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          {/* 2FA */}
          <div className="a-section">
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
              <h3 style={{ margin: 0, fontFamily: 'Space Grotesk', fontSize: 16 }}>Two-factor authentication</h3>
              {twoFa
                ? <span className="a-tag success">ENABLED</span>
                : <span className="a-tag" style={{ background: 'color-mix(in oklab, var(--negative) 14%, transparent)', color: 'var(--negative)' }}>OFF</span>}
            </div>
            <div style={{ fontSize: 13, color: 'var(--text-dim)', marginBottom: 14 }}>
              {twoFa
                ? 'Authenticator app · added Mar 22. Required on login, withdrawals, and bank changes.'
                : 'Add an authenticator app to protect your withdrawals, bank edits, and login.'}
            </div>
            {twoFa
              ? <button className="a-btn secondary" onClick={() => setDisableModal(true)}><I.lock size={13}/> Disable 2FA</button>
              : <button className="a-btn primary" onClick={() => setSetupModal('intro')}><I.shield size={13}/> Enable 2FA</button>}
          </div>

          {/* Password */}
          <div className="a-section">
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
              <h3 style={{ margin: 0, fontFamily: 'Space Grotesk', fontSize: 16 }}>Password</h3>
              <span className="a-tag success"><I.shield size={9}/> STRONG · 73 bits</span>
            </div>
            <div style={{ fontSize: 13, color: 'var(--text-dim)', marginBottom: 14 }}>Last changed 47 days ago</div>
            <button className="a-btn primary" onClick={() => setPwModal(true)}><I.lock size={13}/> Change password</button>
          </div>

          {/* Sessions */}
          <div className="a-section">
            <h3 style={{ margin: '0 0 14px', fontFamily: 'Space Grotesk', fontSize: 16 }}>Sessions & devices</h3>
            {[
              { d: 'Chrome on macOS · Rome, IT', t: 'This device · now', cur: true, ip: '93.34.•.•' },
              { d: 'iPhone 15 Pro · Milan, IT', t: '2h ago', ip: '93.34.•.•' },
              { d: 'Chrome on Windows · Naples, IT', t: '3 days ago', ip: '5.171.•.•' },
            ].map((s, i) => (
              <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 0', borderTop: i > 0 ? '1px solid var(--line-2)' : 'none' }}>
                <I.shield size={18} style={{ color: 'var(--text-dim)' }}/>
                <div style={{ flex: 1 }}>
                  <div style={{ fontWeight: 500, fontSize: 14 }}>{s.d}</div>
                  <div style={{ fontSize: 11, color: 'var(--text-dim)' }}>{s.t} · IP {s.ip}</div>
                </div>
                {s.cur ? <span className="a-tag success">ACTIVE</span> : <button className="a-btn ghost sm">Revoke</button>}
              </div>
            ))}
            <button className="a-btn ghost sm" style={{ marginTop: 12 }}>Sign out everywhere</button>
          </div>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          {/* Alerts */}
          <div className="a-section">
            <h3 style={{ margin: '0 0 14px', fontFamily: 'Space Grotesk', fontSize: 16 }}>Email & security alerts</h3>
            {[
              { k: 'login', l: 'New device sign-in', sub: 'Email when a new device logs in' },
              { k: 'payout', l: 'Payout dispatched', sub: 'Email + push notification' },
              { k: 'withdraw', l: 'Withdrawal initiated', sub: 'Required — cannot disable', locked: true },
              { k: 'marketing', l: 'Marketing emails', sub: 'Promotions and season news' },
            ].map((a, i) => (
              <div key={a.k} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 0', borderTop: i > 0 ? '1px solid var(--line-2)' : 'none' }}>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 14, fontWeight: 500 }}>{a.l}</div>
                  <div style={{ fontSize: 11, color: 'var(--text-dim)' }}>{a.sub}</div>
                </div>
                <div onClick={() => !a.locked && setAlerts(s => ({ ...s, [a.k]: !s[a.k] }))} style={{
                  width: 40, height: 22, borderRadius: 999,
                  background: alerts[a.k] ? 'linear-gradient(90deg, var(--magenta), var(--cyan))' : 'var(--surface-3)',
                  position: 'relative', cursor: a.locked ? 'not-allowed' : 'pointer',
                  opacity: a.locked ? 0.6 : 1,
                }}>
                  <div style={{ position: 'absolute', top: 2, left: alerts[a.k] ? 20 : 2, width: 18, height: 18, borderRadius: 999, background: '#fff', transition: 'left .2s' }}/>
                </div>
              </div>
            ))}
          </div>

          {/* KYC */}
          <ArenaSecurityKyc/>
        </div>
      </div>

      {pwModal && <ArenaPasswordModal onClose={() => setPwModal(false)}/>}
      {setupModal && <ArenaTwoFASetup step={setupModal} setStep={setSetupModal} onDone={() => { setTwoFa(true); setSetupModal(null); }}/>}
      {disableModal && <ArenaTwoFADisable onClose={() => setDisableModal(false)} onConfirm={() => { setTwoFa(false); setDisableModal(false); }}/>}
    </>
  );
}

function ArenaModalShell({ children, onClose, title, subtitle, footer, width = 480 }) {
  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, maxWidth: '92vw', maxHeight: '92vh', zIndex: 201,
        background: 'var(--surface)', border: '1px solid var(--line-3)',
        borderRadius: 18, display: 'flex', flexDirection: 'column',
        boxShadow: '0 30px 80px rgba(0,0,0,0.6)',
      }}>
        <div style={{ padding: '20px 24px', borderBottom: '1px solid var(--line)', display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
          <div>
            <div style={{ fontFamily: 'Space Grotesk', fontSize: 18, fontWeight: 700, letterSpacing: '-0.02em' }}>{title}</div>
            {subtitle && <div style={{ fontSize: 12, color: 'var(--text-dim)', marginTop: 4 }}>{subtitle}</div>}
          </div>
          <button className="a-iconbtn" onClick={onClose}><I.x size={13}/></button>
        </div>
        <div style={{ padding: 24, overflowY: 'auto' }}>{children}</div>
        {footer && <div style={{ padding: '14px 24px', borderTop: '1px solid var(--line)', background: 'var(--surface-2)', display: 'flex', gap: 10, justifyContent: 'flex-end' }}>{footer}</div>}
      </div>
    </>
  );
}

function ArenaPasswordModal({ onClose }) {
  const [show, setShow] = useState(false);
  return (
    <ArenaModalShell
      onClose={onClose}
      title="Change password"
      subtitle="You'll be signed out of other sessions."
      footer={<>
        <button className="a-btn ghost" onClick={onClose}>Cancel</button>
        <button className="a-btn primary" onClick={onClose}><I.check size={13}/> Save password</button>
      </>}
    >
      {['Current password', 'New password', 'Confirm new password'].map((l, i) => (
        <div key={i} style={{ marginBottom: 12 }}>
          <label style={{ fontSize: 11, color: 'var(--text-dim)', textTransform: 'uppercase', letterSpacing: '.08em', fontWeight: 600, display: 'block', marginBottom: 6 }}>{l}</label>
          <div style={{ display: 'flex', gap: 6 }}>
            <input className="a-input" type={show ? 'text' : 'password'} placeholder="••••••••" style={{ flex: 1 }}/>
            <button className="a-iconbtn" style={{ width: 40, height: 40 }} onClick={() => setShow(s => !s)}>
              {show ? <I.eyeOff size={14}/> : <I.eye size={14}/>}
            </button>
          </div>
        </div>
      ))}
      <div style={{ marginTop: 8, fontSize: 12, color: 'var(--text-dim)' }}>Use 12+ characters with letters, numbers, and symbols.</div>
    </ArenaModalShell>
  );
}

function ArenaTwoFASetup({ step, setStep, onDone }) {
  const [code, setCode] = useState('');
  const secret = 'JBSWY3DPEHPK3PXP';

  if (step === 'intro') {
    return (
      <ArenaModalShell
        onClose={() => setStep(null)}
        title="Set up 2FA"
        subtitle="Add a layer of protection. Takes ~60 seconds."
        footer={<>
          <button className="a-btn ghost" onClick={() => setStep(null)}>Cancel</button>
          <button className="a-btn primary" onClick={() => setStep('qr')}>Continue <I.arrowRight size={13}/></button>
        </>}
      >
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          {[
            ['1', 'Install', 'Google Authenticator, 1Password, Authy, or any TOTP app'],
            ['2', 'Scan', 'We show a QR code and a backup secret'],
            ['3', 'Verify', 'Enter the 6-digit code to activate'],
          ].map(([n, h, s]) => (
            <div key={n} style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
              <div style={{ width: 28, height: 28, borderRadius: 999, background: 'linear-gradient(135deg, var(--magenta), var(--cyan))', color: '#06070D', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 700, fontSize: 13, flex: 'none' }}>{n}</div>
              <div>
                <div style={{ fontWeight: 600 }}>{h}</div>
                <div style={{ fontSize: 12, color: 'var(--text-dim)' }}>{s}</div>
              </div>
            </div>
          ))}
        </div>
      </ArenaModalShell>
    );
  }

  if (step === 'qr') {
    return (
      <ArenaModalShell
        onClose={() => setStep(null)}
        title="Scan QR or copy secret"
        subtitle="Add this account to your authenticator app."
        footer={<>
          <button className="a-btn ghost" onClick={() => setStep('intro')}><I.chevronLeft size={13}/> Back</button>
          <button className="a-btn primary" onClick={() => setStep('verify')}>I scanned it <I.arrowRight size={13}/></button>
        </>}
      >
        <div style={{ display: 'flex', gap: 18 }}>
          <div style={{
            width: 160, height: 160, borderRadius: 12,
            background: '#fff', flex: 'none',
            display: 'grid', gridTemplateColumns: 'repeat(16, 1fr)', padding: 12,
          }}>
            {Array.from({ length: 256 }).map((_, i) => (
              <div key={i} style={{ background: ((i * 37 + 11) % 7) < 3 ? '#000' : '#fff', width: '100%', aspectRatio: 1 }}/>
            ))}
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 11, color: 'var(--text-dim)', textTransform: 'uppercase', letterSpacing: '.08em', fontWeight: 600, marginBottom: 8 }}>Backup secret</div>
            <div style={{ display: 'flex', gap: 6 }}>
              <code style={{ flex: 1, padding: '10px 12px', background: 'var(--surface-2)', border: '1px solid var(--line)', borderRadius: 10, fontFamily: 'JetBrains Mono', fontSize: 13, letterSpacing: '0.04em' }}>{secret}</code>
              <button className="a-iconbtn" style={{ width: 40, height: 40 }} onClick={() => navigator.clipboard?.writeText(secret)}><I.copy size={13}/></button>
            </div>
            <div style={{ marginTop: 16, padding: 12, background: 'rgba(0,0,0,0.2)', borderRadius: 10, fontSize: 12, color: 'var(--text-dim)' }}>
              <I.warn size={12} style={{ marginRight: 6, verticalAlign: 'middle', color: 'var(--gold)' }}/>
              Store this somewhere safe. If you lose your device, this is your only way back in.
            </div>
          </div>
        </div>
      </ArenaModalShell>
    );
  }

  if (step === 'verify') {
    return (
      <ArenaModalShell
        onClose={() => setStep(null)}
        title="Enter the 6-digit code"
        subtitle="From your authenticator app"
        footer={<>
          <button className="a-btn ghost" onClick={() => setStep('qr')}><I.chevronLeft size={13}/> Back</button>
          <button className="a-btn primary" disabled={code.length !== 6} onClick={() => setStep('done')} style={code.length !== 6 ? { opacity: 0.5, cursor: 'not-allowed' } : {}}>Activate <I.check size={13}/></button>
        </>}
      >
        <input
          className="a-input"
          value={code}
          onChange={e => setCode(e.target.value.replace(/\D/g, '').slice(0, 6))}
          placeholder="123 456"
          style={{ fontFamily: 'JetBrains Mono', fontSize: 24, textAlign: 'center', letterSpacing: '0.4em', padding: '18px 14px' }}
        />
        <div style={{ marginTop: 14, fontSize: 12, color: 'var(--text-dim)' }}>Code refreshes every 30 seconds.</div>
      </ArenaModalShell>
    );
  }

  if (step === 'done') {
    return (
      <ArenaModalShell
        onClose={onDone}
        title="2FA enabled"
        subtitle="Your account is now protected."
        footer={<button className="a-btn primary" onClick={onDone}>Done</button>}
      >
        <div style={{ textAlign: 'center', padding: '20px 0' }}>
          <div style={{ width: 64, height: 64, borderRadius: 999, background: 'color-mix(in oklab, var(--positive) 20%, transparent)', color: 'var(--positive)', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto' }}><I.check size={32}/></div>
          <div style={{ marginTop: 14, fontSize: 14, color: 'var(--text-dim)' }}>Next sign-in will ask for a 6-digit code.</div>
        </div>
      </ArenaModalShell>
    );
  }

  return null;
}

function ArenaTwoFADisable({ onClose, onConfirm }) {
  const [code, setCode] = useState('');
  return (
    <ArenaModalShell
      onClose={onClose}
      title="Disable 2FA?"
      subtitle="Confirm with a 6-digit code from your authenticator app."
      footer={<>
        <button className="a-btn ghost" onClick={onClose}>Cancel</button>
        <button className="a-btn" disabled={code.length !== 6} onClick={onConfirm} style={{ background: 'color-mix(in oklab, var(--negative) 80%, transparent)', color: '#fff', ...(code.length !== 6 ? { opacity: 0.5, cursor: 'not-allowed' } : {}) }}>Deactivate</button>
      </>}
    >
      <div style={{ padding: 14, background: 'color-mix(in oklab, var(--negative) 10%, transparent)', border: '1px solid color-mix(in oklab, var(--negative) 30%, transparent)', borderRadius: 12, fontSize: 13, marginBottom: 16 }}>
        <I.warn size={13} style={{ marginRight: 6, verticalAlign: 'middle', color: 'var(--negative)' }}/>
        Your account will be more vulnerable. You can re-enable any time.
      </div>
      <input
        className="a-input"
        value={code}
        onChange={e => setCode(e.target.value.replace(/\D/g, '').slice(0, 6))}
        placeholder="123 456"
        style={{ fontFamily: 'JetBrains Mono', fontSize: 22, textAlign: 'center', letterSpacing: '0.4em', padding: '16px 14px' }}
      />
    </ArenaModalShell>
  );
}

// ============ DEPOSIT (3 sub-routes) ============
function ArenaDeposit() {
  const { setPage } = useApp();
  const [amount, setAmount] = useState(500);
  const [method, setMethod] = useState(null);

  function go() {
    if (method === 'crypto') setPage('depositCrypto');
    if (method === 'card')   setPage('depositCard');
    if (method === 'wire')   setPage('depositWire');
  }

  return (
    <>
      <div className="a-pagehead">
        <div>
          <div style={{ fontSize: 12, color: 'var(--text-dim)', display: 'flex', alignItems: 'center', gap: 6 }}>
            <a onClick={() => setPage('wallet')} style={{ cursor: 'pointer', color: 'var(--text-dim)' }}>Wallet</a>
            <I.chevronRight size={10}/>
            <span style={{ color: 'var(--text)', fontWeight: 600 }}>Deposit</span>
          </div>
          <h1 style={{ marginTop: 6 }}>Top up <em>wallet</em>.</h1>
          <div className="sub">Pick an amount and a method · funds appear once payment clears</div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 380px', gap: 18 }}>
        <div className="a-section">
          <h3 style={{ margin: '0 0 14px', fontFamily: 'Space Grotesk', fontSize: 16 }}>Amount</h3>
          <input className="a-input" type="number" value={amount} onChange={e => setAmount(+e.target.value || 0)} style={{ fontFamily: 'JetBrains Mono', fontSize: 28, fontWeight: 600, letterSpacing: '-0.02em' }}/>
          <div style={{ display: 'flex', gap: 8, marginTop: 12, flexWrap: 'wrap' }}>
            {[100, 250, 500, 1000, 2500].map(v => (
              <button key={v} className={'a-btn ' + (amount === v ? 'primary' : 'secondary') + ' sm'} onClick={() => setAmount(v)}>${v}</button>
            ))}
          </div>

          <h3 style={{ margin: '24px 0 14px', fontFamily: 'Space Grotesk', fontSize: 16 }}>Method</h3>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10 }}>
            {[
              { id: 'crypto', l: 'Crypto', sub: 'USDT, USDC, BTC, ETH', i: 'btc' },
              { id: 'card',   l: 'Card',   sub: 'Visa, Mastercard',     i: 'cards' },
              { id: 'wire',   l: 'Bank wire', sub: '1–3 business days', i: 'bank' },
            ].map(m => (
              <button key={m.id} onClick={() => setMethod(m.id)} style={{
                padding: 16, borderRadius: 14,
                border: '1.5px solid ' + (method === m.id ? 'var(--magenta)' : 'var(--line)'),
                background: method === m.id ? 'rgba(255,92,245,0.08)' : 'var(--surface-2)',
                color: 'var(--text)', font: 'inherit', textAlign: 'left', cursor: 'pointer',
                display: 'flex', flexDirection: 'column', gap: 6,
              }}>
                <div style={{ width: 36, height: 36, borderRadius: 10, background: method === m.id ? 'linear-gradient(135deg, var(--magenta), var(--cyan))' : 'rgba(255,255,255,0.04)', color: method === m.id ? '#06070D' : 'var(--text-dim)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{I[m.i]({ size: 18 })}</div>
                <div style={{ fontWeight: 700, fontSize: 14 }}>{m.l}</div>
                <div style={{ fontSize: 11, color: 'var(--text-dim)' }}>{m.sub}</div>
              </button>
            ))}
          </div>
        </div>

        <div className="a-section" style={{ background: 'linear-gradient(135deg, rgba(255,92,245,0.10), rgba(92,217,255,0.06)), var(--surface)' }}>
          <div style={{ fontSize: 11, color: 'var(--text-dim)', textTransform: 'uppercase', letterSpacing: '.1em', fontWeight: 600 }}>Summary</div>
          <div className="mono" style={{ fontSize: 36, fontWeight: 700, letterSpacing: '-0.03em', marginTop: 6 }}>${amount.toFixed(2)}</div>
          <div style={{ marginTop: 10, fontSize: 12, color: 'var(--text-dim)' }}>Method: <b style={{ color: 'var(--text)' }}>{method ? method.toUpperCase() : 'select one'}</b></div>
          <div style={{ marginTop: 4, fontSize: 12, color: 'var(--text-dim)' }}>Fee: <b style={{ color: 'var(--text)' }} className="mono">$0.00</b></div>
          <button
            className="a-btn primary"
            style={{ width: '100%', marginTop: 16, justifyContent: 'center', height: 46, ...(!method || amount < 10 ? { opacity: 0.5, cursor: 'not-allowed' } : {}) }}
            disabled={!method || amount < 10}
            onClick={go}
          >
            Continue <I.arrowRight size={13}/>
          </button>
          <div style={{ marginTop: 12, fontSize: 11, color: 'var(--text-dim)' }}>
            <I.shield size={11} style={{ marginRight: 4, verticalAlign: 'middle' }}/> Real payments stay gated until the deposit backend is enabled.
          </div>
        </div>
      </div>
    </>
  );
}

function ArenaDepositCrypto() {
  const { setPage } = useApp();
  const [chain, setChain] = useState('TRC20');
  const [sent, setSent] = useState(false);
  const [timeLeft, setTimeLeft] = useState(30 * 60);
  const [copied, setCopied] = useState('');
  const addr = chain === 'TRC20' ? 'TXyZ9abcDEFghiJKLmnPqrSTUVwxyz1234'
            : chain === 'ERC20' ? '0xa1b2c3d4e5f60718293a4b5c6d7e8f9012345678'
            : chain === 'BEP20' ? 'bnb1zywdq3lk2pvyec3qm0xx8dx5wq2pqv0v0e3qm9'
            : 'So1ana1234567890abcdefghijklmnopqrstuvwx';
  const amount = 500;
  useEffect(() => {
    if (sent) return;
    const i = setInterval(() => setTimeLeft(t => Math.max(0, t - 1)), 1000);
    return () => clearInterval(i);
  }, [sent]);
  function copy(val, label) {
    navigator.clipboard?.writeText(val);
    setCopied(label);
    setTimeout(() => setCopied(''), 1400);
  }
  const mins = String(Math.floor(timeLeft / 60)).padStart(2, '0');
  const secs = String(timeLeft % 60).padStart(2, '0');

  if (sent) return <ArenaTxSuccess kind="deposit-crypto" amount={amount} setPage={setPage}/>;

  return (
    <>
      <div className="a-pagehead">
        <div>
          <div style={{ fontSize: 12, color: 'var(--text-dim)', display: 'flex', alignItems: 'center', gap: 6 }}>
            <a onClick={() => setPage('deposit')} style={{ cursor: 'pointer', color: 'var(--text-dim)' }}>Deposit</a>
            <I.chevronRight size={10}/>
            <span style={{ color: 'var(--text)', fontWeight: 600 }}>Crypto</span>
          </div>
          <h1 style={{ marginTop: 6 }}>Send <em>USDT</em>.</h1>
          <div className="sub">Confirmation usually arrives within 10 minutes</div>
        </div>
        <button className="a-btn ghost" onClick={() => setPage('deposit')}><I.chevronLeft size={13}/> Back</button>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18, maxWidth: 1080 }}>
        <div className="a-section">
          {/* Status banner */}
          <div style={{
            display: 'flex', alignItems: 'center', gap: 10,
            padding: '12px 14px', borderRadius: 12,
            background: 'color-mix(in oklab, var(--cyan) 10%, var(--surface-2))',
            border: '1px solid color-mix(in oklab, var(--cyan) 28%, var(--line))',
            marginBottom: 18,
          }}>
            <span style={{ width: 10, height: 10, borderRadius: 999, background: 'var(--cyan)', boxShadow: '0 0 0 4px color-mix(in oklab, var(--cyan) 25%, transparent)' }}/>
            <div style={{ flex: 1, fontSize: 12 }}>
              <div style={{ fontWeight: 600, color: 'var(--text)' }}>Awaiting payment</div>
              <div style={{ color: 'var(--text-dim)' }}>Address expires in <b className="mono" style={{ color: 'var(--text)' }}>{mins}:{secs}</b></div>
            </div>
          </div>

          <h3 style={{ margin: '0 0 12px', fontFamily: 'Space Grotesk', fontSize: 14, color: 'var(--text-dim)', letterSpacing: '.06em', textTransform: 'uppercase', fontWeight: 600 }}>Network</h3>
          <div className="a-chips" style={{ marginBottom: 18, width: '100%' }}>
            {['TRC20', 'ERC20', 'BEP20', 'SOL'].map(c => (
              <button key={c} className={chain === c ? 'active' : ''} onClick={() => setChain(c)} style={{ flex: 1, justifyContent: 'center' }}>{c}</button>
            ))}
          </div>

          <h3 style={{ margin: '0 0 12px', fontFamily: 'Space Grotesk', fontSize: 14, color: 'var(--text-dim)', letterSpacing: '.06em', textTransform: 'uppercase', fontWeight: 600 }}>Deposit address</h3>
          <div style={{ display: 'flex', gap: 6 }}>
            <code style={{ flex: 1, padding: '12px 14px', background: 'var(--surface-2)', border: '1px solid var(--line)', borderRadius: 10, fontFamily: 'JetBrains Mono', fontSize: 12, wordBreak: 'break-all' }}>{addr}</code>
            <button className="a-iconbtn" style={{ width: 44, height: 44 }} onClick={() => copy(addr, 'Address')}>
              {copied === 'Address' ? <I.check size={14}/> : <I.copy size={14}/>}
            </button>
          </div>

          <div style={{ marginTop: 14, padding: 12, background: 'color-mix(in oklab, var(--gold) 10%, transparent)', border: '1px solid color-mix(in oklab, var(--gold) 25%, transparent)', borderRadius: 10, fontSize: 12 }}>
            <I.warn size={13} style={{ marginRight: 6, verticalAlign: 'middle', color: 'var(--gold)' }}/>
            Send <b>only USDT on the {chain} network</b>. Funds sent on any other chain will be lost.
          </div>

          <button className="a-btn primary" style={{ width: '100%', marginTop: 16, justifyContent: 'center', height: 46 }} onClick={() => setSent(true)}>
            <I.check size={13}/> I've sent the payment
          </button>
          <div style={{ textAlign: 'center', marginTop: 8, fontSize: 11, color: 'var(--text-faint)' }}>
            Confirmation usually arrives within <b className="mono" style={{ color: 'var(--text-dim)' }}>10 min</b>
          </div>
        </div>

        <div className="a-section" style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', textAlign: 'center', background: 'linear-gradient(135deg, rgba(255,92,245,0.06), rgba(92,217,255,0.04)), var(--surface)' }}>
          <div style={{ fontSize: 11, color: 'var(--text-dim)', textTransform: 'uppercase', letterSpacing: '.1em', fontWeight: 600 }}>Send exactly</div>
          <div className="mono" style={{ fontSize: 32, fontWeight: 700, letterSpacing: '-0.025em', marginTop: 4 }}>${amount.toFixed(2)} <span style={{ color: 'var(--text-dim)', fontWeight: 500, fontSize: 18 }}>USDT</span></div>
          <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, marginTop: 6, padding: '3px 12px', borderRadius: 999, background: 'var(--surface-3)', fontSize: 11, fontWeight: 600 }}>
            <span style={{ width: 6, height: 6, borderRadius: 999, background: '#FF4444' }}/>
            USDT · {chain}
          </div>
          <FakeQR/>
          <div style={{ marginTop: 10, fontSize: 11, color: 'var(--text-faint)' }}>Scan with any USDT-compatible wallet</div>
        </div>
      </div>
    </>
  );
}

function FakeQR() {
  const SIZE = 21;
  const cells = useMemo(() => {
    const grid = Array.from({ length: SIZE }, () => Array(SIZE).fill(0));
    const drawFinder = (r, c) => {
      for (let i = 0; i < 7; i++) for (let j = 0; j < 7; j++) {
        const edge = i === 0 || i === 6 || j === 0 || j === 6;
        const inner = i >= 2 && i <= 4 && j >= 2 && j <= 4;
        grid[r + i][c + j] = (edge || inner) ? 1 : 0;
      }
    };
    drawFinder(0, 0); drawFinder(0, SIZE - 7); drawFinder(SIZE - 7, 0);
    for (let i = 0; i < SIZE; i++) for (let j = 0; j < SIZE; j++) {
      const inFinder = (i < 8 && j < 8) || (i < 8 && j >= SIZE - 8) || (i >= SIZE - 8 && j < 8);
      if (inFinder) continue;
      grid[i][j] = ((Math.sin(i * 7.3 + j * 13.1) + 1) / 2) > 0.55 ? 1 : 0;
    }
    return grid;
  }, []);
  return (
    <div style={{ marginTop: 16, padding: 14, background: '#fff', borderRadius: 14, boxShadow: '0 8px 24px rgba(0,0,0,0.30)' }}>
      <div style={{ display: 'grid', gridTemplateColumns: `repeat(${SIZE}, 7px)`, gridTemplateRows: `repeat(${SIZE}, 7px)`, gap: 0 }}>
        {cells.flatMap((row, i) => row.map((v, j) => (
          <span key={i + '-' + j} style={{ background: v ? '#0A0E11' : '#fff', width: '100%', height: '100%' }}/>
        )))}
      </div>
    </div>
  );
}

function ArenaTxSuccess({ kind, amount, setPage }) {
  const ref = useMemo(() => 'PA-' + Math.random().toString(36).slice(2, 9).toUpperCase(), []);
  const labels = {
    'deposit-crypto': { title: 'Payment confirmed', body: 'credited to your wallet', method: 'USDT TRC-20' },
    'deposit-card':   { title: 'Payment confirmed', body: 'credited to your wallet', method: 'Visa •••• 4242' },
    'deposit-wire':   { title: 'Wire instructions sent', body: 'arrives 1–3 business days', method: 'Bank wire' },
    'withdraw':       { title: 'Withdrawal submitted', body: 'arriving within 24h',         method: 'USDT TRC-20' },
  };
  const m = labels[kind] || labels['deposit-crypto'];
  return (
    <>
      <div className="a-pagehead">
        <div>
          <h1>All <em>set</em>.</h1>
          <div className="sub">{m.body}</div>
        </div>
      </div>
      <div className="a-section" style={{ maxWidth: 540, margin: '0 auto', textAlign: 'center', padding: '36px 28px' }}>
        <div style={{ width: 80, height: 80, borderRadius: 999, background: 'linear-gradient(135deg, var(--positive), oklch(62% 0.18 145))', color: '#06070D', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto', boxShadow: '0 0 60px -10px var(--positive)' }}>
          <I.check size={42}/>
        </div>
        <div style={{ fontFamily: 'Space Grotesk', fontSize: 28, fontWeight: 700, letterSpacing: '-0.025em', marginTop: 22 }}>{m.title}</div>
        <div style={{ marginTop: 6, fontSize: 14, color: 'var(--text-dim)' }}>
          {kind === 'withdraw' ? '−' : '+'}<b className="mono" style={{ color: 'var(--text)' }}>${amount.toFixed(2)}</b> {m.body}
        </div>

        <div style={{ marginTop: 24, padding: 16, background: 'var(--surface-2)', border: '1px solid var(--line)', borderRadius: 12, textAlign: 'left', fontSize: 13 }}>
          <ArenaKv label="Reference" value={ref} mono copy/>
          <ArenaKv label="Amount" value={'$' + amount.toFixed(2)} mono/>
          <ArenaKv label="Method" value={m.method}/>
          <ArenaKv label="Status" value={kind === 'deposit-wire' ? 'Pending' : 'Confirmed'}/>
        </div>

        <div style={{ display: 'flex', gap: 8, marginTop: 22 }}>
          <button className="a-btn ghost" style={{ flex: 1, justifyContent: 'center' }} onClick={() => setPage('wallet')}>View wallet</button>
          <button className="a-btn primary" style={{ flex: 1, justifyContent: 'center' }} onClick={() => setPage('dashboard')}>Done</button>
        </div>
      </div>
    </>
  );
}

function ArenaDepositCard() {
  const { setPage } = useApp();
  const [step, setStep] = useState('form'); // form | processing | success
  const [card, setCard] = useState({ number: '4242 4242 4242 4242', expiry: '09 / 27', cvc: '123', name: 'Yulia Larssen' });
  const [save, setSave] = useState(true);
  const amount = 500;
  const fee = +(amount * 0.025).toFixed(2);
  const total = +(amount + fee).toFixed(2);

  function pay() {
    setStep('processing');
    setTimeout(() => setStep('success'), 1500);
  }

  if (step === 'success') return <ArenaTxSuccess kind="deposit-card" amount={amount} setPage={setPage}/>;

  return (
    <>
      <div className="a-pagehead">
        <div>
          <div style={{ fontSize: 12, color: 'var(--text-dim)', display: 'flex', alignItems: 'center', gap: 6 }}>
            <a onClick={() => setPage('deposit')} style={{ cursor: 'pointer', color: 'var(--text-dim)' }}>Deposit</a>
            <I.chevronRight size={10}/>
            <span style={{ color: 'var(--text)', fontWeight: 600 }}>Card</span>
          </div>
          <h1 style={{ marginTop: 6 }}>Card <em>deposit</em>.</h1>
          <div className="sub">Visa / Mastercard · 2.5% processing fee · 3-D Secure</div>
        </div>
        <button className="a-btn ghost" onClick={() => setPage('deposit')}><I.chevronLeft size={13}/> Back</button>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 380px', gap: 18, maxWidth: 1080 }}>
        <div className="a-section">
          {step === 'form' && (
            <>
              <ArenaInputField label="Card number" v={card.number} onChange={v => setCard({ ...card, number: v })} mono/>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                <ArenaInputField label="Expiry (MM/YY)" v={card.expiry} onChange={v => setCard({ ...card, expiry: v })} mono/>
                <ArenaInputField label="CVC" v={card.cvc} onChange={v => setCard({ ...card, cvc: v })} mono/>
              </div>
              <ArenaInputField label="Cardholder name" v={card.name} onChange={v => setCard({ ...card, name: v })}/>
              <label style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12, color: 'var(--text-dim)', marginTop: 8 }}>
                <input type="checkbox" checked={save} onChange={e => setSave(e.target.checked)}/>
                Save this card for next time
              </label>
              <div style={{ marginTop: 14, padding: 12, background: 'rgba(0,0,0,0.2)', borderRadius: 10, fontSize: 12, color: 'var(--text-dim)', display: 'flex', alignItems: 'center', gap: 8 }}>
                <I.shield size={13}/> Processed by Stripe · PCI-DSS Level 1 · 3-D Secure when required
              </div>
              <button className="a-btn primary" style={{ width: '100%', marginTop: 16, justifyContent: 'center', height: 46 }} onClick={pay}>
                <I.lock size={13}/> Pay ${total.toFixed(2)}
              </button>
            </>
          )}
          {step === 'processing' && (
            <div style={{ padding: '60px 0', textAlign: 'center' }}>
              <div style={{ width: 56, height: 56, border: '3px solid var(--line)', borderTopColor: 'var(--magenta)', borderRadius: '50%', animation: 'spin 0.8s linear infinite', margin: '0 auto' }}/>
              <div style={{ marginTop: 18, fontSize: 15, fontWeight: 600 }}>Processing payment…</div>
              <div style={{ marginTop: 4, fontSize: 12, color: 'var(--text-dim)' }}>Charging Visa •••• {card.number.slice(-4)}</div>
              <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
            </div>
          )}
        </div>

        <div className="a-section" style={{ background: 'linear-gradient(135deg, rgba(255,92,245,0.08), var(--surface))', alignSelf: 'start' }}>
          <h3 style={{ margin: '0 0 14px', fontFamily: 'Space Grotesk', fontSize: 16 }}>Summary</h3>
          <ArenaKv label="Amount" value={'$' + amount.toFixed(2)} mono/>
          <ArenaKv label="Processing fee (2.5%)" value={'$' + fee.toFixed(2)} mono/>
          <ArenaKv label="Total charged" value={'$' + total.toFixed(2)} mono/>
          <ArenaKv label="Credited to wallet" value={'$' + amount.toFixed(2)} mono/>
          <ArenaKv label="Arrival" value="Instant"/>
        </div>
      </div>
    </>
  );
}

function ArenaDepositWire() {
  const { setPage } = useApp();
  const [currency, setCurrency] = useState('USD');
  const [sent, setSent] = useState(false);
  const [copied, setCopied] = useState('');
  const amount = 500;
  const ref = useMemo(() => 'PA-' + Math.random().toString(36).slice(2, 9).toUpperCase(), []);
  function copy(val, label) {
    navigator.clipboard?.writeText(val);
    setCopied(label);
    setTimeout(() => setCopied(''), 1400);
  }
  const details = currency === 'EUR'
    ? { bank: 'Revolut Bank UAB', bankAddr: 'Konstitucijos Ave. 21B, Vilnius, LT', acct: 'LT60 3250 0123 4567 8901', acctLabel: 'IBAN', swift: 'REVOLT21' }
    : currency === 'GBP'
    ? { bank: 'Barclays Bank PLC', bankAddr: '1 Churchill Place, London E14 5HP, UK', acct: 'GB29 NWBK 6016 1331 9268 19', acctLabel: 'IBAN', swift: 'BARCGB22' }
    : { bank: 'JPMorgan Chase Bank, N.A.', bankAddr: '383 Madison Ave, New York, NY 10179', acct: '8761 5500 0942 7714', acctLabel: 'Account number', swift: 'CHASUS33' };

  if (sent) return <ArenaTxSuccess kind="deposit-wire" amount={amount} setPage={setPage}/>;

  function Row({ k, v, mono = true, big }) {
    return (
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '12px 14px', borderRadius: 10, background: 'var(--surface-2)', border: '1px solid var(--line)' }}>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 10, color: 'var(--text-faint)', letterSpacing: '0.06em', textTransform: 'uppercase', fontWeight: 600, marginBottom: 2 }}>{k}</div>
          <div className={mono ? 'mono' : ''} style={{ fontSize: big ? 15 : 13, fontWeight: 600 }}>{v}</div>
        </div>
        <button className="a-iconbtn" style={{ flex: 'none' }} onClick={() => copy(v, k)}>
          {copied === k ? <I.check size={13}/> : <I.copy size={13}/>}
        </button>
      </div>
    );
  }

  return (
    <>
      <div className="a-pagehead">
        <div>
          <div style={{ fontSize: 12, color: 'var(--text-dim)', display: 'flex', alignItems: 'center', gap: 6 }}>
            <a onClick={() => setPage('deposit')} style={{ cursor: 'pointer', color: 'var(--text-dim)' }}>Deposit</a>
            <I.chevronRight size={10}/>
            <span style={{ color: 'var(--text)', fontWeight: 600 }}>Wire</span>
          </div>
          <h1 style={{ marginTop: 6 }}>Bank <em>wire</em>.</h1>
          <div className="sub">Funds clear in 1–3 business days after sent</div>
        </div>
        <button className="a-btn ghost" onClick={() => setPage('deposit')}><I.chevronLeft size={13}/> Back</button>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18, maxWidth: 1080 }}>
        <div className="a-section">
          {/* Status */}
          <div style={{
            display: 'flex', alignItems: 'center', gap: 10,
            padding: '12px 14px', borderRadius: 12,
            background: 'color-mix(in oklab, var(--cyan) 10%, var(--surface-2))',
            border: '1px solid color-mix(in oklab, var(--cyan) 28%, var(--line))',
            marginBottom: 18,
          }}>
            <span style={{ width: 10, height: 10, borderRadius: 999, background: 'var(--cyan)', boxShadow: '0 0 0 4px color-mix(in oklab, var(--cyan) 25%, transparent)' }}/>
            <div style={{ flex: 1, fontSize: 12 }}>
              <div style={{ fontWeight: 600 }}>Awaiting wire</div>
              <div style={{ color: 'var(--text-dim)' }}>Arrives in <b style={{ color: 'var(--text)' }}>1–3 business days</b> after sent</div>
            </div>
          </div>

          {/* Reference — emphasized */}
          <div style={{ fontSize: 10, color: 'var(--text-faint)', letterSpacing: '0.06em', textTransform: 'uppercase', fontWeight: 600, marginBottom: 6, display: 'flex', alignItems: 'center', gap: 6 }}>
            <I.warn size={11} style={{ color: 'var(--gold)' }}/>
            Reference (required)
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '14px 16px', borderRadius: 12, background: 'color-mix(in oklab, var(--gold) 10%, var(--surface))', border: '1.5px solid color-mix(in oklab, var(--gold) 35%, var(--line))', marginBottom: 8 }}>
            <span className="mono" style={{ flex: 1, fontSize: 20, fontWeight: 700, letterSpacing: '0.04em' }}>{ref}</span>
            <button className="a-iconbtn" onClick={() => copy(ref, 'Reference')}>
              {copied === 'Reference' ? <I.check size={13}/> : <I.copy size={13}/>}
            </button>
          </div>
          <div style={{ fontSize: 11, color: 'var(--text-dim)', marginBottom: 16 }}>
            Paste this into the transfer description — without it your wire can't be matched.
          </div>

          {/* Currency toggle */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14 }}>
            <span style={{ fontSize: 11, color: 'var(--text-dim)', letterSpacing: '.06em', textTransform: 'uppercase', fontWeight: 600 }}>Wire in</span>
            <div className="a-chips">
              {['USD', 'EUR', 'GBP'].map(c => <button key={c} className={currency === c ? 'active' : ''} onClick={() => setCurrency(c)}>{c}</button>)}
            </div>
          </div>

          {/* Bank fields */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 14 }}>
            <Row k="Beneficiary" v="Prop Arena Trading Ltd." mono={false}/>
            <Row k={details.acctLabel} v={details.acct} big/>
            <Row k="SWIFT / BIC" v={details.swift}/>
            <Row k="Bank name" v={details.bank} mono={false}/>
          </div>

          <details style={{ marginBottom: 14 }}>
            <summary style={{ fontSize: 11, color: 'var(--text-dim)', cursor: 'pointer', padding: '6px 0', fontWeight: 600, letterSpacing: '0.06em', textTransform: 'uppercase' }}>Additional info</summary>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 8 }}>
              <Row k="Beneficiary address" v="71-75 Shelton St, London WC2H 9JQ, UK" mono={false}/>
              <Row k="Bank address" v={details.bankAddr} mono={false}/>
            </div>
          </details>

          <div style={{ display: 'flex', gap: 8 }}>
            <button className="a-btn secondary" style={{ flex: 1, justifyContent: 'center' }}><I.download size={12}/> PDF</button>
            <button className="a-btn primary" style={{ flex: 1.6, justifyContent: 'center' }} onClick={() => setSent(true)}>
              <I.check size={13}/> I've sent the wire
            </button>
          </div>
        </div>

        <div className="a-section" style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', textAlign: 'center', background: 'linear-gradient(135deg, rgba(255,92,245,0.06), rgba(92,217,255,0.04)), var(--surface)' }}>
          <div style={{ fontSize: 11, color: 'var(--text-dim)', textTransform: 'uppercase', letterSpacing: '.1em', fontWeight: 600 }}>Wire amount</div>
          <div className="mono" style={{ fontSize: 40, fontWeight: 700, letterSpacing: '-0.025em', marginTop: 6 }}>${amount.toFixed(2)} <span style={{ color: 'var(--text-dim)', fontWeight: 500, fontSize: 22 }}>{currency}</span></div>
          <div style={{ marginTop: 18, fontSize: 12, color: 'var(--text-dim)', maxWidth: 280 }}>
            Your wallet will be credited once funds clear (1–3 business days).
          </div>
        </div>
      </div>
    </>
  );
}

// ============ WITHDRAW (4 sub-routes) ============
function ArenaWithdraw() {
  const { setPage } = useApp();
  const [amount, setAmount] = useState('600.00');
  const [method, setMethod] = useState(null);
  const available = window.ARENA_WALLET_BALANCE || 1284.50;
  const amt = parseFloat(amount) || 0;

  function go() {
    if (method === 'crypto') setPage('withdrawCrypto');
    if (method === 'wire')   setPage('withdrawWire');
  }

  return (
    <>
      <div className="a-pagehead">
        <div>
          <div style={{ fontSize: 12, color: 'var(--text-dim)', display: 'flex', alignItems: 'center', gap: 6 }}>
            <a onClick={() => setPage('wallet')} style={{ cursor: 'pointer', color: 'var(--text-dim)' }}>Wallet</a>
            <I.chevronRight size={10}/>
            <span style={{ color: 'var(--text)', fontWeight: 600 }}>Withdraw</span>
          </div>
          <h1 style={{ marginTop: 6 }}>Withdraw <em>funds</em>.</h1>
          <div className="sub">Available <b className="mono" style={{ color: 'var(--text)' }}>${window.fmtMoney(available)}</b> · KYC required for crypto/wire</div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 380px', gap: 18 }}>
        <div className="a-section">
          <h3 style={{ margin: '0 0 14px', fontFamily: 'Space Grotesk', fontSize: 16 }}>Amount</h3>
          <div style={{ display: 'flex', gap: 8 }}>
            <input className="a-input" value={amount} onChange={e => setAmount(e.target.value)} style={{ flex: 1, fontFamily: 'JetBrains Mono', fontSize: 28, fontWeight: 600, letterSpacing: '-0.02em' }}/>
            <button className="a-btn secondary" onClick={() => setAmount(available.toFixed(2))}>Max</button>
          </div>

          <h3 style={{ margin: '24px 0 14px', fontFamily: 'Space Grotesk', fontSize: 16 }}>Method</h3>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
            {[
              { id: 'crypto', l: 'Crypto', sub: 'USDT TRC-20 · 24h', i: 'btc' },
              { id: 'wire',   l: 'Bank wire', sub: '3–5 business days', i: 'bank' },
            ].map(m => (
              <button key={m.id} onClick={() => setMethod(m.id)} style={{
                padding: 16, borderRadius: 14,
                border: '1.5px solid ' + (method === m.id ? 'var(--magenta)' : 'var(--line)'),
                background: method === m.id ? 'rgba(255,92,245,0.08)' : 'var(--surface-2)',
                color: 'var(--text)', font: 'inherit', textAlign: 'left', cursor: 'pointer',
                display: 'flex', flexDirection: 'column', gap: 6,
              }}>
                <div style={{ width: 36, height: 36, borderRadius: 10, background: method === m.id ? 'linear-gradient(135deg, var(--magenta), var(--cyan))' : 'rgba(255,255,255,0.04)', color: method === m.id ? '#06070D' : 'var(--text-dim)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{I[m.i]({ size: 18 })}</div>
                <div style={{ fontWeight: 700, fontSize: 14 }}>{m.l}</div>
                <div style={{ fontSize: 11, color: 'var(--text-dim)' }}>{m.sub}</div>
              </button>
            ))}
          </div>
        </div>

        <div className="a-section" style={{ background: 'linear-gradient(135deg, rgba(255,92,245,0.10), rgba(92,217,255,0.06)), var(--surface)' }}>
          <div style={{ fontSize: 11, color: 'var(--text-dim)', textTransform: 'uppercase', letterSpacing: '.1em', fontWeight: 600 }}>Summary</div>
          <div className="mono" style={{ fontSize: 32, fontWeight: 700, letterSpacing: '-0.03em', marginTop: 6 }}>${amt.toFixed(2)}</div>
          <div style={{ marginTop: 10, fontSize: 12, color: 'var(--text-dim)' }}>Method: <b style={{ color: 'var(--text)' }}>{method ? method.toUpperCase() : 'select one'}</b></div>
          <div style={{ marginTop: 4, fontSize: 12, color: 'var(--text-dim)' }}>Network fee: <b style={{ color: 'var(--text)' }} className="mono">~$1.20</b></div>
          <div style={{ marginTop: 4, fontSize: 12, color: 'var(--text-dim)' }}>You receive: <b style={{ color: 'var(--text)' }} className="mono">${(amt - 1.2).toFixed(2)}</b></div>
          <button
            className="a-btn primary"
            style={{ width: '100%', marginTop: 16, justifyContent: 'center', height: 46, ...(!method || amt < 50 || amt > available ? { opacity: 0.5, cursor: 'not-allowed' } : {}) }}
            disabled={!method || amt < 50 || amt > available}
            onClick={go}
          >
            Continue <I.arrowRight size={13}/>
          </button>
        </div>
      </div>
    </>
  );
}

function ArenaWithdrawCrypto() {
  const { setPage } = useApp();
  const [saved, setSaved] = useState('addr1');
  const [mode, setMode] = useState('saved'); // saved | new
  const [newAddr, setNewAddr] = useState('');
  const savedAddrs = [
    { id: 'addr1', label: 'Main USDT TRC-20', addr: 'TXyZ9abcDEFghiJKLmnPqrSTUVwxyz1234', last: 'May 12' },
    { id: 'addr2', label: 'Backup USDT ERC-20', addr: '0xa1b2c3d4e5f60718293a4b5c6d7e8f90', last: 'Apr 14' },
  ];

  return (
    <>
      <div className="a-pagehead">
        <div>
          <div style={{ fontSize: 12, color: 'var(--text-dim)', display: 'flex', alignItems: 'center', gap: 6 }}>
            <a onClick={() => setPage('withdraw')} style={{ cursor: 'pointer', color: 'var(--text-dim)' }}>Withdraw</a>
            <I.chevronRight size={10}/>
            <span style={{ color: 'var(--text)', fontWeight: 600 }}>Crypto</span>
          </div>
          <h1 style={{ marginTop: 6 }}>Crypto <em>destination</em>.</h1>
          <div className="sub">Choose a saved address or add a new one</div>
        </div>
        <button className="a-btn secondary" onClick={() => setPage('withdraw')}><I.chevronLeft size={13}/> Back</button>
      </div>

      <div className="a-section" style={{ maxWidth: 720 }}>
        <div className="a-chips" style={{ marginBottom: 18 }}>
          <button className={mode === 'saved' ? 'active' : ''} onClick={() => setMode('saved')}>Saved <span className="c">{savedAddrs.length}</span></button>
          <button className={mode === 'new' ? 'active' : ''} onClick={() => setMode('new')}>+ New address</button>
        </div>

        {mode === 'saved' && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {savedAddrs.map(a => (
              <button key={a.id} onClick={() => setSaved(a.id)} style={{
                padding: '14px 16px', borderRadius: 12,
                border: '1.5px solid ' + (saved === a.id ? 'var(--magenta)' : 'var(--line)'),
                background: saved === a.id ? 'rgba(255,92,245,0.06)' : 'var(--surface-2)',
                color: 'var(--text)', font: 'inherit', cursor: 'pointer', textAlign: 'left',
                display: 'flex', alignItems: 'center', gap: 12,
              }}>
                <div style={{ width: 38, height: 38, borderRadius: 10, background: 'rgba(255,255,255,0.04)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--text-dim)' }}><I.btc size={18}/></div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontWeight: 600, fontSize: 14 }}>{a.label}</div>
                  <div className="mono" style={{ fontSize: 11, color: 'var(--text-dim)' }}>{a.addr.slice(0, 12)}…{a.addr.slice(-6)} · last used {a.last}</div>
                </div>
                {saved === a.id && <I.check size={16} style={{ color: 'var(--magenta)' }}/>}
              </button>
            ))}
          </div>
        )}

        {mode === 'new' && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            <ArenaInputField label="Label (e.g. Binance hot wallet)" v="" onChange={() => {}}/>
            <div>
              <label style={{ fontSize: 11, color: 'var(--text-dim)', textTransform: 'uppercase', letterSpacing: '.08em', fontWeight: 600, display: 'block', marginBottom: 6 }}>Network</label>
              <div className="a-chips" style={{ width: '100%' }}>
                {['TRC20', 'ERC20', 'BEP20', 'SOL'].map(c => (<button key={c} className={c === 'TRC20' ? 'active' : ''} style={{ flex: 1, justifyContent: 'center' }}>{c}</button>))}
              </div>
            </div>
            <ArenaInputField label="Wallet address" v={newAddr} onChange={setNewAddr} mono/>
            <div style={{ padding: 12, background: 'color-mix(in oklab, var(--gold) 10%, transparent)', border: '1px solid color-mix(in oklab, var(--gold) 25%, transparent)', borderRadius: 10, fontSize: 12 }}>
              <I.warn size={12} style={{ marginRight: 6, verticalAlign: 'middle', color: 'var(--gold)' }}/>
              We'll send a $1 test deposit to confirm. New addresses are locked for 24h.
            </div>
          </div>
        )}

        <button className="a-btn primary" style={{ width: '100%', marginTop: 18, justifyContent: 'center', height: 46 }} onClick={() => setPage('withdrawConfirm')}>
          Continue <I.arrowRight size={13}/>
        </button>
      </div>
    </>
  );
}

function ArenaWithdrawWire() {
  const { setPage } = useApp();
  const [currency, setCurrency] = useState('EUR');
  const [pick, setPick] = useState('b1');
  const [mode, setMode] = useState('saved'); // saved | new
  const beneficiaries = [
    { id: 'b1', label: 'Revolut · EUR', name: 'Yulia Larssen', iban: 'LT60 3250 0123 4567 8901', swift: 'REVOLT21', bank: 'Revolut Bank UAB', currency: 'EUR' },
    { id: 'b2', label: 'Intesa Sanpaolo · EUR', name: 'Yulia Larssen', iban: 'IT60 X054 2811 1010 0000 0123 456', swift: 'BCITITMM', bank: 'Intesa Sanpaolo', currency: 'EUR' },
  ];

  return (
    <>
      <div className="a-pagehead">
        <div>
          <div style={{ fontSize: 12, color: 'var(--text-dim)', display: 'flex', alignItems: 'center', gap: 6 }}>
            <a onClick={() => setPage('withdraw')} style={{ cursor: 'pointer', color: 'var(--text-dim)' }}>Withdraw</a>
            <I.chevronRight size={10}/>
            <span style={{ color: 'var(--text)', fontWeight: 600 }}>Wire</span>
          </div>
          <h1 style={{ marginTop: 6 }}>Wire <em>destination</em>.</h1>
          <div className="sub">Send to your verified bank account · 3–5 business days</div>
        </div>
        <button className="a-btn ghost" onClick={() => setPage('withdraw')}><I.chevronLeft size={13}/> Back</button>
      </div>

      <div className="a-section" style={{ maxWidth: 720 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 16 }}>
          <span style={{ fontSize: 11, color: 'var(--text-dim)', letterSpacing: '.06em', textTransform: 'uppercase', fontWeight: 600 }}>Currency</span>
          <div className="a-chips">
            {['USD', 'EUR', 'GBP'].map(c => <button key={c} className={currency === c ? 'active' : ''} onClick={() => setCurrency(c)}>{c}</button>)}
          </div>
        </div>

        <div className="a-chips" style={{ marginBottom: 14 }}>
          <button className={mode === 'saved' ? 'active' : ''} onClick={() => setMode('saved')}>Saved <span className="c">{beneficiaries.length}</span></button>
          <button className={mode === 'new' ? 'active' : ''} onClick={() => setMode('new')}>+ New beneficiary</button>
        </div>

        {mode === 'saved' && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {beneficiaries.map(b => (
              <button key={b.id} onClick={() => setPick(b.id)} style={{
                padding: '14px 16px', borderRadius: 12,
                border: '1.5px solid ' + (pick === b.id ? 'var(--magenta)' : 'var(--line)'),
                background: pick === b.id ? 'rgba(255,92,245,0.06)' : 'var(--surface-2)',
                color: 'var(--text)', font: 'inherit', cursor: 'pointer', textAlign: 'left',
                display: 'flex', alignItems: 'center', gap: 12,
              }}>
                <div style={{ width: 38, height: 38, borderRadius: 10, background: 'rgba(255,255,255,0.04)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--text-dim)' }}><I.bank size={18}/></div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontWeight: 600, fontSize: 14 }}>{b.label}</div>
                  <div className="mono" style={{ fontSize: 11, color: 'var(--text-dim)' }}>{b.iban.slice(0, 8)}…{b.iban.slice(-4)} · SWIFT {b.swift}</div>
                  <div style={{ fontSize: 11, color: 'var(--text-faint)', marginTop: 2 }}>{b.name} · {b.bank}</div>
                </div>
                {pick === b.id && <I.check size={16} style={{ color: 'var(--magenta)' }}/>}
              </button>
            ))}
          </div>
        )}

        {mode === 'new' && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            <ArenaInputField label="Beneficiary name" v="" onChange={() => {}}/>
            <ArenaInputField label="IBAN / Account number" v="" onChange={() => {}} mono/>
            <ArenaInputField label="SWIFT / BIC" v="" onChange={() => {}} mono/>
            <ArenaInputField label="Bank name" v="" onChange={() => {}}/>
            <div style={{ padding: 12, background: 'color-mix(in oklab, var(--gold) 10%, transparent)', border: '1px solid color-mix(in oklab, var(--gold) 25%, transparent)', borderRadius: 10, fontSize: 12 }}>
              <I.warn size={12} style={{ marginRight: 6, verticalAlign: 'middle', color: 'var(--gold)' }}/>
              Beneficiary name must match your KYC identity. New bank accounts are locked for 24h.
            </div>
          </div>
        )}

        <button className="a-btn primary" style={{ width: '100%', marginTop: 18, justifyContent: 'center', height: 46 }} onClick={() => setPage('withdrawConfirm')}>
          Continue <I.arrowRight size={13}/>
        </button>
      </div>
    </>
  );
}

function ArenaWithdrawConfirm() {
  const { setPage } = useApp();
  const [code, setCode] = useState('');
  const [step, setStep] = useState('confirm'); // confirm | processing | success
  const amount = 600;

  function submit() {
    if (code.length !== 6) return;
    setStep('processing');
    setTimeout(() => setStep('success'), 1500);
  }

  if (step === 'success') return <ArenaTxSuccess kind="withdraw" amount={amount} setPage={setPage}/>;

  return (
    <>
      <div className="a-pagehead">
        <div>
          <div style={{ fontSize: 12, color: 'var(--text-dim)', display: 'flex', alignItems: 'center', gap: 6 }}>
            <a onClick={() => setPage('withdraw')} style={{ cursor: 'pointer', color: 'var(--text-dim)' }}>Withdraw</a>
            <I.chevronRight size={10}/>
            <span style={{ color: 'var(--text)', fontWeight: 600 }}>Confirm</span>
          </div>
          <h1 style={{ marginTop: 6 }}>Review & <em>confirm</em>.</h1>
          <div className="sub">Final review before we submit your withdrawal</div>
        </div>
        <button className="a-btn ghost" onClick={() => setPage('withdraw')}><I.chevronLeft size={13}/> Edit</button>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 380px', gap: 18, maxWidth: 1080 }}>
        <div className="a-section" style={{ background: 'linear-gradient(135deg, rgba(255,92,245,0.10), rgba(92,217,255,0.06)), var(--surface)' }}>
          <div style={{ fontSize: 11, color: 'var(--text-dim)', textTransform: 'uppercase', letterSpacing: '.1em', fontWeight: 600 }}>You'll receive</div>
          <div className="mono" style={{ fontSize: 40, fontWeight: 700, letterSpacing: '-0.03em', marginTop: 4 }}>${(amount - 1.2).toFixed(2)}</div>
          <div style={{ marginTop: 4, fontSize: 13, color: 'var(--text-dim)' }}>≈ {(amount - 1.2).toFixed(2)} USDT · arrival in ~24h</div>

          <div style={{ marginTop: 22, padding: 16, background: 'var(--surface-2)', border: '1px solid var(--line)', borderRadius: 12 }}>
            <ArenaKv label="From" value="Wallet balance"/>
            <ArenaKv label="Amount" value={'$' + amount.toFixed(2)} mono/>
            <ArenaKv label="Method" value="USDT TRC-20"/>
            <ArenaKv label="Destination" value="Main USDT TRC-20"/>
            <ArenaKv label="Address" value="TXyZ…1234" mono copy/>
            <ArenaKv label="Network fee" value="$1.20" mono/>
            <ArenaKv label="ETA" value="~ 24 hours"/>
          </div>
        </div>

        <div className="a-section" style={{ alignSelf: 'start' }}>
          <h3 style={{ margin: '0 0 12px', fontFamily: 'Space Grotesk', fontSize: 16 }}>2FA required</h3>
          {step === 'confirm' && (
            <>
              <div style={{ fontSize: 13, color: 'var(--text-dim)', marginBottom: 12 }}>Enter the 6-digit code from your authenticator app.</div>
              <input
                className="a-input"
                value={code}
                onChange={e => setCode(e.target.value.replace(/\D/g, '').slice(0, 6))}
                placeholder="123 456"
                style={{ fontFamily: 'JetBrains Mono', fontSize: 24, textAlign: 'center', letterSpacing: '0.4em', padding: '18px 14px' }}
              />
              <button
                className="a-btn primary"
                onClick={submit}
                disabled={code.length !== 6}
                style={{ width: '100%', marginTop: 16, justifyContent: 'center', height: 46, ...(code.length !== 6 ? { opacity: 0.5, cursor: 'not-allowed' } : {}) }}
              >
                <I.shield size={13}/> Confirm withdrawal
              </button>
              <div style={{ marginTop: 10, fontSize: 11, color: 'var(--text-dim)' }}>
                <I.info size={11} style={{ marginRight: 4, verticalAlign: 'middle' }}/>
                Code refreshes every 30 seconds.
              </div>
            </>
          )}
          {step === 'processing' && (
            <div style={{ padding: '40px 0', textAlign: 'center' }}>
              <div style={{ width: 48, height: 48, border: '3px solid var(--line)', borderTopColor: 'var(--magenta)', borderRadius: '50%', animation: 'spin 0.8s linear infinite', margin: '0 auto' }}/>
              <div style={{ marginTop: 14, fontSize: 14, fontWeight: 600 }}>Submitting…</div>
              <div style={{ marginTop: 4, fontSize: 11, color: 'var(--text-dim)' }}>Broadcasting to TRC-20</div>
              <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
            </div>
          )}
        </div>
      </div>
    </>
  );
}

// ============ FORGOT PASSWORD ============
function ArenaForgotPassword() {
  const { setPage } = useApp();
  const [mode, setMode] = useState('request'); // request | reset | sent | done
  const [email, setEmail] = useState('yulia@example.com');
  const [show, setShow] = useState(false);

  return (
    <div className="auth-bg auth-page">
      <div className="auth-card">
        <button className="auth-back" onClick={() => setPage('login')}><I.chevronLeft size={11}/> Back to login</button>
        <div style={{ marginBottom: 22 }}><PropArenaLockup size={28}/></div>

        {mode === 'request' && (
          <>
            <h1 className="auth-h">Forgot <em>password</em>.</h1>
            <p className="auth-sub">Enter your account email · we'll send a reset link.</p>
            <div className="field">
              <label>Email</label>
              <div className="ctrl">
                <I.mail size={15} style={{ color: 'var(--text-faint)' }}/>
                <input type="email" value={email} onChange={e => setEmail(e.target.value)}/>
              </div>
            </div>
            <button className="auth-submit" onClick={() => setMode('sent')}>Send reset link <I.arrowRight size={14}/></button>
            <div style={{ marginTop: 14, fontSize: 12, color: 'var(--text-dim)', textAlign: 'center' }}>
              Already have a token? <a onClick={() => setMode('reset')} style={{ color: 'var(--cyan)', cursor: 'pointer' }}>Enter reset code</a>
            </div>
          </>
        )}

        {mode === 'sent' && (
          <>
            <div style={{ width: 56, height: 56, borderRadius: 14, background: 'color-mix(in oklab, var(--positive) 20%, transparent)', color: 'var(--positive)', display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 18 }}><I.mail size={26}/></div>
            <h1 className="auth-h">Check your <em>email</em>.</h1>
            <p className="auth-sub">If <b style={{ color: 'var(--text)' }}>{email}</b> is registered, you'll get a reset link within a minute.</p>
            <button className="auth-submit" onClick={() => setMode('reset')}>I have the code <I.arrowRight size={14}/></button>
            <div style={{ marginTop: 14, fontSize: 12, color: 'var(--text-dim)', textAlign: 'center' }}>
              <a onClick={() => setMode('request')} style={{ color: 'var(--cyan)', cursor: 'pointer' }}>Resend</a> · <a onClick={() => setPage('login')} style={{ color: 'var(--cyan)', cursor: 'pointer' }}>Back to login</a>
            </div>
          </>
        )}

        {mode === 'reset' && (
          <>
            <h1 className="auth-h">Reset <em>password</em>.</h1>
            <p className="auth-sub">Paste the reset code from your email, then pick a new password.</p>
            <div className="field">
              <label>Reset code</label>
              <div className="ctrl">
                <I.lock size={15} style={{ color: 'var(--text-faint)' }}/>
                <input type="text" placeholder="abc-xyz-123"/>
              </div>
            </div>
            <div className="field">
              <label>New password</label>
              <div className="ctrl">
                <I.lock size={15} style={{ color: 'var(--text-faint)' }}/>
                <input type={show ? 'text' : 'password'} placeholder="At least 12 characters"/>
                <span onClick={() => setShow(s => !s)} style={{ cursor: 'pointer', display: 'inline-flex' }}>
                  {show ? <I.eyeOff size={15} style={{ color: 'var(--text-faint)' }}/> : <I.eye size={15} style={{ color: 'var(--text-faint)' }}/>}
                </span>
              </div>
            </div>
            <button className="auth-submit" onClick={() => setMode('done')}>Reset password <I.arrowRight size={14}/></button>
          </>
        )}

        {mode === 'done' && (
          <>
            <div style={{ width: 56, height: 56, borderRadius: 14, background: 'color-mix(in oklab, var(--positive) 20%, transparent)', color: 'var(--positive)', display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 18 }}><I.check size={26}/></div>
            <h1 className="auth-h">Password <em>updated</em>.</h1>
            <p className="auth-sub">You can now sign in with your new password.</p>
            <button className="auth-submit" onClick={() => setPage('login')}>Continue to login <I.arrowRight size={14}/></button>
          </>
        )}
      </div>
    </div>
  );
}

function ArenaSecurityKyc() {
  const [verified, setVerified] = useState(true);
  const [step, setStep] = useState(null); // null | 'intro' | 'starting' | 'done'

  function start() { setStep('intro'); }
  function launchSumsub() {
    setStep('starting');
    setTimeout(() => { setVerified(true); setStep('done'); }, 1500);
  }

  return (
    <div className="a-section">
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 }}>
        <h3 style={{ margin: 0, fontFamily: 'Space Grotesk', fontSize: 16 }}>KYC verification</h3>
        {verified
          ? <span className="a-tag success">VERIFIED</span>
          : <span className="a-tag" style={{ background: 'color-mix(in oklab, var(--gold) 14%, transparent)', color: 'var(--gold)' }}>PENDING</span>}
      </div>

      {!verified && (
        <>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginBottom: 14 }}>
            {[
              ['Identity document', 'Passport or national ID'],
              ['Selfie / liveness', '5-second face scan'],
              ['Proof of address', 'Utility bill or bank statement, ≤ 3 months'],
            ].map(([l, s]) => (
              <div key={l} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 12px', background: 'var(--surface-2)', border: '1px solid var(--line)', borderRadius: 10 }}>
                <div style={{ width: 32, height: 32, borderRadius: 999, background: 'rgba(255,255,255,0.04)', color: 'var(--text-faint)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><I.file size={14}/></div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontWeight: 600, fontSize: 13 }}>{l}</div>
                  <div style={{ fontSize: 11, color: 'var(--text-dim)' }}>{s}</div>
                </div>
              </div>
            ))}
          </div>
          <div style={{ fontSize: 12, color: 'var(--text-dim)', marginBottom: 14 }}>
            <I.shield size={12} style={{ marginRight: 6, verticalAlign: 'middle' }}/>
            We use Sumsub for identity checks. Takes about 5 minutes.
          </div>
          <button className="a-btn primary" style={{ width: '100%', justifyContent: 'center', background: 'linear-gradient(135deg, #4A6EE0, #2C4DC0)', boxShadow: '0 0 24px -8px #4A6EE0' }} onClick={start}>
            <SumsubMark/> Start verification with Sumsub
          </button>
        </>
      )}

      {verified && (
        <>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginBottom: 14 }}>
            {[
              { l: 'Identity document', sub: 'Passport · IT · Apr 14, 2026' },
              { l: 'Selfie / liveness', sub: 'Match score 98% · Apr 14, 2026' },
              { l: 'Proof of address',  sub: 'Utility bill · Rome · Apr 14, 2026' },
            ].map(k => (
              <div key={k.l} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 12px', background: 'color-mix(in oklab, var(--positive) 6%, transparent)', border: '1px solid color-mix(in oklab, var(--positive) 30%, transparent)', borderRadius: 10 }}>
                <div style={{ width: 32, height: 32, borderRadius: 999, background: 'color-mix(in oklab, var(--positive) 18%, transparent)', color: 'var(--positive)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><I.check size={14}/></div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontWeight: 600, fontSize: 13 }}>{k.l}</div>
                  <div style={{ fontSize: 11, color: 'var(--text-dim)' }}>{k.sub}</div>
                </div>
              </div>
            ))}
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <button className="a-btn secondary" style={{ flex: 1, justifyContent: 'center' }} onClick={() => { setVerified(false); }}>
              <I.refresh size={12}/> Re-verify
            </button>
            <button className="a-btn ghost" style={{ flex: 1, justifyContent: 'center' }}>
              <I.download size={12}/> Download report
            </button>
          </div>
        </>
      )}

      {step === 'intro' && (
        <ArenaModalShell
          onClose={() => setStep(null)}
          title="Verify with Sumsub"
          subtitle="Quick, secure ID check"
          width={460}
          footer={<>
            <button className="a-btn ghost" onClick={() => setStep(null)}>Cancel</button>
            <button className="a-btn primary" style={{ background: 'linear-gradient(135deg, #4A6EE0, #2C4DC0)' }} onClick={launchSumsub}>
              <SumsubMark/> Open Sumsub
            </button>
          </>}
        >
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            {[
              ['1', 'Open Sumsub', 'You\'ll be handed off to Sumsub in a popup or new tab'],
              ['2', 'Capture documents', 'Photo of ID + selfie + address proof'],
              ['3', 'We get notified', 'Approval is usually instant; manual review ≤ 24h'],
            ].map(([n, h, s]) => (
              <div key={n} style={{ display: 'flex', gap: 12 }}>
                <div style={{ width: 28, height: 28, borderRadius: 999, background: 'linear-gradient(135deg, #4A6EE0, #2C4DC0)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 700, fontSize: 13, flex: 'none' }}>{n}</div>
                <div>
                  <div style={{ fontWeight: 600 }}>{h}</div>
                  <div style={{ fontSize: 12, color: 'var(--text-dim)' }}>{s}</div>
                </div>
              </div>
            ))}
            <div style={{ padding: 10, background: 'rgba(0,0,0,0.2)', borderRadius: 8, fontSize: 11, color: 'var(--text-dim)' }}>
              <I.shield size={11} style={{ marginRight: 4, verticalAlign: 'middle' }}/>
              Your documents are processed by Sumsub under EU privacy rules. We never store the source files.
            </div>
          </div>
        </ArenaModalShell>
      )}

      {step === 'starting' && (
        <ArenaModalShell onClose={() => setStep(null)} title="Connecting to Sumsub" subtitle="Setting up your secure session…" width={400}>
          <div style={{ textAlign: 'center', padding: '20px 0' }}>
            <div style={{ width: 48, height: 48, borderRadius: 999, border: '3px solid var(--line)', borderTopColor: '#4A6EE0', margin: '0 auto', animation: 'spin 0.8s linear infinite' }}/>
            <div style={{ marginTop: 14, fontSize: 13, color: 'var(--text-dim)' }}>Handing off to Sumsub…</div>
          </div>
        </ArenaModalShell>
      )}

      {step === 'done' && (
        <ArenaModalShell onClose={() => setStep(null)} title="Verification submitted" subtitle="We'll email you once Sumsub finishes the review." width={400} footer={<button className="a-btn primary" onClick={() => setStep(null)}>Done</button>}>
          <div style={{ textAlign: 'center', padding: '20px 0' }}>
            <div style={{ width: 56, height: 56, borderRadius: 999, background: 'color-mix(in oklab, var(--positive) 20%, transparent)', color: 'var(--positive)', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto' }}><I.check size={28}/></div>
            <div style={{ marginTop: 14, fontSize: 13, color: 'var(--text-dim)' }}>Most reviews complete within minutes.</div>
          </div>
        </ArenaModalShell>
      )}
    </div>
  );
}

function SumsubMark() {
  // Minimal "S" mark for Sumsub button
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      width: 18, height: 18, borderRadius: 4,
      background: '#fff', color: '#4A6EE0',
      fontWeight: 800, fontSize: 11,
      fontFamily: 'Inter Tight, sans-serif',
      letterSpacing: '-0.04em',
    }}>S</span>
  );
}

// ============ ARENATRADER ACCOUNT CHOOSER MODAL ============
function ArenaTraderChooser({ accounts, onClose, onPick, mobile }) {
  if (mobile) {
    return (
      <>
        <div onClick={onClose} style={{ position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.62)', backdropFilter: 'blur(6px)', zIndex: 200 }}/>
        <div style={{
          position: 'absolute', left: 0, right: 0, bottom: 0, zIndex: 201,
          maxHeight: '85%',
          background: 'var(--surface)',
          borderTop: '1px solid var(--line-3)',
          borderRadius: '22px 22px 0 0',
          boxShadow: '0 -20px 60px rgba(0,0,0,0.6)',
          display: 'flex', flexDirection: 'column',
          overflow: 'hidden',
          animation: 'sheet-up .25s cubic-bezier(.4,0,.2,1)',
        }}>
          <style>{`@keyframes sheet-up { from { transform: translateY(100%); } }`}</style>
          <div style={{ padding: '10px 0 0', display: 'flex', justifyContent: 'center' }}>
            <div style={{ width: 36, height: 4, borderRadius: 999, background: 'var(--line-3)' }}/>
          </div>
          <div style={{ padding: '14px 18px 12px', display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12 }}>
            <div>
              <div style={{ fontFamily: 'Space Grotesk', fontSize: 18, fontWeight: 700, letterSpacing: '-0.02em' }}>Choose account</div>
              <div style={{ fontSize: 11, color: 'var(--text-dim)', marginTop: 2 }}>Open ArenaTrader in a new tab.</div>
            </div>
            <button onClick={onClose} style={{
              width: 30, height: 30, 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={12}/></button>
          </div>
          <div style={{ padding: '0 14px 22px', overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: 8 }}>
            {accounts.map(a => <ArenaTraderChooserCard key={a.id} a={a} onPick={onPick}/>)}
          </div>
        </div>
      </>
    );
  }
  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: 480, 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 24px 16px', display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12 }}>
          <div>
            <div style={{ fontFamily: 'Space Grotesk', fontSize: 22, fontWeight: 700, letterSpacing: '-0.025em' }}>Choose account</div>
            <div style={{ fontSize: 12, color: 'var(--text-dim)', marginTop: 4 }}>Open ArenaTrader in a new tab.</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={{ padding: '4px 22px 22px', overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: 8 }}>
          {accounts.map(a => <ArenaTraderChooserCard key={a.id} a={a} onPick={onPick}/>)}
        </div>
      </div>
    </>
  );
}

function ArenaTraderChooserCard({ a, onPick }) {
  const isFunded = a.status === 'funded';
  const isFailed = a.status === 'failed';
  const tagFg = isFunded ? 'var(--magenta)' : 'var(--cyan)';
  const tagLabel = isFunded ? 'FUNDED' : window.planLabel(a).toUpperCase();
  return (
    <button
      disabled={isFailed}
      onClick={() => !isFailed && onPick(a)}
      style={{
        textAlign: 'left',
        background: 'var(--surface-2)',
        border: '1px solid ' + (isFailed ? 'var(--line)' : 'color-mix(in oklab, var(--positive) 30%, var(--line))'),
        borderRadius: 14,
        padding: '12px 16px',
        cursor: isFailed ? 'not-allowed' : 'pointer',
        opacity: isFailed ? 0.5 : 1,
        font: 'inherit', color: 'var(--text)',
        transition: 'background .15s',
        display: 'flex', flexDirection: 'column', gap: 4,
      }}
      onMouseEnter={e => !isFailed && (e.currentTarget.style.background = 'var(--surface-3)')}
      onMouseLeave={e => (e.currentTarget.style.background = 'var(--surface-2)')}
    >
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 8 }}>
        <span className="mono" style={{ fontSize: 11, color: 'var(--text-dim)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{a.login} · {a.plan}</span>
        <span className="mono" style={{ fontSize: 18, fontWeight: 700, letterSpacing: '-0.02em', flex: 'none' }}>${window.fmtMoney(a.equity)}</span>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <span style={{ fontFamily: 'Space Grotesk', fontSize: 18, fontWeight: 700, letterSpacing: '-0.025em' }}>${window.fmtMoneyCompact(a.size)}</span>
        <span style={{
          display: 'inline-flex', alignItems: 'center',
          padding: '3px 10px', borderRadius: 999,
          color: tagFg,
          fontWeight: 700, fontSize: 10, letterSpacing: '0.06em',
          border: '1px solid ' + tagFg,
        }}>{tagLabel}</span>
      </div>
    </button>
  );
}

// Mount one global chooser at the app root
function ArenaTraderChooserHost({ mobile }) {
  const { accounts, setAccountId } = useApp();
  const [open, setOpen] = useState(false);
  useEffect(() => {
    window.openArenaTrader = (accountId) => {
      if (accountId) {
        const a = accounts.find(x => x.id === accountId);
        if (a) { setAccountId(a.id); window.open('about:blank', '_blank'); }
        return;
      }
      setOpen(true);
    };
  }, [accounts, setAccountId]);
  if (!open) return null;
  const node = (
    <ArenaTraderChooser
      accounts={accounts.filter(a => a.status !== 'failed')}
      onClose={() => setOpen(false)}
      onPick={(a) => { setAccountId(a.id); setOpen(false); window.open('about:blank', '_blank'); }}
      mobile={mobile}
    />
  );
  if (mobile) {
    const phoneEl = typeof document !== 'undefined' ? document.querySelector('.d-arena .phone') : null;
    return phoneEl ? ReactDOM.createPortal(node, phoneEl) : node;
  }
  return node;
}

Object.assign(window, { ArenaTraderChooserHost });

// Expose globals
Object.assign(window, {
  ArenaWebtrader, ArenaInbox, ArenaProfile, ArenaProfileEdit, ArenaSecurity,
  ArenaDeposit, ArenaDepositCrypto, ArenaDepositCard, ArenaDepositWire,
  ArenaWithdraw, ArenaWithdrawCrypto, ArenaWithdrawWire, ArenaWithdrawConfirm,
  ArenaForgotPassword,
  ARENA_WALLET_BALANCE: 1284.50,
});
