// ============================================================
// PROP ARENA — extra screens (desktop + mobile)
// New Challenge · Payouts · Billing · Settings · Credentials
// Notifications · Tiers · Journal · Calendar · Affiliates · Help
// ============================================================

const arenaExtrasCSS = `
.d-arena .a-section {
  background: var(--surface);
  border: 1px solid var(--line);
  border-radius: 18px;
  padding: 22px;
}
.d-arena .a-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 13px;
}
.d-arena .a-table th, .d-arena .a-table td {
  padding: 12px 14px;
  text-align: left;
}
.d-arena .a-table th {
  font-size: 10px;
  text-transform: uppercase;
  letter-spacing: 0.08em;
  color: var(--text-faint);
  font-weight: 600;
  background: var(--surface-2);
  border-bottom: 1px solid var(--line);
}
.d-arena .a-table td {
  border-bottom: 1px solid var(--line-2);
}
.d-arena .a-table tr:last-child td { border-bottom: none; }
.d-arena .a-table tr:hover td { background: var(--surface-2); }
.d-arena .a-table .r { text-align: right; }

.d-arena .a-input {
  width: 100%;
  height: 42px;
  padding: 0 14px;
  border-radius: 10px;
  border: 1px solid var(--line-3);
  background: rgba(0,0,0,0.30);
  color: var(--text);
  font-family: inherit; font-size: 14px;
  outline: none;
}
.d-arena .a-input:focus { border-color: var(--magenta); }

.d-arena .a-tag {
  display: inline-flex; align-items: center; gap: 5px;
  padding: 3px 8px;
  border-radius: 5px;
  font-size: 10px;
  font-weight: 700;
  letter-spacing: 0.06em;
  text-transform: uppercase;
}
.d-arena .a-tag.success {
  background: color-mix(in oklab, var(--positive) 14%, transparent);
  color: var(--positive);
  border: 1px solid color-mix(in oklab, var(--positive) 35%, transparent);
}
.d-arena .a-tag.pending {
  background: color-mix(in oklab, var(--gold) 14%, transparent);
  color: var(--gold);
  border: 1px solid color-mix(in oklab, var(--gold) 35%, transparent);
}
.d-arena .a-tag.muted {
  background: var(--surface-3);
  color: var(--text-dim);
}

.d-arena .a-chip-radio {
  display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px;
}
.d-arena .a-chip-radio button {
  padding: 14px;
  border-radius: 12px;
  border: 1.5px solid var(--line);
  background: var(--surface-2);
  color: var(--text);
  font: inherit; font-size: 13px;
  cursor: pointer;
  text-align: left;
  display: flex; flex-direction: column; gap: 4px;
  position: relative;
}
.d-arena .a-chip-radio button:hover { border-color: var(--line-3); }
.d-arena .a-chip-radio button.active {
  border-color: var(--magenta);
  background: linear-gradient(135deg, rgba(255,92,245,0.10), rgba(92,217,255,0.04));
  box-shadow: 0 0 0 3px color-mix(in oklab, var(--magenta) 14%, transparent);
}
.d-arena .a-chip-radio button .label { font-weight: 700; font-size: 16px; letter-spacing: -0.01em; }
.d-arena .a-chip-radio button .sub { font-size: 11px; color: var(--text-dim); }
.d-arena .a-chip-radio button .price { font-family: 'JetBrains Mono', monospace; font-size: 14px; margin-top: 6px; }
.d-arena .a-chip-radio button .strike { color: var(--text-faint); text-decoration: line-through; margin-right: 6px; }

/* Mobile shared */
.d-arena .am-page {
  width: 100%; min-height: 100%;
  padding: 56px 18px 110px;
  background:
    radial-gradient(ellipse 300px 200px at 0% 0%, rgba(255,92,245,0.14), transparent 60%),
    var(--bg);
  position: relative;
}
.d-arena .am-page-head {
  display: flex; align-items: center; justify-content: space-between;
  margin-bottom: 18px;
}
.d-arena .am-page-head h1 {
  font-family: 'Space Grotesk', sans-serif;
  font-size: 24px; font-weight: 700;
  letter-spacing: -0.025em;
  margin: 0;
}
.d-arena .am-card {
  background: var(--surface);
  border: 1px solid var(--line);
  border-radius: 14px;
  padding: 14px;
  margin-bottom: 10px;
}
`;

// Inject immediately
(function() {
  if (typeof document === 'undefined') return;
  if (document.getElementById('arena-extras-css')) return;
  const s = document.createElement('style');
  s.id = 'arena-extras-css';
  s.textContent = arenaExtrasCSS;
  document.head.appendChild(s);
})();

// ============ NEW CHALLENGE ============
function ArenaNewChallenge() {
  const { setPage } = useApp();
  const [plan, setPlan] = useState('sig');
  const [size, setSize] = useState(50000);
  const [platform, setPlatform] = useState('mt5');
  const [addons, setAddons] = useState({ news: false, max: false, weekend: false });
  const [checkout, setCheckout] = useState(null); // null | 'modal' | 'success'
  const planObj = {
    one: { name: 'Signature One',  steps: 1, sizes: [5000, 10000, 25000, 50000, 100000, 200000], target: '8%',     dd: '6%',     daily: '4%', sub: '1-step · fastest path', tag: 'FAST' },
    sig: { name: 'Signature',      steps: 2, sizes: [25000, 50000, 100000, 200000],              target: '8% / 5%', dd: '8%',     daily: '5%', sub: '2-step · most popular', tag: 'POPULAR' },
    pro: { name: 'Signature Pro',  steps: 3, sizes: [50000, 100000, 200000],                     target: '10% / 5% / 5%', dd: '10%', daily: '5%', sub: '3-step · larger DD', tag: 'BIG DD' },
  };
  const cur = planObj[plan];
  const priceMap = { one: { 5000:59, 10000:89, 25000:199, 50000:299, 100000:539, 200000:999 }, sig: { 25000:159, 50000:269, 100000:499, 200000:899 }, pro: { 50000:219, 100000:419, 200000:749 } };
  const price = priceMap[plan][size] || 0;
  const orig = Math.round(price * 1.4);
  const addonPrice = (addons.news ? 49 : 0) + (addons.max ? 79 : 0) + (addons.weekend ? 39 : 0);
  const total = price + addonPrice;
  if (!cur.sizes.includes(size)) setSize(cur.sizes[0]);

  if (checkout === 'success') {
    return <ArenaChallengeSuccess plan={cur.name} size={size} platform={platform} total={total} setPage={setPage}/>;
  }

  return (
    <>
      <div className="a-pagehead">
        <div>
          <h1>New <em>challenge</em>.</h1>
          <div className="sub">30% OFF for first-time buyers · code MAY30 auto-applied</div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1.5fr 1fr', gap: 22 }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          <div className="a-section">
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14 }}>
              <div style={{ width: 26, height: 26, borderRadius: 8, background: 'linear-gradient(135deg, var(--magenta), var(--cyan))', color: '#06070D', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 700, fontSize: 12 }}>1</div>
              <div style={{ fontFamily: 'Space Grotesk', fontWeight: 700, fontSize: 16 }}>Challenge type</div>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10 }}>
              {Object.entries(planObj).map(([k, p]) => {
                const active = plan === k;
                return (
                  <button key={k} onClick={() => setPlan(k)} style={{
                    padding: 16, borderRadius: 14,
                    border: '1.5px solid ' + (active ? 'var(--magenta)' : 'var(--line)'),
                    background: active ? 'linear-gradient(135deg, rgba(255,92,245,0.10), rgba(92,217,255,0.04)), var(--surface-2)' : 'var(--surface-2)',
                    color: 'var(--text)', font: 'inherit', textAlign: 'left',
                    cursor: 'pointer',
                    display: 'flex', flexDirection: 'column', gap: 12,
                    position: 'relative',
                    boxShadow: active ? '0 0 30px -10px var(--magenta)' : 'none',
                  }}>
                    <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between' }}>
                      <span style={{ display: 'inline-flex', alignItems: 'center', padding: '3px 10px', borderRadius: 999, fontSize: 10, fontWeight: 700, letterSpacing: '.06em', border: '1px solid ' + (active ? 'var(--magenta)' : 'var(--line-3)'), color: active ? 'var(--magenta)' : 'var(--text-dim)' }}>
                        {p.steps}-STEP
                      </span>
                      {p.tag === 'POPULAR' && <span style={{ fontSize: 9, fontWeight: 700, padding: '3px 8px', borderRadius: 4, background: 'linear-gradient(135deg, var(--magenta), var(--cyan))', color: '#06070D', letterSpacing: '.06em' }}>POPULAR</span>}
                    </div>
                    <div>
                      <div style={{ fontFamily: 'Space Grotesk', fontSize: 18, fontWeight: 700, letterSpacing: '-0.02em' }}>{p.name}</div>
                      <div style={{ fontSize: 11, color: 'var(--text-dim)', marginTop: 2 }}>{p.sub}</div>
                    </div>
                    {/* Stepper visualization */}
                    <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
                      {Array.from({ length: p.steps }).map((_, i) => (
                        <React.Fragment key={i}>
                          <div style={{
                            width: 22, height: 22, borderRadius: 999,
                            background: active ? 'linear-gradient(135deg, var(--magenta), var(--cyan))' : 'var(--surface-3)',
                            color: active ? '#06070D' : 'var(--text-faint)',
                            display: 'flex', alignItems: 'center', justifyContent: 'center',
                            fontFamily: 'JetBrains Mono', fontSize: 10, fontWeight: 700,
                            flex: 'none',
                          }}>{i + 1}</div>
                          <span style={{ flex: 1, height: 1, background: active ? 'color-mix(in oklab, var(--magenta) 40%, transparent)' : 'var(--line)' }}/>
                        </React.Fragment>
                      ))}
                      <span style={{ display: 'inline-flex', alignItems: 'center', padding: '3px 10px', borderRadius: 999, fontSize: 9, fontWeight: 700, letterSpacing: '.06em', color: active ? 'var(--gold)' : 'var(--text-faint)', border: '1px solid ' + (active ? 'var(--gold)' : 'var(--line)') }}>FUNDED</span>
                    </div>
                    {/* Metrics row */}
                    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8, paddingTop: 10, borderTop: '1px solid var(--line-2)' }}>
                      {[['Target', p.target], ['Daily', p.daily], ['Max DD', p.dd]].map(([l, v]) => (
                        <div key={l}>
                          <div style={{ fontSize: 9, color: 'var(--text-faint)', letterSpacing: '.06em', textTransform: 'uppercase', fontWeight: 600 }}>{l}</div>
                          <div className="mono" style={{ fontSize: 12, fontWeight: 600, marginTop: 2 }}>{v}</div>
                        </div>
                      ))}
                    </div>
                  </button>
                );
              })}
            </div>
          </div>

          <div className="a-section">
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14 }}>
              <div style={{ width: 26, height: 26, borderRadius: 8, background: 'linear-gradient(135deg, var(--magenta), var(--cyan))', color: '#06070D', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 700, fontSize: 12 }}>2</div>
              <div style={{ fontFamily: 'Space Grotesk', fontWeight: 700, fontSize: 16 }}>Account size</div>
            </div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
              {cur.sizes.map(s => (
                <button key={s} onClick={() => setSize(s)} style={{
                  padding: '12px 18px', borderRadius: 10,
                  border: '1.5px solid ' + (size === s ? 'var(--magenta)' : 'var(--line)'),
                  background: size === s ? 'rgba(255,92,245,0.10)' : 'var(--surface-2)',
                  color: 'var(--text)', font: 'inherit', fontWeight: 700, fontSize: 14, cursor: 'pointer',
                  fontFamily: 'JetBrains Mono', letterSpacing: '-0.01em',
                  display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2, minWidth: 90,
                }}>
                  <span style={{ fontSize: 17 }}>${window.fmtMoneyCompact(s)}</span>
                  <span className="mono" style={{ fontSize: 10, color: size === s ? 'var(--magenta)' : 'var(--text-faint)', fontWeight: 500 }}>${(priceMap[plan][s] || 0)}</span>
                </button>
              ))}
            </div>
          </div>

          <div className="a-section">
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14 }}>
              <div style={{ width: 26, height: 26, borderRadius: 8, background: 'linear-gradient(135deg, var(--magenta), var(--cyan))', color: '#06070D', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 700, fontSize: 12 }}>3</div>
              <div style={{ fontFamily: 'Space Grotesk', fontWeight: 700, fontSize: 16 }}>Platform</div>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10 }}>
              {[
                { id: 'mt5',     l: 'MetaTrader 5', sub: 'Recommended · all assets',  rec: true },
                { id: 'mt4',     l: 'MetaTrader 4', sub: 'Forex & majors only' },
                { id: 'ctrader', l: 'cTrader',      sub: 'Soon',                       disabled: true },
              ].map(p => (
                <button key={p.id} disabled={p.disabled} onClick={() => !p.disabled && setPlatform(p.id)} style={{
                  padding: '14px 16px', borderRadius: 12,
                  border: '1.5px solid ' + (platform === p.id ? 'var(--magenta)' : 'var(--line)'),
                  background: platform === p.id ? 'rgba(255,92,245,0.08)' : 'var(--surface-2)',
                  color: 'var(--text)', font: 'inherit', textAlign: 'left',
                  cursor: p.disabled ? 'not-allowed' : 'pointer',
                  opacity: p.disabled ? 0.5 : 1,
                  display: 'flex', flexDirection: 'column', gap: 4,
                  position: 'relative',
                }}>
                  <span style={{ fontWeight: 700, fontSize: 14 }}>{p.l}</span>
                  <span style={{ fontSize: 11, color: 'var(--text-dim)' }}>{p.sub}</span>
                  {p.rec && <span style={{ position: 'absolute', top: 8, right: 8, fontSize: 9, fontWeight: 700, padding: '2px 6px', borderRadius: 4, background: 'color-mix(in oklab, var(--positive) 20%, transparent)', color: 'var(--positive)', letterSpacing: '.06em' }}>BEST</span>}
                </button>
              ))}
            </div>
          </div>

          <div className="a-section">
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14 }}>
              <div style={{ width: 26, height: 26, borderRadius: 8, background: 'linear-gradient(135deg, var(--magenta), var(--cyan))', color: '#06070D', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 700, fontSize: 12 }}>4</div>
              <div style={{ fontFamily: 'Space Grotesk', fontWeight: 700, fontSize: 16 }}>Add-ons <span style={{ fontSize: 11, color: 'var(--text-faint)', fontWeight: 400 }}>· optional</span></div>
            </div>
            {[
              { id: 'news', l: 'News trading allowed', sub: 'Trade FOMC, NFP, CPI without restriction', price: 49 },
              { id: 'max', l: 'Max profit split 90%', sub: 'Default 80% · upgrade to 90% from day one', price: 79 },
              { id: 'weekend', l: 'Weekend hold', sub: 'Hold positions over weekends/news', price: 39 },
            ].map(a => (
              <label key={a.id} style={{
                display: 'flex', alignItems: 'center', gap: 12,
                padding: '14px 16px', borderRadius: 12,
                border: '1.5px solid ' + (addons[a.id]?'var(--magenta)':'var(--line)'),
                background: addons[a.id]?'rgba(255,92,245,0.06)':'var(--surface-2)',
                cursor: 'pointer', marginBottom: 8,
              }}>
                <input type="checkbox" checked={addons[a.id]} onChange={e=>setAddons({...addons, [a.id]:e.target.checked})}/>
                <div style={{ flex: 1 }}>
                  <div style={{ fontWeight: 600, fontSize: 14 }}>{a.l}</div>
                  <div style={{ fontSize: 12, color: 'var(--text-dim)' }}>{a.sub}</div>
                </div>
                <span className="mono" style={{ fontWeight: 600 }}>+${a.price}</span>
              </label>
            ))}
          </div>
        </div>

        <div className="a-section" style={{ position: 'sticky', top: 100, alignSelf: 'start', background: 'linear-gradient(135deg, rgba(255,92,245,0.08), rgba(92,217,255,0.04)), var(--surface)' }}>
          <div style={{ fontSize: 11, color: 'var(--text-dim)', textTransform: 'uppercase', letterSpacing: '.1em', fontWeight: 600, marginBottom: 6 }}>Order summary</div>
          <div style={{ fontFamily: 'Space Grotesk', fontWeight: 700, fontSize: 24, letterSpacing: '-0.02em' }}>{cur.name} ${window.fmtMoneyCompact(size)}</div>
          <div style={{ fontSize: 12, color: 'var(--text-dim)', marginTop: 4 }}>{platform === 'mt5' ? 'MetaTrader 5' : platform === 'mt4' ? 'MetaTrader 4' : 'cTrader'} · {cur.steps}-step · target {cur.target}</div>

          <div style={{ marginTop: 18, paddingTop: 16, borderTop: '1px solid var(--line-2)', display: 'flex', flexDirection: 'column', gap: 10 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13 }}>
              <span style={{ color: 'var(--text-dim)' }}>Plan</span>
              <span className="mono"><span style={{ color: 'var(--text-faint)', textDecoration: 'line-through', marginRight: 6 }}>${orig}</span>${price}</span>
            </div>
            {addons.news && <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13 }}><span style={{ color: 'var(--text-dim)' }}>News trading</span><span className="mono">+$49</span></div>}
            {addons.max && <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13 }}><span style={{ color: 'var(--text-dim)' }}>90% split</span><span className="mono">+$79</span></div>}
            {addons.weekend && <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13 }}><span style={{ color: 'var(--text-dim)' }}>Weekend hold</span><span className="mono">+$39</span></div>}
            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13, color: 'var(--positive)' }}>
              <span>Discount · MAY30</span>
              <span className="mono">−${Math.round((orig-price)*0.3)}</span>
            </div>
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginTop: 14, paddingTop: 14, borderTop: '1px solid var(--line)' }}>
            <span style={{ fontSize: 13, color: 'var(--text-dim)' }}>Total</span>
            <span className="mono" style={{ fontSize: 32, fontWeight: 700, letterSpacing: '-0.025em' }}>${total}</span>
          </div>
          <button className="a-btn primary" style={{ width: '100%', marginTop: 16, height: 48, justifyContent: 'center' }} onClick={() => setCheckout('modal')}>
            <I.lock size={13}/> Checkout · ${total}
          </button>
          <div style={{ display: 'flex', gap: 6, marginTop: 10, justifyContent: 'center', alignItems: 'center', flexWrap: 'wrap', fontSize: 11, color: 'var(--text-faint)' }}>
            <I.cards size={12}/> Visa · Mastercard · USDT · Wire · Wallet
          </div>
        </div>
      </div>

      {checkout === 'modal' && <ArenaChallengeCheckout plan={cur.name} size={size} platform={platform} total={total} onClose={() => setCheckout(null)} onSuccess={() => setCheckout('success')}/>}
    </>
  );
}

