// screens-c.jsx — Money + Admin

// ── Bar chart ─────────────────────────────────────────────────────────────────
function BarChart() {
  const months = ['Mar', 'Apr', 'May', 'Jun'];
  const revenue = [3200, 0, 1200, 8400];
  const expense = [980, 450, 300, 2100];
  const max = 9000;
  const W = 400, H = 160, BAR = 28, GAP = 6, GRP = 80;
  const scale = h => (h / max) * H;

  return (
    <div style={{ overflowX: 'auto' }}>
      <svg width={W} height={H + 40} viewBox={`0 0 ${W} ${H + 40}`} style={{ display: 'block', maxWidth: '100%' }}>
        {/* Y-axis labels */}
        {[0, 3000, 6000, 9000].map(v => {
          const y = H - scale(v);
          return (
            <g key={v}>
              <line x1={36} y1={y} x2={W - 10} y2={y} stroke="#f0f0f0" strokeWidth={1} />
              <text x={32} y={y + 4} textAnchor="end" fontSize={10} fill="#9ca3af">${v/1000}k</text>
            </g>
          );
        })}
        {/* Bars */}
        {months.map((m, i) => {
          const x = 44 + i * GRP;
          const rh = scale(revenue[i]);
          const eh = scale(expense[i]);
          return (
            <g key={m}>
              <rect x={x} y={H - rh} width={BAR} height={rh || 1} fill="#3a5ca8" rx={3} />
              <rect x={x + BAR + GAP} y={H - eh} width={BAR} height={eh || 1} fill="#fca5a5" rx={3} />
              <text x={x + BAR} y={H + 18} textAnchor="middle" fontSize={11} fill="#6b7280">{m}</text>
            </g>
          );
        })}
        {/* Legend */}
        <rect x={44} y={H + 28} width={10} height={10} fill="#3a5ca8" rx={2} />
        <text x={58} y={H + 37} fontSize={11} fill="#6b7280">Revenue</text>
        <rect x={120} y={H + 28} width={10} height={10} fill="#fca5a5" rx={2} />
        <text x={134} y={H + 37} fontSize={11} fill="#6b7280">Expense</text>
      </svg>
    </div>
  );
}

