// ════════════ MONEY · Banking screens (Mercury-shaped) ════════════
// Accounts · Cards (debit + credit + virtual) · Send money.
const { Icon, Spark, Pex, Avatar, Card, Btn, Pill, Label, Num, Toggle } = window;

// ── ACCOUNTS ─────────────────────────────────────────────────
window.MoneyAccounts = function MoneyAccounts() {
  const P = window.PX; const b = window.useBank(); const { toast, go } = window.useApp();
  const [flow, setFlow] = React.useState(null);
  const available = b.accounts.reduce((a, x) => a + x.balance, 0);
  const op = window.PXBank.acct('op');

  // cash-position forecast: run Operating forward over upcoming events
  let running = op.balance;
  const fc = b.upcoming.map(e => { running = window.PXBank.round(running + e.amt); return { ...e, bal: running }; });
  const low = fc.reduce((m, p) => p.bal < m.bal ? p : m, { bal: op.balance, when: 'today', label: 'now' });
  const fcMax = Math.max(op.balance, ...fc.map(p => p.bal));
  const fcMin = Math.min(op.balance, ...fc.map(p => p.bal));
  const covered = fcMin > 0;

  return (
    <div style={{ fontFamily: P.sans, padding: 22 }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', marginBottom: 16 }}>
        <div style={{ flex: 1 }}>
          <div style={{ fontFamily: P.serif, fontStyle: 'italic', fontSize: 26, color: P.ink, letterSpacing: -0.4 }}>Accounts</div>
          <div style={{ fontSize: 12.5, color: P.ink3, marginTop: 2, display: 'flex', alignItems: 'center', gap: 6 }}><Icon name="shield" size={13} color={P.sage}/>Pexxie Business Banking · FDIC insured to $250,000</div>
        </div>
        <Btn kind="default" size="sm" icon="arrowDown" onClick={() => setFlow({ kind: 'deposit' })}>Add money</Btn>
        <Btn kind="spark" size="sm" icon="send" style={{ marginLeft: 8 }} onClick={() => setFlow({ kind: 'move' })}>Move money</Btn>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.1fr', gap: 14, marginBottom: 14 }}>
        <Card pad={22} style={{ boxShadow: P.shMd }}>
          <Label>Available cash · 3 accounts</Label>
          <div style={{ fontFamily: P.serif, fontStyle: 'italic', fontSize: 46, letterSpacing: -1.5, lineHeight: 1, marginTop: 6, color: P.ink }}>{window.money(available)}</div>
          <div style={{ fontSize: 13, color: P.ink3, marginTop: 10 }}>Earning <span style={{ color: P.sage, fontWeight: 600 }}>$27.43</span> this month · Treasury at 4.10% APY</div>
          <div style={{ display: 'flex', gap: 8, marginTop: 16 }}>
            <Btn kind="default" size="sm" icon="send" onClick={() => setFlow({ kind: 'move' })}>Transfer</Btn>
            <Btn kind="default" size="sm" icon="receipt" onClick={() => go('money/invoices/new')}>Invoice</Btn>
          </div>
        </Card>

        {/* forecast */}
        <Card pad={20} style={{ background: covered ? P.sageWash : P.amberWash, border: `1px solid ${covered ? P.sageTint : P.amberTint}` }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
            <Icon name={covered ? 'shield' : 'alert'} size={15} color={covered ? P.sage : P.amber}/>
            <Label style={{ color: covered ? P.sage : P.amber }}>Cash position · next 3 weeks</Label>
          </div>
          <div style={{ fontSize: 15, color: P.ink, fontWeight: 600, lineHeight: 1.4 }}>{covered ? 'You\u2019re covered through payroll and rent.' : 'Heads up \u2014 Operating dips below zero.'}</div>
          <div style={{ fontSize: 12.5, color: P.ink2, marginTop: 3 }}>Lowest point <b style={{ color: P.ink }}>{window.money(low.bal)}</b> on {low.when}, after {low.label.toLowerCase()}.</div>
          <div style={{ display: 'flex', alignItems: 'flex-end', gap: 5, height: 56, marginTop: 14 }}>
            {[{ when: 'Now', bal: op.balance, amt: 0 }, ...fc].map((p, i) => {
              const h = 8 + ((p.bal - fcMin) / Math.max(1, fcMax - fcMin)) * 40;
              const isLow = p.when === low.when && i > 0;
              return (
                <div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4 }} title={`${p.when}: ${window.money(p.bal)}`}>
                  <div style={{ width: '100%', height: h, borderRadius: 4, background: isLow ? P.amber : p.amt < 0 ? P.ink3 : covered ? P.sage : P.amber, opacity: isLow ? 1 : 0.5 }}/>
                  <span style={{ fontSize: 8.5, color: P.ink3, whiteSpace: 'nowrap' }}>{p.when.replace('Mar ', '')}</span>
                </div>
              );
            })}
          </div>
        </Card>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1.55fr 1fr', gap: 14, alignItems: 'start' }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          {/* accounts list — available + current */}
          <Card pad={0}>
            <div style={{ padding: '13px 18px', borderBottom: `1px solid ${P.line}`, display: 'flex', alignItems: 'center' }}>
              <span style={{ fontSize: 14, fontWeight: 600, color: P.ink, flex: 1 }}>Accounts</span>
              <span onClick={() => setFlow({ kind: 'openAccount' })} style={{ fontSize: 12, color: P.spark, cursor: 'pointer', fontWeight: 500, display: 'inline-flex', alignItems: 'center', gap: 4 }}><Icon name="plus" size={13}/>Open account</span>
            </div>
            {b.accounts.map((a, i) => {
              const hold = a.current && a.current > a.balance;
              return (
                <div key={a.id} onClick={() => setFlow({ kind: 'account', id: a.id })} style={{ padding: '14px 18px', display: 'flex', alignItems: 'center', gap: 13, borderBottom: i < b.accounts.length - 1 ? `1px solid ${P.line}` : 'none', cursor: 'pointer' }}
                  onMouseEnter={e => e.currentTarget.style.background = P.hover} onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                  <div style={{ width: 40, height: 40, borderRadius: 11, background: P[a.tone + 'Tint'], color: P[a.tone], display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name={a.icon} size={19}/></div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 14, color: P.ink, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 7 }}>{a.name} <span style={{ fontFamily: P.mono, fontSize: 11, color: P.ink4, fontWeight: 400 }}>••{a.tail}</span></div>
                    <div style={{ fontSize: 11.5, color: P.ink3, marginTop: 1 }}>{a.type}</div>
                  </div>
                  <div style={{ textAlign: 'right' }}>
                    <Num size={19}>{window.money(a.balance)}</Num>
                    <div style={{ fontSize: 10.5, color: hold ? P.amber : P.ink4, marginTop: 1 }}>{hold ? `${window.money(a.current)} current` : 'available'}</div>
                  </div>
                  <Icon name="chevR" size={16} color={P.ink4}/>
                </div>
              );
            })}
          </Card>

          {/* activity */}
          <Card pad={0}>
            <div style={{ padding: '13px 18px', borderBottom: `1px solid ${P.line}`, display: 'flex', alignItems: 'center' }}>
              <span style={{ fontSize: 14, fontWeight: 600, color: P.ink, flex: 1 }}>Recent activity</span>
              <span onClick={() => go('money/transactions')} style={{ fontSize: 12, color: P.spark, cursor: 'pointer' }}>All transactions →</span>
            </div>
            {b.activity.slice(0, 7).map((t, i, arr) => (
              <div key={t.id} style={{ padding: '11px 18px', display: 'grid', gridTemplateColumns: '30px 1fr auto', gap: 11, alignItems: 'center', borderBottom: i < arr.length - 1 ? `1px solid ${P.line}` : 'none' }}>
                <div style={{ width: 30, height: 30, borderRadius: 8, background: t.dir === 'out' ? P.sunk : t.dir === 'sweep' ? P.skyTint : P.sageTint, color: t.dir === 'out' ? P.ink2 : t.dir === 'sweep' ? P.sky : P.sage, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <Icon name={t.dir === 'in' ? 'arrowDown' : t.dir === 'sweep' ? 'refresh' : 'arrowUp'} size={14}/>
                </div>
                <div style={{ minWidth: 0 }}><div style={{ fontSize: 13, color: P.ink }}>{t.desc}</div><div style={{ fontSize: 11, color: P.ink3 }}>{t.date} · {t.sub}{t.status === 'pending' ? ' · pending' : ''}</div></div>
                <div style={{ textAlign: 'right' }}>
                  <div style={{ fontFamily: P.mono, fontSize: 13, fontWeight: 500, color: t.amt < 0 ? P.ink : P.sage }}>{window.signed(t.amt)}</div>
                  {t.status === 'pending' && <div style={{ fontSize: 9.5, color: P.amber }}>pending</div>}
                </div>
              </div>
            ))}
          </Card>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <Card pad={16} style={{ background: P.sparkWash, border: `1px solid ${P.sparkTint}` }}>
            <div style={{ display: 'flex', gap: 11 }}>
              <Pex size={26}/>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 12.5, color: P.ink2, lineHeight: 1.5 }}>You keep ~<b style={{ color: P.ink }}>$6,000</b> idle in Operating most months. Moving it to Treasury earns about <b style={{ color: P.sage }}>$246/yr</b> at 4.10% APY — still same-day available.</div>
                <div style={{ display: 'flex', gap: 8, marginTop: 10 }}>
                  <Btn kind="spark" size="sm" onClick={() => setFlow({ kind: 'move', from: 'op' })}>Move to Treasury</Btn>
                  <Btn kind="ghost" size="sm">Not now</Btn>
                </div>
              </div>
            </div>
          </Card>
          <Card pad={16}>
            <div style={{ fontSize: 13, fontWeight: 600, color: P.ink, marginBottom: 10 }}>This month</div>
            {[['Money in', '+$8,420', P.sage], ['Money out', '−$6,231', P.ink], ['Net', '+$2,189', P.sage]].map((r, i) => (
              <div key={i} style={{ display: 'flex', justifyContent: 'space-between', padding: '7px 0', borderTop: i === 2 ? `1px solid ${P.line}` : 'none', marginTop: i === 2 ? 4 : 0 }}>
                <span style={{ fontSize: 12.5, color: P.ink3, fontWeight: i === 2 ? 600 : 400 }}>{r[0]}</span>
                <span style={{ fontFamily: P.mono, fontSize: 13, color: r[2], fontWeight: i === 2 ? 600 : 500 }}>{r[1]}</span>
              </div>
            ))}
          </Card>
        </div>
      </div>

      {flow && flow.kind === 'move' && <window.MoveMoney fromId={flow.from} onClose={() => setFlow(null)}/>}
      {flow && flow.kind === 'openAccount' && <OpenAccount onClose={() => setFlow(null)}/>}
      {flow && flow.kind === 'account' && <window.AccountDetail id={flow.id} onMove={(id) => setFlow({ kind: 'move', from: id })} onClose={() => setFlow(null)}/>}
      {flow && flow.kind === 'deposit' && <window.DepositModal onClose={() => setFlow(null)}/>}
    </div>
  );
};

