// screens-admin.jsx — admin-facing screens (still on phone, but desktop-ish density)
// Members directory, add visitor, events, reports
const { useState: useStateA } = React;
const DA = window.BHCAC_DATA;

// ── Admin shell ──
function ScreenAdmin({ user, onBack, members, checkIns, events = [], onAddVisitor, onSyncOutline, onExportCSV, onAdminCheckIn, onUpdateMember, onDeleteMember, onCreateEvent, onUpdateEvent, onDeleteEvent, onImportEvents, onExportReport }) {
  const [tab, setTab] = useStateA('members');
  const today = new Date().toISOString().slice(0, 10);
  const todayRecords = checkIns.filter(c => c.date === today);
  const totalMembers = members.length;
  const monthStart = today.slice(0, 7) + '-01';
  const newThisMonth = members.filter(m => (m.addedAt || '') >= monthStart).length;
  const greetName = (user?.en?.split(' ')[0]) || 'admin';

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: 'var(--bg-2)' }}>
      {/* Header */}
      <div className="admin-header" style={{
        padding: '60px 20px 20px',
        background: 'var(--brand-navy)',
        color: '#fff',
        position: 'relative', overflow: 'hidden',
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 18 }}>
          <CircleBtn icon="chevron-left" onClick={onBack} dark />
          <Pill tone="coral" style={{ background: 'rgba(244,63,94,0.2)', color: '#fecdd3' }}>Admin · 管理員</Pill>
        </div>
        <h1 style={{ fontSize: 26, fontWeight: 700, letterSpacing: '-0.02em', margin: 0, color: '#fff' }}>
          Welcome, {greetName}
        </h1>
        {user?.zh && (
          <div style={{ fontFamily: "'Noto Sans TC', sans-serif", color: 'rgba(255,255,255,0.7)', fontSize: 15, marginTop: 4 }}>
            {user.zh}，歡迎
          </div>
        )}

        {/* KPI strip — computed from real data */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 8, marginTop: 22 }}>
          <KPI value={String(todayRecords.length)} label="Today · 今日" sub={totalMembers > 0 ? `of ${totalMembers} members` : 'no members yet'} />
          <KPI value={newThisMonth > 0 ? `+${newThisMonth}` : '0'} label="New this month · 本月新增" sub="visitors & members" coral />
        </div>
      </div>

      {/* Tabs */}
      <div style={{ display: 'flex', gap: 4, padding: '12px 16px', background: 'var(--bg-1)', borderBottom: '1px solid var(--border-subtle)' }}>
        {[
          { id: 'members', en: 'Members', zh: '會友', icon: 'users' },
          { id: 'events',  en: 'Events',  zh: '活動', icon: 'calendar' },
          { id: 'reports', en: 'Reports', zh: '報告', icon: 'bar-chart' },
          { id: 'admins',  en: 'Admins',  zh: '管理員', icon: 'settings' },
        ].map(t => (
          <button key={t.id} onClick={() => setTab(t.id)} style={{
            flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
            padding: '8px 0', background: 'transparent', border: 'none', cursor: 'pointer',
            color: tab === t.id ? 'var(--brand-coral)' : 'var(--fg-3)',
            fontWeight: tab === t.id ? 700 : 500,
            borderRadius: 8,
            position: 'relative',
          }}>
            <Icon name={t.icon} size={18} strokeWidth={tab === t.id ? 2.4 : 2} />
            <span style={{ fontSize: 11 }}>{t.en} · {t.zh}</span>
            {tab === t.id && <div style={{ position: 'absolute', bottom: -12, left: '20%', right: '20%', height: 2, background: 'var(--brand-coral)', borderRadius: 2 }} />}
          </button>
        ))}
      </div>

      {/* Tab content */}
      <div className="admin-tab-content" style={{ flex: 1, overflowY: 'auto' }}>
        {tab === 'members' && <AdminMembers members={members} checkIns={checkIns} onAddVisitor={onAddVisitor} onExportCSV={onExportCSV} onAdminCheckIn={onAdminCheckIn} onUpdateMember={onUpdateMember} onDeleteMember={onDeleteMember} />}
        {tab === 'events'  && <AdminEvents events={events} onSyncOutline={onSyncOutline} onCreateEvent={onCreateEvent} onUpdateEvent={onUpdateEvent} onDeleteEvent={onDeleteEvent} onImportEvents={onImportEvents} />}
        {tab === 'reports' && <AdminReports members={members} checkIns={checkIns} events={events} onSyncOutline={onSyncOutline} onExportReport={onExportReport} />}
        {tab === 'admins'  && <AdminAdmins />}
      </div>
    </div>
  );
}

