// Accounts list, account detail, new account
function Accounts() {
  const { go, accounts } = useApp();
  const [tab, setTab] = useState('all');
  const filtered = tab === 'all' ? accounts : accounts.filter(a => a.type === tab);

  return (
    <div className="screen with-tabs page-enter">
      <StatusBar />
      <AppBar title="Accounts" large right={
        <button className="icon-btn" onClick={() => go('newAccount')}><I.plus /></button>
      }/>
      <div style={{ padding: '0 20px 20px' }}>
        <div className="segmented" style={{ marginBottom: 16 }}>
          {[['all','All'],['live','Live'],['demo','Demo']].map(([id, l]) => (
            <div key={id} className={'seg ' + (tab === id ? 'active' : '')} onClick={() => setTab(id)}>{l}</div>
          ))}
        </div>
        <div className="stack" style={{ gap: 12 }}>
          {filtered.map(a => <AccountCard key={a.id} acc={a} onClick={() => go('account', { id: a.id })} />)}
          <button className="card" onClick={() => go('newAccount')} style={{
            border: '1px dashed var(--line)', background: 'transparent',
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8,
            padding: 24, cursor: 'pointer', color: 'var(--text-dim)'
          }}>
            <div style={{ width: 44, height: 44, borderRadius: 14, background: 'var(--card)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <I.plus />
            </div>
            <span style={{ fontSize: 14, fontWeight: 500, color: 'var(--text)' }}>Open new account</span>
            <span style={{ fontSize: 12 }}>Live or demo · AI WebTrader</span>
          </button>
        </div>
      </div>
      <TabBar />
    </div>
  );
}

function AccountCard({ acc, onClick }) {
  const isDemo = acc.type === 'demo';
  return (
    <button className="card" onClick={onClick} style={{
      padding: 18, textAlign: 'left', cursor: 'pointer', color: 'var(--text)', position: 'relative', overflow: 'hidden',
      background: isDemo ? 'var(--card)' : 'linear-gradient(135deg, var(--card), color-mix(in oklab, var(--green) 5%, var(--card)))'
    }}>
      <div className="between" style={{ marginBottom: 12 }}>
        <span className={'pill ' + (isDemo ? 'pill-demo' : 'pill-green')}>{isDemo ? 'Demo' : 'Live'} · {acc.platform}</span>
        <I.chevR size={18} />
      </div>
      <div className="mono" style={{ fontSize: 11, color: 'var(--text-dim)' }}>#{acc.number}</div>
      <div className="mono" style={{ fontSize: 30, fontWeight: 600, letterSpacing: '-0.02em', marginTop: 2 }}>
        ${acc.balance.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
      </div>
      <div className="row" style={{ gap: 14, marginTop: 12, fontSize: 11, color: 'var(--text-dim)' }}>
        <Stat2 l="Equity" v={`$${acc.equity.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`} />
        <Stat2 l="Leverage" v={acc.leverage} />
        <Stat2 l="Type" v={acc.kind} />
      </div>
    </button>
  );
}

function Stat2({ l, v }) {
  return (
    <div className="col" style={{ gap: 2 }}>
      <span style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.06em' }}>{l}</span>
      <span className="mono" style={{ color: 'var(--text)', fontSize: 13, fontWeight: 500 }}>{v}</span>
    </div>
  );
}

function AccountDetail() {
  const { go, params, accounts } = useApp();
  const acc = accounts.find(a => a.id === params.id) || accounts[0];
  const isDemo = acc.type === 'demo';

  return (
    <div className={desktop ? "desktop-screen-inner" : "screen page-enter"}>
      {!desktop && <><StatusBar /><AppBar title={'#' + acc.number} onBack={() => go('accounts')} right={<button className="icon-btn"><I.more /></button>} /></>}
      <div style={{ padding: '0 20px 30px' }}>
        <div className="card" style={{
          background: isDemo ? 'var(--card)' : 'linear-gradient(135deg, rgba(166,255,61,0.10), rgba(77,224,255,0.06))',
          padding: 22
        }}>
          <span className={'pill ' + (isDemo ? 'pill-demo' : 'pill-green')}>{isDemo ? 'Demo' : 'Live'} · {acc.platform}</span>
          <div className="mono" style={{ fontSize: 38, fontWeight: 600, letterSpacing: '-0.02em', marginTop: 12 }}>
            ${acc.balance.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
          </div>
          <div className="mono" style={{ fontSize: 12, color: 'var(--text-dim)' }}>Balance · {acc.currency}</div>
        </div>

        <div className="row" style={{ gap: 8, marginTop: 14 }}>
          <button className="btn btn-primary btn-sm" onClick={() => alert('AI WebTrader would open in a new tab.')} style={{ flex: 2 }}>
            <I.trade size={18} /> Trade
          </button>
          {!isDemo && (
            <>
              <button className="btn btn-secondary btn-sm" onClick={() => go('deposit')}><I.arrowDown size={16} /></button>
              <button className="btn btn-secondary btn-sm" onClick={() => go('withdraw')}><I.arrowUp size={16} /></button>
            </>
          )}
        </div>

        <div className="card" style={{ marginTop: 16, padding: 0 }}>
          <Detail k="Equity" v={`$${acc.equity.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`} />
          <Detail k="Free margin" v={`$${(acc.equity * 0.85).toFixed(2)}`} />
          <Detail k="Margin level" v="847.20%" />
          <Detail k="Leverage" v={acc.leverage} />
          <Detail k="Type" v={acc.kind} />
          <Detail k="Server" v={acc.platform === 'WebTrader' ? 'AITrader-Live01' : 'AITrader-' + acc.platform} last />
        </div>

        <h3 style={{ fontSize: 15, fontWeight: 600, margin: '24px 0 10px' }}>Connection</h3>
        <div className="card" style={{ padding: 0 }}>
          <Detail k="Login" v={acc.number} copy />
          <Detail k="Investor password" v="••••••••" />
          <Detail k="Server" v={acc.platform === 'WebTrader' ? 'AITrader-Live01' : 'AITrader-' + acc.platform} copy last />
        </div>

        {!isDemo && (
          <button className="btn btn-secondary" onClick={() => go('transfer')} style={{ marginTop: 18 }}>
            <I.swap size={18} /> Transfer between accounts
          </button>
        )}
      </div>
    </div>
  );
}

function Detail({ k, v, last, copy }) {
  return (
    <div className="row between" style={{ padding: '14px 16px', borderBottom: last ? 'none' : '1px solid var(--line-2)' }}>
      <span style={{ fontSize: 13, color: 'var(--text-dim)' }}>{k}</span>
      <div className="row" style={{ gap: 10 }}>
        <span className="mono" style={{ fontSize: 13, fontWeight: 500 }}>{v}</span>
        {copy && <button style={{ background: 'none', border: 'none', color: 'var(--text-dim)', cursor: 'pointer', padding: 0 }}><I.copy size={14} /></button>}
      </div>
    </div>
  );
}

function NewAccount() {
  const { go, addAccount, toast, desktop } = useApp();
  const [type, setType] = useState('live');
  const [platform] = useState('WebTrader');
  const [kind, setKind] = useState('Standard');
  const [leverage, setLeverage] = useState('1:200');
  const [currency, setCurrency] = useState('USD');

  const create = () => {
    const id = 'a' + Date.now();
    const number = String(Math.floor(8000000 + Math.random() * 999999));
    const balance = type === 'demo' ? 10000 : 0;
    addAccount({ id, number, type, platform, kind, leverage, currency, balance, equity: balance });
    toast('Account ' + number + ' created');
    go('accounts');
  };

  return (
    <div className={desktop ? "desktop-screen-inner" : "screen page-enter"}>
      {!desktop && <><StatusBar /><AppBar title="New account" onBack={() => go('accounts')} /></>}
      <div style={{ padding: '0 20px 30px' }}>
        <Section label="Type">
          <div className="row" style={{ gap: 10 }}>
            <Pick active={type==='live'} onClick={() => setType('live')} title="Live" desc="Real money" />
            <Pick active={type==='demo'} onClick={() => setType('demo')} title="Demo" desc="$10,000 virtual" />
          </div>
        </Section>

        <Section label="Platform">
          <div className="card row" style={{ gap: 12, padding: 14 }}>
            <div style={{ width: 40, height: 40, borderRadius: 12, background: 'linear-gradient(135deg, var(--green), var(--cyan))', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#0A0B0D' }}>
              <I.trade size={20} />
            </div>
            <div className="col" style={{ flex: 1 }}>
              <span style={{ fontSize: 14, fontWeight: 600 }}>AI WebTrader</span>
              <span style={{ fontSize: 11, color: 'var(--text-dim)' }}>Browser · zero install · all assets</span>
            </div>
            <span className="pill pill-green">Default</span>
          </div>
        </Section>

        <Section label="Account kind">
          <div className="stack" style={{ gap: 8 }}>
            <Row active={kind==='Standard'} onClick={() => setKind('Standard')} title="Standard" desc="From 1.0 pip · No commission" />
            <Row active={kind==='Pro'} onClick={() => setKind('Pro')} title="Pro" desc="From 0.2 pip · $4 / lot" />
            <Row active={kind==='ECN'} onClick={() => setKind('ECN')} title="ECN" desc="From 0.0 pip · $7 / lot" />
          </div>
        </Section>

        <Section label="Leverage">
          <div className="row" style={{ gap: 8, flexWrap: 'wrap' }}>
            {['1:50','1:100','1:200','1:500'].map(l => (
              <button key={l} onClick={() => setLeverage(l)} className="mono" style={{
                flex: 1, minWidth: 70, padding: '10px 14px', borderRadius: 12, fontSize: 13, fontWeight: 600,
                background: leverage===l ? 'var(--green)' : 'var(--card)',
                color: leverage===l ? '#0A0B0D' : 'var(--text)',
                border: '1px solid ' + (leverage===l ? 'var(--green)' : 'var(--line)'),
                cursor: 'pointer', fontFamily: 'inherit'
              }}>{l}</button>
            ))}
          </div>
        </Section>

        <Section label="Base currency">
          <div className="row" style={{ gap: 8 }}>
            {['USD','EUR','USDT'].map(c => (
              <button key={c} onClick={() => setCurrency(c)} className="mono" style={{
                flex: 1, padding: '12px 14px', borderRadius: 12, fontSize: 14, fontWeight: 600,
                background: currency===c ? 'var(--card)' : 'transparent',
                color: 'var(--text)',
                border: '1px solid ' + (currency===c ? 'var(--green)' : 'var(--line)'),
                cursor: 'pointer', fontFamily: 'inherit'
              }}>{c}</button>
            ))}
          </div>
        </Section>

        <button className="btn btn-primary" onClick={create} style={{ marginTop: 24 }}>Create account</button>
      </div>
    </div>
  );
}

function Section({ label, children }) {
  return (
    <div style={{ marginTop: 18 }}>
      <div className="input-label">{label}</div>
      {children}
    </div>
  );
}

function Pick({ active, onClick, title, desc }) {
  return (
    <button onClick={onClick} className="card" style={{
      flex: 1, textAlign: 'left', cursor: 'pointer',
      padding: 16, color: 'var(--text)',
      borderColor: active ? 'var(--green)' : 'var(--line)',
      borderWidth: active ? 2 : 1,
      background: active ? 'color-mix(in oklab, var(--green) 6%, var(--card))' : 'var(--card)'
    }}>
      <div style={{ fontSize: 15, fontWeight: 600, marginBottom: 2 }}>{title}</div>
      <div style={{ fontSize: 12, color: 'var(--text-dim)' }}>{desc}</div>
    </button>
  );
}

function Row({ active, onClick, title, desc }) {
  return (
    <button onClick={onClick} style={{
      display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12,
      padding: '14px 16px', borderRadius: 14, width: '100%',
      border: '1px solid ' + (active ? 'var(--green)' : 'var(--line)'),
      background: active ? 'color-mix(in oklab, var(--green) 6%, var(--card))' : 'var(--card)',
      color: 'var(--text)', cursor: 'pointer', fontFamily: 'inherit', textAlign: 'left'
    }}>
      <div style={{ display: 'flex', flexDirection: 'column', flex: 1, minWidth: 0, gap: 2 }}>
        <span style={{ fontSize: 14, fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{title}</span>
        <span style={{ fontSize: 11, color: 'var(--text-dim)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{desc}</span>
      </div>
      <div style={{
        width: 20, height: 20, borderRadius: '50%',
        border: '1px solid ' + (active ? 'var(--green)' : 'var(--line)'),
        background: active ? 'var(--green)' : 'transparent',
        display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#0A0B0D'
      }}>
        {active && <I.check size={12} stroke={3} />}
      </div>
    </button>
  );
}

window.Accounts = Accounts;
window.AccountDetail = AccountDetail;
window.NewAccount = NewAccount;