// ── Create virtual card (modal) ──────────────────────────────
function NewVirtualCard({ onClose }) {
  const P = window.PX; const { toast } = window.useApp();
  const [name, setName] = React.useState('');
  const [limit, setLimit] = React.useState('500');
  const [owner, setOwner] = React.useState('Amara Okafor');
  const tones = ['sky', 'plum', 'sage', 'amber', 'rose'];
  const create = () => {
    if (!name.trim()) { toast('Name the card (e.g. Google Ads).', { tone: 'rose', icon: 'alert' }); return; }
    const last4 = String(1000 + (window.PXBank.get().virtual.length * 137 % 9000)).slice(-4);
    window.PXBank.set(s => ({ ...s, virtual: [...s.virtual, { id: window.pxid('v'), name: name.trim(), last4, tone: tones[s.virtual.length % tones.length], spent: 0, limit: parseFloat(limit) || 500, owner: owner.trim() || 'Amara Okafor', frozen: false }] }));
    onClose(); toast(`Virtual card “${name.trim()}” issued — ready to use instantly.`, { tone: 'sage', icon: 'check' });
  };
  return (
    <window.Modal title="New virtual card" sub="Issued instantly · set a limit and owner" w={480} onClose={onClose}
      foot={<><window.Btn kind="ghost" size="md" onClick={onClose}>Cancel</window.Btn><div style={{ flex: 1 }}/><window.Btn kind="spark" size="md" icon="card" onClick={create}>Issue card</window.Btn></>}>
      <window.Field label="Card name" value={name} onChange={setName} placeholder="e.g. Google Ads, SaaS, Contractor" style={{ marginBottom: 14 }}/>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
        <window.Field label="Monthly limit ($)" value={limit} onChange={(v) => setLimit(v.replace(/[^0-9.]/g, ''))} icon="dollar"/>
        <window.Field label="Assigned to" value={owner} onChange={setOwner} icon="user"/>
      </div>
    </window.Modal>
  );
}

