/* global React */
const { useState } = React;

// ─────────── Admin Sidebar ───────────
const AdminSidebar = ({ view, setView }) => {
  const items = [
    { k:'dashboard', label:'Dashboard', icon:'grid', group:'Overview' },
    { k:'monitoring', label:'System monitor', icon:'activity', group:'Overview' },
    { k:'cases', label:'Case oversight', icon:'folder', group:'Operations', count:'1.2k' },
    { k:'users', label:'Users & roles', icon:'users', group:'Operations', count:342 },
    { k:'retention', label:'Retention & deletion', icon:'trash', group:'Operations', count:8 },
    { k:'consent', label:'Consent versions', icon:'doc', group:'Content' },
    { k:'templates', label:'Notification templates', icon:'mail', group:'Content' },
    { k:'audit', label:'Audit log', icon:'list', group:'Security' },
    { k:'ai', label:'AI activity', icon:'sparkle', group:'Security' },
    { k:'security', label:'Security & incidents', icon:'shield', group:'Security', count:3 },
  ];
  let last = null;
  return (
    <aside className="sidebar">
      {items.map(it => {
        const grp = it.group !== last ? <div key={it.group} className="sidebar-section">{it.group}</div> : null;
        last = it.group;
        return <>
          {grp}
          <div key={it.k} className={`nav-item ${view===it.k?'on':''}`} onClick={()=>setView(it.k)}>
            <Icon name={it.icon} size={15}/> <span>{it.label}</span>
            {it.count != null && <span className="count">{it.count}</span>}
          </div>
        </>;
      })}
    </aside>
  );
};