// ============ CHALLENGE CHECKOUT MODAL ============
function ArenaChallengeCheckout({ plan, size, platform, total, onClose, onSuccess }) {
  const [method, setMethod] = useState('card');
  const [step, setStep] = useState('form'); // form | processing
  const [card, setCard] = useState({ number: '4242 4242 4242 4242', expiry: '09 / 27', cvc: '123', name: 'Yulia Larssen' });
  const fee = method === 'card' ? +(total * 0.025).toFixed(2) : 0;
  const finalTotal = total + fee;

  function submit() {
    setStep('processing');
    setTimeout(() => { onSuccess(); }, 1600);
  }

  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: 640, 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: '18px 24px', borderBottom: '1px solid var(--line)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div>
            <div style={{ fontFamily: 'Space Grotesk', fontSize: 18, fontWeight: 700, letterSpacing: '-0.02em' }}>Checkout</div>
            <div style={{ fontSize: 12, color: 'var(--text-dim)', marginTop: 2 }}>{plan} · ${window.fmtMoneyCompact(size)} · {platform.toUpperCase()}</div>
          </div>
          <button className="a-iconbtn" onClick={onClose}><I.x size={13}/></button>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.1fr', flex: 1, overflow: 'hidden' }}>
          {/* Left: summary */}
          <div style={{ padding: 24, background: 'var(--surface)', borderRight: '1px solid var(--line)', overflowY: 'auto' }}>
            <div style={{ fontSize: 12, color: 'var(--text-dim)' }}>You're buying</div>
            <div className="mono" style={{ fontSize: 32, fontWeight: 700, letterSpacing: '-0.025em', marginTop: 4 }}>${finalTotal.toFixed(2)}</div>
            <div style={{ fontSize: 11, color: 'var(--text-faint)', marginTop: 2 }}>USD · {plan} ${window.fmtMoneyCompact(size)}</div>

            <div style={{ marginTop: 22, display: 'flex', flexDirection: 'column', gap: 10, fontSize: 13 }}>
              <ArenaKv label="Plan" value={plan}/>
              <ArenaKv label="Size" value={'$' + window.fmtMoneyCompact(size)}/>
              <ArenaKv label="Platform" value={platform === 'mt5' ? 'MetaTrader 5' : platform === 'mt4' ? 'MetaTrader 4' : 'cTrader'}/>
              <ArenaKv label="Subtotal" value={'$' + total.toFixed(2)} mono/>
              {fee > 0 && <ArenaKv label="Card fee (2.5%)" value={'$' + fee.toFixed(2)} mono/>}
            </div>

            <div style={{ marginTop: 22, fontSize: 11, color: 'var(--text-faint)', display: 'flex', alignItems: 'center', gap: 6 }}>
              <I.shield size={12}/> Secured by Stripe · PCI-DSS Level 1
            </div>
          </div>

          {/* Right: form */}
          <div style={{ padding: 24, background: 'var(--surface-2)', overflowY: 'auto' }}>
            {step === 'form' && (
              <>
                <div style={{ fontSize: 11, color: 'var(--text-dim)', textTransform: 'uppercase', letterSpacing: '.08em', fontWeight: 600, marginBottom: 8 }}>Pay with</div>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 6, marginBottom: 18 }}>
                  {[
                    { id: 'card',   l: 'Card',   i: 'cards' },
                    { id: 'crypto', l: 'Crypto', i: 'btc' },
                    { id: 'wire',   l: 'Wire',   i: 'bank' },
                    { id: 'wallet', l: 'Wallet', i: 'wallet' },
                  ].map(m => {
                    const Ic = I[m.i];
                    return (
                      <button key={m.id} onClick={() => setMethod(m.id)} style={{
                        padding: '12px 8px', borderRadius: 10,
                        border: '1.5px solid ' + (method === m.id ? 'var(--magenta)' : 'var(--line)'),
                        background: method === m.id ? 'rgba(255,92,245,0.10)' : 'var(--surface)',
                        color: 'var(--text)', font: 'inherit', cursor: 'pointer',
                        display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6,
                        fontSize: 11, fontWeight: 600,
                      }}>
                        <Ic size={16}/> {m.l}
                      </button>
                    );
                  })}
                </div>

                {method === 'card' && (
                  <>
                    <ArenaInputField label="Card number" v={card.number} onChange={v => setCard({ ...card, number: v })} mono/>
                    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
                      <ArenaInputField label="Expiry" 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" v={card.name} onChange={v => setCard({ ...card, name: v })}/>
                  </>
                )}

                {method === 'crypto' && (
                  <div style={{ padding: 14, background: 'var(--surface)', border: '1px solid var(--line)', borderRadius: 12, marginBottom: 14 }}>
                    <div style={{ fontWeight: 600, fontSize: 13, marginBottom: 4 }}>Pay with USDT</div>
                    <div style={{ fontSize: 12, color: 'var(--text-dim)' }}>You'll be sent to a deposit address page after this step.</div>
                  </div>
                )}

                {method === 'wire' && (
                  <div style={{ padding: 14, background: 'var(--surface)', border: '1px solid var(--line)', borderRadius: 12, marginBottom: 14 }}>
                    <div style={{ fontWeight: 600, fontSize: 13, marginBottom: 4 }}>Bank wire</div>
                    <div style={{ fontSize: 12, color: 'var(--text-dim)' }}>Wire instructions are emailed. Your account activates once funds clear (1–3 business days).</div>
                  </div>
                )}

                {method === 'wallet' && (
                  <div style={{ padding: 14, background: 'var(--surface)', border: '1px solid var(--line)', borderRadius: 12, marginBottom: 14 }}>
                    <div style={{ fontWeight: 600, fontSize: 13, marginBottom: 4 }}>Use wallet balance</div>
                    <div style={{ fontSize: 12, color: 'var(--text-dim)' }}>Wallet has <b className="mono" style={{ color: 'var(--text)' }}>$1,284.50</b> available. Account activates instantly.</div>
                  </div>
                )}

                <button className="a-btn primary" style={{ width: '100%', marginTop: 16, height: 48, justifyContent: 'center' }} onClick={submit}>
                  {method === 'crypto' ? <>Generate deposit address <I.arrowRight size={13}/></>
                   : method === 'wire' ? <>Get wire details <I.arrowRight size={13}/></>
                   : method === 'wallet' ? <><I.lock size={13}/> Pay ${total.toFixed(2)} from wallet</>
                   : <><I.lock size={13}/> Pay ${finalTotal.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 }}>Provisioning your account…</div>
                <div style={{ marginTop: 4, fontSize: 12, color: 'var(--text-dim)' }}>Setting up {plan} · ${window.fmtMoneyCompact(size)} · {platform.toUpperCase()}</div>
                <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
              </div>
            )}
          </div>
        </div>
      </div>
    </>
  );
}