// ── Open account (modal) ─────────────────────────────────────
function OpenAccount({ onClose }) {
  const P = window.PX; const { toast } = window.useApp();
  const TYPES = { checking: { name: 'Checking', type: 'Business checking', icon: 'briefcase', tone: 'spark' }, savings: { name: 'Savings', type: 'Treasury · 4.10% APY', icon: 'trendUp', tone: 'sage' }, reserve: { name: 'Reserve', type: 'Set-aside account', icon: 'shield', tone: 'sky' } };
  const [type, setType] = React.useState('savings');
  const [name, setName] = React.useState('');
  const open = () => {
    const t = TYPES[type];
    const tail = String(1000 + window.PXBank.get().accounts.length * 417 % 9000).slice(-4);
    window.PXBank.set(s => ({ ...s, accounts: [...s.accounts, { id: window.pxid('acct'), name: name.trim() || t.name, tail, type: t.type, balance: 0, current: 0, icon: t.icon, tone: t.tone, routing: '021000021', acct: '4800216' + tail }] }));
    onClose(); toast(`${name.trim() || t.name} opened — ready in ~30 seconds.`, { tone: 'sage', icon: 'check' });
  };
  return (
    <window.Modal title="Open an account" sub="Free · opens in about 30 seconds" w={460} onClose={onClose}
      foot={<><window.Btn kind="ghost" size="md" onClick={onClose}>Cancel</window.Btn><div style={{ flex: 1 }}/><window.Btn kind="spark" size="md" onClick={open}>Open account</window.Btn></>}>
      <window.Select label="Account type" value={type} onChange={setType} options={[{ v: 'checking', label: 'Checking' }, { v: 'savings', label: 'Savings · 4.10% APY' }, { v: 'reserve', label: 'Reserve / set-aside' }]} style={{ marginBottom: 14 }}/>
      <window.Field label="Nickname (optional)" value={name} onChange={setName} placeholder={TYPES[type].name}/>
    </window.Modal>
  );
}