function MemberEditModal({ member, onCancel, onSave }) {
  const [form, setForm] = useStateA({
    en: member.en || '',
    zh: member.zh || '',
    role: member.role || '',
    congregation: member.congregation || 'cantonese',
    pref: member.pref || 'online',
    phone: member.phone || '',
    email: member.email || '',
  });
  const [saving, setSaving] = useStateA(false);
  const [error, setError] = useStateA(null);
  const update = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const submit = async (e) => {
    e.preventDefault();
    setError(null);
    if (!form.en.trim()) { setError('Name is required.'); return; }
    setSaving(true);
    try { await onSave(form); }
    catch (err) { setError(err.message); setSaving(false); }
  };

  const inputStyle = {
    width: '100%', boxSizing: 'border-box',
    padding: '11px 14px', borderRadius: 12,
    border: '1px solid var(--border-strong)',
    background: 'var(--bg-1)', fontSize: 14, fontFamily: 'Inter, sans-serif',
    outline: 'none',
  };

  return (
    <div onClick={onCancel} style={{
      position: 'fixed', inset: 0, zIndex: 9000,
      background: 'rgba(15,23,42,0.55)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: 16,
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        background: 'var(--bg-1)', borderRadius: 16,
        width: '100%', maxWidth: 460,
        maxHeight: '90vh', overflowY: 'auto',
        boxShadow: 'var(--shadow-2xl)',
      }}>
        <div style={{ padding: '18px 20px 14px', borderBottom: '1px solid var(--border-subtle)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div>
            <Eyebrow style={{ marginBottom: 4 }}>Edit member · 編輯會友</Eyebrow>
            <div style={{ fontSize: 12, color: 'var(--fg-3)' }}>{member.id}</div>
          </div>
          <CircleBtn icon="x" onClick={onCancel} />
        </div>
        <form onSubmit={submit} style={{ padding: 18, display: 'flex', flexDirection: 'column', gap: 10 }}>
          <input style={inputStyle} type="text" placeholder="Name (EN) · 英文姓名"
            value={form.en} onChange={e => update('en', e.target.value)} required />
          <input style={inputStyle} type="text" placeholder="Name (中文) · 中文姓名"
            value={form.zh} onChange={e => update('zh', e.target.value)} />
          <input style={inputStyle} type="text" placeholder="Role (Father/Mother/Member/etc.) · 身份"
            value={form.role} onChange={e => update('role', e.target.value)} />
          <select style={inputStyle} value={form.congregation} onChange={e => update('congregation', e.target.value)}>
            {DA.congregations.map(c => <option key={c.id} value={c.id}>{c.en} · {c.zh}</option>)}
          </select>
          <div style={{ display: 'flex', gap: 8 }}>
            {[
              { id: 'online', label: 'Online · 線上' },
              { id: 'paper',  label: 'Paper · 紙本' },
            ].map(p => (
              <button key={p.id} type="button" onClick={() => update('pref', p.id)} style={{
                flex: 1, padding: '10px 12px', borderRadius: 12,
                background: form.pref === p.id ? 'var(--brand-warm)' : 'transparent',
                border: '1.5px solid ' + (form.pref === p.id ? 'var(--brand-coral)' : 'var(--border-subtle)'),
                fontSize: 13, fontWeight: 600, cursor: 'pointer',
              }}>{p.label}</button>
            ))}
          </div>
          <input style={inputStyle} type="tel" placeholder="Phone · 電話"
            value={form.phone} onChange={e => update('phone', e.target.value)} />
          <input style={inputStyle} type="email" placeholder="Email · 電郵"
            value={form.email} onChange={e => update('email', e.target.value)} />
          {error && <div style={{ fontSize: 12, color: 'var(--coral-700)', background: 'var(--coral-100)', padding: '8px 12px', borderRadius: 8 }}>{error}</div>}
          <div style={{ display: 'flex', gap: 8, marginTop: 6 }}>
            <Btn variant="outline" size="md" onClick={onCancel} type="button" style={{ flex: 1 }}>Cancel</Btn>
            <Btn variant="primary" size="md" type="submit" disabled={saving} style={{ flex: 2 }}>
              {saving ? 'Saving…' : 'Save · 儲存'}
            </Btn>
          </div>
        </form>
      </div>
    </div>
  );
}

function KPI({ value, label, sub, coral }) {
  return (
    <div style={{
      background: 'rgba(255,255,255,0.06)', backdropFilter: 'blur(8px)',
      border: '1px solid rgba(255,255,255,0.1)',
      borderRadius: 14, padding: '12px 12px 10px',
    }}>
      <div style={{ fontSize: 22, fontWeight: 700, letterSpacing: '-0.02em', color: coral ? 'var(--coral-400)' : '#fff' }}>{value}</div>
      <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: '0.08em', color: 'rgba(255,255,255,0.7)', textTransform: 'uppercase', marginTop: 2 }}>{label}</div>
      <div style={{ fontSize: 10, color: 'rgba(255,255,255,0.5)', marginTop: 2 }}>{sub}</div>
    </div>
  );
}