// ============ CHALLENGE SUCCESS PAGE ============
function ArenaChallengeSuccess({ plan, size, platform, total, setPage }) {
  const login = useMemo(() => '510' + Math.floor(Math.random() * 90000 + 10000), []);
  return (
    <>
      <div className="a-pagehead">
        <div>
          <h1>Welcome to the <em>arena</em>.</h1>
          <div className="sub">Your new {plan} account is live · trade when you're ready</div>
        </div>
      </div>

      <div className="a-section" style={{ maxWidth: 640, margin: '0 auto', padding: 0, overflow: 'hidden' }}>
        <div style={{
          padding: 40, textAlign: 'center',
          background: 'linear-gradient(135deg, rgba(255,92,245,0.12), rgba(92,217,255,0.08))',
          borderBottom: '1px solid var(--line)',
        }}>
          <div style={{ width: 84, height: 84, borderRadius: 22, background: 'linear-gradient(135deg, var(--magenta), var(--cyan))', color: '#06070D', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto', boxShadow: '0 0 60px -10px var(--magenta)' }}>
            <I.rocket size={42}/>
          </div>
          <div style={{ fontFamily: 'Space Grotesk', fontSize: 30, fontWeight: 700, letterSpacing: '-0.025em', marginTop: 22 }}>{plan} ${window.fmtMoneyCompact(size)}</div>
          <div style={{ marginTop: 6, fontSize: 14, color: 'var(--text-dim)' }}>Account #{login} · {platform === 'mt5' ? 'MetaTrader 5' : platform === 'mt4' ? 'MetaTrader 4' : 'cTrader'} · ready in &lt;1 min</div>
        </div>

        <div style={{ padding: 28 }}>
          <h3 style={{ margin: '0 0 14px', fontFamily: 'Space Grotesk', fontSize: 14, color: 'var(--text-dim)', letterSpacing: '.06em', textTransform: 'uppercase', fontWeight: 600 }}>What's next</h3>
          {[
            { i: 'mail', l: 'Check your email', sub: 'MT5 credentials are sent to yulia@example.com' },
            { i: 'candles', l: 'Connect & trade', sub: 'Open ArenaTrader (web) or paste credentials into MT5 desktop' },
            { i: 'target', l: 'Hit your target', sub: 'Reach the phase target while respecting daily & max DD' },
          ].map((s, i) => {
            const Ic = I[s.i];
            return (
              <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '12px 0', borderTop: i > 0 ? '1px solid var(--line-2)' : 'none' }}>
                <div style={{ width: 36, height: 36, borderRadius: 10, background: 'rgba(255,255,255,0.04)', color: 'var(--text-dim)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Ic size={16}/></div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontWeight: 600, fontSize: 14 }}>{s.l}</div>
                  <div style={{ fontSize: 12, color: 'var(--text-dim)' }}>{s.sub}</div>
                </div>
              </div>
            );
          })}

          <div style={{ marginTop: 22, padding: 16, background: 'var(--surface-2)', border: '1px solid var(--line)', borderRadius: 12 }}>
            <ArenaKv label="Order" value={'PA-' + Math.random().toString(36).slice(2, 9).toUpperCase()} mono copy/>
            <ArenaKv label="Charged" value={'$' + total.toFixed(2)} mono/>
            <ArenaKv label="Account login" value={login} mono copy/>
            <ArenaKv label="Status" value="Active"/>
          </div>

          <div style={{ display: 'flex', gap: 8, marginTop: 22 }}>
            <button className="a-btn ghost" style={{ flex: 1, justifyContent: 'center' }} onClick={() => setPage('accounts')}>View accounts</button>
            <button className="a-btn primary" style={{ flex: 1, justifyContent: 'center' }} onClick={() => window.openArenaTrader && window.openArenaTrader()}>
              <I.candles size={13}/> Open ArenaTrader
            </button>
          </div>
        </div>
      </div>
    </>
  );
}

// ============ PAYOUTS ============
function ArenaPayouts() {
  return (
    <>
      <div className="a-pagehead">
        <div>
          <h1>My <em>payouts</em>.</h1>
          <div className="sub">$3,427.30 available · next cycle in 2 days</div>
        </div>
        <button className="a-btn primary"><I.upload size={13}/> Request payout</button>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 16, marginBottom: 22 }}>
        <div className="a-tile glow">
          <div className="l"><I.coins size={11}/> AVAILABLE</div>
          <div className="v">$3,427<small style={{ fontSize: 14, color: 'var(--text-dim)' }}>.30</small></div>
          <div className="d pos">80% split · #5098871</div>
        </div>
        <div className="a-tile cyan">
          <div className="l"><I.clock size={11}/> NEXT CYCLE</div>
          <div className="v">2 days</div>
          <div className="d" style={{ color: 'var(--text-dim)' }}>May 21 · 00:00 UTC</div>
        </div>
        <div className="a-tile">
          <div className="l"><I.trophy size={11}/> ALL-TIME PAID</div>
          <div className="v">$8,043<small style={{ fontSize: 14, color: 'var(--text-dim)' }}>.60</small></div>
          <div className="d" style={{ color: 'var(--text-dim)' }}>3 payouts · 0 declined</div>
        </div>
      </div>

      <div className="a-section" style={{ padding: 0 }}>
        <div style={{ padding: '18px 22px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', borderBottom: '1px solid var(--line)' }}>
          <h3 style={{ margin: 0, fontFamily: 'Space Grotesk', fontSize: 16 }}>Payout history</h3>
          <button className="a-btn ghost sm"><I.download size={11}/> CSV</button>
        </div>
        <table className="a-table">
          <thead>
            <tr><th>Date</th><th>Account</th><th>Size</th><th>Method</th><th className="r">Amount</th><th>Status</th><th></th></tr>
          </thead>
          <tbody>
            {window.SEED_PAYOUTS.map(p => (
              <tr key={p.id}>
                <td>{p.date}</td>
                <td className="mono">{p.account}</td>
                <td>${window.fmtMoneyCompact(p.size)}</td>
                <td>{p.method}</td>
                <td className="mono r pos" style={{ fontWeight: 600 }}>+${window.fmtMoney(p.amount)}</td>
                <td><span className="a-tag success">PAID</span></td>
                <td><button className="a-iconbtn"><I.download size={11}/></button></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </>
  );
}

// ============ BILLING ============
function ArenaBilling() {
  const [tab, setTab] = useState('orders');
  return (
    <>
      <div className="a-pagehead">
        <div>
          <h1>Billing & <em>orders</em>.</h1>
          <div className="sub">Manage payment methods, view orders and refunds</div>
        </div>
        <button className="a-btn primary"><I.plus size={13}/> Add payment method</button>
      </div>

      <div className="a-chips" style={{ marginBottom: 18 }}>
        {[
          { id: 'orders', l: 'Orders', c: window.SEED_ORDERS.length },
          { id: 'refunds', l: 'Refunds', c: window.SEED_REFUNDS.length },
          { id: 'methods', l: 'Payment methods', c: 2 },
        ].map(x => (
          <button key={x.id} className={tab===x.id?'active':''} onClick={()=>setTab(x.id)}>
            {x.l} <span className="c">{x.c}</span>
          </button>
        ))}
      </div>

      {tab === 'orders' && (
        <div className="a-section" style={{ padding: 0 }}>
          <table className="a-table">
            <thead><tr><th>Date</th><th>Order</th><th>Plan</th><th>Method</th><th className="r">Amount</th><th>Status</th><th></th></tr></thead>
            <tbody>
              {window.SEED_ORDERS.map(o => (
                <tr key={o.id}>
                  <td>{o.date}</td>
                  <td className="mono">{o.tx}</td>
                  <td>{o.plan}</td>
                  <td>{o.method}</td>
                  <td className="mono r" style={{ fontWeight: 600 }}>${o.amount.toFixed(2)}</td>
                  <td><span className="a-tag success">PAID</span></td>
                  <td><button className="a-iconbtn"><I.download size={11}/></button></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {tab === 'refunds' && (
        <div className="a-section" style={{ padding: 0 }}>
          <table className="a-table">
            <thead><tr><th>Requested</th><th>Reason</th><th>Account</th><th className="r">Amount</th><th>Status</th></tr></thead>
            <tbody>
              {window.SEED_REFUNDS.map(r => (
                <tr key={r.id}>
                  <td>{r.requestedOn}</td>
                  <td>{r.reason}</td>
                  <td className="mono">{r.account}</td>
                  <td className="mono r" style={{ fontWeight: 600 }}>${r.amount.toFixed(2)}</td>
                  <td><span className={'a-tag ' + (r.status==='refunded'?'success':'pending')}>{r.status.toUpperCase()}</span></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {tab === 'methods' && (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(320px, 1fr))', gap: 14 }}>
          {[
            { i: 'cards', t: 'Visa •••• 4242', s: 'Exp 09/27 · Default', def: true },
            { i: 'btc', t: 'USDT TRC-20', s: 'TYxh…a8K9', def: false },
          ].map((m, i) => (
            <div key={i} className="a-section" style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
              <div style={{ width: 44, height: 44, borderRadius: 12, background: 'rgba(255,255,255,0.05)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--text)' }}>{I[m.i]({ size: 22 })}</div>
              <div style={{ flex: 1 }}>
                <div style={{ fontWeight: 600 }}>{m.t}</div>
                <div style={{ fontSize: 12, color: 'var(--text-dim)' }}>{m.s}</div>
              </div>
              {m.def && <span className="a-tag muted">DEFAULT</span>}
              <button className="a-iconbtn"><I.dots size={13}/></button>
            </div>
          ))}
        </div>
      )}
    </>
  );
}

// ============ SETTINGS ============
function ArenaSettings() {
  return (
    <>
      <div className="a-pagehead">
        <div>
          <h1>Settings.</h1>
          <div className="sub">Profile & email preferences</div>
        </div>
        <button className="a-btn primary"><I.check size={13}/> Save changes</button>
      </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 }}>Profile</h3>
          <div style={{ display: 'flex', gap: 12, alignItems: 'center', marginBottom: 16, padding: '12px 0', borderBottom: '1px solid var(--line-2)' }}>
            <div style={{ width: 60, height: 60, borderRadius: 999, background: 'linear-gradient(135deg, var(--magenta), var(--cyan))', color: '#06070D', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 700, fontSize: 22 }}>YL</div>
            <div style={{ flex: 1 }}>
              <div style={{ fontWeight: 600 }}>Yulia Larssen</div>
              <div style={{ fontSize: 12, color: 'var(--text-dim)' }}>KYC verified · since April 2024</div>
            </div>
            <button className="a-btn secondary sm">Change photo</button>
          </div>
          {[
            { l: 'Full name', v: 'Yulia Larssen' },
            { l: 'Email', v: 'yulia@example.com' },
            { l: 'Phone', v: '+39 ••• ••• 4112' },
            { l: 'Country', v: 'Italy' },
            { l: 'Date of birth', v: '1991-03-14' },
          ].map((f, 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 }}>{f.l}</label>
              <input className="a-input" defaultValue={f.v}/>
            </div>
          ))}
        </div>

        <div className="a-section">
          <h3 style={{ margin: '0 0 14px', fontFamily: 'Space Grotesk', fontSize: 16 }}>Email preferences</h3>
          {[
            { l: 'Account updates', sub: 'Payouts approved, accounts funded, stage passed', on: true },
            { l: 'Rule alerts', sub: 'Strike warnings, drawdown nearing limits', on: true },
            { l: 'Weekly performance digest', sub: 'Every Monday at 09:00 UTC', on: true },
            { l: 'Marketing emails', sub: 'Promotions and season events', on: false },
          ].map((s, i) => (
            <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 0', borderBottom: i<3?'1px solid var(--line-2)':'none' }}>
              <div style={{ flex: 1 }}>
                <div style={{ fontWeight: 500, fontSize: 14 }}>{s.l}</div>
                <div style={{ fontSize: 12, color: 'var(--text-dim)' }}>{s.sub}</div>
              </div>
              <div style={{
                width: 40, height: 22, borderRadius: 999,
                background: s.on?'linear-gradient(90deg, var(--magenta), var(--cyan))':'var(--surface-3)',
                position: 'relative', cursor: 'pointer',
              }}>
                <div style={{
                  position: 'absolute',
                  top: 2, left: s.on?20:2,
                  width: 18, height: 18, borderRadius: 999,
                  background: '#fff',
                  transition: 'left .2s',
                }}/>
              </div>
            </div>
          ))}
        </div>
      </div>
    </>
  );
}

// ============ CREDENTIALS / SECURITY ============
function ArenaCredentials() {
  const { setPage, accounts, setAccountId } = useApp();
  const [filter, setFilter] = useState('all');
  const [compact, setCompact] = useState(false);
  const [reveal, setReveal] = useState({});
  const visible = filter === 'all' ? accounts
    : filter === 'funded' ? accounts.filter(a => a.status === 'funded')
    : filter === 'challenge' ? accounts.filter(a => a.status !== 'funded' && a.status !== 'failed')
    : accounts.filter(a => a.status === 'failed');

  function toggleReveal(id) { setReveal(r => ({ ...r, [id]: !r[id] })); }

  return (
    <>
      <div className="a-pagehead">
        <div>
          <h1>Trading <em>credentials</em>.</h1>
          <div className="sub">Logins for your accounts · password fields stay masked / API-pending</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 secondary" onClick={() => setCompact(c => !c)}><I.layers size={13}/> {compact ? 'Expand' : 'Compact'}</button>
        </div>
      </div>

      <div className="a-chips" style={{ marginBottom: 18 }}>
        {[
          { id: 'all',       l: 'All',       c: accounts.length },
          { id: 'challenge', l: 'Challenge', c: accounts.filter(a => a.status !== 'funded' && a.status !== 'failed').length },
          { id: 'funded',    l: 'Funded',    c: accounts.filter(a => a.status === 'funded').length },
          { id: 'failed',    l: 'Failed',    c: accounts.filter(a => a.status === 'failed').length },
        ].map(x => (
          <button key={x.id} className={filter === x.id ? 'active' : ''} onClick={() => setFilter(x.id)}>
            {x.l} <span className="c">{x.c}</span>
          </button>
        ))}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(360px, 1fr))', gap: 14, marginBottom: 18 }}>
        {visible.map(a => {
          const isFunded = a.status === 'funded';
          const tagClass = isFunded ? 'funded' : a.status === 'failed' ? 'failed' : 'eval';
          const tagLabel = isFunded ? 'FUNDED' : a.status === 'failed' ? 'FAILED' : window.planLabel(a).toUpperCase();
          const rev = reveal[a.id];
          return (
            <div key={a.id} className="a-section" style={{ padding: 16, display: 'flex', flexDirection: 'column', gap: 8 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <span className={'a-acct-tag ' + tagClass}>{tagLabel}</span>
                <div style={{ flex: 1 }}>
                  <div className="mono" style={{ fontSize: 14, fontWeight: 600 }}>{a.login}</div>
                  <div style={{ fontSize: 11, color: 'var(--text-dim)' }}>${window.fmtMoneyCompact(a.size)} · {a.plan} · {a.server}</div>
                </div>
                <button className="a-iconbtn" onClick={() => toggleReveal(a.id)} title={rev ? 'Hide details' : 'Reveal details'}>
                  {rev ? <I.eyeOff size={13}/> : <I.eye size={13}/>}
                </button>
              </div>
              {!compact && (
                <div style={{ marginTop: 4 }}>
              <ArenaKv label="Login" value={a.login} mono copy/>
              <ArenaKv label="Server" value={a.server} mono copy/>
              <ArenaKv label="Leverage" value="1:30"/>
                </div>
              )}
              <div style={{ display: 'flex', gap: 6, marginTop: 6 }}>
                <button className="a-btn secondary sm" style={{ flex: 1, justifyContent: 'center' }} onClick={() => { setAccountId(a.id); setPage('account'); }}>
                  <I.external size={11}/> Open account
                </button>
                <button className="a-btn secondary sm" style={{ flex: 1, justifyContent: 'center' }} onClick={() => { setAccountId(a.id); window.openArenaTrader && window.openArenaTrader(a.id); }}>
                  <I.candles size={11}/> ArenaTrader
                </button>
              </div>
            </div>
          );
        })}
      </div>

      <div className="a-section">
        <h3 style={{ margin: '0 0 12px', fontFamily: 'Space Grotesk', fontSize: 16 }}>Account passwords stay masked</h3>
        <div style={{ fontSize: 13, color: 'var(--text-dim)' }}>
          Master and investor passwords aren't copyable until the credentials endpoint is wired up. Once enabled, copy icons appear on the safe fields and reveal toggles unlock per-account.
        </div>
      </div>
    </>
  );
}

// ============ NOTIFICATIONS ============
function ArenaNotifications() {
  const notifs = [
    { i: 'rocket', t: 'Challenge passed · Phase 2', sub: 'Account #5098871 advanced to funded · +200 XP', tm: '2m ago', cat: 'unread' },
    { i: 'wallet', t: 'Payout request approved', sub: '$4,283.50 USDT TRC-20 · arriving in 24h', tm: '14m ago', cat: 'unread' },
    { i: 'trophy', t: 'New badge unlocked: Iron Hands', sub: '90% SL compliance over 30 days', tm: '1h ago', cat: 'unread' },
    { i: 'warn', t: 'Strike warning · Consistency rule', sub: '52% of profit on a single day · #5102771', tm: '3h ago', cat: 'read' },
    { i: 'star', t: 'Tier progress: 660 XP to Platinum', sub: 'Keep your hot streak going!', tm: '1d ago', cat: 'read' },
    { i: 'gift', t: 'Season 6 Grand Cup begins', sub: '14 days · $50K prize pool · you are ranked #247', tm: '2d ago', cat: 'read' },
  ];
  return (
    <>
      <div className="a-pagehead">
        <div>
          <h1>Notifications.</h1>
          <div className="sub">3 unread · 18 total this week</div>
        </div>
        <div style={{ display: 'flex', gap: 10 }}>
          <button className="a-btn secondary"><I.check size={13}/> Mark all read</button>
        </div>
      </div>

      <div className="a-section" style={{ padding: 0 }}>
        {notifs.map((n, i) => (
          <div key={i} style={{
            display: 'flex', alignItems: 'flex-start', gap: 14,
            padding: 16,
            borderBottom: i<notifs.length-1?'1px solid var(--line-2)':'none',
            background: n.cat==='unread'?'linear-gradient(90deg, rgba(255,92,245,0.04), transparent)':'transparent',
          }}>
            <div style={{
              width: 40, height: 40, borderRadius: 12,
              background: n.cat==='unread'?'linear-gradient(135deg, var(--magenta), var(--cyan))':'rgba(255,255,255,0.04)',
              color: n.cat==='unread'?'#06070D':'var(--text-dim)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              flex: 'none',
            }}>{I[n.i]({ size: 18 })}</div>
            <div style={{ flex: 1 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 2 }}>
                <span style={{ fontWeight: 600, fontSize: 14 }}>{n.t}</span>
                <span className="mono" style={{ fontSize: 11, color: 'var(--text-faint)' }}>{n.tm}</span>
              </div>
              <div style={{ fontSize: 13, color: 'var(--text-dim)' }}>{n.sub}</div>
            </div>
            {n.cat==='unread' && <div style={{ width: 8, height: 8, borderRadius: 999, background: 'var(--magenta)', boxShadow: '0 0 6px var(--magenta)' }}/>}
          </div>
        ))}
      </div>
    </>
  );
}

// ============ TRADER TIERS ============
function ArenaTiers() {
  const xp = window.CURRENT_XP;
  const { tier, next, progress } = window.xpToTier(xp);
  return (
    <>
      <div className="a-pagehead">
        <div>
          <h1>Trader <em>tiers</em>.</h1>
          <div className="sub">Gold tier · Lv 28 · 660 XP to Platinum</div>
        </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)', marginBottom: 18 }}>
        <div style={{ display: 'grid', gridTemplateColumns: '120px 1fr auto', gap: 22, alignItems: 'center' }}>
          <div style={{
            width: 100, height: 100, borderRadius: 24,
            background: 'linear-gradient(135deg, var(--gold), oklch(70% 0.18 60))',
            color: '#2A1A00',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontFamily: 'Space Grotesk', fontWeight: 800, fontSize: 48,
            boxShadow: '0 0 48px -6px var(--gold)',
            position: 'relative',
          }}>G
          </div>
          <div>
            <div style={{ fontFamily: 'Space Grotesk', fontWeight: 700, fontSize: 32, letterSpacing: '-0.025em' }}>{tier.name} Trader</div>
            <div style={{ fontSize: 14, color: 'var(--text-dim)', marginTop: 4 }}>{xp.toLocaleString()} XP · {next ? `${next.min - xp} to ${next.name}` : 'Max tier reached'}</div>
            <div style={{ height: 8, background: 'rgba(255,255,255,0.06)', borderRadius: 999, overflow: 'hidden', marginTop: 12 }}>
              <div style={{ width: (progress*100)+'%', height: '100%', background: 'linear-gradient(90deg, var(--magenta), var(--cyan))' }}/>
            </div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <div className="mono" style={{ fontSize: 48, fontWeight: 700, letterSpacing: '-0.03em' }}>Lv 28</div>
            <div style={{ fontSize: 11, color: 'var(--text-dim)', textTransform: 'uppercase', letterSpacing: '.1em' }}>Trader level</div>
          </div>
        </div>
      </div>

      <div className="a-section" style={{ padding: 0, marginBottom: 18 }}>
        <div style={{ padding: '18px 22px', borderBottom: '1px solid var(--line)' }}>
          <h3 style={{ margin: 0, fontFamily: 'Space Grotesk', fontSize: 16 }}>All tiers</h3>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)' }}>
          {window.TIERS.map((t, i) => (
            <div key={t.id} style={{
              padding: 18,
              borderRight: i<5?'1px solid var(--line-2)':'none',
              background: t.id===tier.id?'linear-gradient(180deg, rgba(255,92,245,0.10), transparent)':'transparent',
            }}>
              <div style={{
                width: 36, height: 36, borderRadius: 10,
                background: t.color,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                color: '#06070D',
                fontFamily: 'Space Grotesk', fontWeight: 800,
                marginBottom: 10,
              }}>{t.name[0]}</div>
              <div style={{ fontWeight: 700, fontSize: 14 }}>{t.name}</div>
              <div className="mono" style={{ fontSize: 11, color: 'var(--text-faint)', marginTop: 2 }}>{t.min.toLocaleString()}+ XP</div>
              {t.id===tier.id && <div style={{ marginTop: 8 }}><span className="a-tag" style={{ background: 'var(--magenta)', color: '#fff' }}>YOU'RE HERE</span></div>}
            </div>
          ))}
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 18 }}>
        <div className="a-section">
          <h3 style={{ margin: '0 0 14px', fontFamily: 'Space Grotesk', fontSize: 16 }}>XP history</h3>
          <table className="a-table">
            <thead><tr><th>Date</th><th>Activity</th><th className="r">XP</th></tr></thead>
            <tbody>
              {window.XP_EVENTS.map((e, i) => (
                <tr key={i}>
                  <td className="mono">{e.date}</td>
                  <td>{e.desc}</td>
                  <td className="mono r pos" style={{ fontWeight: 600 }}>+{e.delta}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        <div className="a-section">
          <h3 style={{ margin: '0 0 14px', fontFamily: 'Space Grotesk', fontSize: 16 }}>Platinum unlocks</h3>
          {[
            { l: '90% profit split', sub: 'Up from 80%', got: false },
            { l: 'Free retry per challenge', sub: 'One per quarter', got: false },
            { l: 'Priority support', sub: '< 2h response time', got: false },
            { l: 'Platinum Discord channel', sub: 'Direct access to top traders', got: false },
            { l: 'Custom MT5 server', sub: '0.05ms latency', got: false },
          ].map((u, i) => (
            <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 0', borderBottom: i<4?'1px solid var(--line-2)':'none' }}>
              <I.lock size={16} style={{ color: 'var(--text-faint)' }}/>
              <div style={{ flex: 1 }}>
                <div style={{ fontWeight: 500, fontSize: 14 }}>{u.l}</div>
                <div style={{ fontSize: 11, color: 'var(--text-dim)' }}>{u.sub}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </>
  );
}

function JournalMonthlyPnl() {
  // Month picker
  const months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
  const [m, setM] = useState(4); // 0-indexed; May
  const year = 2026;
  const daysInMonth = new Date(year, m + 1, 0).getDate();

  // Deterministic-ish synthetic daily P&L per month index so navigation feels real.
  const days = useMemo(() => {
    const out = [];
    let seed = (m + 1) * 17;
    for (let d = 1; d <= daysInMonth; d++) {
      const date = new Date(year, m, d);
      const dow = date.getDay(); // 0 Sun .. 6 Sat
      seed = (seed * 9301 + 49297) % 233280;
      const r = seed / 233280;
      let pnl = 0;
      if (dow === 0 || dow === 6) {
        pnl = 0; // no weekend trading
      } else if (r < 0.18) {
        pnl = 0; // no-trade day
      } else if (r < 0.36) {
        pnl = -Math.round((r * 1800 + 60));
      } else {
        pnl = Math.round((r * 1400 + 80) * (r > 0.85 ? 2.4 : 1));
      }
      out.push({ d, dow, pnl });
    }
    return out;
  }, [m]);

  const maxAbs = Math.max(...days.map(x => Math.abs(x.pnl)), 1);
  const total = days.reduce((s, x) => s + x.pnl, 0);
  const tradedDays = days.filter(x => x.pnl !== 0).length;
  const winDays = days.filter(x => x.pnl > 0).length;
  const lossDays = days.filter(x => x.pnl < 0).length;

  const W = 1000;
  const H = 260;
  const padX = 24;
  const padY = 30;
  const innerW = W - padX * 2;
  const innerH = H - padY * 2;
  const midY = padY + innerH / 2;
  const halfH = innerH / 2;
  const colW = innerW / daysInMonth;
  const barW = Math.max(6, colW - 4);

  // Y-axis ticks
  const tickVals = [maxAbs, maxAbs / 2, 0, -maxAbs / 2, -maxAbs];

  return (
    <div className="a-section">
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 14, gap: 12, flexWrap: 'wrap' }}>
        <div>
          <h3 style={{ margin: 0, fontFamily: 'Space Grotesk', fontSize: 16 }}>P&amp;L · {months[m]} {year}</h3>
          <div style={{ marginTop: 6, fontSize: 12, color: 'var(--text-dim)' }}>
            <b className="mono" style={{ color: total >= 0 ? 'var(--positive)' : 'var(--negative)', marginRight: 8 }}>{total >= 0 ? '+' : '−'}${window.fmtMoney(Math.abs(total))}</b>
            <span>{tradedDays} traded · </span>
            <span className="pos">{winDays} green</span>
            <span> · </span>
            <span className="neg">{lossDays} red</span>
            <span> · {daysInMonth - tradedDays} flat</span>
          </div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
          <button className="a-iconbtn" onClick={() => setM(x => (x + 11) % 12)} title="Previous month"><I.chevronLeft size={13}/></button>
          <select
            value={m}
            onChange={e => setM(+e.target.value)}
            className="a-input"
            style={{ height: 36, fontSize: 13, fontWeight: 600, paddingRight: 32, minWidth: 180 }}
          >
            {months.map((mn, i) => <option key={mn} value={i}>{mn} {year}</option>)}
          </select>
          <button className="a-iconbtn" onClick={() => setM(x => (x + 1) % 12)} title="Next month"><I.chevronRight size={13}/></button>
        </div>
      </div>

      <div style={{ width: '100%', overflowX: 'auto' }}>
        <svg viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none" style={{ width: '100%', minWidth: 720, height: H, display: 'block' }}>
          <defs>
            <linearGradient id="jpnl-pos" x1="0" x2="0" y1="0" y2="1">
              <stop offset="0%" stopColor="oklch(78% 0.22 145)" stopOpacity="1"/>
              <stop offset="100%" stopColor="oklch(78% 0.22 145)" stopOpacity="0.5"/>
            </linearGradient>
            <linearGradient id="jpnl-neg" x1="0" x2="0" y1="0" y2="1">
              <stop offset="0%" stopColor="oklch(70% 0.24 25)" stopOpacity="0.5"/>
              <stop offset="100%" stopColor="oklch(70% 0.24 25)" stopOpacity="1"/>
            </linearGradient>
          </defs>

          {/* y-axis grid + labels */}
          {tickVals.map((v, i) => {
            const y = midY - (v / maxAbs) * halfH;
            return (
              <g key={i}>
                <line x1={padX} x2={W - padX} y1={y} y2={y} stroke="rgba(255,255,255,0.05)" strokeWidth={1}/>
                <text x={padX - 6} y={y + 3} textAnchor="end" fontSize="9" fill="var(--text-faint)" fontFamily="JetBrains Mono">{v === 0 ? '0' : (v > 0 ? '+' : '−') + '$' + Math.abs(Math.round(v))}</text>
              </g>
            );
          })}
          {/* zero line emphasized */}
          <line x1={padX} x2={W - padX} y1={midY} y2={midY} stroke="rgba(255,255,255,0.18)" strokeWidth={1}/>

          {/* candle-style bars */}
          {days.map((d, i) => {
            const x = padX + i * colW + (colW - barW) / 2;
            const isFlat = d.pnl === 0;
            const isWeekend = d.dow === 0 || d.dow === 6;
            if (isFlat) {
              // No-trade day — small flat tick on zero line
              return (
                <g key={i}>
                  <line
                    x1={x} x2={x + barW}
                    y1={midY} y2={midY}
                    stroke={isWeekend ? 'rgba(255,255,255,0.10)' : 'rgba(255,255,255,0.22)'}
                    strokeWidth={2}
                    strokeLinecap="round"
                  />
                  <text x={x + barW / 2} y={H - 8} textAnchor="middle" fontSize="9" fill="var(--text-faint)" fontFamily="JetBrains Mono">{d.d}</text>
                </g>
              );
            }
            const bh = (Math.abs(d.pnl) / maxAbs) * halfH;
            const isPos = d.pnl > 0;
            const y = isPos ? midY - bh : midY;
            // wick (high/low representation for a candle feel) — extends 30% beyond body
            const wickExt = bh * 0.25;
            const wickTop = isPos ? y - wickExt : midY;
            const wickBot = isPos ? midY : y + bh + wickExt;
            const wickX = x + barW / 2;
            return (
              <g key={i}>
                <line x1={wickX} x2={wickX} y1={wickTop} y2={wickBot} stroke={isPos ? 'oklch(78% 0.22 145)' : 'oklch(70% 0.24 25)'} strokeWidth={1} opacity={0.6}/>
                <rect
                  x={x} y={y} width={barW} height={bh}
                  rx={2} ry={2}
                  fill={isPos ? 'url(#jpnl-pos)' : 'url(#jpnl-neg)'}
                  stroke={isPos ? 'oklch(78% 0.22 145)' : 'oklch(70% 0.24 25)'}
                  strokeWidth={1}
                />
                <title>{months[m]} {d.d} · {isPos ? '+' : '−'}${Math.abs(d.pnl).toLocaleString()}</title>
                <text x={x + barW / 2} y={H - 8} textAnchor="middle" fontSize="9" fill="var(--text-faint)" fontFamily="JetBrains Mono">{d.d}</text>
              </g>
            );
          })}
        </svg>
      </div>

      <div style={{ display: 'flex', gap: 18, marginTop: 12, fontSize: 11, color: 'var(--text-dim)', flexWrap: 'wrap' }}>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
          <span style={{ width: 10, height: 10, background: 'oklch(78% 0.22 145)', borderRadius: 2 }}/> Green day
        </span>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
          <span style={{ width: 10, height: 10, background: 'oklch(70% 0.24 25)', borderRadius: 2 }}/> Red day
        </span>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
          <span style={{ width: 10, height: 2, background: 'rgba(255,255,255,0.22)', borderRadius: 999 }}/> Flat (no trades)
        </span>
        <span style={{ marginLeft: 'auto' }}>Hover a bar for the day's P&amp;L</span>
      </div>
    </div>
  );
}

// ============ JOURNAL ============
function ArenaJournal() {
  const [tab, setTab] = useState('overview');
  const [drawer, setDrawer] = useState(false);
  const [filters, setFilters] = useState({ side: 'all', outcome: 'all', symbols: [], duration: 'all', session: 'all', tags: [] });

  const trades = [
    { d: 'May 19 14:01', a: '5098871', s: 'EURUSD', side: 'BUY', vol: 1.50, e: 1.08412, x: 1.08540, pip: 12.8, rr: 2.1, pl: 192.00 },
    { d: 'May 19 13:42', a: '5098871', s: 'XAUUSD', side: 'SELL', vol: 0.30, e: 2342.10, x: 2335.40, pip: 67.0, rr: 1.8, pl: 201.00 },
    { d: 'May 19 12:22', a: '5102994', s: 'NAS100', side: 'BUY', vol: 0.80, e: 18420, x: 18395, pip: -25.0, rr: -1.0, pl: -200.00 },
    { d: 'May 19 11:08', a: '5101225', s: 'GBPJPY', side: 'BUY', vol: 0.60, e: 192.45, x: 192.92, pip: 47.0, rr: 2.5, pl: 188.40 },
    { d: 'May 19 10:32', a: '5095110', s: 'BTCUSD', side: 'SELL', vol: 0.10, e: 67420, x: 67200, pip: 22.0, rr: 1.4, pl: 22.00 },
    { d: 'May 19 09:18', a: '5098871', s: 'EURJPY', side: 'BUY', vol: 1.00, e: 169.42, x: 169.81, pip: 39.0, rr: 1.9, pl: 248.20 },
    { d: 'May 19 09:02', a: '5102994', s: 'WTI',    side: 'BUY', vol: 0.50, e: 77.92,  x: 78.42,  pip: 50.0, rr: 2.2, pl: 250.00 },
    { d: 'May 18 16:44', a: '5098871', s: 'XAUUSD', side: 'BUY', vol: 0.40, e: 2330.00,x: 2342.00,pip: 120.0, rr: 3.0, pl: 480.00 },
    { d: 'May 18 14:11', a: '5101225', s: 'USDJPY', side: 'SELL',vol: 0.80, e: 156.85, x: 156.42, pip: 43.0, rr: 2.0, pl: 215.00 },
    { d: 'May 18 11:35', a: '5102994', s: 'GBPUSD', side: 'BUY', vol: 1.20, e: 1.27050,x: 1.27120,pip: 7.0,  rr: 0.9, pl: 84.00 },
  ];
  const filtered = trades.filter(t => {
    if (filters.side !== 'all' && t.side.toLowerCase() !== filters.side) return false;
    if (filters.outcome === 'win' && t.pl < 0) return false;
    if (filters.outcome === 'loss' && t.pl >= 0) return false;
    if (filters.symbols.length && !filters.symbols.includes(t.s)) return false;
    return true;
  });
  const activeCount = (filters.side !== 'all' ? 1 : 0) + (filters.outcome !== 'all' ? 1 : 0) + filters.symbols.length + (filters.duration !== 'all' ? 1 : 0) + (filters.session !== 'all' ? 1 : 0) + filters.tags.length;

  return (
    <>
      <div className="a-pagehead">
        <div>
          <h1>Trade <em>journal</em>.</h1>
          <div className="sub">Last 30 days · 187 trades · 68.4% win rate</div>
        </div>
        <button className="a-btn secondary" onClick={() => setDrawer(true)}>
          <I.filter size={13}/> Filters
          {activeCount > 0 && <span style={{ background: 'var(--magenta)', color: '#fff', borderRadius: 999, padding: '0 6px', fontSize: 10, fontWeight: 700, marginLeft: 6 }}>{activeCount}</span>}
        </button>
      </div>

      <div className="a-chips" style={{ marginBottom: 18 }}>
        {[
          { id: 'overview', l: 'Overview' },
          { id: 'log',      l: 'Trade Log' },
          { id: 'reports',  l: 'Reports' },
        ].map(x => <button key={x.id} className={tab === x.id ? 'active' : ''} onClick={() => setTab(x.id)}>{x.l}</button>)}
      </div>

      {tab === 'overview' && (
        <>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 22 }}>
            <div className="a-tile"><div className="l">WIN RATE</div><div className="v">68.4%</div><div className="d pos">▲ 4.1pp</div></div>
            <div className="a-tile"><div className="l">PROFIT FACTOR</div><div className="v">2.31×</div><div className="d pos">▲ 0.18</div></div>
            <div className="a-tile"><div className="l">AVG R:R</div><div className="v">1.83</div><div className="d" style={{ color: 'var(--text-dim)' }}>Target 1.5+</div></div>
            <div className="a-tile"><div className="l">EXPECTANCY</div><div className="v">+$87</div><div className="d pos">per trade</div></div>
          </div>
          <JournalMonthlyPnl/>
          <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 18, marginTop: 18 }}>
            <JournalByInstrument/>
            <JournalAdvancedAnalytics/>
          </div>
          <JournalTransactionHistory/>
        </>
      )}

      {tab === 'log' && (
        <div className="a-section" style={{ padding: 0 }}>
          <table className="a-table">
            <thead><tr><th>Date</th><th>Account</th><th>Symbol</th><th>Side</th><th className="r">Vol</th><th className="r">Entry</th><th className="r">Exit</th><th className="r">Pips</th><th className="r">R:R</th><th className="r">P/L</th></tr></thead>
            <tbody>
              {filtered.map((t, i) => (
                <tr key={i}>
                  <td className="mono" style={{ color: 'var(--text-dim)', fontSize: 11 }}>{t.d}</td>
                  <td className="mono">{t.a}</td>
                  <td style={{ fontWeight: 600 }}>{t.s}</td>
                  <td><span className="a-tag" style={{ background: t.side==='BUY'?'color-mix(in oklab, var(--positive) 14%, transparent)':'color-mix(in oklab, var(--negative) 14%, transparent)', color: t.side==='BUY'?'var(--positive)':'var(--negative)' }}>{t.side}</span></td>
                  <td className="mono r">{t.vol.toFixed(2)}</td>
                  <td className="mono r" style={{ color: 'var(--text-dim)' }}>{t.e.toLocaleString()}</td>
                  <td className="mono r" style={{ color: 'var(--text-dim)' }}>{t.x.toLocaleString()}</td>
                  <td className={'mono r ' + (t.pip>=0?'pos':'neg')}>{t.pip>=0?'+':''}{t.pip.toFixed(1)}</td>
                  <td className={'mono r ' + (t.rr>=1.5?'pos':'')} style={{ color: t.rr<0?'var(--negative)':t.rr>=1.5?'var(--positive)':'var(--text-dim)' }}>{t.rr.toFixed(1)}R</td>
                  <td className={'mono r ' + (t.pl>=0?'pos':'neg')} style={{ fontWeight: 600 }}>{t.pl>=0?'+':''}${Math.abs(t.pl).toFixed(2)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {tab === 'reports' && (
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18 }}>
          <div className="a-section">
            <h3 style={{ margin: '0 0 12px', fontFamily: 'Space Grotesk', fontSize: 16 }}>By symbol</h3>
            {[['EURUSD',42,'68%','+$1,240'],['XAUUSD',31,'72%','+$2,180'],['NAS100',24,'58%','+$680'],['GBPJPY',18,'66%','+$540'],['BTCUSD',12,'50%','+$120']].map(([s,n,w,p],i)=>(
              <div key={s} style={{ display: 'grid', gridTemplateColumns: '1.5fr 60px 60px 1fr', alignItems: 'center', padding: '10px 0', borderTop: i>0?'1px solid var(--line-2)':'none', fontSize: 13 }}>
                <span style={{ fontWeight: 600 }}>{s}</span>
                <span className="mono" style={{ color: 'var(--text-dim)' }}>{n}</span>
                <span className="mono">{w}</span>
                <span className="mono pos" style={{ textAlign: 'right', fontWeight: 600 }}>{p}</span>
              </div>
            ))}
          </div>
          <div className="a-section">
            <h3 style={{ margin: '0 0 12px', fontFamily: 'Space Grotesk', fontSize: 16 }}>By session</h3>
            {[['London',54,'70%','+$2,380'],['New York',62,'68%','+$1,920'],['Asia',31,'58%','+$560'],['Overlap',40,'72%','+$1,140']].map(([s,n,w,p],i)=>(
              <div key={s} style={{ display: 'grid', gridTemplateColumns: '1.5fr 60px 60px 1fr', alignItems: 'center', padding: '10px 0', borderTop: i>0?'1px solid var(--line-2)':'none', fontSize: 13 }}>
                <span style={{ fontWeight: 600 }}>{s}</span>
                <span className="mono" style={{ color: 'var(--text-dim)' }}>{n}</span>
                <span className="mono">{w}</span>
                <span className="mono pos" style={{ textAlign: 'right', fontWeight: 600 }}>{p}</span>
              </div>
            ))}
          </div>
        </div>
      )}

      {drawer && <JournalFiltersDrawer onClose={() => setDrawer(false)} applied={filters} setApplied={setFilters}/>}
    </>
  );
}

function JournalByInstrument() {
  const data = [
    { s: 'BTCUSD.', v: -602.83 },
    { s: 'EURUSD.', v: -181.92 },
    { s: 'BTCEUR.', v: -34.52 },
    { s: 'CHFJPY.', v: 0.68 },
  ];
  const maxAbs = Math.max(...data.map(d => Math.abs(d.v)), 1);
  return (
    <div className="a-section">
      <h3 style={{ margin: '0 0 18px', fontFamily: 'Space Grotesk', fontSize: 18, fontWeight: 700, letterSpacing: '-0.02em' }}>By instrument</h3>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
        {data.map((d, i) => {
          const pct = Math.min(100, Math.abs(d.v) / maxAbs * 100);
          const isPos = d.v >= 0;
          return (
            <div key={i} style={{ display: 'grid', gridTemplateColumns: '90px 1fr 90px', alignItems: 'center', gap: 14 }}>
              <span style={{ fontFamily: 'Space Grotesk', fontWeight: 700, fontSize: 14, letterSpacing: '-0.01em' }}>{d.s}</span>
              <div style={{ height: 6, background: 'rgba(255,255,255,0.06)', borderRadius: 999, overflow: 'hidden', position: 'relative' }}>
                <div style={{
                  height: '100%', width: pct + '%',
                  background: isPos ? 'oklch(78% 0.22 145)' : 'oklch(70% 0.24 25)',
                  borderRadius: 999,
                }}/>
              </div>
              <span className={'mono ' + (isPos ? 'pos' : 'neg')} style={{ textAlign: 'right', fontWeight: 700, fontSize: 14 }}>
                {isPos ? '+' : '−'}€{Math.abs(d.v).toFixed(2)}
              </span>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function JournalAdvancedAnalytics() {
  return (
    <div className="a-section">
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '4px 0' }}>
        <span style={{ fontSize: 14, color: 'var(--text-dim)' }}>Best trade</span>
        <span className="mono pos" style={{ fontWeight: 700, fontSize: 14 }}>+€340.18</span>
      </div>
      <div style={{ height: 1, background: 'var(--line-2)', margin: '10px 0' }}/>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '4px 0' }}>
        <span style={{ fontSize: 14, color: 'var(--text-dim)' }}>Worst trade</span>
        <span className="mono neg" style={{ fontWeight: 700, fontSize: 14 }}>−€181.92</span>
      </div>
      <div style={{ height: 1, background: 'var(--line-2)', margin: '10px 0' }}/>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '4px 0' }}>
        <span style={{ fontSize: 14, color: 'var(--text-dim)' }}>Total commission</span>
        <span className="mono" style={{ fontWeight: 700, fontSize: 14, color: 'var(--text-faint)' }}>—</span>
      </div>
      <div style={{ height: 1, background: 'var(--line-2)', margin: '10px 0' }}/>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '4px 0' }}>
        <span style={{ fontSize: 14, color: 'var(--text-dim)' }}>Symbols traded</span>
        <span className="mono" style={{ fontWeight: 700, fontSize: 14 }}>4</span>
      </div>
      <div style={{
        marginTop: 18,
        padding: 16,
        border: '1px dashed var(--line-3)',
        borderRadius: 14,
        background: 'rgba(255,255,255,0.02)',
      }}>
        <div style={{ fontFamily: 'Space Grotesk', fontWeight: 700, fontSize: 16, letterSpacing: '-0.01em' }}>Advanced Analytics</div>
        <div style={{ fontSize: 12, color: 'var(--text-dim)', marginTop: 6, lineHeight: 1.55 }}>
          Detailed P/L curves, drawdown tracking, stage/objective filters, and CSV export will appear after the Prop API lands.
        </div>
      </div>
    </div>
  );
}

function JournalTransactionHistory() {
  const txs = [
    { type: 'Withdrawal',       acct: '#1983', ref: '1122', date: 'May 19, 2026 at 05:27 PM', status: 'success', amount: 255.00 },
    { type: 'Refund',           acct: '#1986', ref: '1121', date: 'May 19, 2026 at 03:23 PM', status: 'pending', amount: 100.00 },
    { type: 'Challenge Account',acct: '#1986', ref: '1119', date: 'May 19, 2026 at 03:16 PM', status: 'success', amount: 100.00 },
    { type: 'Wallet Payment',   acct: '#1983', ref: '1118', date: 'May 19, 2026 at 03:16 PM', status: 'success', amount: 100.00 },
    { type: 'Challenge Account',acct: '#1982', ref: '1117', date: 'May 19, 2026 at 11:10 AM', status: 'success', amount: 100.00 },
    { type: 'Wallet Payment',   acct: '#1983', ref: '1116', date: 'May 19, 2026 at 11:10 AM', status: 'success', amount: 100.00 },
    { type: 'Deposit',          acct: '#1983', ref: '1115', date: 'May 19, 2026 at 11:09 AM', status: 'success', amount: 14500.00 },
    { type: 'Deposit',          acct: '#1984', ref: '1114', date: 'May 19, 2026 at 11:08 AM', status: 'timeout', amount: 2000.00 },
    { type: 'Deposit',          acct: '#1982', ref: '1113', date: 'May 19, 2026 at 11:01 AM', status: 'timeout', amount: 100.00 },
    { type: 'Order',            acct: '#1983', ref: '1112', date: 'May 19, 2026 at 09:45 AM', status: 'success', amount: 299.00 },
  ];
  const statusMap = {
    success: { l: 'Success', bg: 'color-mix(in oklab, var(--positive) 14%, transparent)', fg: 'var(--positive)', border: 'color-mix(in oklab, var(--positive) 40%, transparent)' },
    pending: { l: 'Pending', bg: 'color-mix(in oklab, oklch(70% 0.18 295) 14%, transparent)', fg: 'oklch(78% 0.18 295)', border: 'color-mix(in oklab, oklch(70% 0.18 295) 40%, transparent)' },
    timeout: { l: 'Timeout', bg: 'color-mix(in oklab, var(--negative) 14%, transparent)', fg: 'var(--negative)', border: 'color-mix(in oklab, var(--negative) 40%, transparent)' },
  };
  return (
    <div className="a-section" style={{ marginTop: 18, padding: 0 }}>
      <div style={{ padding: '20px 24px 14px', display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12 }}>
        <div>
          <h3 style={{ margin: 0, fontFamily: 'Space Grotesk', fontSize: 18, fontWeight: 700, letterSpacing: '-0.02em' }}>Transaction history</h3>
          <div style={{ fontSize: 12, color: 'var(--text-dim)', marginTop: 4 }}>{txs.length} deposits, withdrawals, transfers, refunds, and orders</div>
        </div>
        <span style={{
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          minWidth: 30, height: 24,
          padding: '0 8px',
          borderRadius: 8,
          background: 'var(--surface-2)',
          border: '1px solid var(--line)',
          color: 'var(--text-dim)',
          fontFamily: 'JetBrains Mono', fontSize: 12, fontWeight: 600,
        }}>{txs.length}</span>
      </div>
      <table className="a-table">
        <thead>
          <tr>
            <th>Type</th>
            <th>Account</th>
            <th>Reference</th>
            <th>Date</th>
            <th>Status</th>
            <th className="r">Amount</th>
          </tr>
        </thead>
        <tbody>
          {txs.map((t, i) => {
            const s = statusMap[t.status] || statusMap.success;
            return (
              <tr key={i}>
                <td style={{ fontWeight: 500 }}>{t.type}</td>
                <td className="mono" style={{ color: 'var(--text-dim)' }}>{t.acct}</td>
                <td className="mono" style={{ color: 'var(--text-dim)' }}>{t.ref}</td>
                <td className="mono" style={{ color: 'var(--text-dim)', fontSize: 12 }}>{t.date}</td>
                <td>
                  <span style={{
                    display: 'inline-flex', alignItems: 'center',
                    padding: '3px 10px', borderRadius: 6,
                    background: s.bg, color: s.fg,
                    fontSize: 11, fontWeight: 600,
                    border: '1px solid ' + s.border,
                  }}>{s.l}</span>
                </td>
                <td className="mono r" style={{ fontWeight: 700, fontSize: 13 }}>+${window.fmtMoney(t.amount)}</td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}

function JournalFiltersDrawer({ onClose, applied, setApplied }) {
  const [local, setLocal] = useState(applied);
  function toggle(key, val) {
    const arr = local[key];
    setLocal({ ...local, [key]: arr.includes(val) ? arr.filter(x => x !== val) : [...arr, val] });
  }
  function reset() { setLocal({ side: 'all', outcome: 'all', symbols: [], duration: 'all', session: 'all', tags: [] }); }
  return (
    <>
      <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.55)', backdropFilter: 'blur(4px)', zIndex: 150 }}/>
      <div style={{
        position: 'fixed', top: 0, right: 0, bottom: 0,
        width: 420, maxWidth: '92vw', zIndex: 160,
        background: 'var(--surface)',
        borderLeft: '1px solid var(--line)',
        display: 'flex', flexDirection: 'column',
        boxShadow: '-30px 0 80px rgba(0,0,0,0.4)',
      }}>
        <div style={{ padding: '20px 24px', borderBottom: '1px solid var(--line)', display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
          <div>
            <div style={{ fontSize: 17, fontWeight: 700, fontFamily: 'Space Grotesk', letterSpacing: '-0.02em' }}>Journal filters</div>
            <div style={{ fontSize: 12, color: 'var(--text-dim)', marginTop: 2 }}>Refine the trade log & analytics</div>
          </div>
          <button className="a-iconbtn" onClick={onClose}><I.x size={13}/></button>
        </div>

        <div style={{ flex: 1, overflowY: 'auto', padding: '20px 24px' }}>
          <div style={{ marginBottom: 22 }}>
            <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--text-dim)', letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 10 }}>Side</div>
            <div className="a-chips" style={{ width: '100%' }}>
              {[{id:'all',l:'Any'},{id:'buy',l:'Long'},{id:'sell',l:'Short'}].map(o =>
                <button key={o.id} className={local.side===o.id?'active':''} onClick={() => setLocal({...local, side: o.id})} style={{ flex: 1, justifyContent: 'center' }}>{o.l}</button>
              )}
            </div>
          </div>
          <div style={{ marginBottom: 22 }}>
            <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--text-dim)', letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 10 }}>Outcome</div>
            <div className="a-chips" style={{ width: '100%' }}>
              {[{id:'all',l:'All'},{id:'win',l:'Wins'},{id:'loss',l:'Losses'},{id:'be',l:'Break-even'}].map(o =>
                <button key={o.id} className={local.outcome===o.id?'active':''} onClick={() => setLocal({...local, outcome: o.id})} style={{ flex: 1, justifyContent: 'center' }}>{o.l}</button>
              )}
            </div>
          </div>
          <div style={{ marginBottom: 22 }}>
            <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--text-dim)', letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 10 }}>Symbol</div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
              {['EURUSD','XAUUSD','NAS100','GBPJPY','BTCUSD','WTI','USDJPY','GBPUSD','EURJPY'].map(s => (
                <button key={s} onClick={() => toggle('symbols', s)} style={{
                  padding: '8px 12px', borderRadius: 10,
                  border: '1.5px solid ' + (local.symbols.includes(s) ? 'var(--magenta)' : 'var(--line)'),
                  background: local.symbols.includes(s) ? 'rgba(255,92,245,0.10)' : 'var(--surface-2)',
                  color: 'var(--text)', fontFamily: 'JetBrains Mono', fontSize: 12, fontWeight: 600, cursor: 'pointer',
                }}>{s}</button>
              ))}
            </div>
          </div>
          <div style={{ marginBottom: 22 }}>
            <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--text-dim)', letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 10 }}>Duration</div>
            <div className="a-chips" style={{ width: '100%' }}>
              {[{id:'all',l:'Any'},{id:'scalp',l:'< 5m'},{id:'intra',l:'< 4h'},{id:'swing',l:'> 4h'}].map(o =>
                <button key={o.id} className={local.duration===o.id?'active':''} onClick={() => setLocal({...local, duration: o.id})} style={{ flex: 1, justifyContent: 'center' }}>{o.l}</button>
              )}
            </div>
          </div>
          <div style={{ marginBottom: 22 }}>
            <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--text-dim)', letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 10 }}>Session</div>
            <div className="a-chips" style={{ width: '100%' }}>
              {[{id:'all',l:'All'},{id:'asia',l:'Asia'},{id:'eu',l:'London'},{id:'us',l:'NY'}].map(o =>
                <button key={o.id} className={local.session===o.id?'active':''} onClick={() => setLocal({...local, session: o.id})} style={{ flex: 1, justifyContent: 'center' }}>{o.l}</button>
              )}
            </div>
          </div>
          <div style={{ marginBottom: 22 }}>
            <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--text-dim)', letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 10 }}>Tags</div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
              {['News','Breakout','Reversal','Trend','Range','High-conviction','Mistake'].map(t => (
                <button key={t} onClick={() => toggle('tags', t)} style={{
                  padding: '8px 12px', borderRadius: 10,
                  border: '1.5px solid ' + (local.tags.includes(t) ? 'var(--magenta)' : 'var(--line)'),
                  background: local.tags.includes(t) ? 'rgba(255,92,245,0.10)' : 'var(--surface-2)',
                  color: 'var(--text)', fontSize: 12, fontWeight: 500, cursor: 'pointer',
                }}>{t}</button>
              ))}
            </div>
          </div>
        </div>

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

// ============ CALENDAR ============
function ArenaCalendar() {
  const events = [
    { time: '14:30', country: 'US', title: 'US Retail Sales (MoM)', impact: 'high', f: '0.4%', a: '0.6%', p: '0.7%' },
    { time: '14:30', country: 'US', title: 'Core Retail Sales (MoM)', impact: 'high', f: '0.3%', a: '0.4%', p: '0.5%' },
    { time: '15:00', country: 'US', title: 'Crude Oil Inventories', impact: 'med', f: '-1.4M', a: '0.8M', p: '-3.1M' },
    { time: '16:00', country: 'EU', title: 'ECB Economic Bulletin', impact: 'low', f: '—', a: '—', p: '—' },
    { time: '17:00', country: 'EU', title: 'ECB President Lagarde Speaks', impact: 'high', f: '—', a: '—', p: '—' },
    { time: '18:00', country: 'US', title: 'FOMC Member Bostic Speaks', impact: 'med', f: '—', a: '—', p: '—' },
    { time: '21:00', country: 'CA', title: 'BoC Senior Loan Officer Survey', impact: 'low', f: '—', a: '—', p: '—' },
    { time: '23:50', country: 'JP', title: 'GDP Capital Expenditure', impact: 'high', f: '0.8%', a: '—', p: '2.0%' },
  ];
  return (
    <>
      <div className="a-pagehead">
        <div>
          <h1>Economic <em>calendar</em>.</h1>
          <div className="sub">Tuesday May 19, 2026 · 8 events · 4 high-impact</div>
        </div>
        <div style={{ display: 'flex', gap: 10 }}>
          <div className="a-chips">
            <button className="active">Today</button>
            <button>Tomorrow</button>
            <button>This week</button>
          </div>
        </div>
      </div>

      <div className="a-section" style={{ padding: 0 }}>
        <table className="a-table">
          <thead><tr><th>Time</th><th>Region</th><th style={{ width: 60 }}>Impact</th><th>Event</th><th className="r">Forecast</th><th className="r">Actual</th><th className="r">Previous</th></tr></thead>
          <tbody>
            {events.map((e, i) => (
              <tr key={i}>
                <td className="mono">{e.time}</td>
                <td><CountryDot c={e.country}/></td>
                <td>
                  <div style={{ display: 'flex', gap: 3 }}>
                    <div style={{ width: 4, height: 12, background: e.impact!=='—'?'var(--negative)':'var(--surface-3)', borderRadius: 1, opacity: e.impact==='high'||e.impact==='med'||e.impact==='low'?1:0.3 }}/>
                    <div style={{ width: 4, height: 12, background: e.impact==='high'||e.impact==='med'?'var(--gold)':'var(--surface-3)', borderRadius: 1 }}/>
                    <div style={{ width: 4, height: 12, background: e.impact==='high'?'var(--positive)':'var(--surface-3)', borderRadius: 1 }}/>
                  </div>
                </td>
                <td style={{ fontWeight: 500 }}>{e.title}</td>
                <td className="mono r" style={{ color: 'var(--text-dim)' }}>{e.f}</td>
                <td className="mono r" style={{ fontWeight: 600 }}>{e.a}</td>
                <td className="mono r" style={{ color: 'var(--text-dim)' }}>{e.p}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </>
  );
}

// ============ AFFILIATES ============
function ArenaAffiliates() {
  return (
    <>
      <div className="a-pagehead">
        <div>
          <h1>Affiliates & <em>referrals</em>.</h1>
          <div className="sub">Earn 15% on every challenge your friends buy · paid in USDT</div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 22 }}>
        <div className="a-tile glow">
          <div className="l"><I.coins size={11}/> EARNED</div>
          <div className="v">$1,847</div>
          <div className="d pos">+$240 this month</div>
        </div>
        <div className="a-tile cyan">
          <div className="l"><I.users size={11}/> REFERRALS</div>
          <div className="v">23</div>
          <div className="d" style={{ color: 'var(--text-dim)' }}>14 converted</div>
        </div>
        <div className="a-tile">
          <div className="l"><I.fire size={11}/> CONVERSION</div>
          <div className="v">61%</div>
          <div className="d" style={{ color: 'var(--text-dim)' }}>Above 45% avg</div>
        </div>
        <div className="a-tile">
          <div className="l"><I.bolt size={11}/> COMMISSION</div>
          <div className="v">15%</div>
          <div className="d" style={{ color: 'var(--text-dim)' }}>Gold tier · 18% at Plat</div>
        </div>
      </div>

      <div className="a-section" style={{ marginBottom: 18 }}>
        <h3 style={{ margin: '0 0 14px', fontFamily: 'Space Grotesk', fontSize: 16 }}>Your referral link</h3>
        <div style={{ display: 'flex', gap: 8, padding: '12px 16px', background: 'rgba(0,0,0,0.30)', border: '1px solid var(--line-3)', borderRadius: 12 }}>
          <span className="mono" style={{ flex: 1, fontSize: 14 }}>https://proparena.io/r/yulia-l</span>
          <button className="a-btn primary sm"><I.copy size={11}/> Copy</button>
          <button className="a-btn secondary sm"><I.external size={11}/> Share</button>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 10, marginTop: 14 }}>
          {[
            { l: 'X / Twitter', i: 'speak', url: 'https://twitter.com/intent/tweet?text=Trade%20with%20me%20on%20Prop%20Arena&url=https%3A%2F%2Fproparena.io%2Fr%2Fyulia-l' },
            { l: 'WhatsApp',    i: 'speak', url: 'https://wa.me/?text=Join%20me%20on%20Prop%20Arena%20https%3A%2F%2Fproparena.io%2Fr%2Fyulia-l' },
            { l: 'Telegram',    i: 'speak', url: 'https://t.me/share/url?url=https%3A%2F%2Fproparena.io%2Fr%2Fyulia-l&text=Join%20me%20on%20Prop%20Arena' },
            { l: 'Discord',     i: 'diamond', url: 'https://discord.com/channels/@me' },
          ].map(s => {
            const Ic = I[s.i];
            return (
              <a key={s.l} href={s.url} target="_blank" rel="noopener" className="a-btn secondary sm" style={{ justifyContent: 'center', textDecoration: 'none' }}>
                <Ic size={12}/> Share to {s.l}
              </a>
            );
          })}
        </div>
      </div>

      <div className="a-section" style={{ padding: 0 }}>
        <div style={{ padding: '18px 22px', borderBottom: '1px solid var(--line)' }}>
          <h3 style={{ margin: 0, fontFamily: 'Space Grotesk', fontSize: 16 }}>Recent referrals</h3>
        </div>
        <table className="a-table">
          <thead><tr><th>Date</th><th>Trader</th><th>Source</th><th>Plan</th><th className="r">Earned</th><th>Status</th></tr></thead>
          <tbody>
            {[
              { d: 'May 18', t: 'L. Castillo', s: 'Discord', p: 'Signature 50K', e: 40.35, st: 'paid' },
              { d: 'May 12', t: 'K. Tanaka',   s: 'Twitter', p: 'Signature One 25K', e: 29.85, st: 'paid' },
              { d: 'May 09', t: 'A. Khaled',   s: 'YouTube', p: 'Signature 100K', e: 74.85, st: 'pending' },
              { d: 'May 03', t: 'M. Bianchi',  s: 'Direct',  p: 'Signature Pro 200K', e: 112.35, st: 'paid' },
              { d: 'Apr 28', t: 'J. Mills',    s: 'Discord', p: 'Signature 50K', e: 40.35, st: 'paid' },
            ].map((r, i) => (
              <tr key={i}>
                <td>{r.d}</td>
                <td>{r.t}</td>
                <td>{r.s}</td>
                <td>{r.p}</td>
                <td className="mono r pos" style={{ fontWeight: 600 }}>+${r.e.toFixed(2)}</td>
                <td><span className={'a-tag ' + (r.st==='paid'?'success':'pending')}>{r.st.toUpperCase()}</span></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </>
  );
}

// ============ HELP ============
function ArenaHelp() {
  return (
    <>
      <div className="a-pagehead">
        <div>
          <h1>Help & <em>support</em>.</h1>
          <div className="sub">We typically respond within 2 hours · 24/7 chat</div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 14, marginBottom: 22 }}>
        {[
          { i: 'speak', t: 'Live chat', sub: 'Talk to support now', cta: 'Open chat', glow: true },
          { i: 'mail',  t: 'Email support', sub: 'support@proparena.io', cta: 'Compose' },
        ].map((c, i) => (
          <div key={i} className={'a-section ' + (c.glow?'':'')} style={c.glow?{ background: 'linear-gradient(135deg, rgba(255,92,245,0.10), rgba(92,217,255,0.04)), var(--surface)' }:{}}>
            <div style={{ width: 44, height: 44, borderRadius: 12, background: c.glow?'linear-gradient(135deg, var(--magenta), var(--cyan))':'rgba(255,255,255,0.04)', color: c.glow?'#06070D':'var(--text-dim)', display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 14 }}>{I[c.i]({ size: 22 })}</div>
            <div style={{ fontWeight: 700, fontSize: 17, fontFamily: 'Space Grotesk' }}>{c.t}</div>
            <div style={{ fontSize: 13, color: 'var(--text-dim)', marginTop: 4, marginBottom: 14 }}>{c.sub}</div>
            <button className={'a-btn ' + (c.glow?'primary':'secondary') + ' sm'}>{c.cta} <I.arrowRight size={11}/></button>
          </div>
        ))}
      </div>

      <div className="a-section">
        <h3 style={{ margin: '0 0 14px', fontFamily: 'Space Grotesk', fontSize: 16 }}>Popular topics</h3>
        {[
          { c: 'Rules & objectives', q: 'What is the consistency rule?', sub: 'Max 40% of total profit on a single day…' },
          { c: 'Payouts', q: 'How long do payouts take?', sub: 'USDT 24h · Wire 3-5 business days…' },
          { c: 'Account', q: 'Can I reset my challenge?', sub: 'Yes, free retry available at Platinum tier…' },
          { c: 'Trading', q: 'Can I trade news with Signature?', sub: 'Add the News Trading add-on at checkout…' },
          { c: 'KYC', q: 'When do I need to verify identity?', sub: 'Before first payout · Sumsub takes 5 minutes…' },
        ].map((q, i) => (
          <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '14px 0', borderBottom: i<4?'1px solid var(--line-2)':'none', cursor: 'pointer' }}>
            <span className="a-tag muted">{q.c.toUpperCase()}</span>
            <div style={{ flex: 1 }}>
              <div style={{ fontWeight: 500, fontSize: 14 }}>{q.q}</div>
              <div style={{ fontSize: 12, color: 'var(--text-dim)', marginTop: 2 }}>{q.sub}</div>
            </div>
            <I.chevronRight size={14} style={{ color: 'var(--text-faint)' }}/>
          </div>
        ))}
      </div>
    </>
  );
}


// ============ WALLET & PAYOUTS (6 tabs matching original) ============
const ARENA_WALLET_BALANCE = 1284.50;

function WalletStatusBadge({ status }) {
  const map = {
    done:    { label: 'DONE',    bg: 'color-mix(in oklab, var(--positive) 16%, transparent)', fg: 'var(--positive)', border: 'color-mix(in oklab, var(--positive) 40%, transparent)' },
    pending: { label: 'PENDING', bg: 'color-mix(in oklab, var(--cyan) 14%, transparent)',     fg: 'var(--cyan)',     border: 'color-mix(in oklab, var(--cyan) 40%, transparent)' },
    failed:  { label: 'FAILED',  bg: 'color-mix(in oklab, var(--negative) 16%, transparent)', fg: 'var(--negative)', border: 'color-mix(in oklab, var(--negative) 40%, transparent)' },
  };
  const s = map[status] || map.done;
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 5,
      fontSize: 10, fontWeight: 700,
      letterSpacing: '0.06em',
      padding: '3px 8px',
      borderRadius: 5,
      background: s.bg,
      color: s.fg,
      border: '1px solid ' + s.border,
    }}>
      <span style={{ width: 6, height: 6, borderRadius: 999, background: s.fg, boxShadow: status === 'pending' ? '0 0 6px ' + s.fg : 'none' }}/>
      {s.label}
    </span>
  );
}
const ARENA_WALLET_TX = [
  { id: 'w1', date: 'May 17', kind: 'purchase', label: 'Signature 100K · #5102994',  amount: -539.00, method: 'Wallet',        status: 'done' },
  { id: 'w2', date: 'May 12', kind: 'payout',   label: 'Payout #PT-19 · #5098871',   amount: 4283.50, method: 'Wallet credit', status: 'done' },
  { id: 'w3', date: 'May 04', kind: 'purchase', label: 'Signature 50K · #5102771',   amount: -299.00, method: 'Wallet',        status: 'done' },
  { id: 'w4', date: 'May 02', kind: 'deposit',  label: 'Wallet top-up',              amount: 1000.00, method: 'USDT TRC-20',   status: 'done' },
  { id: 'w5', date: 'Apr 28', kind: 'payout',   label: 'Payout #PT-17 · #5098871',   amount: 3120.00, method: 'Wallet credit', status: 'pending' },
  { id: 'w6', date: 'Apr 22', kind: 'purchase', label: 'Signature One 25K',          amount: -199.00, method: 'Visa •••• 4242',status: 'failed' },
  { id: 'w7', date: 'Apr 14', kind: 'payout',   label: 'Payout #PT-15',              amount: 640.10,  method: 'Wallet credit', status: 'done' },
  { id: 'w8', date: 'Apr 01', kind: 'withdraw', label: 'Withdrawal to USDT TRC-20',  amount: -2200.00,method: 'USDT TRC-20',   status: 'done' },
];

function ArenaWallet() {
  const { setPage } = useApp();
  const [tab, setTab] = useState('overview');
  const tabs = [
    { id: 'overview', l: 'Activity' },
    { id: 'payouts',  l: 'Payouts' },
    { id: 'orders',   l: 'Order history' },
    { id: 'refunds',  l: 'Refunds' },
  ];
  return (
    <>
      <div className="a-pagehead">
        <div>
          <h1>Wallet & <em>payouts</em>.</h1>
          <div className="sub">Top up, withdraw, and view every transaction</div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <button className="a-btn primary" onClick={() => setPage('deposit')}><I.arrowDown size={13}/> Deposit</button>
          <button className="a-btn secondary" onClick={() => setPage('withdraw')}><I.arrowUp size={13}/> Withdraw</button>
        </div>
      </div>
      <div className="a-chips" style={{ marginBottom: 18 }}>
        {tabs.map(x => (
          <button key={x.id} className={tab===x.id?'active':''} onClick={()=>setTab(x.id)}>{x.l}</button>
        ))}
      </div>
      {tab === 'overview'  && <ArenaWalletOverview setTab={setTab}/>}
      {tab === 'payouts'   && <ArenaWalletPayouts/>}
      {tab === 'orders'    && <ArenaWalletOrders/>}
      {tab === 'refunds'   && <ArenaWalletRefunds/>}
    </>
  );
}

function ArenaWalletOverview({ setTab }) {
  const { setPage } = useApp();
  const [kind, setKind] = useState('all');
  const totalPaid = window.SEED_PAYOUTS.reduce((s, p) => s + p.amount, 0);
  const filtered = kind === 'all' ? ARENA_WALLET_TX : ARENA_WALLET_TX.filter(t => t.kind === kind);
  return (
    <>
      <div className="a-section" style={{ background: 'linear-gradient(135deg, rgba(255,92,245,0.10), rgba(92,217,255,0.06)), var(--surface)', marginBottom: 18 }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 28, alignItems: 'center' }}>
          <div>
            <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--text-dim)' }}>Wallet balance</div>
            <div className="mono" style={{ fontSize: 48, fontWeight: 600, letterSpacing: '-0.035em', marginTop: 6 }}>${window.fmtMoney(ARENA_WALLET_BALANCE)}</div>
            <div style={{ fontSize: 13, color: 'var(--text-dim)', marginTop: 4 }}>Available to spend on challenges or withdraw anytime.</div>
            <div style={{ display: 'flex', gap: 8, marginTop: 18 }}>
              <button className="a-btn primary" onClick={()=>setPage('deposit')}><I.arrowDown size={13}/> Deposit</button>
              <button className="a-btn secondary" onClick={()=>setPage('withdraw')}><I.arrowUp size={13}/> Withdraw</button>
            </div>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
            <div className="a-tile"><div className="l">All-time payouts</div><div className="v">${window.fmtMoneyCompact(totalPaid)}</div><div className="d" style={{ color: 'var(--text-faint)' }}>{window.SEED_PAYOUTS.length} cashed</div></div>
            <div className="a-tile"><div className="l">Next eligible</div><div className="v">2d</div><div className="d" style={{ color: 'var(--text-faint)' }}>#5098871</div></div>
            <div className="a-tile"><div className="l">Profit split</div><div className="v">80%</div><div className="d pos">→ 90% after 4 payouts</div></div>
            <div className="a-tile"><div className="l">Pending</div><div className="v">$0</div><div className="d" style={{ color: 'var(--text-faint)' }}>No open requests</div></div>
          </div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 18 }}>
        <div className="a-section" style={{ padding: 0 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '16px 20px', gap: 10, flexWrap: 'wrap', borderBottom: '1px solid var(--line)' }}>
            <div style={{ fontWeight: 700, fontFamily: 'Space Grotesk', fontSize: 16 }}>Wallet activity</div>
            <div className="a-chips" style={{ padding: 3 }}>
              {[
                { id: 'all', l: 'All' },
                { id: 'deposit', l: 'Deposits' },
                { id: 'withdraw', l: 'Withdrawals' },
                { id: 'payout', l: 'Payouts' },
                { id: 'purchase', l: 'Purchases' },
              ].map(p => {
                const n = p.id === 'all' ? ARENA_WALLET_TX.length : ARENA_WALLET_TX.filter(t => t.kind === p.id).length;
                return <button key={p.id} className={kind===p.id?'active':''} onClick={()=>setKind(p.id)}>{p.l} <span className="c">{n}</span></button>;
              })}
            </div>
          </div>
          <table className="a-table">
            <thead><tr><th>Date</th><th>Activity</th><th>Method</th><th>Status</th><th className="r">Amount</th></tr></thead>
            <tbody>
              {filtered.map(t => {
                const kindLabel = { deposit: 'Deposit', withdraw: 'Withdrawal', payout: 'Payout', purchase: 'Purchase' }[t.kind];
                return (
                  <tr key={t.id}>
                    <td style={{ color: 'var(--text-dim)' }}>{t.date}</td>
                    <td><div style={{ fontWeight: 500 }}>{t.label}</div><div style={{ fontSize: 11, color: 'var(--text-faint)' }}>{kindLabel}</div></td>
                    <td style={{ color: 'var(--text-dim)' }}>{t.method}</td>
                    <td><WalletStatusBadge status={t.status}/></td>
                    <td className={'mono r ' + (t.amount>=0?'pos':'')} style={{ fontWeight: 600 }}>{t.amount>=0?'+':'−'}${window.fmtMoney(Math.abs(t.amount))}</td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          <div className="a-section">
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
              <div style={{ width: 28, height: 28, borderRadius: 8, background: 'linear-gradient(135deg, #4A6EE0, #2C4DC0)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 800, fontSize: 12 }}>S</div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 14, fontWeight: 600 }}>Sumsub KYC</div>
                <div style={{ fontSize: 11, color: 'var(--text-dim)' }}>Required for payouts</div>
              </div>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px', borderRadius: 10, background: 'color-mix(in oklab, var(--positive) 12%, var(--surface-2))', border: '1px solid color-mix(in oklab, var(--positive) 28%, var(--line))' }}>
              <div style={{ width: 18, height: 18, borderRadius: 999, background: 'var(--positive)', color: '#06070D', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><I.check size={11}/></div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13, fontWeight: 600 }}>Verified</div>
                <div style={{ fontSize: 11, color: 'var(--text-dim)' }}>Payouts & withdrawals enabled</div>
              </div>
              <span className="a-tag success">ACTIVE</span>
            </div>
          </div>

          <div className="a-section">
            <div style={{ fontWeight: 700, fontFamily: 'Space Grotesk', fontSize: 14, marginBottom: 10 }}>How the wallet works</div>
            {[
              ['Top up your wallet', 'Wire, crypto, card, or local APMs — all credit your wallet balance.'],
              ['Buy challenges instantly', 'Pay from your wallet at checkout. No re-entering payment details.'],
              ['Payouts land in your wallet', 'Funded P&L payouts arrive as wallet credit by default.'],
              ['Withdraw whenever', 'Send to crypto, bank wire or APM. KYC required.'],
            ].map(([t, s], i) => (
              <div key={i} style={{ display: 'grid', gridTemplateColumns: '24px 1fr', gap: 12, padding: '10px 0' }}>
                <div className="mono" style={{ width: 24, height: 24, borderRadius: 999, background: 'var(--surface-3)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 11, fontWeight: 700 }}>{i+1}</div>
                <div>
                  <div style={{ fontSize: 13, fontWeight: 500 }}>{t}</div>
                  <div style={{ fontSize: 12, color: 'var(--text-dim)' }}>{s}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </>
  );
}

function ArenaWalletDeposit() {
  const [method, setMethod] = useState('crypto');
  const [amount, setAmount] = useState(500);
  const methods = [
    { id: 'crypto', i: 'btc',   t: 'Crypto',     s: 'USDT, USDC, BTC, ETH · instant · no fees' },
    { id: 'card',   i: 'cards', t: 'Card',       s: 'Visa / Mastercard / Amex · instant · 2.9% fee' },
    { id: 'wire',   i: 'bank',  t: 'Bank wire',  s: 'USD / EUR / GBP · 1–3 business days' },
    { id: 'apm',    i: 'external', t: 'Local APM', s: 'SEPA, iDEAL, PIX, UPI, Klarna…' },
  ];
  const fee = method === 'card' ? amount * 0.029 : 0;
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 18 }}>
      <div className="a-section">
        <div style={{ fontWeight: 700, fontFamily: 'Space Grotesk', fontSize: 16, marginBottom: 16 }}>Top up wallet</div>
        <div style={{ marginBottom: 14 }}>
          <label style={{ fontSize: 11, color: 'var(--text-dim)', letterSpacing: '0.08em', textTransform: 'uppercase', fontWeight: 600, display: 'block', marginBottom: 6 }}>Amount (USD)</label>
          <div style={{ position: 'relative' }}>
            <span style={{ position: 'absolute', left: 16, top: 18, color: 'var(--text-dim)', fontFamily: 'JetBrains Mono', fontSize: 18 }}>$</span>
            <input className="a-input mono" style={{ paddingLeft: 30, fontSize: 22, height: 56, fontWeight: 600 }} value={amount} onChange={e=>setAmount(Number(e.target.value)||0)}/>
          </div>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 8, marginBottom: 18 }}>
          {[100, 250, 500, 1000].map(q => (
            <button key={q} onClick={()=>setAmount(q)} style={{
              padding: '10px 0', borderRadius: 10,
              border: '1.5px solid ' + (amount===q?'var(--magenta)':'var(--line)'),
              background: amount===q?'rgba(255,92,245,0.10)':'var(--surface-2)',
              color: 'var(--text)', fontFamily: 'JetBrains Mono', fontSize: 13, fontWeight: 600, cursor: 'pointer',
            }}>${q}</button>
          ))}
        </div>
        <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--text-dim)', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: 8 }}>Pay with</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {methods.map(m => (
            <div key={m.id} onClick={()=>setMethod(m.id)} style={{
              display: 'flex', alignItems: 'center', gap: 12, padding: 14,
              background: method===m.id?'rgba(255,92,245,0.06)':'rgba(0,0,0,0.20)',
              border: '1.5px solid ' + (method===m.id?'var(--magenta)':'var(--line)'),
              borderRadius: 12, cursor: 'pointer',
            }}>
              <div style={{ width: 36, height: 36, borderRadius: 10, background: 'var(--surface-3)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{I[m.i]({ size: 16 })}</div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 14, fontWeight: 600 }}>{m.t}</div>
                <div style={{ fontSize: 11, color: 'var(--text-faint)' }}>{m.s}</div>
              </div>
              <span style={{ width: 18, height: 18, borderRadius: 999, border: '1.5px solid ' + (method===m.id?'var(--magenta)':'var(--line-3)'), display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                {method===m.id && <span style={{ width: 9, height: 9, borderRadius: 999, background: 'var(--magenta)' }}/>}
              </span>
            </div>
          ))}
        </div>
        <button className="a-btn primary" style={{ width: '100%', marginTop: 18, height: 46, justifyContent: 'center' }}><I.arrowDown size={13}/> Top up ${amount}</button>
      </div>
      <div className="a-section" style={{ alignSelf: 'start' }}>
        <div style={{ fontWeight: 700, fontFamily: 'Space Grotesk', fontSize: 14, marginBottom: 4 }}>Summary</div>
        <div style={{ fontSize: 12, color: 'var(--text-dim)', marginBottom: 14 }}>{methods.find(m=>m.id===method).t}</div>
        {[
          ['Amount', '$' + amount],
          ['Fees', method==='card' ? '$' + fee.toFixed(2) : 'Free'],
          ['Arrival', method==='crypto'?'Instant':method==='card'?'Instant':method==='wire'?'1–3 days':'≤ 30 min'],
        ].map(([k,v]) => (
          <div key={k} style={{ display: 'flex', justifyContent: 'space-between', padding: '8px 0', fontSize: 13 }}>
            <span style={{ color: 'var(--text-dim)' }}>{k}</span>
            <span className="mono">{v}</span>
          </div>
        ))}
        <div style={{ height: 1, background: 'var(--line)', margin: '8px 0' }}/>
        <div style={{ display: 'flex', justifyContent: 'space-between', padding: '8px 0', fontSize: 13 }}>
          <span>You'll receive</span>
          <span className="mono" style={{ fontWeight: 700 }}>${(amount - fee).toFixed(2)}</span>
        </div>
      </div>
    </div>
  );
}

function ArenaWalletWithdraw() {
  const [method, setMethod] = useState('crypto');
  const [amount, setAmount] = useState('600.00');
  const [network, setNetwork] = useState('TRC-20');
  const fee = method === 'wire' ? 12 : 0;
  const amt = Number(amount) || 0;
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 18 }}>
      <div className="a-section">
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 }}>
          <div style={{ fontWeight: 700, fontFamily: 'Space Grotesk', fontSize: 16 }}>Withdraw from wallet</div>
          <span style={{ fontSize: 12, color: 'var(--text-dim)' }}>Available <b className="mono">${window.fmtMoney(ARENA_WALLET_BALANCE)}</b></span>
        </div>
        <div className="a-chips" style={{ marginBottom: 16 }}>
          <button className={method==='crypto'?'active':''} onClick={()=>setMethod('crypto')}>Crypto</button>
          <button className={method==='wire'?'active':''} onClick={()=>setMethod('wire')}>Bank wire</button>
        </div>
        <label style={{ fontSize: 11, color: 'var(--text-dim)', letterSpacing: '0.08em', textTransform: 'uppercase', fontWeight: 600, display: 'block', marginBottom: 6 }}>Amount</label>
        <div style={{ position: 'relative', marginBottom: 18 }}>
          <span style={{ position: 'absolute', left: 16, top: 18, color: 'var(--text-dim)', fontFamily: 'JetBrains Mono', fontSize: 18 }}>$</span>
          <input className="a-input mono" style={{ paddingLeft: 30, fontSize: 22, height: 56, fontWeight: 600 }} value={amount} onChange={e=>setAmount(e.target.value)}/>
        </div>

        {method === 'crypto' && (
          <>
            <label style={{ fontSize: 11, color: 'var(--text-dim)', letterSpacing: '0.08em', textTransform: 'uppercase', fontWeight: 600, display: 'block', marginBottom: 6 }}>Network</label>
            <div className="a-chips" style={{ marginBottom: 14 }}>
              {['TRC-20', 'ERC-20', 'BEP-20'].map(n => (
                <button key={n} className={network===n?'active':''} onClick={()=>setNetwork(n)}>{n}</button>
              ))}
            </div>
            <label style={{ fontSize: 11, color: 'var(--text-dim)', letterSpacing: '0.08em', textTransform: 'uppercase', fontWeight: 600, display: 'block', marginBottom: 6 }}>Saved addresses</label>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 14 }}>
              {[
                { l: 'Personal TRC-20', a: 'TYxhAaPaJ8tnAQVjmLnp4kQRNkLcDr92K3', tag: 'Primary' },
                { l: 'Cold storage', a: 'TQn8YRgmK6mp5yXzS9LqWHkR3uA3xRvNvT' },
              ].map((sa, i) => (
                <label key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: 14, background: 'rgba(0,0,0,0.20)', border: '1px solid var(--line)', borderRadius: 10, cursor: 'pointer' }}>
                  <input type="radio" defaultChecked={i===0}/>
                  <div style={{ flex: 1 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                      <span style={{ fontWeight: 600 }}>{sa.l}</span>
                      {sa.tag && <span className="a-tag muted">{sa.tag.toUpperCase()}</span>}
                    </div>
                    <div className="mono" style={{ fontSize: 11, color: 'var(--text-faint)' }}>{sa.a}</div>
                  </div>
                </label>
              ))}
            </div>
            <button className="a-btn secondary sm"><I.plus size={11}/> Add new address</button>
          </>
        )}

        {method === 'wire' && (
          <>
            <label style={{ fontSize: 11, color: 'var(--text-dim)', letterSpacing: '0.08em', textTransform: 'uppercase', fontWeight: 600, display: 'block', marginBottom: 6 }}>Beneficiary</label>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 14 }}>
              {[
                { l: 'My Revolut · EUR', iban: 'IT60 X054 2811 1010 0000 0123 456', tag: 'Primary' },
                { l: 'Intesa Sanpaolo · EUR', iban: 'IT45 B030 6909 6061 0000 0098 720' },
              ].map((b, i) => (
                <label key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: 14, background: 'rgba(0,0,0,0.20)', border: '1px solid var(--line)', borderRadius: 10, cursor: 'pointer' }}>
                  <input type="radio" defaultChecked={i===0}/>
                  <div style={{ flex: 1 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                      <span style={{ fontWeight: 600 }}>{b.l}</span>
                      {b.tag && <span className="a-tag muted">{b.tag.toUpperCase()}</span>}
                    </div>
                    <div className="mono" style={{ fontSize: 11, color: 'var(--text-faint)' }}>{b.iban}</div>
                  </div>
                </label>
              ))}
            </div>
            <button className="a-btn secondary sm"><I.plus size={11}/> Add new beneficiary</button>
          </>
        )}

        <button className="a-btn primary" style={{ width: '100%', marginTop: 18, height: 46, justifyContent: 'center' }}><I.arrowUp size={13}/> Withdraw ${amt.toFixed(2)}</button>
      </div>

      <div className="a-section" style={{ alignSelf: 'start' }}>
        <div style={{ fontWeight: 700, fontFamily: 'Space Grotesk', fontSize: 14, marginBottom: 4 }}>Summary</div>
        <div style={{ fontSize: 12, color: 'var(--text-dim)', marginBottom: 14 }}>{method==='crypto'?'USDT '+network:'Bank wire'}</div>
        {[
          ['Amount', '$' + amt.toFixed(2)],
          ['Fee', '$' + fee.toFixed(2)],
          ['Arrival', method==='crypto'?'~30 min':'1–3 days'],
        ].map(([k,v]) => (
          <div key={k} style={{ display: 'flex', justifyContent: 'space-between', padding: '8px 0', fontSize: 13 }}>
            <span style={{ color: 'var(--text-dim)' }}>{k}</span>
            <span className="mono">{v}</span>
          </div>
        ))}
        <div style={{ height: 1, background: 'var(--line)', margin: '8px 0' }}/>
        <div style={{ display: 'flex', justifyContent: 'space-between', padding: '8px 0', fontSize: 13 }}>
          <span>You receive</span>
          <span className="mono" style={{ fontWeight: 700 }}>${(amt - fee).toFixed(2)}</span>
        </div>
        <div style={{ marginTop: 14, padding: 12, background: 'rgba(0,0,0,0.20)', borderRadius: 10, fontSize: 12, color: 'var(--text-dim)' }}>
          <I.shield size={12} style={{ marginRight: 6 }}/> 2FA code required to confirm withdrawal.
        </div>
      </div>
    </div>
  );
}