// ── Add recipient (modal) ────────────────────────────────────
function AddRecipient({ onClose }) {
  const P = window.PX; const { toast } = window.useApp();
  const [name, setName] = React.useState('');
  const [kind, setKind] = React.useState('vendor');
  const [method, setMethod] = React.useState('ACH');
  const [acct, setAcct] = React.useState('');
  const add = () => {
    if (!name.trim()) { toast('Add the recipient’s name.', { tone: 'rose', icon: 'alert' }); return; }
    const tail = (acct.replace(/\D/g, '').slice(-4) || String(1000 + window.PXBank.get().recipients.length * 311 % 9000).slice(-4));
    window.PXBank.set(s => ({ ...s, recipients: [...s.recipients, { id: window.pxid('r'), name: name.trim(), detail: `${kind === 'person' ? 'Team' : 'Vendor'} · ${method} ••${tail}`, tail, kind, method, last: 'No payments yet' }] }));
    onClose(); toast(`${name.trim()} added to recipients.`, { tone: 'sage', icon: 'check' });
  };
  return (
    <window.Modal title="Add a recipient" sub="Pay them by ACH, wire, or check" w={480} onClose={onClose}
      foot={<><window.Btn kind="ghost" size="md" onClick={onClose}>Cancel</window.Btn><div style={{ flex: 1 }}/><window.Btn kind="primary" size="md" onClick={add}>Add recipient</window.Btn></>}>
      <window.Field label="Name" value={name} onChange={setName} placeholder="Vendor or person" style={{ marginBottom: 14 }}/>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginBottom: 14 }}>
        <window.Select label="Type" value={kind} onChange={setKind} options={[{ v: 'vendor', label: 'Vendor' }, { v: 'person', label: 'Person' }]}/>
        <window.Select label="Method" value={method} onChange={setMethod} options={['ACH', 'Wire', 'Check']}/>
      </div>
      <window.Field label="Account number (optional)" value={acct} onChange={setAcct} placeholder="••••••••1234" icon="card" mono/>
    </window.Modal>
  );
}