// ─── Members tab ───
function AdminMembers({ members, checkIns, onAddVisitor, onExportCSV, onAdminCheckIn, onUpdateMember, onDeleteMember }) {
  const [filter, setFilter] = useStateA('all'); // all | online | paper | here
  const [query, setQuery] = useStateA('');
  const [editingMember, setEditingMember] = useStateA(null);
  const today = new Date().toISOString().slice(0, 10);
  const checkedToday = new Set(checkIns.filter(c => c.date === today).map(c => c.member_id));

  const filtered = members.filter(m => {
    if (filter === 'online' && m.pref !== 'online') return false;
    if (filter === 'paper'  && m.pref !== 'paper') return false;
    if (filter === 'here'   && !checkedToday.has(m.id)) return false;
    if (query) {
      const q = query.toLowerCase();
      if (!m.en.toLowerCase().includes(q) && !m.zh.includes(query)) return false;
    }
    return true;
  });

  return (
    <div style={{ padding: '16px 16px 24px' }}>
      {/* Search */}
      <div style={{ position: 'relative', marginBottom: 12 }}>
        <Icon name="search" size={16} color="var(--fg-3)" style={{ position: 'absolute', left: 14, top: 13 }} />
        <input
          value={query}
          onChange={e => setQuery(e.target.value)}
          placeholder="Search name or 中文 …"
          style={{
            width: '100%', boxSizing: 'border-box',
            padding: '11px 16px 11px 38px',
            borderRadius: 9999, border: '1px solid var(--border-subtle)',
            background: 'var(--bg-1)', fontFamily: 'Inter, sans-serif',
            fontSize: 14, outline: 'none',
          }}
        />
      </div>

      {/* Filter chips */}
      <div style={{ display: 'flex', gap: 6, marginBottom: 14, flexWrap: 'wrap' }}>
        {[
          { id: 'all',    label: `All · 全部 (${members.length})` },
          { id: 'here',   label: `Here today · 已到 (${checkedToday.size})` },
          { id: 'online', label: `Online ${members.filter(m=>m.pref==='online').length}` },
          { id: 'paper',  label: `Paper ${members.filter(m=>m.pref==='paper').length}` },
        ].map(f => (
          <button key={f.id} onClick={() => setFilter(f.id)} style={{
            padding: '6px 12px', borderRadius: 9999,
            background: filter === f.id ? 'var(--brand-navy)' : 'var(--bg-1)',
            color: filter === f.id ? '#fff' : 'var(--fg-2)',
            border: '1px solid ' + (filter === f.id ? 'var(--brand-navy)' : 'var(--border-subtle)'),
            fontSize: 12, fontWeight: 600, cursor: 'pointer',
          }}>{f.label}</button>
        ))}
      </div>

      {/* Action buttons */}
      <div style={{ display: 'flex', gap: 8, marginBottom: 16 }}>
        <Btn variant="primary" size="sm" icon="plus" onClick={onAddVisitor} style={{ whiteSpace: 'nowrap' }}>Add visitor</Btn>
        <Btn variant="outline" size="sm" icon="download" onClick={onExportCSV} style={{ whiteSpace: 'nowrap' }}>Export CSV</Btn>
      </div>

      {/* List */}
      {filtered.length === 0 ? (
        <Card padding={20} style={{ textAlign: 'center' }}>
          <Icon name="users" size={28} color="var(--fg-3)" />
          <div style={{ fontSize: 14, fontWeight: 700, marginTop: 8 }}>No members yet · 尚未有會友</div>
          <div style={{ fontSize: 12, color: 'var(--fg-3)', marginTop: 4 }}>
            New members appear here when they sign up, or when an admin adds a visitor.
          </div>
        </Card>
      ) : (
        <Card padding={0}>
          {filtered.map((m, i) => {
            const here = checkedToday.has(m.id);
            return (
              <div key={m.id} style={{
                display: 'flex', alignItems: 'center', gap: 12,
                padding: '12px 16px',
                borderBottom: i < filtered.length - 1 ? '1px solid var(--border-subtle)' : 'none',
              }}>
                <Avatar member={m} size={40} ring={here} ringColor="var(--brand-teal)" />
                <button onClick={() => setEditingMember(m)} style={{
                  flex: 1, minWidth: 0, textAlign: 'left',
                  background: 'transparent', border: 'none', cursor: 'pointer',
                  padding: 0, fontFamily: 'inherit',
                }}>
                  <div style={{ fontSize: 14, fontWeight: 700, letterSpacing: '-0.01em', display: 'flex', gap: 6, alignItems: 'baseline' }}>
                    <span>{m.en}</span>
                    {m.zh && <span style={{ fontSize: 12, color: 'var(--fg-3)', fontFamily: "'Noto Sans TC', sans-serif", fontWeight: 500 }}>{m.zh}</span>}
                  </div>
                  <div style={{ display: 'flex', gap: 8, fontSize: 11, color: 'var(--fg-3)', marginTop: 3, alignItems: 'center' }}>
                    <Pill tone={m.pref === 'online' ? 'online' : 'paper'} style={{ fontSize: 9, padding: '2px 7px' }}>
                      {m.pref === 'online' ? 'ONLINE' : 'PAPER'}
                    </Pill>
                    <span>{DA.congregations.find(c => c.id === m.congregation)?.en || m.congregation}</span>
                    {here && <Pill tone="success" icon="check" style={{ fontSize: 9, padding: '2px 7px' }}>HERE</Pill>}
                  </div>
                </button>
                {!here ? (
                  <button onClick={() => onAdminCheckIn && onAdminCheckIn(m.id)} style={{
                    padding: '6px 12px', borderRadius: 9999,
                    background: 'var(--brand-coral)', color: '#fff',
                    border: 'none', fontSize: 11, fontWeight: 700, cursor: 'pointer',
                  }}>Check in</button>
                ) : (
                  <Icon name="check" size={18} color="var(--brand-teal)" strokeWidth={3} />
                )}
                {onDeleteMember && (
                  <button
                    onClick={(e) => { e.stopPropagation(); onDeleteMember(m.id); }}
                    title="Delete member · 刪除會友"
                    style={{
                      padding: '6px 8px', borderRadius: 9999, marginLeft: 6,
                      background: 'transparent', color: 'var(--coral-700)',
                      border: '1px solid var(--coral-100)', cursor: 'pointer',
                    }}>
                    <Icon name="x" size={14} />
                  </button>
                )}
              </div>
            );
          })}
        </Card>
      )}

      {editingMember && (
        <MemberEditModal
          member={editingMember}
          onCancel={() => setEditingMember(null)}
          onSave={async (patch) => {
            await onUpdateMember(editingMember.id, patch);
            setEditingMember(null);
          }} />
      )}

      <div style={{ marginTop: 16, padding: 14, background: 'var(--brand-warm)', borderRadius: 'var(--radius-lg)', display: 'flex', gap: 10 }}>
        <Icon name="sparkles" size={16} color="var(--brand-coral)" style={{ marginTop: 1, flexShrink: 0 }} />
        <div style={{ fontSize: 12, color: '#7c2d12', lineHeight: 1.5 }}>
          <strong>Paper preference</strong> means the member checks in via the paper roster at the door. Admins can mark them present here on their behalf.
          <span style={{ display: 'block', fontFamily: "'Noto Sans TC', sans-serif", color: '#9a3412', marginTop: 2 }}>「紙本」會友以紙本簽到，管理員可代為登記。</span>
        </div>
      </div>
    </div>
  );
}