window.MoneyScreen = function MoneyScreen({ screen, setScreen, role }) {
  const [moneyData, setMoneyData] = React.useState(DATA.money);
  const [showAdd, setShowAdd] = React.useState(false);
  const [addForm, setAddForm] = React.useState({ kind: 'revenue', source: '', event: '', amount: '' });

  const approved = moneyData.filter(e => e.status === 'approved');
  const totalRev = approved.filter(e => e.kind === 'revenue').reduce((s, e) => s + e.amount, 0);
  const totalExp = approved.filter(e => e.kind === 'expense').reduce((s, e) => s + e.amount, 0);
  const net = totalRev - totalExp;

  const canEdit = role === 'admin' || role === 'editor';

  function approve(id) {
    setMoneyData(d => d.map(e => e.id === id ? {...e, status: 'approved'} : e));
  }
  function reject(id) {
    setMoneyData(d => d.map(e => e.id === id ? {...e, status: 'rejected'} : e));
  }

  const fundraiserEvents = DATA.events.filter(e => e.fundraiser);

  return (
    <AppShell screen={screen} setScreen={setScreen} role={role}>
      <div className="page-header">
        <h1>Money</h1>
        {canEdit && <Btn variant="primary" onClick={() => setShowAdd(true)}>+ Add Entry</Btn>}
      </div>

      {/* Summary tiles */}
      <div className="stat-grid">
        <StatTile label="Total Revenue" value={fmt(totalRev)} accentValue />
        <StatTile label="Total Expenses" value={fmt(totalExp)} />
        <StatTile label="Net Profit" value={fmt(net)} sub="approved entries only" accentValue={net > 0} />
      </div>

      {/* Chart */}
      <div className="card">
        <div className="card-header"><span className="card-title">Revenue vs Expenses</span></div>
        <BarChart />
      </div>

      {/* Which events earn */}
      <div className="card">
        <div className="card-header"><span className="card-title">Which events earn?</span></div>
        <table>
          <thead>
            <tr><th>Event</th><th>Revenue</th><th>Expenses</th><th>Net Profit</th></tr>
          </thead>
          <tbody>
            {fundraiserEvents
              .map(e => ({ ...e, net: e.revenue - e.expense }))
              .sort((a, b) => b.net - a.net)
              .map(e => (
                <tr key={e.id} className="no-hover">
                  <td style={{ fontWeight: 500 }}>{e.title}</td>
                  <td className="kind-revenue">{fmt(e.revenue)}</td>
                  <td className="kind-expense">{fmt(e.expense)}</td>
                  <td className={e.net >= 0 ? 'profit-positive' : 'profit-negative'}>{fmt(e.net)}</td>
                </tr>
              ))
            }
          </tbody>
        </table>
      </div>

      {/* Ledger */}
      <div className="card-header" style={{ marginBottom: '0.5rem' }}>
        <span className="card-title">Ledger</span>
      </div>
      <div className="table-wrap">
        <table>
          <thead>
            <tr><th>Date</th><th>Source</th><th>Event</th><th>Kind</th><th>Amount</th><th>Status</th>{role === 'admin' && <th></th>}</tr>
          </thead>
          <tbody>
            {moneyData.map(e => (
              <tr key={e.id} className="no-hover">
                <td style={{ color: '#6b7280', whiteSpace: 'nowrap' }}>{e.date}</td>
                <td style={{ fontWeight: 500 }}>{e.source}</td>
                <td style={{ color: '#6b7280' }}>{e.event}</td>
                <td><span className={e.kind === 'revenue' ? 'kind-revenue' : 'kind-expense'}>{e.kind}</span></td>
                <td style={{ fontWeight: 600 }}>{fmt(e.amount)}</td>
                <td><StatusBadge status={e.status} /></td>
                {role === 'admin' && (
                  <td>
                    {e.status === 'pending' && (
                      <div style={{ display: 'flex', gap: '0.3rem' }}>
                        <Btn variant="success" size="sm" onClick={() => approve(e.id)}>Approve</Btn>
                        <Btn variant="danger" size="sm" onClick={() => reject(e.id)}>Reject</Btn>
                      </div>
                    )}
                  </td>
                )}
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* Add entry modal */}
      <Modal open={showAdd} onClose={() => setShowAdd(false)} title="Add Money Entry"
        footer={
          <>
            <Btn variant="ghost" onClick={() => setShowAdd(false)}>Cancel</Btn>
            <Btn variant="primary" onClick={() => setShowAdd(false)}>Save Entry</Btn>
          </>
        }
      >
        <div style={{ display: 'flex', gap: '0.5rem', marginBottom: '1rem' }}>
          <button onClick={() => setAddForm(f => ({...f, kind:'revenue'}))}
            style={{ flex: 1, padding: '0.5rem', border: '2px solid', borderRadius: 8, cursor: 'pointer', fontWeight: 500, fontSize: '0.875rem', background: addForm.kind==='revenue' ? '#dcfce7' : 'white', color: addForm.kind==='revenue' ? '#16a34a' : '#6b7280', borderColor: addForm.kind==='revenue' ? '#16a34a' : '#dde1e9' }}>
            Revenue
          </button>
          <button onClick={() => setAddForm(f => ({...f, kind:'expense'}))}
            style={{ flex: 1, padding: '0.5rem', border: '2px solid', borderRadius: 8, cursor: 'pointer', fontWeight: 500, fontSize: '0.875rem', background: addForm.kind==='expense' ? '#fee2e2' : 'white', color: addForm.kind==='expense' ? '#dc2626' : '#6b7280', borderColor: addForm.kind==='expense' ? '#dc2626' : '#dde1e9' }}>
            Expense
          </button>
        </div>
        <div className="form-group"><label>Source / Description</label><input placeholder="e.g. Ticket Sales" value={addForm.source} onChange={e => setAddForm(f => ({...f, source: e.target.value}))} /></div>
        <div className="form-group"><label>Linked Event (optional)</label>
          <select value={addForm.event} onChange={e => setAddForm(f => ({...f, event: e.target.value}))}>
            <option value="">— none —</option>
            {DATA.events.map(ev => <option key={ev.id} value={ev.id}>{ev.title}</option>)}
          </select>
        </div>
        <div className="form-group"><label>Amount ($)</label><input type="number" placeholder="0.00" value={addForm.amount} onChange={e => setAddForm(f => ({...f, amount: e.target.value}))} /></div>
      </Modal>
    </AppShell>
  );
};

// ── Admin screen ──────────────────────────────────────────────────────────────
const CAPABILITIES = [
  { label: 'View dashboard / club stats',  admin: true, editor: true,  member: true,  viewer: true  },
  { label: 'RSVP to events',               admin: true, editor: true,  member: true,  viewer: false },
  { label: 'Edit own profile',             admin: true, editor: true,  member: true,  viewer: false },
  { label: 'Create / edit events',         admin: true, editor: true,  member: false, viewer: false },
  { label: 'Add money entries',            admin: true, editor: true,  member: false, viewer: false },
  { label: 'Approve money entries',        admin: true, editor: false, member: false, viewer: false },
  { label: 'Add / remove members',         admin: true, editor: false, member: false, viewer: false },
  { label: 'Assign roles',                 admin: true, editor: false, member: false, viewer: false },
  { label: 'Club settings & CSV export',   admin: true, editor: false, member: false, viewer: false },
];

window.AdminScreen = function AdminScreen({ screen, setScreen, role }) {
  const [tab, setTab] = React.useState('people');
  const [showInvite, setShowInvite] = React.useState(false);
  const [approvals, setApprovals] = React.useState(DATA.money.filter(e => e.status === 'pending'));
  const [toast, setToast] = React.useState('');
  const [settings, setSettings] = React.useState({ requireApproval: true, membersRevenue: false, clubName: 'The Lions', currency: 'USD' });

  function showToast(msg) {
    setToast(msg);
    setTimeout(() => setToast(''), 2500);
  }

  function approveEntry(id) {
    setApprovals(a => a.filter(e => e.id !== id));
    showToast('Entry approved ✓');
  }
  function rejectEntry(id) {
    setApprovals(a => a.filter(e => e.id !== id));
    showToast('Entry rejected');
  }

  const tabs = ['people', 'permissions', 'approvals', 'settings'];

  return (
    <AppShell screen={screen} setScreen={setScreen} role={role}>
      <div className="page-header"><h1>Admin Console</h1></div>

      <div className="tab-bar">
        {tabs.map(t => (
          <button key={t} className={`tab-btn${tab === t ? ' active' : ''}`} onClick={() => setTab(t)}>
            {t.charAt(0).toUpperCase() + t.slice(1)}
            {t === 'approvals' && approvals.length > 0 && (
              <span style={{ marginLeft: '0.4rem', background: '#dc2626', color: 'white', borderRadius: 999, padding: '0 5px', fontSize: '0.7rem', fontWeight: 700 }}>{approvals.length}</span>
            )}
          </button>
        ))}
      </div>

      {/* People tab */}
      {tab === 'people' && (
        <>
          <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: '1rem' }}>
            <Btn variant="primary" onClick={() => setShowInvite(true)}>+ Invite Member</Btn>
          </div>
          <div className="table-wrap">
            <table>
              <thead>
                <tr><th>Name</th><th>Email</th><th>Chapter</th><th>Role</th><th></th></tr>
              </thead>
              <tbody>
                {DATA.members.map(m => (
                  <tr key={m.id} className="no-hover">
                    <td>
                      <div style={{ display: 'flex', alignItems: 'center', gap: '0.6rem' }}>
                        <Avatar name={m.name} />
                        <div>
                          <div style={{ fontWeight: 500 }}>{m.name}</div>
                          {m.status === 'invited' && <StatusBadge status="invited" />}
                        </div>
                      </div>
                    </td>
                    <td style={{ color: '#6b7280', fontSize: '0.85rem' }}>{m.email}</td>
                    <td style={{ color: '#6b7280' }}>{m.chapter}</td>
                    <td>
                      <select style={{ border: '1px solid #dde1e9', borderRadius: 6, padding: '0.25rem 0.5rem', fontSize: '0.85rem', background: 'white' }}>
                        {['admin','editor','member','viewer'].map(r => <option key={r} selected={r===m.role}>{r}</option>)}
                      </select>
                    </td>
                    <td>
                      {m.id !== 1 && (
                        <Btn variant="ghost" size="sm" style={{ color: '#dc2626' }}>Remove</Btn>
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          <Modal open={showInvite} onClose={() => setShowInvite(false)} title="Invite Member"
            footer={
              <>
                <Btn variant="ghost" onClick={() => setShowInvite(false)}>Cancel</Btn>
                <Btn variant="primary" onClick={() => { setShowInvite(false); showToast('Invite sent ✓'); }}>Send Invite</Btn>
              </>
            }
          >
            <div className="form-group"><label>Full Name</label><input placeholder="e.g. Jane Smith" /></div>
            <div className="form-group"><label>Email Address</label><input type="email" placeholder="jane@example.com" /></div>
            <div className="form-group">
              <label>Role</label>
              <select><option>Editor</option><option>Member</option><option>Viewer</option></select>
            </div>
            <p style={{ fontSize: '0.8rem', color: '#6b7280' }}>An invite link will be emailed, valid for 7 days.</p>
          </Modal>
        </>
      )}

      {/* Permissions tab */}
      {tab === 'permissions' && (
        <>
          <div className="table-wrap">
            <table>
              <thead>
                <tr>
                  <th style={{ width: '40%' }}>Capability</th>
                  <th style={{ textAlign: 'center' }}>Admin</th>
                  <th style={{ textAlign: 'center' }}>Editor</th>
                  <th style={{ textAlign: 'center' }}>Member</th>
                  <th style={{ textAlign: 'center' }}>Viewer</th>
                </tr>
              </thead>
              <tbody>
                {CAPABILITIES.map((cap, i) => (
                  <tr key={i} className="no-hover">
                    <td style={{ fontSize: '0.875rem' }}>{cap.label}</td>
                    {['admin','editor','member','viewer'].map(r => (
                      <td key={r} style={{ textAlign: 'center' }}>
                        {cap[r]
                          ? <span className="matrix-check">✓</span>
                          : <span className="matrix-dash">—</span>}
                      </td>
                    ))}
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          <div className="info-note">Permissions are enforced server-side. The client UI only hides controls — access is always validated on the server.</div>
        </>
      )}

      {/* Approvals tab */}
      {tab === 'approvals' && (
        approvals.length === 0
          ? <EmptyState icon="✓" title="All clear" sub="No pending money entries." />
          : (
            <div className="table-wrap">
              <table>
                <thead>
                  <tr><th>Source</th><th>Event</th><th>Amount</th><th>Submitted by</th><th>Date</th><th></th></tr>
                </thead>
                <tbody>
                  {approvals.map(e => (
                    <tr key={e.id} className="no-hover">
                      <td style={{ fontWeight: 500 }}>{e.source}</td>
                      <td style={{ color: '#6b7280' }}>{e.event}</td>
                      <td style={{ fontWeight: 600 }}>{fmt(e.amount)}</td>
                      <td style={{ color: '#6b7280' }}>{e.by}</td>
                      <td style={{ color: '#6b7280' }}>{e.date}</td>
                      <td>
                        <div style={{ display: 'flex', gap: '0.3rem' }}>
                          <Btn variant="success" size="sm" onClick={() => approveEntry(e.id)}>Approve</Btn>
                          <Btn variant="danger" size="sm" onClick={() => rejectEntry(e.id)}>Reject</Btn>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )
      )}

      {/* Settings tab */}
      {tab === 'settings' && (
        <div style={{ maxWidth: 560 }}>
          <div className="card">
            <div className="card-header"><span className="card-title">Club Profile</span></div>
            <div className="form-group"><label>Club Name</label><input value={settings.clubName} onChange={e => setSettings(s => ({...s, clubName: e.target.value}))} /></div>
            <div className="form-row">
              <div className="form-group">
                <label>Currency</label>
                <select value={settings.currency} onChange={e => setSettings(s => ({...s, currency: e.target.value}))}>
                  <option value="USD">USD — US Dollar</option>
                  <option value="AUD">AUD — Australian Dollar</option>
                  <option value="GBP">GBP — British Pound</option>
                  <option value="EUR">EUR — Euro</option>
                </select>
              </div>
              <div className="form-group">
                <label>Timezone</label>
                <select><option>America/New_York</option><option>America/Los_Angeles</option><option>Australia/Sydney</option><option>Europe/London</option></select>
              </div>
            </div>
          </div>

          <div className="card">
            <div className="card-header"><span className="card-title">Access Controls</span></div>
            <div className="switch-label">
              <div>
                <div className="switch-text">Require approval for money entries</div>
                <div className="switch-sub">Editor-submitted entries go to pending until an Admin approves.</div>
              </div>
              <Toggle on={settings.requireApproval} onToggle={() => setSettings(s => ({...s, requireApproval: !s.requireApproval}))} />
            </div>
            <div className="switch-label">
              <div>
                <div className="switch-text">Members can see revenue totals</div>
                <div className="switch-sub">Allow Member and Viewer roles to see financial summaries.</div>
              </div>
              <Toggle on={settings.membersRevenue} onToggle={() => setSettings(s => ({...s, membersRevenue: !s.membersRevenue}))} />
            </div>
          </div>

          <div style={{ display: 'flex', gap: '0.75rem', marginTop: '0.25rem' }}>
            <Btn variant="primary" onClick={() => showToast('Settings saved ✓')}>Save Settings</Btn>
            <Btn variant="secondary">Export CSV</Btn>
          </div>
        </div>
      )}

      <Toast msg={toast} />
    </AppShell>
  );
};