// ── CARDS ────────────────────────────────────────────────────
window.MoneyCards = function MoneyCards() {
  const P = window.PX; const b = window.useBank(); const { toast } = window.useApp();
  const [manageDebit, setManageDebit] = React.useState(false);
  const [newCard, setNewCard] = React.useState(false);
  const cc = b.credit;
  const debitSpend = b.card.spentMonth;
  const vSpend = b.virtual.reduce((a, v) => a + v.spent, 0);
  const totalSpend = debitSpend + vSpend + cc.balance;

  const setCredit = (patch) => window.PXBank.set(s => ({ ...s, credit: { ...s.credit, ...patch } }));
  const toggleV = (id) => window.PXBank.set(s => ({ ...s, virtual: s.virtual.map(v => v.id === id ? { ...v, frozen: !v.frozen } : v) }));

  return (
    <div style={{ fontFamily: P.sans, padding: 22 }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', marginBottom: 16 }}>
        <div style={{ flex: 1 }}>
          <div style={{ fontFamily: P.serif, fontStyle: 'italic', fontSize: 26, color: P.ink, letterSpacing: -0.4 }}>Cards</div>
          <div style={{ fontSize: 12.5, color: P.ink3, marginTop: 2 }}>{window.money(totalSpend)} spent this month · debit, credit &amp; {b.virtual.length} virtual</div>
        </div>
        <Btn kind="spark" size="sm" icon="plus" onClick={() => setNewCard(true)}>Create virtual card</Btn>
      </div>

      {/* CREDIT — charge card */}
      <Label style={{ marginBottom: 10 }}>Credit</Label>
      <Card pad={0} style={{ marginBottom: 18, overflow: 'hidden' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '300px 1fr' }}>
          <div style={{ padding: 18, borderRight: `1px solid ${P.line}` }}>
            <div style={{ position: 'relative', aspectRatio: '1.586', borderRadius: 16, padding: 18, overflow: 'hidden', color: '#F4ECFA',
              background: cc.frozen ? 'linear-gradient(135deg,#6E7A82,#3C444C)' : 'linear-gradient(135deg,#8A6AA8 0%,#5E4080 55%,#3F2A5C 100%)', boxShadow: '0 10px 24px rgba(75,45,110,0.30)' }}>
              <div style={{ position: 'absolute', top: -40, right: -30, width: 160, height: 160, borderRadius: 160, background: 'rgba(255,255,255,0.10)' }}/>
              <div style={{ position: 'relative', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <span style={{ fontFamily: P.serif, fontStyle: 'italic', fontSize: 19, fontWeight: 600 }}>Pexxie</span>
                <span style={{ fontSize: 9.5, letterSpacing: 1.5, opacity: 0.85, fontWeight: 600 }}>CREDIT</span>
              </div>
              <div style={{ position: 'relative', width: 36, height: 27, borderRadius: 6, marginTop: 16, background: 'linear-gradient(135deg,#E6D5F0,#B79AD0)' }}/>
              <div style={{ position: 'relative', fontFamily: P.mono, fontSize: 15, letterSpacing: 2, marginTop: 14 }}>••••  ••••  ••••  {cc.last4}</div>
              <div style={{ position: 'relative', display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginTop: 12 }}>
                <div style={{ fontSize: 11.5, fontWeight: 600, letterSpacing: 0.5 }}>HONEST LOAVES</div>
                <Icon name="globe" size={20} color="#F4ECFA" style={{ opacity: 0.85 }}/>
              </div>
            </div>
          </div>
          <div style={{ padding: 20 }}>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 12 }}>
              {[['Current balance', window.money(cc.balance), P.ink], ['Available credit', window.money(cc.limit - cc.balance), P.sage], ['Cashback · March', window.money(cc.cashbackMonth), P.spark]].map((s, i) => (
                <div key={i} style={{ minWidth: 0 }}><Label>{s[0]}</Label><Num size={19} style={{ marginTop: 4 }} color={s[2]}>{s[1]}</Num></div>
              ))}
            </div>
            <div style={{ height: 6, background: P.sunk, borderRadius: 6, overflow: 'hidden', margin: '16px 0 6px' }}><div style={{ width: (cc.balance / cc.limit) * 100 + '%', height: '100%', background: P.plum }}/></div>
            <div style={{ fontSize: 11.5, color: P.ink3 }}>{window.money(cc.balance)} of {window.money(cc.limit)} limit · {cc.cashbackRate}% cashback on everything</div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 16, paddingTop: 14, borderTop: `1px solid ${P.line}` }}>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13, color: P.ink, fontWeight: 500 }}>Statement due {cc.statementDue}</div>
                <div style={{ fontSize: 11.5, color: P.ink3 }}>Autopay {cc.autopay ? 'on' : 'off'} · full balance from Operating ••4290</div>
              </div>
              <Toggle on={cc.autopay} size="sm" onClick={() => setCredit({ autopay: !cc.autopay })}/>
              <Btn kind="default" size="sm" onClick={() => {
                const bal = window.PXBank.get().credit.balance;
                if (bal <= 0) { toast('Credit card balance is already $0.', { icon: 'check' }); return; }
                window.PXBank.set(s => ({ ...s, credit: { ...s.credit, balance: 0 }, accounts: s.accounts.map(a => a.id === 'op' ? { ...a, balance: window.PXBank.round(a.balance - bal) } : a), activity: [{ id: window.pxid('cc'), acct: 'op', dir: 'out', desc: 'Payment · Pexxie Credit', sub: 'Operating → Credit card', amt: -bal, date: 'Today', status: 'settled' }, ...s.activity] }));
                toast(`${window.money(bal)} paid to Pexxie Credit from Operating.`, { tone: 'sage', icon: 'check' });
              }}>Pay early</Btn>
            </div>
          </div>
        </div>
      </Card>

      {/* DEBIT */}
      <Label style={{ marginBottom: 10 }}>Debit</Label>
      <Card pad={16} style={{ marginBottom: 18, display: 'flex', gap: 18, alignItems: 'center' }}>
        <div onClick={() => setManageDebit(true)} style={{ position: 'relative', width: 200, aspectRatio: '1.586', borderRadius: 14, padding: 15, overflow: 'hidden', color: '#FFF6EE', cursor: 'pointer', flexShrink: 0,
          background: b.card.frozen ? 'linear-gradient(135deg,#6E7A82,#3C444C)' : 'linear-gradient(135deg,#EC7A45 0%,#D2561F 52%,#A23E12 100%)', boxShadow: '0 8px 18px rgba(180,70,20,0.26)' }}>
          <div style={{ position: 'absolute', top: -30, right: -24, width: 120, height: 120, borderRadius: 120, background: 'rgba(255,255,255,0.10)' }}/>
          <div style={{ position: 'relative', display: 'flex', justifyContent: 'space-between' }}><span style={{ fontFamily: P.serif, fontStyle: 'italic', fontSize: 16, fontWeight: 600 }}>Pexxie</span><span style={{ fontSize: 8, letterSpacing: 1, opacity: 0.85, fontWeight: 600 }}>DEBIT</span></div>
          <div style={{ position: 'relative', fontFamily: P.mono, fontSize: 12.5, letterSpacing: 1.5, marginTop: 22 }}>••••  4290</div>
          <div style={{ position: 'relative', fontSize: 10, fontWeight: 600, marginTop: 8 }}>AMARA OKAFOR</div>
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}><span style={{ fontSize: 14, fontWeight: 600, color: P.ink }}>Amara’s debit card</span><Pill tone={b.card.frozen ? 'sky' : 'sage'} dot>{b.card.frozen ? 'Frozen' : 'Active'}</Pill></div>
          <div style={{ fontSize: 12, color: P.ink3, marginTop: 2 }}>Physical · linked to Operating ••4290</div>
          <div style={{ fontSize: 12.5, color: P.ink2, marginTop: 10 }}>{window.money(debitSpend)} spent this month · {window.money(b.card.dailyLimit)} daily limit</div>
          <div style={{ display: 'flex', gap: 8, marginTop: 12 }}><Btn kind="default" size="sm" icon="sliders" onClick={() => setManageDebit(true)}>Manage card</Btn></div>
        </div>
      </Card>

      {/* VIRTUAL */}
      <div style={{ display: 'flex', alignItems: 'center', marginBottom: 10 }}>
        <Label style={{ flex: 1 }}>Virtual cards</Label>
        <span style={{ fontSize: 11.5, color: P.ink3 }}>Set a limit, assign to a person, freeze anytime</span>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2,1fr)', gap: 14 }}>
        {b.virtual.map(v => (
          <Card key={v.id} pad={16} style={{ opacity: v.frozen ? 0.62 : 1 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 11, marginBottom: 12 }}>
              <div style={{ width: 38, height: 26, borderRadius: 6, background: `linear-gradient(135deg, ${P[v.tone]}, ${P[v.tone + 'Dim'] || P[v.tone]})`, display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="card" size={14} color="#fff"/></div>
              <div style={{ flex: 1, minWidth: 0 }}><div style={{ fontSize: 13.5, fontWeight: 600, color: P.ink }}>{v.name}</div><div style={{ fontFamily: P.mono, fontSize: 11, color: P.ink4 }}>••{v.last4} · {v.owner}</div></div>
              <Toggle on={!v.frozen} size="sm" onClick={() => toggleV(v.id)}/>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11.5, color: P.ink3, marginBottom: 4 }}><span>{window.money(v.spent)} spent</span><span>of {window.money(v.limit)}/mo</span></div>
            <div style={{ height: 5, background: P.sunk, borderRadius: 5, overflow: 'hidden' }}><div style={{ width: Math.min(100, (v.spent / v.limit) * 100) + '%', height: '100%', background: v.spent / v.limit > 0.85 ? P.rose : P[v.tone] }}/></div>
          </Card>
        ))}
        <Card pad={16} hover style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 9, border: `1px dashed ${P.lineStrong}`, cursor: 'pointer', color: P.ink3 }}
          onClick={() => setNewCard(true)}>
          <Icon name="plus" size={17}/><span style={{ fontSize: 13, fontWeight: 500 }}>New virtual card</span>
        </Card>
      </div>

      {manageDebit && <window.CardControls onClose={() => setManageDebit(false)}/>}
      {newCard && <NewVirtualCard onClose={() => setNewCard(false)}/>}
    </div>
  );
};