// ─── Events tab ───
function AdminEvents({ events = [], onSyncOutline, onCreateEvent, onUpdateEvent, onDeleteEvent, onImportEvents }) {
  const [editing, setEditing] = useStateA(null); // event id or 'new'
  const fileRef = React.useRef(null);
  const months = ['JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC'];

  const downloadTemplate = () => {
    const csv = [
      'name_en,name_zh,date,time,congregations,description',
      'Baptism Sunday,浸禮主日,2026-05-31,11:00,"cantonese,mandarin,english",Pastors lead the baptism after each service.',
      "Mother's Day Lunch,母親節愛筵,2026-05-10,12:30,\"cantonese,mandarin\",Lunch in the hall after the 11:00 service.",
    ].join('\r\n');
    const blob = new Blob(['﻿' + csv], { type: 'text/csv;charset=utf-8' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url; a.download = 'bhcac-events-template.csv';
    document.body.appendChild(a); a.click();
    setTimeout(() => { document.body.removeChild(a); URL.revokeObjectURL(url); }, 100);
  };

  const handleImport = async (e) => {
    const file = e.target.files?.[0];
    if (!file) return;
    e.target.value = ''; // allow re-selecting the same file
    const text = await file.text();
    const lines = text.replace(/^﻿/, '').split(/\r?\n/).filter(l => l.trim());
    if (lines.length < 2) { alert('CSV is empty.'); return; }
    const parseRow = (line) => {
      const out = []; let buf = ''; let q = false;
      for (let i = 0; i < line.length; i++) {
        const c = line[i];
        if (q) {
          if (c === '"' && line[i+1] === '"') { buf += '"'; i++; }
          else if (c === '"') q = false;
          else buf += c;
        } else {
          if (c === '"') q = true;
          else if (c === ',') { out.push(buf); buf = ''; }
          else buf += c;
        }
      }
      out.push(buf);
      return out;
    };
    const headers = parseRow(lines[0]).map(h => h.trim().toLowerCase());
    const rows = lines.slice(1).map(parseRow).map(r => Object.fromEntries(headers.map((h, i) => [h, r[i] || ''])));
    const payload = rows.map(r => ({
      en: (r.name_en || r.en || '').trim(),
      zh: (r.name_zh || r.zh || '').trim(),
      date: (r.date || '').trim(),
      time: (r.time || '').trim(),
      congregations: (r.congregations || r.services || '').split(',').map(s => s.trim()).filter(Boolean),
      description: (r.description || '').trim(),
    })).filter(e => e.en && e.date && e.time);
    if (payload.length === 0) { alert('No valid rows found. Make sure name_en, date and time are filled.'); return; }
    await onImportEvents(payload);
  };

  return (
    <div style={{ padding: '16px 16px 24px' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14, gap: 8, flexWrap: 'wrap' }}>
        <Eyebrow>Upcoming · 即將舉行</Eyebrow>
        <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
          <Btn variant="primary" size="sm" icon="plus" onClick={() => setEditing('new')}>New event</Btn>
          <Btn variant="outline" size="sm" icon="download" onClick={downloadTemplate}>Template</Btn>
          <Btn variant="outline" size="sm" icon="plus" onClick={() => fileRef.current?.click()}>Import CSV</Btn>
          <input ref={fileRef} type="file" accept=".csv,text/csv" onChange={handleImport} style={{ display: 'none' }} />
        </div>
      </div>

      {editing && (
        <EventForm
          event={editing === 'new' ? null : events.find(e => e.id === editing)}
          onCancel={() => setEditing(null)}
          onSave={async (payload) => {
            if (editing === 'new') await onCreateEvent(payload);
            else await onUpdateEvent(editing, payload);
            setEditing(null);
          }} />
      )}

      {events.length === 0 && !editing && (
        <Card padding={20} style={{ textAlign: 'center', marginBottom: 12 }}>
          <Icon name="calendar" size={28} color="var(--fg-3)" />
          <div style={{ fontSize: 14, fontWeight: 700, marginTop: 8 }}>No events yet · 尚未有活動</div>
          <div style={{ fontSize: 12, color: 'var(--fg-3)', marginTop: 4 }}>
            Create one above, or import from the CSV template.
          </div>
        </Card>
      )}

      {events.map((e, i) => {
        const accents = ['var(--brand-coral)', 'var(--brand-teal)', 'var(--brand-navy)'];
        const accent = accents[i % 3];
        const month = months[Number((e.date || '').slice(5, 7)) - 1] || '';
        return (
          <div key={e.id} style={{ marginBottom: 12 }}>
            <Card padding={0} accent={accent}>
              <div style={{ padding: 16 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 10, gap: 8 }}>
                  <div style={{ minWidth: 0 }}>
                    <div style={{ fontSize: 16, fontWeight: 700, letterSpacing: '-0.015em' }}>{e.en}</div>
                    {e.zh && <div style={{ fontFamily: "'Noto Sans TC', sans-serif", fontSize: 13, color: 'var(--fg-3)', marginTop: 2 }}>{e.zh}</div>}
                    {e.time && (
                      <div style={{ display: 'flex', alignItems: 'center', gap: 4, marginTop: 6, fontSize: 12, fontWeight: 600, color: 'var(--brand-navy)' }}>
                        <Icon name="clock" size={12} color="var(--fg-3)" />
                        <span>{e.time}</span>
                      </div>
                    )}
                    {e.description && <div style={{ fontSize: 12, color: 'var(--fg-3)', marginTop: 6, lineHeight: 1.5 }}>{e.description}</div>}
                    {(e.closed_at || e.synced_at) && (
                      <div style={{ display: 'flex', gap: 6, marginTop: 8, flexWrap: 'wrap' }}>
                        {e.closed_at && (
                          <Pill tone="muted" style={{ fontSize: 10 }}>Closed · {String(e.closed_at).slice(11, 16)}</Pill>
                        )}
                        {e.synced_at && (
                          <Pill tone="success" style={{ fontSize: 10 }}>Synced · {String(e.synced_at).slice(0, 10)}</Pill>
                        )}
                      </div>
                    )}
                  </div>
                  <Pill tone="navy" icon="calendar" style={{ flexShrink: 0 }}>{(e.date || '').slice(8)} {month}</Pill>
                </div>
                {Array.isArray(e.congregations) && e.congregations.length > 0 && (
                  <div style={{ display: 'flex', gap: 4, marginTop: 12, flexWrap: 'wrap' }}>
                    {e.congregations.map(cid => {
                      const s = DA.congregations.find(x => x.id === cid);
                      return <Pill key={cid} tone="muted" style={{ fontSize: 10, padding: '3px 8px' }}>{s ? s.en : cid}</Pill>;
                    })}
                  </div>
                )}
                <div style={{ display: 'flex', gap: 6, marginTop: 12, paddingTop: 12, borderTop: '1px solid var(--border-subtle)' }}>
                  <Btn variant="outline" size="sm" icon="edit" onClick={() => setEditing(e.id)}>Edit</Btn>
                  <Btn variant="outline" size="sm" icon="x" onClick={async () => {
                    if (!window.confirm(`Delete "${e.en}"?`)) return;
                    await onDeleteEvent(e.id);
                  }}>Delete</Btn>
                </div>
              </div>
            </Card>
          </div>
        );
      })}

      <button onClick={onSyncOutline} style={{
        width: '100%', marginTop: 12, padding: 14,
        background: 'var(--bg-1)', border: '1px dashed var(--border-strong)',
        borderRadius: 'var(--radius-lg)', textAlign: 'center',
        cursor: 'pointer', fontFamily: 'inherit',
      }}>
        <Icon name="calendar" size={20} color="var(--fg-3)" />
        <div style={{ fontSize: 13, fontWeight: 600, marginTop: 6 }}>Sync to Outline · 同步至 Outline</div>
        <div style={{ fontSize: 11, color: 'var(--fg-3)', marginTop: 2 }}>wiki.bhcac.org.au · tap to sync now</div>
      </button>
    </div>
  );
}

function EventForm({ event, onSave, onCancel }) {
  // Default new events to all three congregations so a freshly-created
  // event matches every member's check-in by default. Admin can untick.
  const defaultCongregations = ['cantonese', 'mandarin', 'english'];
  const [form, setForm] = useStateA({
    en: event?.en || '',
    zh: event?.zh || '',
    date: event?.date || new Date().toISOString().slice(0, 10),
    time: event?.time || '11:00',
    congregations: event?.congregations && event.congregations.length > 0 ? event.congregations : defaultCongregations,
    description: event?.description || '',
  });
  const [saving, setSaving] = useStateA(false);
  const [error, setError] = useStateA(null);
  const update = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const toggleCongregation = (cid) => setForm(f => ({
    ...f,
    congregations: f.congregations.includes(cid) ? f.congregations.filter(s => s !== cid) : [...f.congregations, cid],
  }));

  const submit = async (e) => {
    e.preventDefault();
    setError(null);
    if (!form.en.trim()) { setError('Name is required.'); return; }
    if (!form.date) { setError('Date is required.'); return; }
    if (!form.time) { setError('Start time is required.'); return; }
    if (form.congregations.length === 0) { setError('Pick at least one congregation this event applies to.'); return; }
    setSaving(true);
    try {
      await onSave({ ...form });
    } catch (err) {
      setError(err.message);
      setSaving(false);
    }
  };

  const inputStyle = {
    width: '100%', boxSizing: 'border-box',
    padding: '11px 14px', borderRadius: 12,
    border: '1px solid var(--border-strong)',
    background: 'var(--bg-1)', fontSize: 14, fontFamily: 'Inter, sans-serif',
    outline: 'none',
  };

  return (
    <Card padding={16} style={{ marginBottom: 16 }}>
      <Eyebrow style={{ marginBottom: 10 }}>{event ? 'Edit event · 編輯活動' : 'New event · 新增活動'}</Eyebrow>
      <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        <input style={inputStyle} type="text" placeholder="Name (EN) · 英文名稱"
          value={form.en} onChange={e => update('en', e.target.value)} required />
        <input style={inputStyle} type="text" placeholder="Name (中文) — optional"
          value={form.zh} onChange={e => update('zh', e.target.value)} />
        <div style={{ display: 'flex', gap: 8 }}>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--fg-3)', marginBottom: 4 }}>Date · 日期</div>
            <input style={inputStyle} type="date"
              value={form.date} onChange={e => update('date', e.target.value)} required />
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--fg-3)', marginBottom: 4 }}>Start time · 開始時間</div>
            <input style={inputStyle} type="time"
              value={form.time}
              onChange={e => update('time', e.target.value)} required />
          </div>
        </div>
        <textarea style={{ ...inputStyle, minHeight: 70, fontFamily: 'inherit' }} placeholder="Description (optional) · 簡介"
          value={form.description} onChange={e => update('description', e.target.value)} />
        <div>
          <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--fg-3)', marginBottom: 6 }}>
            Congregations · 適用崇拜 <span style={{ fontWeight: 500, color: 'var(--fg-3)', textTransform: 'none', letterSpacing: 0 }}>(at least one)</span>
          </div>
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            {DA.congregations.map(s => {
              const on = form.congregations.includes(s.id);
              return (
                <button key={s.id} type="button" onClick={() => toggleCongregation(s.id)} style={{
                  padding: '6px 12px', borderRadius: 9999,
                  background: on ? `var(--brand-${s.accent})` : 'transparent',
                  color: on ? '#fff' : 'var(--fg-2)',
                  border: '1px solid ' + (on ? `var(--brand-${s.accent})` : 'var(--border-subtle)'),
                  fontSize: 11, fontWeight: 600, cursor: 'pointer',
                }}>{s.en}</button>
              );
            })}
          </div>
        </div>
        {error && <div style={{ fontSize: 12, color: 'var(--coral-700)', background: 'var(--coral-100)', padding: '8px 12px', borderRadius: 8 }}>{error}</div>}
        <div style={{ display: 'flex', gap: 8, marginTop: 6 }}>
          <Btn variant="outline" size="md" onClick={onCancel} type="button" style={{ flex: 1 }}>Cancel</Btn>
          <Btn variant="primary" size="md" type="submit" disabled={saving} style={{ flex: 2 }}>
            {saving ? 'Saving…' : (event ? 'Save changes · 儲存' : 'Create event · 建立')}
          </Btn>
        </div>
      </form>
    </Card>
  );
}

