function useClickOutside(open, onClose) {
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (!open) return;
    function handle(e) { if (ref.current && !ref.current.contains(e.target)) onClose(); }
    document.addEventListener('mousedown', handle);
    return () => document.removeEventListener('mousedown', handle);
  }, [open]);
  return ref;
}

function MultiSelectChips({ options, value, onChange, placeholder }) {
  const [open, setOpen] = React.useState(false);
  const [query, setQuery] = React.useState('');
  const ref = useClickOutside(open, () => setOpen(false));
  function toggle(v) { onChange(value.includes(v) ? value.filter((x) => x !== v) : [...value, v]); }
  const selected = options.filter((o) => value.includes(o.value));
  const filtered = options.filter((o) => o.label.toLowerCase().includes(query.toLowerCase()));
  return (
    <div ref={ref} style={{ position: 'relative' }}>
      <button type="button" onClick={() => setOpen((o) => !o)} style={{ width: '100%', boxSizing: 'border-box', minHeight: 40, display: 'flex', alignItems: 'center', flexWrap: 'wrap', gap: 6, padding: '8px 12px', borderRadius: 'var(--radius-md)', border: '1.5px solid ' + (open ? 'var(--ud-fill)' : 'var(--border-default)'), background: 'white', cursor: 'pointer', textAlign: 'left' }}>
        {selected.length === 0 && <span style={{ color: 'var(--text-muted)', fontSize: 'var(--text-sm)' }}>{placeholder || 'Select events…'}</span>}
        {selected.map((o) => (
          <span key={o.value} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, background: 'var(--ud-tint)', color: 'var(--ud-text)', borderRadius: 'var(--radius-pill)', padding: '3px 8px 3px 10px', fontSize: 'var(--text-xs)', fontWeight: 600 }}>
            {o.label}
            <span onClick={(e) => { e.stopPropagation(); toggle(o.value); }} style={{ cursor: 'pointer', fontSize: 13, lineHeight: 1 }}>×</span>
          </span>
        ))}
      </button>
      {open && (
        <div style={{ position: 'absolute', top: 'calc(100% + 6px)', left: 0, right: 0, background: 'white', border: '1px solid var(--border-default)', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-lg)', zIndex: 60, overflow: 'hidden', animation: 'udPopIn 140ms var(--ease-standard) both' }}>
          <div style={{ padding: 8, borderBottom: '1px solid var(--border-default)' }}>
            <input autoFocus value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Search events…" style={{ width: '100%', boxSizing: 'border-box', padding: '7px 10px', fontSize: 'var(--text-sm)', border: '1px solid var(--border-default)', borderRadius: 'var(--radius-md)', fontFamily: 'var(--font-body)' }} />
          </div>
          <div style={{ maxHeight: 200, overflowY: 'auto' }}>
            {filtered.map((o) => (
              <label key={o.value} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 'var(--text-sm)', cursor: 'pointer', padding: '9px 14px' }} className="ud-row">
                <input type="checkbox" checked={value.includes(o.value)} onChange={() => toggle(o.value)} />
                {o.label}
              </label>
            ))}
            {filtered.length === 0 && <div style={{ padding: '14px', fontSize: 'var(--text-sm)', color: 'var(--text-muted)' }}>No matching events.</div>}
          </div>
        </div>
      )}
    </div>
  );
}