// ── SEND MONEY ───────────────────────────────────────────────
window.MoneySend = function MoneySend() {
  const P = window.PX; const b = window.useBank(); const { toast, go } = window.useApp();
  const [flow, setFlow] = React.useState(null);
  const outbound = b.activity.filter(t => t.amt < 0).slice(0, 6);
  const approve = (ap, ok) => {
    window.PXBank.set(s => {
      const approvals = s.approvals.filter(x => x.id !== ap.id);
      if (!ok) return { ...s, approvals };
      const accounts = s.accounts.map(a => a.id === 'op' ? { ...a, balance: window.PXBank.round(a.balance - ap.amt) } : a);
      const act = { id: 'ap' + Math.random().toString(36).slice(2, 6), acct: 'op', dir: 'out', desc: `ACH to ${ap.to}`, sub: ap.note + ' · approved', amt: -ap.amt, date: 'Just now', status: 'pending' };
      return { ...s, approvals, accounts, activity: [act, ...s.activity] };
    });
    toast(ok ? `Approved — ${window.money(ap.amt)} sent to ${ap.to}.` : 'Request declined.', { tone: ok ? 'sage' : 'neutral', icon: ok ? 'check' : 'x' });
  };

  return (
    <div style={{ fontFamily: P.sans, padding: 22 }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', marginBottom: 16 }}>
        <div style={{ flex: 1 }}>
          <div style={{ fontFamily: P.serif, fontStyle: 'italic', fontSize: 26, color: P.ink, letterSpacing: -0.4 }}>Send money</div>
          <div style={{ fontSize: 12.5, color: P.ink3, marginTop: 2 }}>Transfers, ACH &amp; wires, and recurring payments</div>
        </div>
        <Btn kind="spark" size="sm" icon="send" onClick={() => setFlow({ kind: 'move' })}>Send</Btn>
      </div>

      {/* quick actions */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 14, marginBottom: 14 }}>
        {[['Pay a recipient', 'ACH, wire, or check', 'send', 'pay'], ['Move between accounts', 'Instant & free', 'refresh', 'internal'], ['Pay a bill', 'From Bill Pay', 'fileText', 'bills']].map((q, i) => (
          <Card key={i} pad={16} hover style={{ cursor: 'pointer' }} onClick={() => q[3] === 'bills' ? go('money/bills') : setFlow({ kind: 'move', mode: q[3] })}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 11 }}>
              <div style={{ width: 38, height: 38, borderRadius: 10, background: P.sparkTint, color: P.spark, display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name={q[2]} size={17}/></div>
              <div><div style={{ fontSize: 13.5, fontWeight: 600, color: P.ink }}>{q[0]}</div><div style={{ fontSize: 11, color: P.ink3 }}>{q[1]}</div></div>
            </div>
          </Card>
        ))}
      </div>

      {/* approvals — ties to Team permissions */}
      {b.approvals.length > 0 && (
        <Card pad={0} style={{ marginBottom: 14, border: `1px solid ${P.amberTint}` }}>
          <div style={{ padding: '11px 16px', background: P.amberWash, borderBottom: `1px solid ${P.amberTint}`, display: 'flex', alignItems: 'center', gap: 8 }}>
            <Icon name="alert" size={15} color={P.amber}/><span style={{ fontSize: 13, fontWeight: 600, color: P.ink, flex: 1 }}>Needs your approval</span><Pill tone="amber">{b.approvals.length}</Pill>
          </div>
          {b.approvals.map(ap => (
            <div key={ap.id} style={{ padding: '13px 16px', display: 'flex', alignItems: 'center', gap: 12 }}>
              <Avatar name={ap.who} size={32}/>
              <div style={{ flex: 1 }}><div style={{ fontSize: 13, color: P.ink }}><b>{ap.who}</b> wants to send <b>{window.money(ap.amt)}</b> to {ap.to}</div><div style={{ fontSize: 11, color: P.ink3 }}>{ap.note} · {ap.when}</div></div>
              <Btn kind="ghost" size="sm" onClick={() => approve(ap, false)}>Decline</Btn>
              <Btn kind="spark" size="sm" icon="check" onClick={() => approve(ap, true)}>Approve</Btn>
            </div>
          ))}
        </Card>
      )}

      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 14, alignItems: 'start' }}>
        {/* recipients */}
        <Card pad={0}>
          <div style={{ padding: '13px 18px', borderBottom: `1px solid ${P.line}`, display: 'flex', alignItems: 'center' }}>
            <span style={{ fontSize: 14, fontWeight: 600, color: P.ink, flex: 1 }}>Recipients</span>
            <span style={{ fontSize: 12, color: P.spark, cursor: 'pointer', fontWeight: 500, display: 'inline-flex', alignItems: 'center', gap: 4 }} onClick={() => setFlow({ kind: 'addRecipient' })}><Icon name="plus" size={13}/>Add</span>
          </div>
          {b.recipients.map((r, i) => (
            <div key={r.id} style={{ padding: '13px 18px', display: 'flex', alignItems: 'center', gap: 12, borderBottom: i < b.recipients.length - 1 ? `1px solid ${P.line}` : 'none' }}>
              <div style={{ width: 34, height: 34, borderRadius: 9, background: P.sunk, color: P.ink2, display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name={r.kind === 'person' ? 'user' : 'building'} size={16}/></div>
              <div style={{ flex: 1, minWidth: 0 }}><div style={{ fontSize: 13.5, color: P.ink, fontWeight: 500 }}>{r.name}</div><div style={{ fontSize: 11, color: P.ink3 }}>{r.detail} · {r.last}</div></div>
              <Btn kind="default" size="sm" onClick={() => setFlow({ kind: 'move', mode: 'pay', to: r.id })}>Pay</Btn>
            </div>
          ))}
        </Card>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          {/* scheduled */}
          <Card pad={0}>
            <div style={{ padding: '13px 16px', borderBottom: `1px solid ${P.line}`, fontSize: 14, fontWeight: 600, color: P.ink }}>Scheduled &amp; recurring</div>
            {b.transfers.map((t, i) => (
              <div key={t.id} style={{ padding: '12px 16px', display: 'flex', alignItems: 'center', gap: 11, borderBottom: i < b.transfers.length - 1 ? `1px solid ${P.line}` : 'none', opacity: t.on ? 1 : 0.55 }}>
                <div style={{ width: 30, height: 30, borderRadius: 8, background: t.tone === 'neutral' ? P.sunk : P[t.tone + 'Tint'], color: t.tone === 'neutral' ? P.ink2 : P[t.tone], display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name={t.icon} size={14}/></div>
                <div style={{ flex: 1, minWidth: 0 }}><div style={{ fontSize: 12.5, color: P.ink, fontWeight: 500 }}>{t.t}</div><div style={{ fontSize: 10.5, color: P.ink3 }}>{t.when}</div></div>
                <Toggle on={t.on} size="sm" onClick={() => window.PXBank.set(s => ({ ...s, transfers: s.transfers.map(x => x.id === t.id ? { ...x, on: !x.on } : x) }))}/>
              </div>
            ))}
          </Card>
          {/* recent payments */}
          <Card pad={0}>
            <div style={{ padding: '13px 16px', borderBottom: `1px solid ${P.line}`, fontSize: 14, fontWeight: 600, color: P.ink }}>Recent payments</div>
            {outbound.map((t, i) => (
              <div key={t.id} style={{ padding: '11px 16px', display: 'flex', alignItems: 'center', gap: 10, borderBottom: i < outbound.length - 1 ? `1px solid ${P.line}` : 'none' }}>
                <div style={{ flex: 1, minWidth: 0 }}><div style={{ fontSize: 12.5, color: P.ink, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{t.desc}</div><div style={{ fontSize: 10.5, color: t.status === 'pending' ? P.amber : P.ink3 }}>{t.date}{t.status === 'pending' ? ' · pending' : ' · sent'}</div></div>
                <span style={{ fontFamily: P.mono, fontSize: 12.5, color: P.ink }}>{window.signed(t.amt)}</span>
              </div>
            ))}
          </Card>
        </div>
      </div>

      {flow && flow.kind === 'move' && <window.MoveMoney fromId={flow.from} initialMode={flow.mode} initialTo={flow.to} onClose={() => setFlow(null)}/>}
      {flow && flow.kind === 'addRecipient' && <AddRecipient onClose={() => setFlow(null)}/>}
    </div>
  );
};