// ─── Reports tab — per-event cards (last 28 days) ───
function AdminReports({ members = [], checkIns = [], events = [], onSyncOutline, onExportReport }) {
  const today = new Date().toISOString().slice(0, 10);
  const fourWeeksAgo = new Date(Date.now() - 28 * 24 * 60 * 60 * 1000).toISOString().slice(0, 10);

  const recentEvents = events
    .filter(e => e.date >= fourWeeksAgo && e.date <= today)
    .sort((a, b) => (b.date + 'T' + b.time).localeCompare(a.date + 'T' + a.time));

  return (
    <div style={{ padding: '16px 16px 24px' }}>
      <Eyebrow style={{ marginBottom: 12 }}>Recent events · 最近活動 (last 28 days)</Eyebrow>

      {recentEvents.length === 0 ? (
        <Card padding={20} style={{ textAlign: 'center', marginBottom: 16 }}>
          <Icon name="bar-chart" size={28} color="var(--fg-3)" />
          <div style={{ fontSize: 14, fontWeight: 700, marginTop: 8 }}>No recent events · 暫無近期活動</div>
          <div style={{ fontSize: 12, color: 'var(--fg-3)', marginTop: 4 }}>
            Create events under the Events tab; they appear here once attended.
          </div>
        </Card>
      ) : recentEvents.map(ev => (
        <EventReportCard key={ev.id} event={ev} checkIns={checkIns} members={members} />
      ))}

      <div style={{ display: 'flex', gap: 8, marginTop: 16, flexWrap: 'wrap' }}>
        <Btn variant="outline" size="md" icon="download" onClick={onExportReport} style={{ flex: 1, minWidth: 200 }}>
          Export report · 匯出 CSV
        </Btn>
        <Btn variant="outline" size="md" icon="download" onClick={onSyncOutline} style={{ flex: 1, minWidth: 200 }}>
          Sync to Outline · 同步至 Outline
        </Btn>
      </div>
    </div>
  );
}

