/* ============================================================
   UNSTOPPABLES — Client Check-In (Flow A + Flow B) + Settings
   Flow A: 30-second repeat visit (typeahead → recorded by →
   reason → service → food extras → submit)
   Flow B: full intake wizard (IntakeWizard)
   Exports: FoodBankPage, SettingsPage
   ============================================================ */

const VISIT_REASONS = {
  'Day to Day Services': ['Food', 'Clothing', 'Education', 'Transportation', 'Recreation', 'Shelter', 'Language Skills', 'Translation and Interpretation', 'Legal Matter', 'Family Counseling'],
  'Settlement Services': ['Immigration', 'Housing', 'Employment', 'Canadian Citizenship', 'PR Card', 'Health', 'Family Benefit/Welfare', 'Family & Sponsorship', 'Subsidized Childcare', 'Navigation of Social Systems', 'Other'],
  'Domestic Violence Support': ['Health Care', 'Financial Assistance', 'Safety', 'Police', 'Legal Aid/Lawyer', 'Counselling', 'Risk Assessment', 'Family Planning']
};
const FB_ITEMS = ['Produce', 'Canned Goods', 'Protein', 'Dairy', 'Baby Formula', 'Personal Care', 'Household', 'Other'];

function FoodBankPage({ push, params = {}, openPage }) {
  const S = window.TRELLIS_SCHEMA;
  const D = window.TRELLIS_DATA;
  const me = useEhcwUser();

  const [mode, setMode] = React.useState(params.flow === 'new' ? 'new' : 'checkin');
  React.useEffect(() => {
    if (params.flow === 'new') setMode('new');
    else if (params.tab === 'log') setMode('log');
  }, [params]);

  const [visits, setVisits] = React.useState(D.VISITS);
  // "Today's Log" means TODAY — historical visits live in the database and the
  // client dossiers, never mislabeled as today's activity. Optimistic entries
  // created this session have no ts yet and count as today.
  const todayStr = new Date().toLocaleDateString('en-CA');
  const todayVisits = visits.filter(v => !v.ts || v.ts === todayStr);
  const totalLbs = todayVisits.reduce((s, v) => s + (v.weight || 0), 0);

  // ---- Flow A state ----
  // Re-derive roster + visit log when the live Firestore subscriptions update
  const [rosterTick, setRosterTick] = React.useState(0);
  React.useEffect(() => {
    const bump = () => setRosterTick(t => t + 1);
    const syncVisits = () => setVisits(window.TRELLIS_DATA.VISITS);
    document.addEventListener('ehcw:data:clients', bump);
    document.addEventListener('ehcw:data:visits', syncVisits);
    return () => {
      document.removeEventListener('ehcw:data:clients', bump);
      document.removeEventListener('ehcw:data:visits', syncVisits);
    };
  }, []);
  const roster = React.useMemo(() => D.clients.map(c => ({
    id: c.id, initials: c.initials, _docId: c._docId,
    firstName: c.firstName, lastName: c.lastName,
    displayName: `${c.firstName} ${c.lastName ? c.lastName[0] + '.' : ''}`.trim(),
    lastVisit: c.lastContact
  })), [rosterTick]);
  const [client, setClient] = React.useState(null);
  const [qName, setQName] = React.useState('');
  // RecordedBy: ONLY official roster caseworkers are selectable (user rule
  // 2026-06-10 — admins are not caseworkers). Roster members signing in get
  // themselves as the default; everyone else must pick who handled the visit.
  const meOnRoster = !!(me?.displayName && S.EHCW_STAFF.some(st => st.name === me.displayName));
  const [recordedBy, setRecordedBy] = React.useState(() => {
    const n = window.EHCW_AUTH?.getUser()?.displayName;
    return n && window.TRELLIS_SCHEMA.EHCW_STAFF.some(st => st.name === n) ? n : '';
  });
  const [recordedByTouched, setRecordedByTouched] = React.useState(false);
  React.useEffect(() => {
    if (meOnRoster && !recordedByTouched && recordedBy !== me.displayName) {
      setRecordedBy(me.displayName);
    }
  }, [me, recordedByTouched]);
  const [reason, setReason] = React.useState(null);
  const [service, setService] = React.useState(null);
  const [foodLoc, setFoodLoc] = React.useState(null);
  const [hamper, setHamper] = React.useState(false);
  const [weight, setWeight] = React.useState('');
  const [items, setItems] = React.useState([]);
  const [notes, setNotes] = React.useState('');

  const matches = qName.trim() && !client
    ? roster.filter(c => (c.displayName + ' ' + c.id).toLowerCase().includes(qName.trim().toLowerCase())).slice(0, 6)
    : [];

  const isFood = reason === 'Day to Day Services' && service === 'Food';
  const canSubmit = client && recordedBy && reason && service && (!isFood || foodLoc);

  const reset = () => {
    setClient(null); setQName(''); setReason(null); setService(null);
    setFoodLoc(null); setHamper(false); setWeight(''); setItems([]); setNotes('');
  };

  const submit = async () => {
    if (!canSubmit) { push('Complete the required fields first'); return; }
    const parts = recordedBy.split(' ');
    const byShort = parts[0] + (parts[1] ? ' ' + parts[1][0] + '.' : '');
    setVisits(v => [{
      id: 'v' + Date.now(), initials: client.initials,
      time: new Date().toLocaleTimeString('en-CA', { hour: '2-digit', minute: '2-digit', hour12: false }),
      weight: isFood ? Number(weight) || 0 : 0,
      items: isFood ? items.map(i => i.split(' ')[0]) : [],
      by: byShort, family: 0, reason, subtype: service, loc: isFood ? foodLoc : null
    }, ...v]);
    const saved = { client, reason, service, foodLoc, hamper, weight, items: [...items], notes };
    push(`Check-in logged ✓ ${client.displayName} · ${service}${isFood ? ' · ' + foodLoc : ''}`);
    reset(); setMode('log');

    // Persist — field names mirror the Airtable Visit Log + intake parity
    if (window.EHCW_DB) {
      try {
        await window.EHCW_DB.saveVisit({
          clientName: `${saved.client.firstName || ''} ${saved.client.lastName || ''}`.trim() || saved.client.displayName,
          clientInitials: saved.client.initials,
          clientId: saved.client._docId || null,
          visitReason: saved.reason,
          visitSubtype: saved.service,
          hamperReceived: saved.hamper,
          hamperWeightLbs: isFood ? Number(saved.weight) || 0 : 0,
          itemsReceived: isFood ? saved.items : [],
          foodLocation: isFood ? saved.foodLoc : null,
          recordedBy: recordedBy.trim(),
          notes: (saved.notes || '').trim(),
          formCategory: saved.reason === 'Day to Day Services' ? 'Food'
            : saved.reason === 'Settlement Services' ? 'Settlement'
            : 'Domestic Violence'
        });
      } catch (e) {
        console.warn('[EHCW] saveVisit failed:', e.code || e.message);
        push('Saved locally — sync pending');
      }
    }
  };

  const inputStyle = {
    width: '100%', padding: '13px 16px', borderRadius: 14, border: '1px solid var(--hairline-strong)',
    background: 'var(--glass-input)', fontSize: 15, outline: 'none', boxSizing: 'border-box', backdropFilter: 'blur(8px)'
  };
  const labelStyle = { fontSize: 12.5, fontWeight: 700, letterSpacing: '.04em', color: 'var(--ink-soft)', marginBottom: 7, display: 'block' };
  const chip = (on, accent = 'var(--accent)', ink = 'var(--accent-ink)') => ({
    padding: '11px 18px', borderRadius: 99, fontSize: 13.5, fontWeight: 700, minHeight: 44,
    background: on ? accent : 'var(--hover)', color: on ? ink : 'var(--ink-soft)',
    border: '1px solid ' + (on ? 'transparent' : 'var(--hairline)'), transition: 'all .15s'
  });

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 20, maxWidth: 900 }} data-comment-anchor="7afb9ec524-div-36-5">
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', gap: 14, flexWrap: 'wrap' }}>
        <div>
          <h1 style={{ fontSize: 'clamp(24px, 3.4vw, 32px)', fontWeight: 700, letterSpacing: '-0.025em' }}>Client Check-In</h1>
          <p className="t-soft" style={{ margin: '6px 0 0', fontSize: 14.5 }}>30-second repeat visits · full intake for new clients · works offline.</p>
        </div>
        <Badge tone="leaf"><span style={{ width: 7, height: 7, borderRadius: 99, background: 'var(--leaf)' }}></span> Online · synced</Badge>
      </div>

      {/* mode tabs */}
      <div className="glass" style={{ display: 'flex', borderRadius: 16, padding: 5, width: 'fit-content', gap: 4, flexWrap: 'wrap', maxWidth: '100%' }}>
        {[['checkin', 'Check-In'], ['new', 'New Client'], ['log', `Today's Log (${todayVisits.length})`]].map(([id, label]) =>
          <button key={id} onClick={() => setMode(id)} style={{
            padding: '10px 22px', borderRadius: 12, fontSize: 14, fontWeight: 700, minHeight: 44,
            background: mode === id ? 'var(--accent)' : 'transparent',
            color: mode === id ? 'var(--accent-ink)' : 'var(--ink-soft)', transition: 'all .2s'
          }}>{label}</button>
        )}
      </div>

      {/* ============ FLOW B — new client wizard ============ */}
      {mode === 'new' && (
        <IntakeWizard push={push}
          onCancel={() => setMode('checkin')}
          onComplete={nc => { setClient(nc); setQName(''); setMode('checkin'); }} />
      )}

      {/* ============ FLOW A — existing client ============ */}
      {mode === 'checkin' && (
        <div className="glass" style={{ borderRadius: 'var(--radius-l)', padding: 'clamp(20px, 3vw, 30px)', boxShadow: 'var(--shadow-card)', display: 'flex', flexDirection: 'column', gap: 20 }}>
          {/* client typeahead */}
          <div style={{ position: 'relative' }}>
            <label style={labelStyle}>Client</label>
            {client ? (
              <div style={{ display: 'inline-flex', alignItems: 'center', gap: 10, padding: '10px 14px', borderRadius: 14, background: 'var(--accent-soft)', border: '1.5px solid var(--accent)' }}>
                <Avatar initials={client.initials} hue={parseInt((client.id || 'EH-1').slice(3), 10) % 360} size={30} />
                <span style={{ fontSize: 14.5, fontWeight: 700 }}>{client.displayName}</span>
                <span className="mono t-faint" style={{ fontSize: 12 }}>{client.id}</span>
                {client.category && <Badge tone="leaf">New ✓</Badge>}
                <button onClick={() => { setClient(null); setQName(''); }} style={{ padding: 6, borderRadius: 8, background: 'var(--hover)' }}><Icon name="x" size={13} /></button>
              </div>
            ) : (
              <React.Fragment>
                <input value={qName} onChange={e => setQName(e.target.value)} placeholder="Start typing a name or Client ID…" style={inputStyle} />
                {matches.length > 0 && (
                  <div className="glass-strong" style={{ position: 'absolute', top: '100%', left: 0, right: 0, zIndex: 20, marginTop: 6, borderRadius: 14, overflow: 'hidden', boxShadow: 'var(--shadow-pop)' }}>
                    {matches.map(m => (
                      <button key={m.id} onClick={() => setClient(m)} style={{ display: 'flex', alignItems: 'center', gap: 11, width: '100%', textAlign: 'left', padding: '11px 14px', borderBottom: '1px solid var(--hairline)', transition: 'background .12s' }}
                        onMouseEnter={e => e.currentTarget.style.background = 'var(--hover)'}
                        onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                        <Avatar initials={m.initials} hue={parseInt(m.id.slice(3), 10) % 360} size={28} />
                        <span style={{ fontSize: 13.5, fontWeight: 700 }}>{m.displayName}</span>
                        <span className="mono t-faint" style={{ fontSize: 11.5 }}>{m.id}</span>
                        <span className="t-faint" style={{ fontSize: 11.5, marginLeft: 'auto' }}>last visit {m.lastVisit}</span>
                      </button>
                    ))}
                  </div>
                )}
                {qName.trim() && matches.length === 0 && (
                  <div style={{ marginTop: 8, display: 'flex', alignItems: 'center', gap: 10, fontSize: 12.5 }} className="t-soft">
                    No match. <button onClick={() => setMode('new')} style={{ fontWeight: 700, color: 'var(--accent)' }}>Register as a new client →</button>
                  </div>
                )}
              </React.Fragment>
            )}
          </div>

          {/* recorded by */}
          <div>
            <label style={labelStyle}>Recorded by</label>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
              {(meOnRoster
                ? [{ ...S.EHCW_STAFF.find(st => st.name === me.displayName), you: true },
                   ...S.EHCW_STAFF.filter(st => st.name !== me.displayName)]
                : S.EHCW_STAFF
              ).map(st => {
                const on = recordedBy === st.name;
                return (
                  <button key={st.name} onClick={() => { setRecordedBy(st.name); setRecordedByTouched(true); }} title={st.name} style={{
                    display: 'inline-flex', alignItems: 'center', gap: 8, padding: '7px 14px 7px 7px', borderRadius: 99, minHeight: 44,
                    background: on ? 'var(--accent-soft)' : 'var(--hover)',
                    border: on ? '1.5px solid var(--accent)' : '1px solid var(--hairline)', transition: 'all .15s'
                  }}>
                    <StaffAvatar staff={st} size={30} />
                    <span style={{ fontSize: 12.5, fontWeight: 700, color: on ? 'var(--accent)' : 'var(--ink-soft)' }}>
                      {st.you ? 'You' : st.name.split(' ')[0]}
                    </span>
                  </button>
                );
              })}
            </div>
          </div>

          {/* reason for visit */}
          <div>
            <label style={labelStyle}>Reason for visit</label>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
              {Object.keys(VISIT_REASONS).map(r => (
                <button key={r} onClick={() => { setReason(r); setService(null); }} style={chip(reason === r)}>{reason === r ? '✓ ' : ''}{r}</button>
              ))}
            </div>
            {reason && (
              <div style={{ marginTop: 12 }}>
                <label style={{ ...labelStyle, marginTop: 0 }}>Select service</label>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                  {VISIT_REASONS[reason].map(sv => (
                    <button key={sv} onClick={() => setService(sv)} style={{ ...chip(service === sv, 'var(--blue)', 'white'), padding: '9px 14px', fontSize: 12.5, minHeight: 40 }}>{service === sv ? '✓ ' : ''}{sv}</button>
                  ))}
                </div>
              </div>
            )}
          </div>

          {/* food extras — only for Day to Day → Food */}
          {isFood && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }} data-comment-anchor="c5332cf925-div-71-11">
              <div>
                <label style={labelStyle}>Location <span style={{ color: 'var(--coral)' }}>*</span></label>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                  {S.LOCATIONS.map(l => <button key={l} onClick={() => setFoodLoc(l)} style={chip(foodLoc === l, 'var(--gold-deep)', 'white')}>{foodLoc === l ? '✓ ' : ''}{l}</button>)}
                </div>
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 16, alignItems: 'end' }}>
                <div>
                  <label style={labelStyle}>Hamper received</label>
                  <button onClick={() => setHamper(h => !h)} style={{
                    display: 'flex', alignItems: 'center', gap: 12, padding: '11px 16px', borderRadius: 14, width: '100%',
                    background: hamper ? 'var(--leaf-soft)' : 'var(--hover)', border: '1px solid var(--hairline-strong)'
                  }}>
                    <span style={{ width: 46, height: 26, borderRadius: 99, position: 'relative', flexShrink: 0, background: hamper ? 'var(--leaf)' : 'var(--hairline-strong)', transition: 'background .25s' }}>
                      <span style={{ position: 'absolute', top: 3, left: hamper ? 23 : 3, width: 20, height: 20, borderRadius: 99, background: 'white', transition: 'left .25s var(--ease-spring)', boxShadow: '0 1px 4px rgba(0,0,0,.25)' }}></span>
                    </span>
                    <span style={{ fontSize: 14.5, fontWeight: 700 }}>{hamper ? 'Yes' : 'No'}</span>
                  </button>
                </div>
                <div>
                  <label style={labelStyle}>Hamper weight (lbs)</label>
                  <input type="number" min="0" value={weight} onChange={e => setWeight(e.target.value)} placeholder="0" style={inputStyle} />
                </div>
              </div>
              <div>
                <label style={labelStyle}>Items received</label>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                  {FB_ITEMS.map(it => {
                    const on = items.includes(it);
                    return <button key={it} onClick={() => setItems(v => on ? v.filter(x => x !== it) : [...v, it])} style={chip(on)}>{on ? '✓ ' : ''}{it}</button>;
                  })}
                </div>
              </div>
            </div>
          )}

          <div>
            <label style={labelStyle}>Notes <span className="t-faint" style={{ fontWeight: 500 }}>(optional)</span></label>
            <textarea value={notes} onChange={e => setNotes(e.target.value)} rows="2" placeholder="Anything to remember…" style={{ ...inputStyle, resize: 'vertical', fontFamily: 'var(--font-body)' }}></textarea>
          </div>

          <button onClick={submit} disabled={!canSubmit} style={{
            padding: '16px 24px', borderRadius: 16, fontSize: 16, fontWeight: 700, fontFamily: 'var(--font-display)',
            background: canSubmit ? 'linear-gradient(135deg, oklch(0.64 0.11 155), oklch(0.56 0.11 175))' : 'var(--hover)',
            color: canSubmit ? 'white' : 'var(--ink-faint)',
            boxShadow: canSubmit ? '0 12px 28px -10px oklch(0.6 0.11 160)' : 'none',
            minHeight: 54, cursor: canSubmit ? 'pointer' : 'not-allowed'
          }}>{canSubmit ? 'Submit check-in' : isFood && !foodLoc && client && reason && service ? 'Pick a location to submit' : 'Submit check-in'}</button>
        </div>
      )}

      {/* ============ Today's Log ============ */}
      {mode === 'log' && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <div className="glass" style={{ borderRadius: 'var(--radius-l)', padding: '18px 24px', display: 'flex', gap: 28, flexWrap: 'wrap', boxShadow: 'var(--shadow-card)' }}>
            <div><span style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 26 }}>{todayVisits.length}</span> <span className="t-soft" style={{ fontSize: 13.5 }}>check-ins today</span></div>
            <div><span style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 26 }}>{totalLbs}</span> <span className="t-soft" style={{ fontSize: 13.5 }}>lbs food distributed</span></div>
          </div>
          <div className="glass" style={{ borderRadius: 'var(--radius-l)', overflow: 'hidden', boxShadow: 'var(--shadow-card)' }}>
            {todayVisits.length === 0 && (
              <div className="t-faint" style={{ padding: '26px 24px', fontSize: 13.5, display: 'flex', alignItems: 'center', gap: 9 }}>
                <Icon name="check" size={16} style={{ color: 'var(--leaf)' }} /> No check-ins yet today. Past visits live on each client's record.
              </div>
            )}
            {todayVisits.map((v, i) =>
              <div key={v.id} style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '14px 20px', borderTop: i === 0 ? 'none' : '1px solid var(--hairline)', animation: 'trellis-rise .3s ease' }}>
                <Avatar initials={v.initials} hue={i * 67 % 360} size={36} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 14, fontWeight: 700 }}>Client {v.initials} {v.reason && <span className="t-faint" style={{ fontWeight: 500 }}>· {v.reason} › {v.subtype}{v.loc ? ' · ' + v.loc : ''}</span>}</div>
                  {v.items.length > 0 && <div className="t-faint" style={{ fontSize: 12 }}>{v.items.join(' · ')}</div>}
                </div>
                <div style={{ textAlign: 'right' }}>
                  {v.weight > 0 && <div className="mono" style={{ fontSize: 13.5, fontWeight: 600 }}>{v.weight} lbs</div>}
                  <div className="t-faint mono" style={{ fontSize: 11 }}>{v.time} · {v.by}</div>
                </div>
              </div>
            )}
          </div>
        </div>
      )}
    </div>);
}