function AddPayoutDialog({ open, initial, subOptions, feePercent, onClose, onSave }) {
  const { Button, Input, Radio } = window.TheUpperDeckDesignSystem_4d3294;
  const { CustomSelect } = window.UdUI;
  const [payeeName, setPayeeName] = React.useState('');
  const [payeeDescription, setPayeeDescription] = React.useState('');
  const [subEventIds, setSubEventIds] = React.useState([]);
  const [amountType, setAmountType] = React.useState('fixed');
  const [fixedAmount, setFixedAmount] = React.useState('');
  const [percentValue, setPercentValue] = React.useState('10');
  const [percentSubEventIds, setPercentSubEventIds] = React.useState([]);
  const [status, setStatus] = React.useState('not_initiated');
  const [saving, setSaving] = React.useState(false);
  React.useEffect(() => {
    if (!open) return;
    if (initial) {
      setPayeeName(initial.payeeName || ''); setPayeeDescription(initial.payeeDescription || '');
      setSubEventIds(initial.subEventIds || []); setAmountType(initial.amountType || 'fixed');
      setFixedAmount(initial.amountType === 'fixed' ? String(initial.net) : ''); setPercentValue(String(initial.percentValue || 10));
      setPercentSubEventIds(initial.percentSubEventIds || []); setStatus(initial.status || 'not_initiated');
    } else {
      setPayeeName(''); setPayeeDescription(''); setSubEventIds([]); setAmountType('fixed'); setFixedAmount(''); setPercentValue('10'); setPercentSubEventIds([]); setStatus('not_initiated');
    }
  }, [open, initial]);
  if (!open) return null;

  const percentGross = subOptions.filter((s) => percentSubEventIds.includes(s.value)).reduce((sum, s) => sum + (s.gross || 0), 0);
  const netCents = amountType === 'fixed' ? Math.round(Number(fixedAmount) || 0) : Math.round(percentGross * (Number(percentValue) || 0) / 100);
  const grossCents = amountType === 'percent' ? Math.round(percentGross) : netCents;
  const feeCents = Math.max(grossCents - netCents, 0);
  const valid = payeeName.trim() && subEventIds.length > 0 && (amountType === 'fixed' ? Number(fixedAmount) > 0 : percentSubEventIds.length > 0 && Number(percentValue) > 0);

  async function submit() {
    setSaving(true);
    await onSave({ payeeName: payeeName.trim(), payeeDescription: payeeDescription.trim(), subEventIds, amountType, percentValue: Number(percentValue) || 0, percentSubEventIds, grossCents, feeCents, netCents, status });
    setSaving(false);
  }

  return ReactDOM.createPortal(
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(8,21,27,0.6)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1100, padding: 24 }}>
      <div onClick={(e) => e.stopPropagation()} style={{ width: 480, maxHeight: '90vh', overflowY: 'auto', background: 'white', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-lg)', padding: 28, display: 'flex', flexDirection: 'column', gap: 14 }}>
        <h3 style={{ fontFamily: 'var(--font-display)', margin: 0 }}>{initial ? 'Edit payout' : 'Add payout'}</h3>
        <Input label="Payee name" value={payeeName} onChange={setPayeeName} required />
        <div>
          <div style={{ fontSize: 'var(--text-sm)', fontWeight: 600, marginBottom: 6 }}>Payee description</div>
          <textarea value={payeeDescription} onChange={(e) => setPayeeDescription(e.target.value)} rows={2} placeholder="e.g. Lead coach, IMC Day 1–2" style={{ width: '100%', boxSizing: 'border-box', padding: 10, borderRadius: 'var(--radius-md)', border: '1px solid var(--border-default)', fontFamily: 'var(--font-body)', fontSize: 'var(--text-sm)', resize: 'vertical' }} />
        </div>
        <div>
          <div style={{ fontSize: 'var(--text-sm)', fontWeight: 600, marginBottom: 6 }}>Events associated with this payout</div>
          <MultiSelectChips options={subOptions} value={subEventIds} onChange={setSubEventIds} />
        </div>
        <div>
          <div style={{ fontSize: 'var(--text-sm)', fontWeight: 600, marginBottom: 6 }}>Amount</div>
          <Radio label="Fixed amount" checked={amountType === 'fixed'} onChange={() => setAmountType('fixed')} />
          {amountType === 'fixed' && <input type="number" value={fixedAmount} onChange={(e) => setFixedAmount(e.target.value)} placeholder="e.g. 50000" style={{ marginTop: 6, width: '100%', boxSizing: 'border-box', padding: '8px 10px', borderRadius: 'var(--radius-md)', border: '1px solid var(--border-default)' }} />}
          <div style={{ marginTop: 8 }}><Radio label="Percentage of revenue" checked={amountType === 'percent'} onChange={() => setAmountType('percent')} /></div>
          {amountType === 'percent' && (
            <div style={{ marginTop: 6, display: 'flex', flexDirection: 'column', gap: 8 }}>
              <input type="number" value={percentValue} onChange={(e) => setPercentValue(e.target.value)} placeholder="e.g. 10" style={{ width: 120, boxSizing: 'border-box', padding: '8px 10px', borderRadius: 'var(--radius-md)', border: '1px solid var(--border-default)' }} />
              <div style={{ fontSize: 'var(--text-xs)', color: 'var(--text-muted)' }}>Which events' revenue is this percentage cut coming from?</div>
              <MultiSelectChips options={subOptions} value={percentSubEventIds} onChange={setPercentSubEventIds} />
              <div style={{ fontSize: 'var(--text-sm)' }}>Revenue base: {window.fmtUSD(percentGross)} → payout {window.fmtUSD(netCents)}</div>
            </div>
          )}
        </div>
        <div>
          <div style={{ fontSize: 'var(--text-sm)', fontWeight: 600, marginBottom: 6 }}>Status</div>
          <CustomSelect value={status} onChange={setStatus} width="100%" options={[{ value: 'not_initiated', label: 'Not initiated' }, { value: 'pending', label: 'Pending' }, { value: 'paid', label: 'Paid' }, { value: 'cancelled', label: 'Cancelled' }]} />
        </div>
        <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 10, marginTop: 8 }}>
          <Button variant="secondary" onClick={onClose}>Cancel</Button>
          <Button disabled={!valid || saving} onClick={submit}>{saving ? 'Saving…' : (initial ? 'Save changes' : 'Add payout')}</Button>
        </div>
      </div>
    </div>, document.body
  );
}