function EventReportCard({ event, checkIns, members }) {
  const recs = checkIns.filter(c => c.event_id === event.id);
  const total = recs.length;
  const online = recs.filter(c => c.source === 'online').length;
  const paper  = recs.filter(c => c.source === 'paper').length;
  const adminN = recs.filter(c => c.source === 'admin').length;
  const lateRecs = recs.filter(c => (c.late_minutes || 0) > 0);
  const lateAvg = lateRecs.length > 0
    ? Math.round(lateRecs.reduce((s, r) => s + (r.late_minutes || 0), 0) / lateRecs.length)
    : 0;
  const lateMax = lateRecs.length > 0 ? Math.max(...lateRecs.map(r => r.late_minutes || 0)) : 0;
  const pct = (n) => total > 0 ? Math.round((n / total) * 100) : 0;
  const cong = (DA.congregations || []).filter(c => Array.isArray(event.congregations) && event.congregations.includes(c.id));
  const accent = `var(--brand-${cong[0]?.accent || 'navy'})`;

  return (
    <Card padding={0} style={{ marginBottom: 12 }} accent={accent}>
      <div style={{ padding: 16 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 10, gap: 8 }}>
          <div style={{ minWidth: 0 }}>
            <div style={{ fontSize: 16, fontWeight: 700 }}>{event.en}</div>
            {event.zh && <div style={{ fontFamily: "'Noto Sans TC', sans-serif", fontSize: 13, color: 'var(--fg-3)', marginTop: 2 }}>{event.zh}</div>}
            <div style={{ fontSize: 12, color: 'var(--fg-3)', marginTop: 4 }}>
              {event.date} · {event.time} · {cong.map(c => c.en).join(' / ') || '—'}
            </div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <div style={{ fontSize: 28, fontWeight: 700, color: accent, letterSpacing: '-0.02em' }}>{total}</div>
            <div style={{ fontSize: 10, color: 'var(--fg-3)' }}>checked in</div>
          </div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8, marginBottom: 10 }}>
          <SourceTile label="Online" zh="線上" n={online} pct={pct(online)} color="var(--brand-coral)" />
          <SourceTile label="Paper"  zh="紙本" n={paper}  pct={pct(paper)}  color="var(--brand-teal)" />
          <SourceTile label="Admin"  zh="代簽" n={adminN} pct={pct(adminN)} color="var(--brand-navy)" />
        </div>

        <div style={{ padding: '10px 12px', background: 'var(--bg-2)', borderRadius: 10, fontSize: 12, color: 'var(--fg-2)' }}>
          <strong>Late · 遲到:</strong> {lateRecs.length > 0
            ? `${lateRecs.length} ${lateRecs.length === 1 ? 'person' : 'people'} · avg ${lateAvg} min · max ${lateMax} min`
            : 'None — everyone on time 🎉'}
        </div>

        {(event.closed_at || event.synced_at) && (
          <div style={{ display: 'flex', gap: 6, marginTop: 10, fontSize: 11, color: 'var(--fg-3)', flexWrap: 'wrap' }}>
            {event.closed_at && <Pill tone="muted" style={{ fontSize: 10 }}>Closed · {event.closed_at.slice(0, 16).replace('T', ' ')}</Pill>}
            {event.synced_at && <Pill tone="success" style={{ fontSize: 10 }}>Synced to Outline</Pill>}
          </div>
        )}
      </div>
    </Card>
  );
}