/* ============================ SETTINGS ============================ */

function SettingsPage({ role, theme, setTheme, push }) {
  const D = window.TRELLIS_DATA;
  const meSettings = useEhcwUser();
  const KIND_ICON = { reveal: 'eye', report: 'report', system: 'spark', write: 'plus' };
  const [, setTick] = React.useState(0);
  React.useEffect(() => {
    const bump = () => setTick(t => t + 1);
    document.addEventListener('ehcw:data:audit', bump);
    return () => document.removeEventListener('ehcw:data:audit', bump);
  }, []);
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 20, maxWidth: 880 }}>
      <div>
        <h1 style={{ fontSize: 'clamp(24px, 3.4vw, 32px)', fontWeight: 700, letterSpacing: '-0.025em' }}>Settings &amp; Trust</h1>
        <p className="t-soft" style={{ margin: '6px 0 0', fontSize: 14.5 }}>How Unstoppables keeps client data private, and who can do what.</p>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: 16 }}>
        {/* policy cards */}
        <div className="glass" style={{ borderRadius: 'var(--radius-l)', padding: 24, boxShadow: 'var(--shadow-card)', display: 'flex', flexDirection: 'column', gap: 14 }}>
          <h3 style={{ fontSize: 16, fontWeight: 700, display: 'flex', alignItems: 'center', gap: 8 }}><Icon name="shield" size={18} style={{ color: 'var(--leaf)' }} /> Data residency &amp; privacy</h3>
          {[
          ['Region', 'northamerica-northeast1 · Montréal — every read and write'],
          ['PII at rest', 'Masked everywhere in the app. Visible only in Admin-generated reports.'],
          ['Audit trail', 'Every reveal, export and import is logged with who, when, and why.'],
          ['Access', 'Google sign-in, @ehcw.ca domain only. No passwords stored.'],
          ['Client comms', 'Unstoppables never messages clients. Staff-facing only.']].
          map(([k, v]) =>
          <div key={k} style={{ display: 'grid', gridTemplateColumns: '92px 1fr', gap: 12, fontSize: 13, lineHeight: 1.55 }}>
              <span style={{ fontWeight: 700, color: 'var(--ink-soft)' }}>{k}</span>
              <span className="t-soft">{v}</span>
            </div>
          )}
        </div>

        {/* appearance + role */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div className="glass" style={{ borderRadius: 'var(--radius-l)', padding: 24, boxShadow: 'var(--shadow-card)', display: 'flex', flexDirection: 'column', gap: 14 }}>
            <h3 style={{ fontSize: 16, fontWeight: 700 }}>Appearance</h3>
            <div style={{ display: 'flex', gap: 10 }}>
              {[['light', 'sun', 'Light'], ['dark', 'moon', 'Dark']].map(([t, ic, label]) =>
              <button key={t} onClick={() => setTheme(t)} style={{
                flex: 1, padding: '14px 12px', borderRadius: 16, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8,
                background: theme === t ? 'var(--accent-soft)' : 'var(--hover)',
                border: theme === t ? '1.5px solid var(--accent)' : '1px solid var(--hairline)',
                fontWeight: 700, fontSize: 13.5, transition: 'all .2s'
              }}><Icon name={ic} size={20} /> {label}</button>
              )}
            </div>
            <p className="t-faint" style={{ fontSize: 12, margin: 0 }}>The wallpaper follows your cursor in both modes. Click anywhere on it for a ripple.</p>
          </div>
          <div className="glass" style={{ borderRadius: 'var(--radius-l)', padding: 24, boxShadow: 'var(--shadow-card)', display: 'flex', flexDirection: 'column', gap: 12 }}>
            <h3 style={{ fontSize: 16, fontWeight: 700 }}>Your access</h3>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              <PersonAvatar name={meSettings?.displayName || 'June Park'} photo={meSettings?.photoURL} size={40} />
              <div>
                <div style={{ fontSize: 14.5, fontWeight: 700 }}>{meSettings?.displayName || 'June Park'}</div>
                <div className="t-faint mono" style={{ fontSize: 12 }}>{meSettings?.email || 'june@ehcw.ca'}</div>
              </div>
              <span style={{ marginLeft: 'auto' }}><Badge tone={role === 'admin' ? 'plum' : 'blue'}>{role === 'admin' ? 'Admin' : 'Caseworker'}</Badge></span>
            </div>
            <p className="t-faint" style={{ fontSize: 12, margin: 0, lineHeight: 1.55 }}>Admin status is assigned from the backend (Firebase custom claims) — it cannot be self-granted in the app.</p>
          </div>
        </div>
      </div>

      {/* audit trail */}
      <div className="glass" style={{ borderRadius: 'var(--radius-l)', padding: 24, boxShadow: 'var(--shadow-card)', display: 'flex', flexDirection: 'column', gap: 14 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 8 }}>
          <h3 style={{ fontSize: 16, fontWeight: 700 }}>Audit trail — today</h3>
          <button onClick={() => push('Audit log exported — CSV')} className="t-faint" style={{ fontSize: 12.5, fontWeight: 700, display: 'flex', alignItems: 'center', gap: 5 }}>
            <Icon name="download" size={14} /> Export CSV
          </button>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column' }}>
          {D.AUDIT.map((a, i) =>
          <div key={i} style={{ display: 'flex', gap: 14, alignItems: 'center', padding: '11px 0', borderTop: i === 0 ? 'none' : '1px solid var(--hairline)' }}>
              <span className="mono t-faint" style={{ fontSize: 12, width: 42, flexShrink: 0 }}>{a.t}</span>
              <span style={{
              width: 30, height: 30, borderRadius: 10, display: 'grid', placeItems: 'center', flexShrink: 0,
              background: a.kind === 'reveal' ? 'var(--coral-soft)' : a.kind === 'report' ? 'var(--blue-soft)' : 'var(--hover)',
              color: a.kind === 'reveal' ? 'var(--coral)' : a.kind === 'report' ? 'var(--blue)' : 'var(--ink-faint)'
            }}><Icon name={KIND_ICON[a.kind]} size={15} /></span>
              <span style={{ fontSize: 13.5, lineHeight: 1.5 }}><strong>{a.who}</strong> <span className="t-soft">— {a.what}</span></span>
            </div>
          )}
        </div>
      </div>
    </div>);

}

Object.assign(window, { FoodBankPage, SettingsPage });