// ─────────── Admin Dashboard ───────────
const AdminDashboard = ({ nav }) => (
  <div className="main-col">
    <div className="page-head">
      <div>
        <h1>Operations overview</h1>
        <p className="lead">Wednesday, Apr 23 · all systems nominal</p>
      </div>
      <div style={{display:'flex', gap:8}}>
        <Btn variant="secondary" size="sm">Export report</Btn>
        <Btn variant="primary" size="sm"><Icon name="bell" size={13}/> 3 alerts</Btn>
      </div>
    </div>
    <div className="page-body">
      <div className="grid-4" style={{marginBottom:20}}>
        <StatCard label="Active cases" value="1,284" delta="+42" deltaDir="up" note="vs yesterday"/>
        <StatCard label="Cases filed (mtd)" value="318" delta="+18%" deltaDir="up" note="MoM"/>
        <StatCard label="Avg time-to-file" value="4.8 days" delta="−0.6d" deltaDir="up" note="quarter trend"/>
        <StatCard label="Open incidents" value="3" note="1 P2, 2 P3"/>
      </div>

      <div style={{display:'grid', gridTemplateColumns:'2fr 1fr', gap:18, marginBottom:18}}>
        <div className="card">
          <div style={{padding:'14px 20px', borderBottom:'1px solid var(--line)'}}><h3 style={{fontFamily:'var(--serif)', fontSize:18, fontWeight:400}}>Case flow · past 30 days</h3></div>
          <div style={{padding:'22px 24px', height:200, display:'flex', alignItems:'flex-end', gap:3}}>
            {Array.from({length:30}).map((_,i) => {
              const h = 40 + Math.abs(Math.sin(i * 0.5) * 50) + Math.abs(Math.cos(i*0.3)*20);
              return <div key={i} style={{flex:1, height:`${h}%`, background:'var(--accent)', opacity: 0.4 + (i/30)*0.6, borderRadius:'3px 3px 0 0'}}/>;
            })}
          </div>
        </div>
        <div className="card">
          <div style={{padding:'14px 20px', borderBottom:'1px solid var(--line)'}}><h3 style={{fontFamily:'var(--serif)', fontSize:18, fontWeight:400}}>Reviewer load</h3></div>
          <div style={{padding:'14px 20px'}}>
            {[['J. Delacruz', 14, 20],['A. Sokolov', 11, 20],['L. Kim', 18, 20],['M. Osei', 9, 20],['T. Navarro', 7, 20]].map(([n,v,m]) => (
              <div key={n} style={{marginBottom:10}}>
                <div style={{display:'flex', justifyContent:'space-between', fontSize:12.5, marginBottom:4}}>
                  <span>{n}</span><span className="mono tiny">{v}/{m}</span>
                </div>
                <Progress value={(v/m)*100}/>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:18}}>
        <div className="card">
          <div style={{padding:'14px 20px', borderBottom:'1px solid var(--line)', display:'flex', justifyContent:'space-between'}}>
            <h3 style={{fontFamily:'var(--serif)', fontSize:18, fontWeight:400}}>Needs attention</h3>
            <button className="tiny" style={{color:'var(--accent)'}}>View all</button>
          </div>
          <div>
            {[
              { t:'3 cases past SLA', sub:'Assigned to L. Kim', lvl:'danger', act:'Reassign' },
              { t:'Consent v2026.04 pending publish', sub:'Draft by you · 2d ago', lvl:'warn', act:'Review', go:()=>nav('consent') },
              { t:'8 retention requests awaiting action', sub:'Oldest: 4d', lvl:'warn', act:'Process', go:()=>nav('retention') },
              { t:'AI extraction confidence dropped', sub:'OCR v3.2 · now 89% (was 94%)', lvl:'info', act:'Inspect', go:()=>nav('ai') },
            ].map((row, i) => (
              <div key={i} style={{padding:'12px 20px', borderBottom: i<3?'1px solid var(--line)':'0', display:'flex', alignItems:'center', gap:12}}>
                <Badge variant={row.lvl} dot>{row.lvl}</Badge>
                <div style={{flex:1}}>
                  <div style={{fontSize:13, fontWeight:500}}>{row.t}</div>
                  <div className="tiny">{row.sub}</div>
                </div>
                <Btn variant="secondary" size="sm" onClick={row.go}>{row.act}</Btn>
              </div>
            ))}
          </div>
        </div>

        <div className="card">
          <div style={{padding:'14px 20px', borderBottom:'1px solid var(--line)'}}><h3 style={{fontFamily:'var(--serif)', fontSize:18, fontWeight:400}}>Last 24h activity</h3></div>
          <div style={{padding:'14px 20px'}}>
            <div className="timeline">
              {[
                ['11 min ago','Consent v2026.04 edited by A. Khan',''],
                ['1h ago','Escalation resolved · GE-2026-4751',''],
                ['2h ago','Auto-deletion: 4 expired cases purged','warn'],
                ['4h ago','New reviewer onboarded: T. Navarro',''],
                ['8h ago','Security scan complete · no findings','ai'],
              ].map(([w, t, type], i) => (
                <div key={i} className="timeline-item" style={{gridTemplateColumns:'100px 1fr'}}>
                  <div className="when">{w}</div>
                  <div className={`body ${type}`}><div style={{fontSize:13}}>{t}</div></div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
);

// ─────────── Users & Roles ───────────
const AdminUsers = () => {
  const [sel, setSel] = useState(null);
  return (
    <div className="main-col">
      <div className="page-head">
        <div><h1>Users & roles</h1><p className="lead">342 users · 24 admins · 118 reviewers · 200 applicants</p></div>
        <div style={{display:'flex', gap:8}}>
          <Btn variant="secondary" size="sm"><Icon name="download" size={13}/> Export</Btn>
          <Btn variant="primary" size="sm"><Icon name="plus" size={13}/> Invite user</Btn>
        </div>
      </div>
      <div className="page-body">
        <div style={{display:'flex', gap:8, marginBottom:14}}>
          <div style={{position:'relative', flex:1, maxWidth:360}}>
            <Icon name="search" size={14} style={{position:'absolute', left:10, top:'50%', transform:'translateY(-50%)', color:'var(--ink-3)'}}/>
            <input className="input" placeholder="Search users…" style={{paddingLeft:32}}/>
          </div>
          <div className="seg" style={{padding:2}}>
            {['All','Super admin','Admin','Reviewer L2','Reviewer L1'].map((f,i) => <button key={i} className={i===0?'on':''}>{f}</button>)}
          </div>
        </div>

        <div className="card" style={{overflow:'hidden'}}>
          <table className="table">
            <thead><tr><th>Name</th><th>Email</th><th>Role</th><th>Last active</th><th>MFA</th><th>Cases</th><th></th></tr></thead>
            <tbody>
              {[
                ['A. Khan','a.khan@dss.state.gov','Super Admin','Active now', true, '—'],
                ['M. Reeves','m.reeves@dss.state.gov','Admin','12 min ago', true, '—'],
                ['J. Delacruz','j.delacruz@dss.state.gov','Reviewer L2','Active now', true, 14],
                ['A. Sokolov','a.sokolov@dss.state.gov','Reviewer L2','32 min ago', true, 11],
                ['L. Kim','l.kim@dss.state.gov','Reviewer L2','1h ago', true, 18],
                ['T. Navarro','t.navarro@dss.state.gov','Reviewer L1','4h ago', true, 7],
                ['D. Cole','d.cole@contractor.gov','Reviewer L1','2d ago', false, 0],
              ].map((r, i) => (
                <tr key={i} onClick={()=>setSel(i)} className={sel===i?'sel':''}>
                  <td style={{fontWeight:500}}>{r[0]}</td>
                  <td className="mono" style={{fontSize:12}}>{r[1]}</td>
                  <td><Badge variant={r[2]==='Super Admin'?'danger':r[2]==='Admin'?'info':'accent'}>{r[2]}</Badge></td>
                  <td className="tiny">{r[3]}</td>
                  <td>{r[4] ? <Icon name="check" size={13} style={{color:'var(--accent)'}}/> : <Badge variant="warn" dot>Off</Badge>}</td>
                  <td className="mono tiny">{r[5]}</td>
                  <td><button className="icon-btn"><Icon name="more" size={14}/></button></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
};

// ─────────── Case Oversight ───────────
const AdminCases = () => (
  <div className="main-col">
    <div className="page-head">
      <div><h1>Case oversight</h1><p className="lead">Search, intervene, or reassign any case in the system.</p></div>
      <div style={{display:'flex', gap:8}}>
        <Btn variant="secondary" size="sm"><Icon name="filter" size={13}/> Saved filters</Btn>
        <Btn variant="secondary" size="sm"><Icon name="download" size={13}/> Export</Btn>
      </div>
    </div>
    <div className="page-body">
      <div style={{position:'relative', marginBottom:14}}>
        <Icon name="search" size={15} style={{position:'absolute', left:12, top:'50%', transform:'translateY(-50%)', color:'var(--ink-3)'}}/>
        <input className="input" placeholder="Search by case ID, applicant name, or email…" style={{paddingLeft:36, padding:'14px 14px 14px 36px'}}/>
      </div>
      <div className="grid-4" style={{marginBottom:18}}>
        <StatCard label="Active" value="1,284"/>
        <StatCard label="Filed" value="6,482" note="all time"/>
        <StatCard label="Deleted" value="284" note="90d"/>
        <StatCard label="Reassignments" value="12" note="this week"/>
      </div>
      <div className="card" style={{overflow:'hidden'}}>
        <table className="table">
          <thead><tr><th>Case</th><th>Applicant</th><th>Type</th><th>Reviewer</th><th>Status</th><th>Created</th><th>Flags</th><th></th></tr></thead>
          <tbody>
            {[
              ['GE-2026-4782','M. Ramirez','SSDI','J. Delacruz','In review','Apr 21', 2],
              ['GE-2026-4779','S. Okafor','VA Disability','A. Sokolov','Needs info','Apr 20', 3],
              ['GE-2026-4778','Y. Tanaka','SSI','—','Unassigned','Apr 20', 0],
              ['GE-2026-4761','J. Park','SSI','L. Kim','Ready','Apr 19', 0],
              ['GE-2026-4758','M. Brown','SSDI','L. Kim','Overdue','Apr 18', 4],
              ['GE-2026-4742','A. Farah','VA Healthcare','T. Navarro','In review','Apr 18', 0],
            ].map((r,i) => (
              <tr key={i}>
                <td className="mono" style={{fontSize:12}}>{r[0]}</td>
                <td style={{fontWeight:500}}>{r[1]}</td>
                <td><Badge>{r[2]}</Badge></td>
                <td>{r[3] === '—' ? <span style={{color:'var(--ink-4)'}}>—</span> : r[3]}</td>
                <td><Badge variant={r[4]==='Overdue'?'danger':r[4]==='Ready'?'accent':r[4]==='Needs info'?'warn':'info'} dot>{r[4]}</Badge></td>
                <td className="tiny">{r[5]}</td>
                <td>{r[6] > 0 ? <Badge variant={r[6]>2?'danger':'warn'}>{r[6]}</Badge> : <span style={{color:'var(--ink-4)'}}>—</span>}</td>
                <td><button className="icon-btn"><Icon name="more" size={14}/></button></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  </div>
);

// ─────────── Consent Versions ───────────
const AdminConsent = () => (
  <div className="main-col">
    <div className="page-head">
      <div><h1>Consent text manager</h1><p className="lead">Each version is immutable once published. Applicants always see the version in effect when they accepted.</p></div>
      <div style={{display:'flex', gap:8}}>
        <Btn variant="secondary" size="sm"><Icon name="eye" size={13}/> Preview draft</Btn>
        <Btn variant="accent" size="sm"><Icon name="check" size={13}/> Publish v2026.04</Btn>
      </div>
    </div>
    <div className="page-body">
      <div style={{display:'grid', gridTemplateColumns:'340px 1fr', gap:18}}>
        <div className="card" style={{padding:0}}>
          <div style={{padding:'10px 14px', borderBottom:'1px solid var(--line)'}}>
            <span className="mono tiny" style={{color:'var(--ink-3)', letterSpacing:'.12em', textTransform:'uppercase'}}>Versions</span>
          </div>
          {[
            ['v2026.04', 'Draft', 'You · 2d ago', true],
            ['v2026.01', 'Active', 'A. Khan · Jan 14', false],
            ['v2025.10', 'Retired', 'M. Reeves · Oct 2025', false],
            ['v2025.07', 'Retired', 'A. Khan · Jul 2025', false],
            ['v2025.01', 'Retired', 'M. Reeves · Jan 2025', false],
          ].map(([v, status, who, on], i) => (
            <button key={i} style={{
              width:'100%', textAlign:'left', padding:'12px 14px',
              borderBottom: i<4?'1px solid var(--line)':'0',
              background: on ? 'var(--accent-soft)' : 'transparent',
              cursor:'pointer'
            }}>
              <div style={{display:'flex', justifyContent:'space-between', alignItems:'center'}}>
                <span className="mono" style={{fontSize:13, fontWeight:500}}>{v}</span>
                <Badge variant={status==='Active'?'accent':status==='Draft'?'warn':null} dot={status!=='Retired'}>{status}</Badge>
              </div>
              <div className="tiny" style={{marginTop:3}}>{who}</div>
            </button>
          ))}
        </div>

        <div className="card">
          <div style={{padding:'14px 20px', borderBottom:'1px solid var(--line)', display:'flex', justifyContent:'space-between'}}>
            <div>
              <span className="mono tiny" style={{color:'var(--ink-3)', letterSpacing:'.12em', textTransform:'uppercase'}}>v2026.04 · Draft</span>
              <div style={{fontFamily:'var(--serif)', fontSize:22, marginTop:4}}>DCW Consent — Applicant</div>
            </div>
            <div className="seg" style={{padding:2}}>
              <button className="on">English</button>
              <button>Español</button>
            </div>
          </div>
          <div style={{padding:'20px 22px', fontSize:13.5, lineHeight:1.65, color:'var(--ink-2)'}}>
            <h4 style={{fontFamily:'var(--serif)', fontSize:17, fontWeight:400, color:'var(--ink)', marginBottom:8}}>How we use your information</h4>
            <p style={{marginBottom:14}}>Your information is used only to prepare this application. It is never sold, shared for marketing, or submitted to any agency without your approval. <mark style={{background:'var(--accent-soft)'}}>Effective April 2026, we also disclose retention policy in plain language before any document upload.</mark></p>
            <h4 style={{fontFamily:'var(--serif)', fontSize:17, fontWeight:400, color:'var(--ink)', marginBottom:8}}>AI assistance + human review</h4>
            <p style={{marginBottom:14}}>We use AI to help draft your application. Every step is logged. A human reviewer checks everything before anything is submitted. You can always see which parts of your application were AI-assisted in the audit trail.</p>
            <h4 style={{fontFamily:'var(--serif)', fontSize:17, fontWeight:400, color:'var(--ink)', marginBottom:8}}>Retention & deletion</h4>
            <p>Your case is retained for 24 months after submission. You can request deletion anytime from your dashboard.</p>
          </div>
          <div style={{padding:'14px 20px', borderTop:'1px solid var(--line)', background:'var(--bg-sunk)', display:'flex', gap:10, justifyContent:'space-between'}}>
            <div className="tiny">
              <strong>Diff vs v2026.01:</strong> +1 paragraph (retention), 3 phrasing clarifications. <a style={{color:'var(--accent)'}}>See diff</a>
            </div>
            <div style={{display:'flex', gap:8}}>
              <Btn variant="ghost" size="sm">Save draft</Btn>
              <Btn variant="accent" size="sm"><Icon name="check" size={13}/> Publish</Btn>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
);

// ─────────── Notification Templates ───────────
const AdminTemplates = () => (
  <div className="main-col">
    <div className="page-head">
      <div><h1>Notification templates</h1><p className="lead">Email, SMS, and in-app — localized EN / ES</p></div>
      <div style={{display:'flex', gap:8}}>
        <Btn variant="primary" size="sm"><Icon name="plus" size={13}/> New template</Btn>
      </div>
    </div>
    <div className="page-body">
      <div className="grid-auto">
        {[
          { k:'welcome', t:'Welcome email', trigger:'Account created', ch:['Email'], sent:'1,284 this month' },
          { k:'mfa', t:'MFA code', trigger:'Sign-in step', ch:['SMS'], sent:'4,921 this month' },
          { k:'needsinfo', t:'Reviewer needs info', trigger:'Reviewer request', ch:['Email','In-app'], sent:'84 this month' },
          { k:'reup', t:'Please re-upload document', trigger:'Quality flag', ch:['Email','In-app'], sent:'62 this month' },
          { k:'approved', t:'Your case was filed', trigger:'Case approved', ch:['Email','SMS','In-app'], sent:'318 this month' },
          { k:'delete', t:'Deletion confirmation', trigger:'Retention request', ch:['Email'], sent:'24 this month' },
        ].map(tpl => (
          <div key={tpl.k} className="card card-pad" style={{cursor:'pointer'}}>
            <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-start', marginBottom:8}}>
              <div>
                <div style={{fontFamily:'var(--serif)', fontSize:18}}>{tpl.t}</div>
                <div className="tiny">Triggered when: {tpl.trigger}</div>
              </div>
              <button className="icon-btn"><Icon name="pen" size={14}/></button>
            </div>
            <div style={{display:'flex', gap:6, flexWrap:'wrap', marginTop:6}}>
              {tpl.ch.map(c => <Badge key={c} variant="info">{c}</Badge>)}
              <Badge>EN · ES</Badge>
            </div>
            <div className="tiny" style={{marginTop:10, color:'var(--ink-3)'}}>{tpl.sent}</div>
          </div>
        ))}
      </div>
    </div>
  </div>
);

// ─────────── Retention Console ───────────
const AdminRetention = () => (
  <div className="main-col">
    <div className="page-head">
      <div><h1>Retention & deletion</h1><p className="lead">8 active requests · 284 cases auto-purged in last 90d</p></div>
      <div style={{display:'flex', gap:8}}>
        <Btn variant="secondary" size="sm"><Icon name="settings" size={13}/> Policy settings</Btn>
      </div>
    </div>
    <div className="page-body">
      <div className="grid-3" style={{marginBottom:18}}>
        <StatCard label="Pending requests" value="8" note="oldest 4d"/>
        <StatCard label="Scheduled auto-purge" value="42" note="next 7 days"/>
        <StatCard label="Holds" value="3" note="legal hold active"/>
      </div>
      <div className="card" style={{overflow:'hidden'}}>
        <table className="table">
          <thead><tr><th>Case</th><th>Applicant</th><th>Requested</th><th>Reason</th><th>Status</th><th>Age</th><th></th></tr></thead>
          <tbody>
            {[
              ['GE-2026-4612','J. Nakamura','Apr 19','Withdrew application','Awaiting review','4d','warn'],
              ['GE-2026-4591','R. Castillo','Apr 18','Privacy right','Awaiting review','5d','warn'],
              ['GE-2026-4588','D. Park','Apr 17','Duplicate case','Awaiting review','6d','warn'],
              ['GE-2026-4212','L. Martinez','Feb 08','24m auto-purge','Complete','—','accent'],
              ['GE-2026-3987','R. Chen','Jan 14','Privacy right','Complete','—','accent'],
              ['GE-2026-3901','A. Smith','Jan 02','Legal hold','Blocked','—','danger'],
            ].map((r, i) => (
              <tr key={i}>
                <td className="mono" style={{fontSize:12}}>{r[0]}</td>
                <td>{r[1]}</td>
                <td className="tiny">{r[2]}</td>
                <td className="tiny">{r[3]}</td>
                <td><Badge variant={r[6]} dot>{r[4]}</Badge></td>
                <td className="tiny">{r[5]}</td>
                <td style={{display:'flex', gap:6}}>
                  {r[4].includes('Await') && <>
                    <Btn variant="accent" size="sm">Process</Btn>
                    <Btn variant="ghost" size="sm">Hold</Btn>
                  </>}
                  {!r[4].includes('Await') && <Btn variant="ghost" size="sm"><Icon name="eye" size={12}/></Btn>}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  </div>
);

// ─────────── Audit Log ───────────
const AdminAudit = () => (
  <div className="main-col">
    <div className="page-head">
      <div><h1>Audit log</h1><p className="lead">Immutable record of every access, action, and consent event.</p></div>
      <div style={{display:'flex', gap:8}}>
        <Btn variant="secondary" size="sm"><Icon name="filter" size={13}/> Filters</Btn>
        <Btn variant="secondary" size="sm"><Icon name="download" size={13}/> Export (30d)</Btn>
      </div>
    </div>
    <div className="page-body">
      <div className="card" style={{overflow:'hidden'}}>
        <table className="table">
          <thead><tr><th>Timestamp</th><th>Actor</th><th>Role</th><th>Action</th><th>Target</th><th>IP</th><th>Result</th></tr></thead>
          <tbody>
            {[
              ['2026-04-23 14:14:02','j.delacruz','Reviewer L2','case.flag.create','GE-2026-4782','10.44.12.9','OK'],
              ['2026-04-23 14:11:30','a.khan','Super Admin','consent.draft.edit','v2026.04','10.44.12.3','OK'],
              ['2026-04-23 13:58:12','maria.r','Applicant','auth.login','self','173.x.x.x','OK'],
              ['2026-04-23 13:41:00','system','System','retention.purge.scheduled','GE-2024-0128','—','OK'],
              ['2026-04-23 12:05:45','l.kim','Reviewer L2','case.reassign','GE-2026-4703','10.44.12.14','OK'],
              ['2026-04-23 11:02:15','system','System','case.assign.auto','GE-2026-4782','—','OK'],
              ['2026-04-23 09:12:03','a.khan','Super Admin','user.role.change','d.cole → Reviewer L1','10.44.12.3','OK'],
              ['2026-04-23 08:45:18','unknown','—','auth.login','s.okafor@...','94.x.x.x','DENIED · bad password'],
              ['2026-04-23 08:44:02','unknown','—','auth.login','s.okafor@...','94.x.x.x','DENIED · bad password'],
              ['2026-04-23 07:30:00','system','System','backup.snapshot','full','—','OK'],
            ].map((r, i) => (
              <tr key={i} style={r[6].includes('DENIED')?{background:'var(--danger-soft)'}:null}>
                <td className="mono" style={{fontSize:11}}>{r[0]}</td>
                <td style={{fontSize:12.5, fontWeight:500}}>{r[1]}</td>
                <td className="tiny">{r[2]}</td>
                <td className="mono" style={{fontSize:11.5, color:'var(--ink-2)'}}>{r[3]}</td>
                <td className="mono" style={{fontSize:11.5}}>{r[4]}</td>
                <td className="mono tiny">{r[5]}</td>
                <td><Badge variant={r[6].includes('DENIED')?'danger':'accent'} dot>{r[6]}</Badge></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  </div>
);

// ─────────── AI Activity ───────────
const AdminAI = () => (
  <div className="main-col">
    <div className="page-head">
      <div><h1>AI activity</h1><p className="lead">Every model invocation, with inputs hashed and outputs retained 90d for explainability.</p></div>
      <div style={{display:'flex', gap:8}}>
        <Btn variant="secondary" size="sm">Model registry</Btn>
      </div>
    </div>
    <div className="page-body">
      <div className="grid-4" style={{marginBottom:18}}>
        <StatCard label="Calls (24h)" value="4,218" delta="+6%" deltaDir="up"/>
        <StatCard label="Avg confidence" value="92.4%" delta="−1.6pp" deltaDir="down"/>
        <StatCard label="Human overrides" value="11%" note="of flagged items"/>
        <StatCard label="Est. cost (24h)" value="$187.40"/>
      </div>

      <div className="card" style={{overflow:'hidden'}}>
        <div style={{padding:'14px 20px', borderBottom:'1px solid var(--line)'}}>
          <h3 style={{fontFamily:'var(--serif)', fontSize:18, fontWeight:400}}>Recent invocations</h3>
        </div>
        <table className="table">
          <thead><tr><th>Timestamp</th><th>Model</th><th>Purpose</th><th>Case</th><th>Confidence</th><th>Outcome</th></tr></thead>
          <tbody>
            {[
              ['14:13:41','claude-extract-v3','date.consistency.check','GE-2026-4782','91%','flagged · reviewer notified'],
              ['14:02:10','vision-qa-v2','document.quality','GE-2026-4782','42%','flagged · re-upload requested'],
              ['13:48:55','claude-extract-v3','medical.record.parse','GE-2026-4782','96%','accepted · 14 fields'],
              ['13:12:09','claude-intake-v1','clarifier.question','GE-2026-4791','—','generated follow-up'],
              ['12:58:22','claude-draft-v2','ssa-16.fill','GE-2026-4761','94%','draft generated'],
              ['12:30:41','whisper-xl','voice.transcribe','GE-2026-4779','—','transcript OK'],
            ].map((r,i) => (
              <tr key={i}>
                <td className="mono" style={{fontSize:11}}>{r[0]}</td>
                <td className="mono" style={{fontSize:11.5, color:'var(--info)'}}>{r[1]}</td>
                <td className="mono" style={{fontSize:11.5}}>{r[2]}</td>
                <td className="mono" style={{fontSize:11.5}}>{r[3]}</td>
                <td className="mono" style={{fontSize:11.5, color: parseInt(r[4])>=90 ? 'var(--accent)' : parseInt(r[4])>=70 ? 'var(--warn)' : 'var(--danger)'}}>{r[4]}</td>
                <td style={{fontSize:12.5}}>{r[5]}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  </div>
);

// ─────────── System Monitoring ───────────
const AdminMonitoring = () => (
  <div className="main-col">
    <div className="page-head">
      <div><h1>System monitor</h1><p className="lead">Real-time uptime, queue depth, error rate.</p></div>
      <Badge variant="accent" dot>All systems nominal</Badge>
    </div>
    <div className="page-body">
      <div className="grid-4" style={{marginBottom:20}}>
        <StatCard label="Uptime (30d)" value="99.98%"/>
        <StatCard label="API p95 latency" value="184ms" delta="−12ms" deltaDir="up"/>
        <StatCard label="Error rate" value="0.04%"/>
        <StatCard label="Queue depth" value="1,284"/>
      </div>

      <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:18, marginBottom:18}}>
        {['API Gateway','Document storage','AI inference','Email/SMS queue'].map(svc => (
          <div key={svc} className="card card-pad">
            <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:8}}>
              <div style={{fontSize:14, fontWeight:500}}>{svc}</div>
              <Badge variant="accent" dot>Healthy</Badge>
            </div>
            <div style={{display:'flex', alignItems:'flex-end', gap:2, height:38, marginBottom:8}}>
              {Array.from({length:60}).map((_,i) => {
                const h = 20 + Math.abs(Math.sin(i*0.4 + svc.length)*60);
                return <div key={i} style={{flex:1, height:`${h}%`, background:'var(--accent)', opacity:0.55, borderRadius:'2px 2px 0 0'}}/>;
              })}
            </div>
            <div className="tiny" style={{display:'flex', justifyContent:'space-between'}}>
              <span>p50 {42+Math.floor(Math.random()*40)}ms · p95 {180+Math.floor(Math.random()*40)}ms</span>
              <span className="mono">last 60m</span>
            </div>
          </div>
        ))}
      </div>
    </div>
  </div>
);

// ─────────── Security / Incidents ───────────
const AdminSecurity = () => (
  <div className="main-col">
    <div className="page-head">
      <div><h1>Security & incidents</h1><p className="lead">3 open alerts · last scan 4h ago</p></div>
      <div style={{display:'flex', gap:8}}>
        <Btn variant="secondary" size="sm"><Icon name="refresh" size={13}/> Run scan now</Btn>
        <Btn variant="primary" size="sm" style={{background:'var(--danger)', color:'#fff'}}>Incident response</Btn>
      </div>
    </div>
    <div className="page-body">
      <div className="grid-3" style={{marginBottom:18}}>
        <StatCard label="Open incidents" value="3" note="1 P2, 2 P3"/>
        <StatCard label="Failed logins (24h)" value="142" delta="+38" deltaDir="down" note="geo spike: Brazil"/>
        <StatCard label="Data access reviews" value="12" note="due this month"/>
      </div>

      <div className="card" style={{marginBottom:18}}>
        <div style={{padding:'14px 20px', borderBottom:'1px solid var(--line)'}}><h3 style={{fontFamily:'var(--serif)', fontSize:18, fontWeight:400}}>Active alerts</h3></div>
        <div>
          {[
            { pri:'P2', t:'Brute-force attempt · s.okafor@... (14 attempts in 6 min)', when:'8h ago · auto-locked', actor:'94.x.x.x', lvl:'danger' },
            { pri:'P3', t:'Unusual download volume · d.cole@contractor.gov (18 case files)', when:'1d ago', actor:'Reviewer L1', lvl:'warn' },
            { pri:'P3', t:'Session from new geo (Germany) · a.khan@dss.state.gov', when:'2d ago · confirmed by admin', actor:'Super Admin', lvl:'warn' },
          ].map((a, i) => (
            <div key={i} style={{padding:'14px 20px', borderBottom: i<2?'1px solid var(--line)':'0', display:'grid', gridTemplateColumns:'60px 1fr auto auto', gap:14, alignItems:'center'}}>
              <Badge variant={a.lvl}>{a.pri}</Badge>
              <div>
                <div style={{fontSize:13.5, fontWeight:500}}>{a.t}</div>
                <div className="tiny">{a.when} · {a.actor}</div>
              </div>
              <Btn variant="ghost" size="sm">Details</Btn>
              <Btn variant="secondary" size="sm">Resolve</Btn>
            </div>
          ))}
        </div>
      </div>

      <div className="card card-pad">
        <div style={{display:'flex', alignItems:'center', gap:12}}>
          <div style={{width:44, height:44, borderRadius:12, background:'var(--accent-soft)', color:'var(--accent-ink)', display:'grid', placeItems:'center'}}><Icon name="shieldCheck" size={22}/></div>
          <div style={{flex:1}}>
            <div style={{fontSize:15, fontWeight:500, fontFamily:'var(--serif)', fontWeight:400, fontSize:20}}>Compliance snapshot</div>
            <div className="tiny">SOC 2 Type II, HIPAA, NIST 800-53 · all on track</div>
          </div>
          <Btn variant="secondary" size="sm">View report</Btn>
        </div>
      </div>
    </div>
  </div>
);

Object.assign(window, { AdminSidebar, AdminDashboard, AdminUsers, AdminCases, AdminConsent, AdminTemplates, AdminRetention, AdminAudit, AdminAI, AdminMonitoring, AdminSecurity });