function SourceTile({ label, zh, n, pct, color }) {
  return (
    <div style={{ background: 'var(--bg-2)', borderRadius: 10, padding: '10px 12px' }}>
      <div style={{ fontSize: 18, fontWeight: 700, color }}>{n}</div>
      <div style={{ fontSize: 10, fontWeight: 700, color: 'var(--fg-3)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>
        {label} · {zh}
      </div>
      <div style={{ fontSize: 10, color: 'var(--fg-3)', marginTop: 2 }}>{pct}%</div>
    </div>
  );
}

// ─── Add visitor modal-screen ───
function ScreenAddVisitor({ onBack, onSave }) {
  const [form, setForm] = useStateA({
    en: '', zh: '', phone: '', email: '',
    congregation: 'cantonese', pref: 'online',
  });
  const [saving, setSaving] = useStateA(false);
  const [error, setError] = useStateA(null);

  const update = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const submit = async () => {
    if (!form.en.trim()) { setError('Name is required.'); return; }
    setError(null); setSaving(true);
    try {
      await onSave(form);
      // App.handleSaveVisitor navigates back on success
    } catch (err) {
      setError(err.message || 'Save failed.');
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="focused-screen" style={{ height: '100%', display: 'flex', flexDirection: 'column', background: 'var(--bg-2)' }}>
      <div style={{ padding: '60px 20px 16px', background: 'var(--bg-1)', borderBottom: '1px solid var(--border-subtle)' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
          <CircleBtn icon="x" onClick={onBack} />
          <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--fg-3)' }}>Admin · 管理員</div>
          <div style={{ width: 40 }} />
        </div>
        <Eyebrow style={{ marginBottom: 6 }}>New Visitor · 新朋友</Eyebrow>
        <h1 style={{ fontSize: 24, fontWeight: 700, letterSpacing: '-0.02em', margin: 0, lineHeight: 1.15 }}>Add someone to today</h1>
        <div style={{ fontFamily: "'Noto Sans TC', sans-serif", fontSize: 14, color: 'var(--fg-3)', marginTop: 4 }}>新增今日簽到</div>
      </div>

      <div style={{ flex: 1, overflowY: 'auto', padding: '20px 16px' }}>
        <Field label="Name · 姓名" placeholder="Full name" value={form.en} onChange={v => update('en', v)} />
        <Field label="Chinese name · 中文名" placeholder="可選 (optional)" value={form.zh} onChange={v => update('zh', v)} />
        <Field label="Phone · 電話" placeholder="04xx xxx xxx" type="tel" value={form.phone} onChange={v => update('phone', v)} />
        <Field label="Email · 電郵" placeholder="optional" type="email" value={form.email} onChange={v => update('email', v)} />

        {/* Congregation picker */}
        <div style={{ marginBottom: 18 }}>
          <Eyebrow color="var(--fg-3)" style={{ marginBottom: 8 }}>Congregation · 崇拜</Eyebrow>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8 }}>
            {DA.congregations.map(c => (
              <button key={c.id} onClick={() => update('congregation', c.id)} style={{
                padding: '12px 10px', borderRadius: 12, textAlign: 'left',
                background: form.congregation === c.id ? 'var(--bg-1)' : 'transparent',
                border: '1.5px solid ' + (form.congregation === c.id ? `var(--brand-${c.accent})` : 'var(--border-subtle)'),
                cursor: 'pointer',
                boxShadow: form.congregation === c.id ? `0 0 0 3px color-mix(in oklab, var(--brand-${c.accent}) 18%, transparent)` : 'none',
                transition: 'all 200ms',
              }}>
                <div style={{ fontSize: 13, fontWeight: 700 }}>{c.en}</div>
                <div style={{ fontSize: 11, color: 'var(--fg-3)', fontFamily: "'Noto Sans TC', sans-serif" }}>{c.zh} · {c.defaultTime}</div>
              </button>
            ))}
          </div>
        </div>

        {/* Preference */}
        <div style={{ marginBottom: 22 }}>
          <Eyebrow color="var(--fg-3)" style={{ marginBottom: 8 }}>Check-in preference · 簽到方式</Eyebrow>
          <div style={{ display: 'flex', gap: 8 }}>
            {[
              { id: 'online', en: 'Online', zh: '線上', sub: 'Phone app' },
              { id: 'paper',  en: 'Paper',  zh: '紙本', sub: 'At the door' },
            ].map(p => (
              <button key={p.id} onClick={() => update('pref', p.id)} style={{
                flex: 1, padding: '12px 10px', borderRadius: 12, textAlign: 'left',
                background: form.pref === p.id ? 'var(--brand-warm)' : 'transparent',
                border: '1.5px solid ' + (form.pref === p.id ? 'var(--brand-coral)' : 'var(--border-subtle)'),
                cursor: 'pointer',
              }}>
                <div style={{ fontSize: 13, fontWeight: 700 }}>{p.en} · <span style={{ fontFamily: "'Noto Sans TC', sans-serif", fontWeight: 500 }}>{p.zh}</span></div>
                <div style={{ fontSize: 11, color: 'var(--fg-3)', marginTop: 2 }}>{p.sub}</div>
              </button>
            ))}
          </div>
        </div>

        {error && (
          <div style={{ padding: '10px 12px', marginBottom: 12, background: 'var(--coral-100)', borderRadius: 8, color: 'var(--coral-700)', fontSize: 13, fontWeight: 600 }}>
            {error}
          </div>
        )}

        <p style={{ fontSize: 11, color: 'var(--fg-3)', lineHeight: 1.5, fontFamily: "'Noto Sans TC', Inter, sans-serif" }}>
          本會收集以上個人資料，將遵行澳洲保護個人私隱條例指引處理。
          The above information will comply with Australian Privacy Principles.
        </p>
      </div>

      <div style={{ padding: '12px 16px 28px', background: 'var(--bg-1)', borderTop: '1px solid var(--border-subtle)' }}>
        <Btn variant="primary" full size="lg" trailingIcon="check" disabled={saving} onClick={submit}>
          {saving ? 'Saving…' : 'Save & check in · 儲存並簽到'}
        </Btn>
      </div>
    </div>
  );
}

function Field({ label, placeholder, type = 'text', value, onChange }) {
  return (
    <div style={{ marginBottom: 14 }}>
      <label style={{ display: 'block', fontSize: 11, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--fg-3)', marginBottom: 6 }}>{label}</label>
      <input
        type={type}
        placeholder={placeholder}
        value={value ?? ''}
        onChange={(e) => onChange && onChange(e.target.value)}
        style={{
          width: '100%', boxSizing: 'border-box',
          padding: '12px 14px',
          borderRadius: 12, border: '1px solid var(--border-subtle)',
          background: 'var(--bg-1)', fontSize: 15, fontFamily: 'Inter, sans-serif',
          outline: 'none',
        }} />
    </div>
  );
}

// ─── Admins tab — list + invite ───
function AdminAdmins() {
  const [admins, setAdmins] = useStateA([]);
  const [loading, setLoading] = useStateA(true);
  const [email, setEmail] = useStateA('');
  const [en, setEn] = useStateA('');
  const [submitting, setSubmitting] = useStateA(false);
  const [error, setError] = useStateA(null);
  const [success, setSuccess] = useStateA(null);

  const refresh = async () => {
    setLoading(true);
    try {
      const r = await window.BHCAC_API.listAdmins();
      setAdmins(r.admins || []);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  React.useEffect(() => { refresh(); }, []);

  const submit = async (e) => {
    e.preventDefault();
    setError(null); setSuccess(null);
    if (!email || !email.includes('@')) { setError('Enter a valid email.'); return; }
    setSubmitting(true);
    try {
      const r = await window.BHCAC_API.inviteAdmin({ email, en });
      setSuccess(r.alreadyAdmin ? 'Already an admin.' : `Invite sent to ${r.email} · 邀請已寄出`);
      setEmail(''); setEn('');
      await refresh();
    } catch (err) {
      setError(err.message);
    } finally {
      setSubmitting(false);
    }
  };

  const revoke = async (e) => {
    if (!window.confirm(`Remove admin access for ${e}?`)) return;
    try {
      await window.BHCAC_API.revokeAdmin(e);
      await refresh();
    } catch (err) {
      setError(err.message);
    }
  };

  const inputStyle = {
    width: '100%', boxSizing: 'border-box',
    padding: '11px 14px', borderRadius: 12,
    border: '1px solid var(--border-strong)',
    background: 'var(--bg-1)', fontSize: 14, fontFamily: 'Inter, sans-serif',
    outline: 'none',
  };

  return (
    <div style={{ padding: '16px 16px 24px' }}>
      <Eyebrow style={{ marginBottom: 8 }}>Invite an admin · 邀請管理員</Eyebrow>
      <Card padding={16} style={{ marginBottom: 16 }}>
        <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          <input style={inputStyle} type="email" placeholder="Email · 電郵"
            value={email} onChange={e => setEmail(e.target.value)} required />
          <input style={inputStyle} type="text" placeholder="Name (optional) · 姓名"
            value={en} onChange={e => setEn(e.target.value)} />
          {error && (
            <div style={{ fontSize: 12, color: 'var(--coral-700)', background: 'var(--coral-100)', padding: '8px 12px', borderRadius: 8 }}>
              {error}
            </div>
          )}
          {success && (
            <div style={{ fontSize: 12, color: 'var(--teal-700)', background: 'rgba(13,148,136,0.1)', padding: '8px 12px', borderRadius: 8 }}>
              {success}
            </div>
          )}
          <Btn variant="primary" type="submit" full size="md" icon="plus" disabled={submitting}>
            {submitting ? 'Sending…' : 'Send invite · 發送邀請'}
          </Btn>
          <p style={{ fontSize: 11, color: 'var(--fg-3)', lineHeight: 1.5, margin: 0 }}>
            The invitee will receive a welcome email. Their admin role activates as soon as they sign up (or sign in) with that email address.
          </p>
        </form>
      </Card>

      <Eyebrow style={{ marginBottom: 8 }}>
        Current admins · 目前管理員 {admins.length > 0 && `(${admins.length})`}
      </Eyebrow>
      {loading ? (
        <div style={{ padding: 14, textAlign: 'center', color: 'var(--fg-3)', fontSize: 13 }}>Loading…</div>
      ) : (
        <Card padding={0}>
          {admins.length === 0 ? (
            <div style={{ padding: 14, textAlign: 'center', color: 'var(--fg-3)', fontSize: 13 }}>None yet.</div>
          ) : admins.map((a, i) => (
            <div key={a.email} style={{
              display: 'flex', alignItems: 'center', gap: 12,
              padding: '12px 16px',
              borderBottom: i < admins.length - 1 ? '1px solid var(--border-subtle)' : 'none',
            }}>
              <div style={{
                width: 36, height: 36, borderRadius: '50%',
                background: a.source === 'env' ? 'var(--brand-navy)' : 'var(--brand-coral)',
                color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 13, fontWeight: 700, textTransform: 'uppercase',
              }}>{a.email.slice(0, 1)}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13, fontWeight: 700, overflow: 'hidden', textOverflow: 'ellipsis' }}>{a.email}</div>
                <div style={{ display: 'flex', gap: 6, alignItems: 'center', fontSize: 11, color: 'var(--fg-3)', marginTop: 2 }}>
                  <Pill tone={a.source === 'env' ? 'navy' : 'coral'} style={{ fontSize: 9, padding: '2px 7px' }}>
                    {a.source === 'env' ? 'BUILT-IN' : 'INVITED'}
                  </Pill>
                  {a.invitedAt && <span>{a.invitedAt.slice(0, 10)}</span>}
                </div>
              </div>
              {a.source === 'invited' ? (
                <button onClick={() => revoke(a.email)} title="Remove admin access" style={{
                  padding: '6px 10px', borderRadius: 9999,
                  background: 'transparent', color: 'var(--coral-700)',
                  border: '1px solid var(--coral-100)', fontSize: 11, fontWeight: 600,
                  cursor: 'pointer',
                }}>Revoke</button>
              ) : (
                <span title="Built-in admins are managed via the SUPERADMIN_EMAILS env var" style={{
                  fontSize: 11, color: 'var(--fg-3)', padding: '6px 10px',
                }}>—</span>
              )}
            </div>
          ))}
        </Card>
      )}

      <div style={{ marginTop: 16, padding: 14, background: 'var(--brand-warm)', borderRadius: 'var(--radius-lg)', display: 'flex', gap: 10 }}>
        <Icon name="sparkles" size={16} color="var(--brand-coral)" style={{ marginTop: 1, flexShrink: 0 }} />
        <div style={{ fontSize: 12, color: '#7c2d12', lineHeight: 1.5 }}>
          <strong>BUILT-IN</strong> admins are set in Netlify env <code>SUPERADMIN_EMAILS</code> and can only be changed there.
          <strong> INVITED</strong> admins are managed here.
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ScreenAdmin, ScreenAddVisitor });