function ArenaWalletPayouts() {
  return (
    <div className="a-section" style={{ padding: 0 }}>
      <table className="a-table">
        <thead><tr><th>Date</th><th>Account</th><th>Size</th><th>Method</th><th className="r">Amount</th><th>Status</th><th></th></tr></thead>
        <tbody>
          {window.SEED_PAYOUTS.map(p => (
            <tr key={p.id}>
              <td>{p.date}</td>
              <td className="mono">{p.account}</td>
              <td>${window.fmtMoneyCompact(p.size)}</td>
              <td>{p.method}</td>
              <td className="mono r pos" style={{ fontWeight: 600 }}>+${window.fmtMoney(p.amount)}</td>
              <td><span className="a-tag success">PAID</span></td>
              <td><button className="a-iconbtn"><I.download size={11}/></button></td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

function ArenaWalletOrders() {
  return (
    <div className="a-section" style={{ padding: 0 }}>
      <table className="a-table">
        <thead><tr><th>Date</th><th>Order</th><th>Plan</th><th>Method</th><th className="r">Amount</th><th>Status</th><th></th></tr></thead>
        <tbody>
          {window.SEED_ORDERS.map(o => (
            <tr key={o.id}>
              <td>{o.date}</td>
              <td className="mono">{o.tx}</td>
              <td>{o.plan}</td>
              <td>{o.method}</td>
              <td className="mono r" style={{ fontWeight: 600 }}>${o.amount.toFixed(2)}</td>
              <td><span className="a-tag success">PAID</span></td>
              <td><button className="a-iconbtn"><I.download size={11}/></button></td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

function ArenaWalletRefunds() {
  const [f, setF] = useState('all');
  const filtered = f==='all'?window.SEED_REFUNDS:window.SEED_REFUNDS.filter(r => r.status===f);
  return (
    <>
      <div className="a-chips" style={{ marginBottom: 14 }}>
        {[
          { id: 'all', l: 'All' },
          { id: 'requested', l: 'Requested' },
          { id: 'approved', l: 'Approved' },
          { id: 'refunded', l: 'Refunded' },
          { id: 'declined', l: 'Declined' },
        ].map(x => {
          const n = x.id==='all'?window.SEED_REFUNDS.length:window.SEED_REFUNDS.filter(r=>r.status===x.id).length;
          return <button key={x.id} className={f===x.id?'active':''} onClick={()=>setF(x.id)}>{x.l} <span className="c">{n}</span></button>;
        })}
      </div>
      <div className="a-section" style={{ padding: 0 }}>
        <table className="a-table">
          <thead><tr><th>Requested</th><th>Plan</th><th>Reason</th><th>Method</th><th className="r">Amount</th><th>Status</th><th></th></tr></thead>
          <tbody>
            {filtered.map(r => (
              <tr key={r.id}>
                <td><div>{r.requestedOn}</div>{r.refundedOn && <div style={{ fontSize: 10, color: 'var(--text-faint)' }}>refunded {r.refundedOn}</div>}</td>
                <td><div style={{ fontWeight: 600 }}>{r.plan}</div><div className="mono" style={{ fontSize: 11, color: 'var(--text-faint)' }}>#{r.account} · {r.orderId}</div></td>
                <td style={{ color: 'var(--text-dim)', fontSize: 12, maxWidth: 220 }}>{r.reason}</td>
                <td>{r.method}</td>
                <td className={'mono r ' + (r.status==='refunded'?'pos':'')} style={{ fontWeight: 600 }}>{r.status==='refunded'?'+':''}${r.amount.toFixed(2)}</td>
                <td><span className={'a-tag ' + (r.status==='refunded'?'success':r.status==='declined'?'failed':'pending')}>{r.status.toUpperCase()}</span></td>
                <td><button className="a-iconbtn"><I.download size={11}/></button></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14, marginTop: 18 }}>
        {[
          ['1. Request', 'Open a refund request from order history or via support.'],
          ['2. Approve', 'Tradeify reviews within 24h. Eligible: untraded within 30d, duplicate orders, hardship.'],
          ['3. Refunded', 'Funds return to your original payment method (or wallet for crypto).'],
        ].map(([t,b], i) => (
          <div key={i} className="a-section">
            <div style={{ fontFamily: 'Space Grotesk', fontWeight: 700, fontSize: 14 }}>{t}</div>
            <div style={{ fontSize: 12, color: 'var(--text-dim)', marginTop: 6, lineHeight: 1.5 }}>{b}</div>
          </div>
        ))}
      </div>
    </>
  );
}

// ============ GRAND CUP / Tournament ============
function ArenaGrandCup() {
  return (
    <>
      <div className="a-pagehead">
        <div>
          <h1>Grand <em>Cup</em>. Season 6.</h1>
          <div className="sub">14 days remaining · $50,000 prize pool · 18,402 traders</div>
        </div>
        <button className="a-btn primary"><I.trophy size={13}/> View prize tiers</button>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 22 }}>
        <div className="a-tile glow"><div className="l"><I.trophy size={11}/> YOUR RANK</div><div className="v">#247</div><div className="d pos">▲ 42 this week</div></div>
        <div className="a-tile cyan"><div className="l"><I.fire size={11}/> GAIN</div><div className="v">+3.8%</div><div className="d" style={{ color: 'var(--text-dim)' }}>top 1.3%</div></div>
        <div className="a-tile"><div className="l"><I.coins size={11}/> ENTRY</div><div className="v pos">FREE</div><div className="d" style={{ color: 'var(--text-dim)' }}>Funded accounts only</div></div>
        <div className="a-tile"><div className="l"><I.clock size={11}/> ENDS</div><div className="v">14d</div><div className="d" style={{ color: 'var(--text-dim)' }}>June 2 · 17:00 UTC</div></div>
      </div>
      <div className="a-section" style={{ padding: 0 }}>
        <div style={{ padding: '18px 22px', borderBottom: '1px solid var(--line)' }}>
          <h3 style={{ margin: 0, fontFamily: 'Space Grotesk', fontSize: 16 }}>Leaderboard · live</h3>
        </div>
        <table className="a-table">
          <thead><tr><th>Rank</th><th>Trader</th><th>Country</th><th>Account</th><th className="r">Gain</th><th className="r">Prize</th></tr></thead>
          <tbody>
            {window.SEED_LEADERBOARD.map((r, i) => (
              <tr key={i} style={{ background: r.self?'linear-gradient(90deg, rgba(255,92,245,0.10), transparent)':'transparent' }}>
                <td className="mono" style={{ fontWeight: 700, color: r.rank===1?'var(--gold)':r.rank===2?'#C7C9D1':r.rank===3?'oklch(70% 0.13 40)':'var(--text)' }}>#{r.rank}</td>
                <td><b>{r.trader}</b></td>
                <td><CountryDot c={r.country}/></td>
                <td className="mono">{r.rank===247?'$50K Signature':'$200K Signature'}</td>
                <td className="mono r pos" style={{ fontWeight: 600 }}>{window.fmtPct(r.gain, 1)}</td>
                <td className="mono r">{r.rank===1?'$15,000':r.rank===2?'$10,000':r.rank===3?'$5,000':r.rank<=10?'$1,000':r.rank<=100?'$250':'—'}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </>
  );
}

// ============ EDUCATION ============
function ArenaEducation() {
  const courses = [
    { c: 'Foundations',  t: 'Risk management 101', sub: '12 lessons · 2h 40m', prog: 1.0 },
    { c: 'Foundations',  t: 'Reading the tape', sub: '8 lessons · 1h 20m', prog: 0.6 },
    { c: 'Strategies',   t: 'London open breakouts', sub: '14 lessons · 3h 10m', prog: 0.2 },
    { c: 'Strategies',   t: 'Mean reversion on FX majors', sub: '10 lessons · 2h', prog: 0 },
    { c: 'Psychology',   t: 'Handling drawdowns', sub: '6 lessons · 1h 10m', prog: 0.4 },
    { c: 'Compliance',   t: 'The rulebook · explained', sub: '4 lessons · 35m', prog: 1.0 },
  ];
  return (
    <>
      <div className="a-pagehead">
        <div>
          <h1>Education <em>Academy</em>.</h1>
          <div className="sub">Free for all traders · 6 courses · 47 lessons</div>
        </div>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(360px, 1fr))', gap: 14 }}>
        {courses.map((co, i) => (
          <div key={i} className="a-section" style={{ position: 'relative' }}>
            <span className="a-tag muted" style={{ marginBottom: 10 }}>{co.c.toUpperCase()}</span>
            <div style={{ fontFamily: 'Space Grotesk', fontWeight: 700, fontSize: 17, marginTop: 8 }}>{co.t}</div>
            <div style={{ fontSize: 12, color: 'var(--text-dim)', marginTop: 4 }}>{co.sub}</div>
            <div style={{ marginTop: 14, height: 4, background: 'rgba(255,255,255,0.06)', borderRadius: 999, overflow: 'hidden' }}>
              <div style={{ width: (co.prog*100)+'%', height: '100%', background: 'linear-gradient(90deg, var(--magenta), var(--cyan))' }}/>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 6, fontSize: 11, color: 'var(--text-faint)' }}>
              <span>{Math.round(co.prog*100)}% complete</span>
              <button className="a-btn ghost sm">{co.prog===0?'Start':co.prog===1?'Review':'Continue'} <I.arrowRight size={11}/></button>
            </div>
          </div>
        ))}
      </div>
    </>
  );
}

// ============ TRADEIFY TV ============
function ArenaTV() {
  const videos = [
    { t: 'Weekly markets recap · May 17', sub: 'Anand · 14m', dur: '14:32', live: false },
    { t: 'Live · London open with Dario', sub: 'Vukovic · LIVE NOW', dur: 'LIVE', live: true },
    { t: 'Funded trader interview: Schmidt', sub: 'Schmidt · 22m', dur: '22:18' },
    { t: 'How I passed my $200K challenge', sub: 'Tanaka · 18m', dur: '18:04' },
    { t: 'Reading volume profile in real time', sub: 'Castillo · 12m', dur: '12:40' },
    { t: 'Rules-deep dive: consistency', sub: 'Tradeify staff · 9m', dur: '09:15' },
  ];
  return (
    <>
      <div className="a-pagehead">
        <div>
          <h1>Arena <em>TV</em>.</h1>
          <div className="sub">Live streams and trader interviews · 1 live · 124 on-demand</div>
        </div>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(320px, 1fr))', gap: 14 }}>
        {videos.map((v, i) => (
          <div key={i} className="a-section" style={{ padding: 0, overflow: 'hidden', cursor: 'pointer' }}>
            <div style={{ aspectRatio: '16/9', background: 'linear-gradient(135deg, rgba(255,92,245,0.20), rgba(92,217,255,0.15)), var(--surface-2)', position: 'relative', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <div style={{ width: 60, height: 60, borderRadius: 999, background: 'rgba(0,0,0,0.45)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff' }}><I.play size={22}/></div>
              <span style={{ position: 'absolute', bottom: 10, right: 10, fontFamily: 'JetBrains Mono', fontSize: 11, padding: '3px 8px', background: v.live?'var(--negative)':'rgba(0,0,0,0.6)', color: '#fff', borderRadius: 4, fontWeight: 700 }}>{v.dur}</span>
            </div>
            <div style={{ padding: 14 }}>
              <div style={{ fontWeight: 600, fontSize: 14 }}>{v.t}</div>
              <div style={{ fontSize: 12, color: 'var(--text-dim)', marginTop: 4 }}>{v.sub}</div>
            </div>
          </div>
        ))}
      </div>
    </>
  );
}

// ============ MERCHANDISE ============
function ArenaMerchandise() {
  const items = [
    { t: 'Arena Hoodie · Black', sub: 'Heavyweight cotton · embroidered crest', p: '$79', tag: 'BESTSELLER' },
    { t: 'Tee · Holographic logo', sub: '100% organic cotton', p: '$32' },
    { t: 'Trader Cap · Gold tier edition', sub: 'Snapback · gold thread', p: '$28' },
    { t: 'Mousepad · Trading desk XXL', sub: '900×400mm · stitched edges', p: '$45' },
    { t: 'Sticker pack · 12 pieces', sub: 'Vinyl · waterproof', p: '$8' },
    { t: 'Coffee mug · "Funded"', sub: 'Ceramic 330ml', p: '$18' },
  ];
  return (
    <>
      <div className="a-pagehead">
        <div>
          <h1>Arena <em>Shop</em>.</h1>
          <div className="sub">Gold tier members get 20% off · free shipping over $100</div>
        </div>
        <button className="a-btn secondary"><I.cards size={13}/> View cart · 0</button>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: 14 }}>
        {items.map((m, i) => (
          <div key={i} className="a-section" style={{ padding: 0, overflow: 'hidden' }}>
            <div style={{ aspectRatio: '1', background: 'linear-gradient(135deg, rgba(255,92,245,0.10), rgba(92,217,255,0.06)), var(--surface-2)', position: 'relative' }}>
              {m.tag && <span style={{ position: 'absolute', top: 12, left: 12, fontFamily: 'JetBrains Mono', fontSize: 9, fontWeight: 700, padding: '3px 7px', background: 'var(--magenta)', color: '#fff', borderRadius: 4, letterSpacing: 0.06 }}>{m.tag}</span>}
            </div>
            <div style={{ padding: 14 }}>
              <div style={{ fontWeight: 600 }}>{m.t}</div>
              <div style={{ fontSize: 12, color: 'var(--text-dim)', marginTop: 2 }}>{m.sub}</div>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 10 }}>
                <span className="mono" style={{ fontWeight: 700, fontSize: 17 }}>{m.p}</span>
                <button className="a-btn primary sm"><I.plus size={11}/> Add</button>
              </div>
            </div>
          </div>
        ))}
      </div>
    </>
  );
}

Object.assign(window, {
  ArenaNewChallenge, ArenaPayouts, ArenaBilling, ArenaSettings, ArenaCredentials,
  ArenaNotifications, ArenaTiers, ArenaJournal, ArenaCalendar, ArenaAffiliates, ArenaHelp,
  ArenaWallet, ArenaGrandCup, ArenaEducation, ArenaTV, ArenaMerchandise,
});
