/* Screen — Admin / CMS · Members
   Focus: PII anonymization, anti-farming activity log & metrics, admin actions.
   Layout: admin nav → segmented filters → member table → detail drawer for selected member */

function ScreenAdminMembers() {
  const [showPII, setShowPII] = React.useState(false);
  const [selected, setSelected] = React.useState(0);
  const [filter, setFilter] = React.useState('all');

  // Mask helpers
  const maskEmail = (e) => {
    const [u, d] = e.split('@');
    if (!u || !d) return '••••@••••';
    return u[0] + '•••' + u.slice(-1) + '@' + d;
  };
  const maskName = (n) => {
    const parts = n.split(' ');
    return parts.map((p, i) => i === 0 ? p[0] + '.' : '••••').join(' ');
  };
  const maskInst = (i) => i.split(' ').map(w => w[0]).join('') + ' (anon)';

  // Risk = aggregate signal of CME farming behavior
  const MEMBERS = [
    {
      id: 'M-104821', name: 'Maya Chen', email: 'm.chen@stanford-med.edu', role: 'Student · MS-2',
      inst: 'Stanford School of Medicine', plan: 'Free (verified .edu)', joined: '2025-09-14',
      status: 'Active', lastSeen: '2h ago', risk: 4, riskLabel: 'Low',
      credits: 0, sessions: 124, dwellAvg: '6m 12s', passRate: 92, ipCount: 2, country: 'US',
      flags: []
    },
    {
      id: 'M-102117', name: 'Dr. Ravi Iyer', email: 'r.iyer@uchicagomed.org', role: 'Practitioner · IM',
      inst: 'UChicago Medicine', plan: 'Practitioner · monthly', joined: '2024-03-08',
      status: 'Active', lastSeen: 'Yesterday', risk: 12, riskLabel: 'Low',
      credits: 28.5, sessions: 86, dwellAvg: '14m 03s', passRate: 88, ipCount: 1, country: 'US',
      flags: []
    },
    {
      id: 'M-108993', name: 'Dr. K. Suzuki', email: 'k.suzuki.md@protonmail.com', role: 'Practitioner · Cards',
      inst: '— self-reported', plan: 'Practitioner · annual', joined: '2026-01-04',
      status: 'Flagged · review', lastSeen: '14m ago', risk: 78, riskLabel: 'High',
      credits: 42.0, sessions: 28, dwellAvg: '1m 48s', passRate: 100, ipCount: 7, country: 'mixed',
      flags: ['Sub-threshold dwell on 38 modules', '100% pass rate (statistical outlier)', 'IP across 4 countries in 30d', 'Quiz attempts ≤ 8s']
    },
    {
      id: 'M-101455', name: 'Sarah Kim, NP', email: 'skim@mtsinai.org', role: 'Nurse · NP',
      inst: 'Mount Sinai', plan: 'Practitioner', joined: '2024-11-22',
      status: 'Active', lastSeen: '4h ago', risk: 8, riskLabel: 'Low',
      credits: 18.0, sessions: 64, dwellAvg: '11m 41s', passRate: 86, ipCount: 1, country: 'US',
      flags: []
    },
    {
      id: 'M-110204', name: 'Dr. Amos Klein', email: 'a.klein@kaiser.org', role: 'Practitioner · ED',
      inst: 'Kaiser Permanente', plan: 'Institution · 240 seats', joined: '2023-05-19',
      status: 'Active', lastSeen: '1d ago', risk: 6, riskLabel: 'Low',
      credits: 36.0, sessions: 142, dwellAvg: '12m 30s', passRate: 84, ipCount: 2, country: 'US',
      flags: []
    },
    {
      id: 'M-112038', name: 'Dr. R. Adelaja', email: 'r.adelaja@kpmd.com', role: 'Practitioner',
      inst: '— self-reported', plan: 'Practitioner', joined: '2025-12-02',
      status: 'Payment failed', lastSeen: '3d ago', risk: 22, riskLabel: 'Medium',
      credits: 12.0, sessions: 31, dwellAvg: '4m 02s', passRate: 95, ipCount: 3, country: 'US/CA',
      flags: ['Card declined ×3', 'Multiple short sessions']
    },
    {
      id: 'M-114002', name: 'James O\u2019Hara', email: 'jo@nyp.org', role: 'Resident · PGY-3',
      inst: 'NewYork-Presbyterian', plan: 'Trial · 11d left', joined: '2026-05-01',
      status: 'Trial', lastSeen: '32m ago', risk: 5, riskLabel: 'Low',
      credits: 1.5, sessions: 12, dwellAvg: '8m 14s', passRate: 80, ipCount: 1, country: 'US',
      flags: []
    },
    {
      id: 'M-098341', name: 'Dr. Yuki Tanaka', email: 'y.tanaka@osakam.jp', role: 'Practitioner · Cards',
      inst: 'Osaka University', plan: 'Practitioner', joined: '2024-08-12',
      status: 'Suspended', lastSeen: '12d ago', risk: 84, riskLabel: 'Banned',
      credits: 64.0, sessions: 18, dwellAvg: '0m 52s', passRate: 100, ipCount: 12, country: 'mixed',
      flags: ['Credentials shared across 12 devices', 'CME claim revoked × 2', 'Account sharing confirmed by audit']
    },
  ];

  // ─ Filters ─
  const tabs = [
    { id: 'all', label: 'All', n: MEMBERS.length },
    { id: 'flagged', label: 'Flagged', n: MEMBERS.filter(m => m.risk >= 20).length },
    { id: 'trial', label: 'Trials', n: MEMBERS.filter(m => m.status === 'Trial').length },
    { id: 'inst', label: 'Institutions', n: MEMBERS.filter(m => m.plan.startsWith('Institution')).length },
    { id: 'suspended', label: 'Suspended / banned', n: MEMBERS.filter(m => m.status === 'Suspended').length },
  ];
  const filtered = MEMBERS.filter(m => {
    if (filter === 'all') return true;
    if (filter === 'flagged') return m.risk >= 20;
    if (filter === 'trial') return m.status === 'Trial';
    if (filter === 'inst') return m.plan.startsWith('Institution');
    if (filter === 'suspended') return m.status === 'Suspended';
    return true;
  });

  const sel = filtered[selected] || filtered[0];

  // ─ Pill helpers ─
  const riskTone = (risk) => {
    if (risk >= 70) return { bg: '#fdecec', fg: '#b1413f', bd: '#f5c5c4', label: risk >= 80 ? 'Banned' : 'High' };
    if (risk >= 20) return { bg: 'var(--warn-tint)', fg: 'var(--warn)', bd: '#f1d4a1', label: 'Medium' };
    return { bg: '#eaf6ef', fg: '#14804a', bd: '#bfe3cb', label: 'Low' };
  };

  const RiskBadge = ({ risk }) => {
    const c = riskTone(risk);
    return (
      <span style={{
        display: 'inline-flex', alignItems: 'center', gap: 6,
        padding: '3px 8px', fontSize: 11, fontWeight: 500,
        background: c.bg, color: c.fg, border: `1px solid ${c.bd}`,
        borderRadius: 999, fontFamily: "'IBM Plex Mono', monospace",
        letterSpacing: '0.04em', textTransform: 'uppercase'
      }}>
        <span style={{ width: 6, height: 6, borderRadius: '50%', background: c.fg }} />
        {c.label} · {risk}
      </span>
    );
  };

  const StatusPill = ({ s }) => {
    let bg = 'var(--paper-2)', fg = 'var(--ink-2)', bd = 'var(--line)';
    if (s === 'Active') { bg = '#eaf6ef'; fg = '#14804a'; bd = '#bfe3cb'; }
    else if (s === 'Trial') { bg = 'var(--sky-tint)'; fg = 'var(--sky-deep)'; bd = 'var(--sky-tint-2)'; }
    else if (s.toLowerCase().includes('flag')) { bg = 'var(--warn-tint)'; fg = 'var(--warn)'; bd = '#f1d4a1'; }
    else if (s.toLowerCase().includes('suspend') || s.toLowerCase().includes('fail')) { bg = '#fdecec'; fg = '#b1413f'; bd = '#f5c5c4'; }
    return (
      <span style={{
        display: 'inline-flex', alignItems: 'center', gap: 6,
        padding: '2px 7px', fontSize: 10, fontWeight: 500,
        background: bg, color: fg, border: `1px solid ${bd}`,
        borderRadius: 4, fontFamily: "'IBM Plex Mono', monospace",
        letterSpacing: '0.06em', textTransform: 'uppercase'
      }}>{s}</span>
    );
  };

  // ─ Activity log entries for selected member ─
  const ACTIVITY = sel.flags.length > 0 && sel.id === 'M-108993' ? [
    { t: '14:08', d: 'Module quiz · "Sepsis recognition"', meta: 'Submitted in 6s · 9/10 correct', flag: 'Sub-threshold attempt time', tone: 'warn' },
    { t: '14:03', d: 'Module viewed · "GDMT in 2026"', meta: 'Dwell 1m 12s · expected 38m', flag: 'Speed-watch', tone: 'warn' },
    { t: '13:51', d: 'Module quiz · "HFpEF post-read"', meta: 'Submitted in 4s · 6/6 correct', flag: 'Sub-threshold + 100%', tone: 'warn' },
    { t: '13:50', d: 'Course "Heart Failure 2026" · started', meta: 'Resumed module 1', tone: 'ok' },
    { t: '11:24', d: 'IP changed · 142.250.xxx.xxx → 81.2.69.xxx', meta: 'PL → DE in 38min', flag: 'Geo velocity', tone: 'warn' },
    { t: '09:02', d: 'Login · password', meta: 'New device · Chrome 124 / Win', tone: 'ok' },
    { t: 'Yest 22:14', d: 'CME credit claimed · 1.5 AMA PRA', meta: 'HFpEF article quiz', tone: 'warn' },
    { t: 'Yest 21:58', d: 'Article viewed · "HFpEF phenotypes"', meta: 'Dwell 0m 42s · article needs ~14m', flag: 'Speed-read', tone: 'warn' },
  ] : [
    { t: '2h ago', d: 'Module completed · "Stroke door-to-needle"', meta: 'Dwell 18m 22s · 8/10 pass', tone: 'ok' },
    { t: '4h ago', d: 'Article bookmarked · "AKI biomarkers"', meta: 'Nephrology', tone: 'ok' },
    { t: 'Yesterday', d: 'CME credit claimed · 0.5 AMA PRA', meta: 'Antimicrobial stewardship', tone: 'ok' },
    { t: '2d ago', d: 'Login', meta: 'Same device · Safari 17 / macOS', tone: 'ok' },
    { t: '4d ago', d: 'Note added · 6 lines', meta: 'on RSV under-twos', tone: 'ok' },
    { t: '5d ago', d: 'Module quiz · 7/8 correct', meta: 'Dwell on module 22m', tone: 'ok' },
  ];

  // ─ Member detail drawer ─
  function MemberDetail() {
    const showName = showPII ? sel.name : maskName(sel.name);
    const showMail = showPII ? sel.email : maskEmail(sel.email);
    const showInst = showPII ? sel.inst : maskInst(sel.inst);

    return (
      <div style={{ background: 'var(--paper)', display: 'flex', flexDirection: 'column' }}>
        {/* Detail header */}
        <div style={{ padding: '22px 24px', borderBottom: '1px solid var(--line)' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 14 }}>
            <div style={{ display: 'flex', gap: 14, alignItems: 'center' }}>
              <div style={{
                width: 56, height: 56, borderRadius: '50%',
                background: showPII ? 'var(--sky-tint)' : 'var(--paper-3)',
                color: showPII ? 'var(--sky-deep)' : 'var(--muted)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontFamily: "'Newsreader', serif", fontSize: 22, fontWeight: 500,
                border: '1px solid var(--line-2)',
                filter: showPII ? 'none' : 'blur(0.5px)'
              }}>
                {showPII ? sel.name.split(' ').slice(-2).map(n => n[0]).join('').slice(-2) : '••'}
              </div>
              <div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 4 }}>
                  <span className="mono" style={{ fontSize: 11, color: 'var(--muted)', letterSpacing: '0.08em' }}>{sel.id}</span>
                  <StatusPill s={sel.status} />
                  <RiskBadge risk={sel.risk} />
                </div>
                <div className="hand" style={{ fontSize: 26, lineHeight: 1, color: 'var(--ink)' }}>{showName}</div>
                <div className="mono" style={{ fontSize: 12, color: 'var(--muted)', marginTop: 4 }}>{showMail}</div>
              </div>
            </div>
            <div style={{ display: 'flex', gap: 6 }}>
              <button className="btn">⋯</button>
              <button className="btn">↗ Open as user</button>
              <button className="btn" style={{
                background: sel.status === 'Suspended' ? '#fdecec' : 'var(--warn-tint)',
                color: sel.status === 'Suspended' ? '#b1413f' : 'var(--warn)',
                borderColor: sel.status === 'Suspended' ? '#f5c5c4' : '#f1d4a1'
              }}>⏸ Suspend</button>
              <button className="btn" style={{ background: '#b1413f', color: '#fff', borderColor: '#b1413f' }}>⊘ Ban</button>
            </div>
          </div>

          {/* PII bar */}
          <div className="wf-border-thin" style={{
            padding: '10px 14px', background: showPII ? 'var(--warn-tint)' : 'var(--paper-2)',
            display: 'flex', alignItems: 'center', gap: 12, fontSize: 13,
            borderColor: showPII ? '#f1d4a1' : 'var(--line)'
          }}>
            <span style={{
              width: 24, height: 24, borderRadius: '50%',
              background: showPII ? 'var(--warn)' : 'var(--ink-2)',
              color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontWeight: 700, fontSize: 11
            }}>{showPII ? '!' : '🔒'}</span>
            <div style={{ flex: 1, color: showPII ? 'var(--warn)' : 'var(--ink-2)' }}>
              {showPII ? (
                <>
                  <strong>PII is visible.</strong> This view is recorded in the audit log and tied to your admin session (PR · 2026-05-12 14:32). Re-anonymize when finished.
                </>
              ) : (
                <>
                  <strong>PII is anonymized.</strong> Names, emails, institutions and IPs are masked. Reveal requires a logged reason and step-up auth.
                </>
              )}
            </div>
            <button
              className="btn"
              onClick={() => setShowPII(!showPII)}
              style={{
                background: showPII ? 'var(--paper)' : 'var(--ink)',
                color: showPII ? 'var(--ink)' : 'var(--paper)',
                borderColor: showPII ? 'var(--line-2)' : 'var(--ink)'
              }}
            >
              {showPII ? '🔒 Re-anonymize' : '👁 Reveal PII'}
            </button>
          </div>
        </div>

        {/* Identity grid */}
        <div style={{ padding: '20px 24px', borderBottom: '1px solid var(--line)' }}>
          <div className="sec-tag" style={{ marginBottom: 10 }}>Identity</div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14 }}>
            {[
              { l: 'Role', v: sel.role },
              { l: 'Institution', v: showInst, pii: true },
              { l: 'Plan', v: sel.plan },
              { l: 'Joined', v: sel.joined, mono: true },
              { l: 'Verification', v: showPII ? '.edu confirmed · 2025-09-15' : '.edu verified', mono: true },
              { l: 'Country', v: showPII ? sel.country : 'masked', mono: true, pii: true },
              { l: 'Last seen', v: sel.lastSeen, mono: true },
              { l: 'License (CME)', v: showPII ? 'CA-MD-A82193' : '••-••-••••••', mono: true, pii: true },
            ].map((f, i) => (
              <div key={i}>
                <div className="sec-tag" style={{ marginBottom: 4, opacity: f.pii && !showPII ? 0.6 : 1 }}>
                  {f.l}{f.pii && <span style={{ marginLeft: 4, color: 'var(--warn)' }}>·</span>}
                </div>
                <div style={{
                  fontSize: 13, fontFamily: f.mono ? "'IBM Plex Mono', monospace" : "'IBM Plex Sans', sans-serif",
                  color: f.pii && !showPII ? 'var(--muted)' : 'var(--ink)',
                  fontStyle: f.pii && !showPII ? 'italic' : 'normal'
                }}>{f.v}</div>
              </div>
            ))}
          </div>
        </div>

        {/* Anti-farming metrics */}
        <div style={{ padding: '20px 24px', borderBottom: '1px solid var(--line)', background: 'var(--paper-2)' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
            <div className="sec-tag">CME integrity · last 90d</div>
            <span className="mono" style={{ fontSize: 11, color: 'var(--muted)' }}>Algorithm v3.2 · ACCME-aligned</span>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 12, marginBottom: 16 }}>
            {[
              { l: 'CME claimed', v: `${sel.credits.toFixed(1)}`, sub: 'AMA PRA Cat 1', tone: sel.credits > 50 ? 'warn' : 'ink' },
              { l: 'Sessions', v: `${sel.sessions}`, sub: 'unique sign-ins' },
              { l: 'Avg dwell / module', v: sel.dwellAvg, sub: 'target ≥ 80% of runtime', tone: parseInt(sel.dwellAvg) < 5 ? 'warn' : 'ok' },
              { l: 'Quiz pass rate', v: `${sel.passRate}%`, sub: 'avg cohort 78%', tone: sel.passRate === 100 ? 'warn' : 'ink' },
              { l: 'Distinct IPs / 30d', v: `${sel.ipCount}`, sub: showPII ? sel.country : 'masked', tone: sel.ipCount >= 5 ? 'warn' : 'ok' },
            ].map((m, i) => (
              <div key={i} className="wf-border-thin" style={{ padding: 12, background: 'var(--paper)' }}>
                <div className="sec-tag" style={{ marginBottom: 6 }}>{m.l}</div>
                <div className="hand" style={{
                  fontSize: 24, lineHeight: 1,
                  color: m.tone === 'warn' ? 'var(--warn)' : m.tone === 'ok' ? '#14804a' : 'var(--ink)'
                }}>{m.v}</div>
                <div className="mono" style={{ fontSize: 10, color: 'var(--muted)', marginTop: 4 }}>{m.sub}</div>
              </div>
            ))}
          </div>

          {/* Risk score visualization */}
          <div className="wf-border-thin" style={{ padding: 14, background: 'var(--paper)' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 8 }}>
              <div>
                <div className="sec-tag">Composite risk score</div>
                <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginTop: 2 }}>
                  <span className="hand" style={{ fontSize: 28, color: riskTone(sel.risk).fg, lineHeight: 1 }}>{sel.risk}</span>
                  <span className="mono" style={{ fontSize: 11, color: 'var(--muted)' }}>/ 100 · {riskTone(sel.risk).label.toLowerCase()}</span>
                </div>
              </div>
              <span className="mono" style={{ fontSize: 11, color: 'var(--muted)' }}>Updated 4 min ago</span>
            </div>
            <div style={{ height: 8, background: 'var(--paper-3)', borderRadius: 4, overflow: 'hidden', display: 'flex' }}>
              <div style={{ width: '20%', background: '#bfe3cb' }} />
              <div style={{ width: '50%', background: '#f1d4a1' }} />
              <div style={{ width: '30%', background: '#f5c5c4' }} />
            </div>
            <div style={{ position: 'relative', height: 0 }}>
              <div style={{
                position: 'absolute', top: -14, left: `${sel.risk}%`,
                width: 2, height: 16, background: 'var(--ink)',
                transform: 'translateX(-1px)'
              }} />
            </div>
            <div className="mono" style={{ fontSize: 10, color: 'var(--muted)', display: 'flex', justifyContent: 'space-between', marginTop: 10 }}>
              <span>0 · trusted</span><span>20 · review</span><span>70 · high-risk</span><span>100 · banned</span>
            </div>
          </div>

          {/* Flags */}
          {sel.flags.length > 0 && (
            <div style={{ marginTop: 14 }}>
              <div className="sec-tag" style={{ marginBottom: 8 }}>Triggered signals · {sel.flags.length}</div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                {sel.flags.map((f, i) => (
                  <div key={i} style={{
                    display: 'flex', alignItems: 'center', gap: 10,
                    padding: '10px 12px', background: 'var(--warn-tint)',
                    border: '1px solid #f1d4a1', borderRadius: 'var(--radius-sm)',
                    fontSize: 13, color: 'var(--warn)'
                  }}>
                    <span style={{ width: 18, height: 18, borderRadius: '50%', background: 'var(--warn)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 11, fontWeight: 700 }}>!</span>
                    <span style={{ flex: 1, color: 'var(--ink)' }}>{f}</span>
                    <span className="mono" style={{ fontSize: 10, color: 'var(--muted)' }}>auto-detected</span>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>

        {/* Activity log */}
        <div style={{ padding: '20px 24px' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
            <div className="sec-tag">Activity log · last 24h</div>
            <div style={{ display: 'flex', gap: 6 }}>
              <span className="chip chip-sky">All</span>
              <span className="chip">CME events</span>
              <span className="chip">Auth</span>
              <span className="chip">Flags only</span>
            </div>
          </div>
          <div className="wf-border" style={{ background: 'var(--paper)', overflow: 'hidden' }}>
            {ACTIVITY.map((row, i) => (
              <div key={i} style={{
                display: 'grid', gridTemplateColumns: '90px 1fr 200px 120px',
                gap: 12, padding: '12px 16px', alignItems: 'center',
                borderBottom: i < ACTIVITY.length - 1 ? '1px solid var(--line)' : 'none',
                background: row.tone === 'warn' ? 'rgba(180, 83, 9, 0.04)' : 'var(--paper)'
              }}>
                <span className="mono" style={{ fontSize: 11, color: 'var(--muted)' }}>{row.t}</span>
                <span style={{ fontSize: 13 }}>{row.d}</span>
                <span className="mono" style={{ fontSize: 11, color: 'var(--muted)' }}>{row.meta}</span>
                <span>
                  {row.flag ? (
                    <span style={{
                      display: 'inline-flex', alignItems: 'center', gap: 4,
                      padding: '2px 7px', fontSize: 10, fontWeight: 500,
                      background: 'var(--warn-tint)', color: 'var(--warn)',
                      border: '1px solid #f1d4a1', borderRadius: 4,
                      fontFamily: "'IBM Plex Mono', monospace",
                      letterSpacing: '0.04em', textTransform: 'uppercase'
                    }}>! {row.flag}</span>
                  ) : (
                    <span className="mono" style={{ fontSize: 10, color: '#14804a' }}>● ok</span>
                  )}
                </span>
              </div>
            ))}
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 10 }}>
            <span className="mono" style={{ fontSize: 11, color: 'var(--muted)' }}>Showing 8 of 1,240 events · all events kept 24 months</span>
            <button className="btn" style={{ padding: '4px 10px', fontSize: 12 }}>↓ Export CSV</button>
          </div>
        </div>

        {/* Admin actions panel */}
        <div style={{ padding: '20px 24px', borderTop: '1px solid var(--line)', background: 'var(--paper-2)' }}>
          <div className="sec-tag" style={{ marginBottom: 12 }}>Administrative actions</div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }}>
            {[
              { icon: '🔍', t: 'Inspect session', d: 'Replay last 7 days of pages, dwell, quiz timing.', btn: 'Open inspector', tone: 'ink' },
              { icon: '↺', t: 'Revoke CME claim', d: `Roll back ${sel.credits.toFixed(1)} credits. Member receives email + state-board notification.`, btn: 'Revoke credits…', tone: 'warn', disabled: sel.credits === 0 },
              { icon: '✉', t: 'Send warning', d: 'Templated email; resolution required within 14d.', btn: 'Compose warning', tone: 'ink' },
              { icon: '⏸', t: 'Suspend account', d: 'Read-only access; CME accrual paused. Reversible.', btn: 'Suspend…', tone: 'warn' },
              { icon: '⊘', t: 'Ban account', d: 'Full block, email + IP blocklist, 24-month audit retention.', btn: 'Ban…', tone: 'danger' },
              { icon: '⤓', t: 'Export & delete (GDPR)', d: 'Subject-access export, then irreversible delete + anonymize.', btn: 'Start request', tone: 'ink' },
            ].map((a, i) => (
              <div key={i} className="wf-border-thin" style={{
                padding: 14, background: 'var(--paper)',
                opacity: a.disabled ? 0.5 : 1
              }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
                  <span style={{ fontSize: 16 }}>{a.icon}</span>
                  <span style={{ fontWeight: 600, fontSize: 14 }}>{a.t}</span>
                </div>
                <div style={{ fontSize: 12, color: 'var(--ink-2)', lineHeight: 1.45, marginBottom: 10, minHeight: 50 }}>{a.d}</div>
                <button className="btn" style={{
                  width: '100%', fontSize: 12, padding: '6px 10px',
                  background: a.tone === 'danger' ? '#b1413f' : a.tone === 'warn' ? 'var(--warn-tint)' : 'var(--paper)',
                  color: a.tone === 'danger' ? '#fff' : a.tone === 'warn' ? 'var(--warn)' : 'var(--ink)',
                  borderColor: a.tone === 'danger' ? '#b1413f' : a.tone === 'warn' ? '#f1d4a1' : 'var(--line-2)'
                }}>{a.btn}</button>
              </div>
            ))}
          </div>
          <div className="mono" style={{ fontSize: 11, color: 'var(--muted)', marginTop: 12, display: 'flex', gap: 8, alignItems: 'center' }}>
            <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--warn)' }} />
            Any destructive action requires step-up MFA and a written reason; both are logged in the audit trail and visible to the member upon request.
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="wf" style={{ background: 'var(--paper-2)', minHeight: '100vh' }}>
      {/* Admin nav */}
      <div style={{ borderBottom: '1.5px solid var(--ink)', padding: '12px 28px', display: 'flex', alignItems: 'center', gap: 22, background: 'var(--ink)', color: 'var(--paper)' }}>
        <div className="hand" style={{ fontSize: 22, display: 'flex', alignItems: 'center', gap: 8 }}>
          <span style={{ display: 'inline-flex', width: 26, height: 26, alignItems: 'center', justifyContent: 'center', border: '1.5px solid var(--paper)', borderRadius: '50%', fontSize: 14, background: 'var(--sky-tint)', color: 'var(--ink)' }}>+</span>
          OpenMedEdu <span style={{ opacity: 0.5, fontSize: 16 }}>· admin</span>
        </div>
        <div style={{ display: 'flex', gap: 18, fontSize: 14, marginLeft: 20 }}>
          <span style={{ opacity: 0.7 }}>Overview</span>
          <span style={{ opacity: 0.7 }}>Content</span>
          <span style={{ opacity: 0.7 }}>Reviews</span>
          <span style={{ borderBottom: '1.5px solid var(--paper)', paddingBottom: 2 }}>Members</span>
          <span style={{ opacity: 0.7 }}>CME &amp; accreditation</span>
          <span style={{ opacity: 0.7 }}>Settings</span>
          <span style={{ opacity: 0.7 }}>Audit log</span>
        </div>
        <div style={{ flex: 1 }} />
        <span className="mono" style={{ fontSize: 12, opacity: 0.7 }}>env: prod · v 2026.05.12</span>
        <div style={{ width: 28, height: 28, borderRadius: '50%', background: 'var(--sky-tint)', color: 'var(--ink)', display: 'flex', alignItems: 'center', justifyContent: 'center' }} className="hand">PR</div>
      </div>

      {/* Page header */}
      <div style={{ padding: '28px 28px 18px', borderBottom: '1px solid var(--line)', background: 'var(--paper)' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 18 }}>
          <div>
            <div className="sec-tag" style={{ marginBottom: 4 }}>Admin · Members</div>
            <div className="hand" style={{ fontSize: 38, lineHeight: 1 }}>Member directory</div>
            <div style={{ fontSize: 14, color: 'var(--ink-2)', marginTop: 4, maxWidth: 660 }}>
              14,237 members · PII masked by default; reveal is logged. Activity signals flag CME-farming patterns automatically.
            </div>
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <button className="btn">↑ Bulk import</button>
            <button className="btn">⤓ Export (anonymized)</button>
            <button className="btn btn-primary">+ Invite member</button>
          </div>
        </div>

        {/* KPI strip */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 12, marginBottom: 18 }}>
          {[
            { l: 'Members', v: '14,237', d: '+ 230 this week' },
            { l: 'Flagged for review', v: '38', d: '12 high-risk', warn: true },
            { l: 'CME claims (90d)', v: '4,182', d: '94 awaiting validation' },
            { l: 'Anti-farming actions', v: '17', d: '4 banned · 9 suspended · 4 reversed', warn: true },
            { l: 'PII reveals (today)', v: '6', d: 'all logged · 0 anomalies', mono: true },
          ].map((s, i) => (
            <div key={i} className="wf-border-thin" style={{ padding: 12, background: 'var(--paper)' }}>
              <div className="sec-tag" style={{ marginBottom: 4 }}>{s.l}</div>
              <div className="hand" style={{ fontSize: 24, lineHeight: 1 }}>{s.v}</div>
              <div className="mono" style={{ fontSize: 10, color: s.warn ? 'var(--warn)' : 'var(--muted)', marginTop: 4 }}>{s.d}</div>
            </div>
          ))}
        </div>

        {/* Filters + global PII toggle */}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12 }}>
          <div style={{ display: 'inline-flex', border: '1px solid var(--line-2)', borderRadius: 'var(--radius-sm)', background: 'var(--paper-2)', padding: 3 }}>
            {tabs.map((tb) => (
              <button
                key={tb.id}
                onClick={() => { setFilter(tb.id); setSelected(0); }}
                style={{
                  padding: '8px 16px', border: 'none', cursor: 'pointer',
                  background: filter === tb.id ? 'var(--paper)' : 'transparent',
                  color: filter === tb.id ? 'var(--ink)' : 'var(--muted)',
                  boxShadow: filter === tb.id ? 'var(--shadow-sm)' : 'none',
                  borderRadius: 4,
                  fontFamily: "'IBM Plex Sans', sans-serif",
                  fontSize: 14, fontWeight: filter === tb.id ? 600 : 500,
                  display: 'inline-flex', alignItems: 'center', gap: 8,
                }}
              >
                {tb.label}
                <span className="mono" style={{
                  fontSize: 11, color: filter === tb.id ? 'var(--sky-deep)' : 'var(--muted-2)',
                  background: filter === tb.id ? 'var(--sky-tint)' : 'transparent',
                  padding: '1px 6px', borderRadius: 4
                }}>{tb.n}</span>
              </button>
            ))}
          </div>

          <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
            <div className="search" style={{ padding: '6px 12px', minWidth: 240, boxShadow: 'none' }}>
              <span className="mono" style={{ fontSize: 13, color: 'var(--muted)' }}>⌕</span>
              <span style={{ fontSize: 13, color: 'var(--muted)' }}>Search by ID · email · IP…</span>
            </div>
            <div style={{
              display: 'inline-flex', alignItems: 'center', gap: 8,
              padding: '6px 12px', border: '1px solid var(--line-2)', borderRadius: 'var(--radius-sm)',
              background: showPII ? 'var(--warn-tint)' : 'var(--paper)',
              fontSize: 13, color: showPII ? 'var(--warn)' : 'var(--ink-2)', cursor: 'pointer'
            }} onClick={() => setShowPII(!showPII)}>
              <span style={{ fontSize: 14 }}>{showPII ? '👁' : '🔒'}</span>
              <span style={{ fontWeight: 500 }}>{showPII ? 'PII visible' : 'PII anonymized'}</span>
              <span style={{
                width: 30, height: 16, borderRadius: 8,
                background: showPII ? 'var(--warn)' : 'var(--muted-2)',
                position: 'relative', transition: 'background 0.15s'
              }}>
                <span style={{
                  position: 'absolute', top: 2, left: showPII ? 16 : 2,
                  width: 12, height: 12, borderRadius: '50%', background: '#fff',
                  transition: 'left 0.15s'
                }} />
              </span>
            </div>
          </div>
        </div>
      </div>

      {/* Body: member table + detail */}
      <div style={{ display: 'grid', gridTemplateColumns: '460px 1fr', minHeight: 1500 }}>
        {/* LEFT — member list */}
        <aside style={{ borderRight: '1px solid var(--line)', background: 'var(--paper)' }}>
          <div style={{ padding: '12px 18px', borderBottom: '1px solid var(--line)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <span className="sec-tag">{filtered.length} members</span>
            <span className="mono" style={{ fontSize: 11, color: 'var(--muted)' }}>Sort: Risk ▾</span>
          </div>
          {filtered.map((m, i) => {
            const showName = showPII ? m.name : maskName(m.name);
            const showMail = showPII ? m.email : maskEmail(m.email);
            return (
              <div
                key={m.id}
                onClick={() => setSelected(i)}
                style={{
                  padding: '14px 18px',
                  borderBottom: '1px solid var(--line)',
                  borderLeft: selected === i ? '3px solid var(--sky)' : '3px solid transparent',
                  background: selected === i ? 'var(--sky-tint)' : 'var(--paper)',
                  cursor: 'pointer'
                }}
              >
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 10, marginBottom: 6 }}>
                  <span className="mono" style={{ fontSize: 10, color: 'var(--muted)', letterSpacing: '0.06em' }}>{m.id}</span>
                  <RiskBadge risk={m.risk} />
                </div>
                <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--ink)', marginBottom: 2 }}>{showName}</div>
                <div className="mono" style={{ fontSize: 11, color: 'var(--muted)', marginBottom: 6 }}>{showMail}</div>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: 12 }}>
                  <span style={{ color: 'var(--ink-2)' }}>{m.role}</span>
                  <StatusPill s={m.status} />
                </div>
                <div className="mono" style={{ fontSize: 10, color: 'var(--muted-2)', marginTop: 6, display: 'flex', justifyContent: 'space-between' }}>
                  <span>{m.credits.toFixed(1)} CME · {m.sessions} sessions</span>
                  <span>last {m.lastSeen}</span>
                </div>
              </div>
            );
          })}
        </aside>

        {/* RIGHT — detail */}
        <main><MemberDetail /></main>
      </div>
    </div>
  );
}

window.ScreenAdminMembers = ScreenAdminMembers;