function Finances_Tab({ tabs, active, onChange }) {
  const { Tabs } = window.TheUpperDeckDesignSystem_4d3294;
  return <Tabs tabs={tabs} active={active} onChange={onChange} />;
}

function FinancesScreen({ adminId }) {
  const { Badge } = window.TheUpperDeckDesignSystem_4d3294;
  const { CustomSelect, CustomDatePicker, Btn, ColumnPicker, useColumnPrefs } = window.UdUI;
  const REVENUE_COLUMNS = [{ key: 'event', label: 'Event', locked: true }, { key: 'orders', label: 'Orders' }, { key: 'gross', label: 'Gross revenue' }, { key: 'refunds', label: 'Refunds' }, { key: 'net', label: 'Net revenue' }];
  const [revCols, setRevCols] = useColumnPrefs('finances_revenue', REVENUE_COLUMNS.map((c) => c.key));
  const [tab, setTab] = React.useState('revenue');
  const [loading, setLoading] = React.useState(true);
  const [orders, setOrders] = React.useState([]);
  const [feePercent, setFeePercent] = React.useState(4);
  const [payouts, setPayouts] = React.useState([]);
  const [eventFilter, setEventFilter] = React.useState('');
  const [startDate, setStartDate] = React.useState('');
  const [endDate, setEndDate] = React.useState('');
  const [expanded, setExpanded] = React.useState({});
  const [payoutPrompt, setPayoutPrompt] = React.useState(null);
  const [addingPayout, setAddingPayout] = React.useState(false);
  const [editingPayout, setEditingPayout] = React.useState(null);
  const [actionError, setActionError] = React.useState('');
  const [allSubEvents, setAllSubEvents] = React.useState([]);

  const RENEWAL_FEE_MIN = 500;
  const RENEWAL_FEE_MAX = 2500;
  const [certs, setCerts] = React.useState([]);
  React.useEffect(() => { window.fetchCertsForRenewalLive().then(setCerts); }, []);
  function certRenewStatus(expiresAt) { const days = Math.floor((new Date(expiresAt) - new Date()) / 86400000); if (days < 0) return 'expired'; if (days <= 30) return 'expiring'; return 'active'; }
  const certActive = certs.filter((c) => certRenewStatus(c.expiresAt) === 'active').length;
  const certExpiring = certs.filter((c) => certRenewStatus(c.expiresAt) === 'expiring');
  const certExpired = certs.filter((c) => certRenewStatus(c.expiresAt) === 'expired');
  const dueForRenewal = certExpiring.concat(certExpired);
  async function renewCert(id) { try { await window.renewCertificateLive(id); const fresh = await window.fetchCertsForRenewalLive(); setCerts(fresh); } catch (e) { setActionError('Renew failed: ' + e.message); } }

  function reload() {
    setLoading(true);
    Promise.all([window.fetchFinanceDataLive(), window.fetchMainEventsLive()]).then(([d, mainEvents]) => {
      setOrders(d.orders); setFeePercent(d.feePercent); setPayouts(d.payouts);
      setAllSubEvents(mainEvents.flatMap((m) => m.subEvents.map((s) => ({ sid: s.id, title: s.title, mainTitle: m.title }))));
      setLoading(false);
    });
  }
  React.useEffect(() => { reload(); }, []);

  const mainEvents = Array.from(new Map(orders.map((o) => [o.mainId, o.mainTitle])).entries()).map(([value, label]) => ({ value, label }));

  const scoped = orders.filter((o) => {
    const matchEv = !eventFilter || o.mainId === eventFilter;
    const purchased = new Date(o.purchasedOn);
    const matchStart = !startDate || purchased >= new Date(startDate);
    const matchEnd = !endDate || purchased <= new Date(endDate);
    return matchEv && matchStart && matchEnd;
  });

  const paid = scoped.filter((o) => o.status === 'paid');
  const refunded = scoped.filter((o) => o.status === 'refunded');
  const totalRevenue = paid.reduce((s, o) => s + o.amount, 0);
  const totalRefunds = refunded.reduce((s, o) => s + o.originalAmount, 0);
  const motiveoCut = totalRevenue * feePercent / 100;
  const totalPaidPayouts = payouts.filter((p) => p.status === 'paid').reduce((s, p) => s + p.net, 0);
  const net = totalRevenue - totalRefunds - motiveoCut - totalPaidPayouts;

  const byMain = {};
  scoped.forEach((o) => {
    if (!byMain[o.mainId]) byMain[o.mainId] = { title: o.mainTitle, gross: 0, refunds: 0, count: 0, subs: {} };
    const m = byMain[o.mainId];
    m.count++;
    if (o.status === 'paid') m.gross += o.amount;
    if (o.status === 'refunded') m.refunds += o.originalAmount;
    if (!m.subs[o.eventId]) m.subs[o.eventId] = { title: o.eventTitle, gross: 0, refunds: 0, count: 0 };
    const sub = m.subs[o.eventId];
    sub.count++;
    if (o.status === 'paid') sub.gross += o.amount;
    if (o.status === 'refunded') sub.refunds += o.originalAmount;
  });

  async function addPayout(payload) {
    try {
      if (editingPayout) await window.updatePayoutLive(editingPayout.id, {
        payee_name: payload.payeeName, payee_description: payload.payeeDescription || null, sub_event_ids: payload.subEventIds,
        amount_type: payload.amountType, percent_value: payload.amountType === 'percent' ? payload.percentValue : null,
        percent_sub_event_ids: payload.amountType === 'percent' ? payload.percentSubEventIds : [],
        gross_amount_cents: payload.grossCents, fee_amount_cents: payload.feeCents, net_amount_cents: payload.netCents, status: payload.status,
      }, adminId);
      else await window.createPayoutBatchLive(payload, adminId);
      setAddingPayout(false); setEditingPayout(null);
      reload();
    } catch (e) { setActionError('Could not save payout: ' + e.message); }
  }
  async function markPaid(payoutId) {
    try { await window.markPayoutPaidLive(payoutId, adminId); reload(); } catch (e) { setActionError('Could not mark paid: ' + e.message); }
  }
  async function cancelPayout(payoutId) {
    try { await window.updatePayoutLive(payoutId, { status: 'cancelled' }, adminId); reload(); } catch (e) { setActionError('Could not cancel: ' + e.message); }
  }
  async function deletePayout(payoutId) {
    if (!window.confirm('Delete this payout record? This cannot be undone.')) return;
    try { await window.deletePayoutLive(payoutId); reload(); } catch (e) { setActionError('Could not delete: ' + e.message); }
  }

  function exportCsv() {
    const rows = ['event,gross,refunds,status,purchased_on'].concat(scoped.map((o) => [o.eventTitle, o.amount, o.status, o.purchasedOn].join(',')));
    const blob = new Blob([rows.join('\n')], { type: 'text/csv' });
    const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = 'finances.csv'; a.click();
  }

  const tabs = [{ value: 'revenue', label: 'Revenue by event' }, { value: 'certs', label: 'Certificates renewal' }, { value: 'refunds', label: 'Refunds' }, { value: 'payouts', label: 'Payouts' }];

  const subTitleById = {};
  allSubEvents.forEach((s) => { subTitleById[s.sid] = s.title; });
  const payoutStatusTone = { not_initiated: 'default', pending: 'warning', paid: 'success', cancelled: 'error' };
  const payoutStatusLabel = { not_initiated: 'Not initiated', pending: 'Pending', paid: 'Paid', cancelled: 'Cancelled' };

  return (
    <div>
      <div style={{ display: 'flex', gap: 12, marginBottom: 20, alignItems: 'center', flexWrap: 'wrap' }}>
        <CustomSelect value={eventFilter} onChange={setEventFilter} placeholder="All events" width={200} options={mainEvents} />
        <CustomDatePicker value={startDate} onChange={setStartDate} placeholder="Purchased from" />
        <CustomDatePicker value={endDate} onChange={setEndDate} placeholder="to" />
        <Btn onClick={exportCsv}>Export CSV</Btn>
        {tab === 'revenue' && <ColumnPicker columns={REVENUE_COLUMNS} visible={revCols} onChange={setRevCols} />}
      </div>
      {loading ? <div style={{ padding: 32, textAlign: 'center', color: 'var(--text-muted)' }}>Loading…</div> : <>
      <div style={{ display: 'flex', gap: 16, marginBottom: 24, flexWrap: 'wrap' }}>
        <div style={{ flex: 1, minWidth: 180, background: 'var(--navy-700)', color: 'white', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-md)', padding: '16px 20px' }}>
          <div style={{ fontSize: 'var(--text-xs)', color: 'rgba(255,255,255,0.75)', textTransform: 'uppercase' }}>Gross revenue</div>
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 'var(--text-2xl)', fontWeight: 700 }}>{window.fmtUSD(totalRevenue)}</div>
        </div>
        <div style={{ flex: 1, minWidth: 180, background: 'var(--status-error)', color: 'white', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-md)', padding: '16px 20px' }}>
          <div style={{ fontSize: 'var(--text-xs)', color: 'rgba(255,255,255,0.75)', textTransform: 'uppercase' }}>Refunded</div>
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 'var(--text-2xl)', fontWeight: 700 }}>{window.fmtUSD(totalRefunds)}</div>
          <div style={{ fontSize: 'var(--text-xs)', color: 'rgba(255,255,255,0.75)' }}>{refunded.length} orders</div>
        </div>
        <div style={{ flex: 1, minWidth: 180, background: 'var(--navy-900)', color: 'white', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-md)', padding: '16px 20px' }}>
          <div style={{ fontSize: 'var(--text-xs)', color: 'rgba(255,255,255,0.75)', textTransform: 'uppercase' }}>Platform fee ({feePercent}%)</div>
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 'var(--text-2xl)', fontWeight: 700 }}>{window.fmtUSD(motiveoCut)}</div>
        </div>
        <div style={{ flex: 1, minWidth: 180, background: 'var(--status-success)', color: 'white', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-md)', padding: '16px 20px' }}>
          <div style={{ fontSize: 'var(--text-xs)', color: 'rgba(255,255,255,0.75)', textTransform: 'uppercase' }}>Net after fees</div>
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 'var(--text-2xl)', fontWeight: 700 }}>{window.fmtUSD(net)}</div>
          <div style={{ fontSize: 'var(--text-xs)', color: 'rgba(255,255,255,0.75)' }}>Gross - Refunded - Fee - Payouts</div>
        </div>
      </div>

      <div style={{ marginBottom: 20 }}><Finances_Tab tabs={tabs} active={tab} onChange={setTab} /></div>

      {tab === 'revenue' && (
        <div style={{ background: 'white', border: '1px solid var(--border-default)', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-sm)', overflow: 'hidden' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 'var(--text-sm)' }}>
            <thead><tr style={{ textAlign: 'left', background: 'var(--bg-sunken)', color: 'var(--text-muted)', fontSize: 'var(--text-xs)', textTransform: 'uppercase' }}>
              {revCols.includes('event') && <th style={{ padding: '12px 16px' }}>Event</th>}
              {revCols.includes('orders') && <th>Orders</th>}
              {revCols.includes('gross') && <th>Gross revenue</th>}
              {revCols.includes('refunds') && <th>Refunds</th>}
              {revCols.includes('net') && <th>Net revenue</th>}
            </tr></thead>
            <tbody>
              {Object.keys(byMain).map((mid) => {
                const m = byMain[mid];
                const isOpen = !!expanded[mid];
                return (
                  <React.Fragment key={mid}>
                    <tr className="ud-row" style={{ borderTop: '1px solid var(--border-default)', background: 'var(--bg-sunken)', cursor: 'pointer' }} onClick={() => setExpanded((e) => ({ ...e, [mid]: !e[mid] }))}>
                      <td style={{ padding: '12px 16px', fontWeight: 700, display: 'flex', alignItems: 'center', gap: 8 }}>
                        <window.UdUI.ChevronIcon open={isOpen} />
                        {revCols.includes('event') ? m.title : null}
                      </td>
                      {revCols.includes('orders') && <td>{m.count}</td>}
                      {revCols.includes('gross') && <td>{window.fmtUSD(m.gross)}</td>}
                      {revCols.includes('refunds') && <td style={{ color: 'var(--status-error)' }}>-{window.fmtUSD(m.refunds)}</td>}
                      {revCols.includes('net') && <td style={{ fontWeight: 700 }}>{window.fmtUSD(m.gross - m.refunds)}</td>}
                    </tr>
                    {isOpen && Object.keys(m.subs).map((sid) => {
                      const s = m.subs[sid];
                      return (
                        <tr key={sid} className="ud-row" style={{ borderTop: '1px solid var(--border-default)' }}>
                          {revCols.includes('event') && <td style={{ padding: '10px 16px 10px 32px', color: 'var(--text-secondary)' }}>{s.title}</td>}
                          {revCols.includes('orders') && <td style={{ color: 'var(--text-secondary)' }}>{s.count}</td>}
                          {revCols.includes('gross') && <td style={{ color: 'var(--text-secondary)' }}>{window.fmtUSD(s.gross)}</td>}
                          {revCols.includes('refunds') && <td style={{ color: 'var(--status-error)' }}>-{window.fmtUSD(s.refunds)}</td>}
                          {revCols.includes('net') && <td style={{ color: 'var(--text-secondary)' }}>{window.fmtUSD(s.gross - s.refunds)}</td>}
                        </tr>
                      );
                    })}
                  </React.Fragment>
                );
              })}
              {Object.keys(byMain).length === 0 && <tr><td colSpan={5} style={{ padding: 16, color: 'var(--text-muted)' }}>No orders in range.</td></tr>}
            </tbody>
          </table>
        </div>
      )}

      {tab === 'certs' && (
        <div>
          <div style={{ display: 'flex', gap: 16, marginBottom: 20, flexWrap: 'wrap' }}>
            <div style={{ flex: 1, minWidth: 160, background: 'white', border: '1px solid var(--border-default)', borderRadius: 'var(--radius-lg)', padding: '16px 20px' }}>
              <div style={{ fontSize: 'var(--text-xs)', color: 'var(--text-muted)', textTransform: 'uppercase' }}>Active</div>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 'var(--text-2xl)', fontWeight: 700 }}>{certActive}</div>
            </div>
            <div style={{ flex: 1, minWidth: 160, background: 'white', border: '1px solid var(--border-default)', borderRadius: 'var(--radius-lg)', padding: '16px 20px' }}>
              <div style={{ fontSize: 'var(--text-xs)', color: 'var(--text-muted)', textTransform: 'uppercase' }}>Expiring soon</div>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 'var(--text-2xl)', fontWeight: 700, color: 'var(--status-warning)' }}>{certExpiring.length}</div>
            </div>
            <div style={{ flex: 1, minWidth: 160, background: 'white', border: '1px solid var(--border-default)', borderRadius: 'var(--radius-lg)', padding: '16px 20px' }}>
              <div style={{ fontSize: 'var(--text-xs)', color: 'var(--text-muted)', textTransform: 'uppercase' }}>Expired</div>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 'var(--text-2xl)', fontWeight: 700, color: 'var(--status-error)' }}>{certExpired.length}</div>
            </div>
            <div style={{ flex: 1, minWidth: 200, background: 'var(--navy-900)', color: 'white', borderRadius: 'var(--radius-lg)', padding: '16px 20px' }}>
              <div style={{ fontSize: 'var(--text-xs)', color: 'rgba(255,255,255,0.75)', textTransform: 'uppercase' }}>Renewal revenue opportunity</div>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 'var(--text-2xl)', fontWeight: 700 }}>{window.fmtUSD(dueForRenewal.length * RENEWAL_FEE_MIN)} – {window.fmtUSD(dueForRenewal.length * RENEWAL_FEE_MAX)}</div>
              <div style={{ fontSize: 'var(--text-xs)', color: 'rgba(255,255,255,0.75)' }}>{dueForRenewal.length} certificates · ₱500 - ₱2,500 renewal fee each</div>
            </div>
          </div>
          <div className="ud-scroll" style={{ background: 'white', border: '1px solid var(--border-default)', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-sm)', overflowX: 'auto', overflowY: 'hidden' }}>
            <table style={{ width: '100%', minWidth: 600, borderCollapse: 'collapse', fontSize: 'var(--text-sm)' }}>
              <thead><tr style={{ textAlign: 'left', background: 'var(--bg-sunken)', color: 'var(--text-muted)', fontSize: 'var(--text-xs)', textTransform: 'uppercase' }}>
                <th style={{ padding: '12px 16px' }}>Attendee</th><th>Event</th><th>Expires</th><th>Status</th><th>Renewal fee</th><th></th>
              </tr></thead>
              <tbody>
                {dueForRenewal.map((c) => (
                  <tr key={c.id} className="ud-row" style={{ borderTop: '1px solid var(--border-default)' }}>
                    <td style={{ padding: '12px 16px', fontWeight: 600 }}>{c.name}</td>
                    <td style={{ color: 'var(--text-secondary)' }}>{c.eventTitle}</td>
                    <td style={{ color: 'var(--text-muted)', fontSize: 'var(--text-xs)' }}>{new Date(c.expiresAt).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}</td>
                    <td><Badge tone={certRenewStatus(c.expiresAt) === 'expired' ? 'error' : 'warning'}>{certRenewStatus(c.expiresAt) === 'expired' ? 'Expired' : 'Expiring soon'}</Badge></td>
                    <td>₱500 - ₱2,500</td>
                    <td style={{ textAlign: 'right', paddingRight: 16 }}><Btn size="sm" variant="secondary" onClick={() => renewCert(c.id)}>Renew</Btn></td>
                  </tr>
                ))}
                {dueForRenewal.length === 0 && <tr><td colSpan={6} style={{ padding: 16, color: 'var(--text-muted)' }}>No certificates due for renewal.</td></tr>}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {tab === 'refunds' && (
        <div style={{ background: 'white', border: '1px solid var(--border-default)', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-sm)', overflow: 'hidden' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 'var(--text-sm)' }}>
            <thead><tr style={{ textAlign: 'left', background: 'var(--bg-sunken)', color: 'var(--text-muted)', fontSize: 'var(--text-xs)', textTransform: 'uppercase' }}>
              <th style={{ padding: '12px 16px' }}>Ref</th><th>Event</th><th>Amount</th><th>Date</th>
            </tr></thead>
            <tbody>
              {refunded.map((o) => (
                <tr key={o.ref} className="ud-row" style={{ borderTop: '1px solid var(--border-default)' }}>
                  <td style={{ padding: '12px 16px', fontFamily: 'var(--font-mono)', fontSize: 'var(--text-xs)' }}>{o.ref}</td>
                  <td style={{ color: 'var(--text-secondary)' }}>{o.eventTitle}</td>
                  <td>{window.fmtUSD(o.originalAmount)}</td><td>{new Date(o.purchasedOn).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}</td>
                </tr>
              ))}
              {refunded.length === 0 && <tr><td colSpan={4} style={{ padding: 16, color: 'var(--text-muted)' }}>No refunds recorded.</td></tr>}
            </tbody>
          </table>
        </div>
      )}

      {tab === 'payouts' && (
        <div>
          <div style={{ marginBottom: 14 }}>
            <Btn onClick={() => setAddingPayout(true)}>+ Add payout</Btn>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            {payouts.map((p) => (
              <div key={p.id} style={{ background: 'white', border: '1px solid var(--border-default)', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-sm)', padding: '18px 20px', display: 'flex', flexDirection: 'column', gap: 12 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 16, flexWrap: 'wrap' }}>
                  <div>
                    <div style={{ fontWeight: 700, fontSize: 'var(--text-base)' }}>{p.payeeName}</div>
                    {p.payeeDescription && <div style={{ color: 'var(--text-muted)', fontSize: 'var(--text-sm)', marginTop: 2 }}>{p.payeeDescription}</div>}
                  </div>
                  <Badge tone={payoutStatusTone[p.status]}>{payoutStatusLabel[p.status]}</Badge>
                </div>
                <div style={{ fontSize: 'var(--text-sm)', color: 'var(--text-secondary)' }}>
                  <span style={{ color: 'var(--text-muted)' }}>Events: </span>{(p.subEventIds || []).map((sid) => subTitleById[sid] || sid).join(', ') || '\u2014'}
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', flexWrap: 'wrap', gap: 12, borderTop: '1px solid var(--border-default)', paddingTop: 12 }}>
                  <div>
                    <div style={{ fontFamily: 'var(--font-display)', fontSize: 'var(--text-xl)', fontWeight: 700 }}>{window.fmtUSD(p.net)}</div>
                    {p.amountType === 'percent' && <div style={{ color: 'var(--text-muted)', fontSize: 'var(--text-xs)' }}>{p.percentValue}% of {(p.percentSubEventIds || []).map((sid) => subTitleById[sid] || sid).join(', ')}{p.status !== 'paid' && p.status !== 'cancelled' ? ' · live' : ''}</div>}
                    <div style={{ color: 'var(--text-muted)', fontSize: 'var(--text-xs)', marginTop: 4 }}>Created {new Date(p.createdAt).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })} · Updated {new Date(p.updatedAt).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}</div>
                  </div>
                  <div style={{ display: 'flex', gap: 8 }}>
                    <Btn size="sm" variant="secondary" onClick={() => setEditingPayout(p)}>Edit</Btn>
                    {(p.status === 'pending' || p.status === 'not_initiated') && <Btn size="sm" onClick={() => markPaid(p.id)}>Mark as paid</Btn>}
                    {p.status !== 'paid' && p.status !== 'cancelled' && <Btn size="sm" variant="danger" onClick={() => cancelPayout(p.id)}>Cancel</Btn>}
                    <Btn size="sm" variant="danger" onClick={() => deletePayout(p.id)}>Delete</Btn>
                  </div>
                </div>
              </div>
            ))}
            {payouts.length === 0 && <div style={{ background: 'white', border: '1px solid var(--border-default)', borderRadius: 'var(--radius-lg)', padding: 24, textAlign: 'center', color: 'var(--text-muted)' }}>No payouts yet.</div>}
          </div>
        </div>
      )}
      </>}
      <AddPayoutDialog open={addingPayout || !!editingPayout} initial={editingPayout} subOptions={allSubEvents.map((s) => ({ value: s.sid, label: s.title, gross: ((byMain[Object.keys(byMain).find((m) => byMain[m].subs[s.sid])] || {}).subs || {})[s.sid] ? byMain[Object.keys(byMain).find((m) => byMain[m].subs[s.sid])].subs[s.sid].gross : 0 }))} feePercent={feePercent} onClose={() => { setAddingPayout(false); setEditingPayout(null); }} onSave={addPayout} />
      {actionError && <div style={{ position: 'fixed', bottom: 24, left: 24, zIndex: 1200, background: 'var(--status-error-bg)', color: 'var(--status-error)', padding: '10px 16px', borderRadius: 'var(--radius-md)', fontSize: 'var(--text-sm)' }} onClick={() => setActionError('')}>{actionError} (click to dismiss)</div>}
    </div>
  );
}

window.FinancesScreen = FinancesScreen;
