// Vyuu admin console — Server Identity & Health, Audit Log, Policy History drawer.
// New screens that the original kit did not include.
const { Server: SrvIcon, ShieldCheck: ShChk, Globe: GlbIcon, Wifi: WifiX,
  Activity: ActX, Clock: ClkX, KeyRound, Copy: CpyX, RefreshCw,
  AlertTriangle: AlertX, CheckCircle2: CheckX, Filter: FltX, Download: DLX,
  ChevronRight: CRX, FileSearch, History: HistIcon, GitBranch,
  ArrowDownToLine, Eye: EyeX, RotateCcw } = window.LucideReact;

// ─────────────────────────────────────────────────────────────────
// Server Identity & Health (Settings → Server Identity & Health)
// ─────────────────────────────────────────────────────────────────
const REGIONS = [
  { name:'ap-south-1 (Mumbai)', id:'srv-ap-south-1-a', primary:true, status:'healthy', latency:'42 ms', uptime:'99.99%', agents:38, version:'1.42.0', cert:'expires Mar 2027' },
  { name:'ap-south-1 (Mumbai) · DR', id:'srv-ap-south-1-b', primary:false, status:'healthy', latency:'48 ms', uptime:'99.97%', agents:38, version:'1.42.0', cert:'expires Mar 2027' },
  { name:'us-east-1 (N. Virginia)', id:'srv-us-east-1-a', primary:false, status:'degraded', latency:'214 ms', uptime:'99.78%', agents:9, version:'1.41.7', cert:'expires Sep 2026' },
  { name:'eu-west-1 (Dublin)', id:'srv-eu-west-1-a', primary:false, status:'healthy', latency:'168 ms', uptime:'99.99%', agents:0, version:'1.42.0', cert:'expires Sep 2026' },
];

const ServerHealth = () => {
  const [copied, setCopied] = React.useState(null);
  const copy = (txt, key) => { navigator.clipboard?.writeText(txt); setCopied(key); setTimeout(()=>setCopied(null), 1400); };

  const tone = (s) => s==='healthy' ? 'orange' : s==='degraded' ? 'amber' : 'terracotta';

  return (
    <div>
      <SectionTitle eyebrow="Settings · Server Identity & Health" title="Vyuu control-plane regions you trust"
        actions={<>
          <Button small icon={RefreshCw} onClick={()=>alert('Stub: would re-run health probe across all regions.')}>Re-run probe</Button>
          <Button small primary icon={KeyRound} onClick={()=>alert('Stub: would rotate the tenant signing key.')}>Rotate tenant key</Button>
        </>}/>

      <div style={{display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:14, marginBottom:20}}>
        <KPI label="Regions configured" value="4" delta="1 primary · 3 standby" tone="orange"/>
        <KPI label="All-region uptime · 30d" value="99.96%" delta="SLA: 99.9%" tone="orange"/>
        <KPI label="Avg client latency" value="64 ms" delta="From your devices" tone="orange"/>
        <KPI label="Cert expiries · 90d" value="0" delta="No imminent expiries" tone="orange"/>
      </div>

      {/* Tenant identity card */}
      <Card style={{marginBottom:16}}>
        <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:24}}>
          <div>
            <Eyebrow>Tenant identity</Eyebrow>
            <div style={{fontFamily:theme.serif, fontSize:18, color:theme.ink, fontWeight:500, marginTop:4}}>LLP Industries · Production</div>
            <div style={{display:'grid', gap:10, marginTop:14, fontSize:13}}>
              <IdRow label="Tenant ID" value="llp-prod" onCopy={()=>copy('llp-prod','tid')} copied={copied==='tid'}/>
              <IdRow label="Tenant signing key" value="vyuu_pk_3f2a…d801" onCopy={()=>copy('vyuu_pk_3f2a…d801','sig')} copied={copied==='sig'} mono/>
              <IdRow label="Enrollment CA" value="CN=vyuu-llp-enroll, O=Vyuu" onCopy={()=>copy('CN=vyuu-llp-enroll, O=Vyuu','ca')} copied={copied==='ca'}/>
              <IdRow label="Created" value="14 Aug 2024 · 11:02 IST"/>
              <IdRow label="Plan" value={<><Pill tone="ocean">Enterprise</Pill> <span style={{marginLeft:6, color:theme.muted, fontSize:11.5}}>BFSI add-on enabled</span></>}/>
            </div>
          </div>
          <div>
            <Eyebrow>Trust posture</Eyebrow>
            <div style={{display:'grid', gap:10, marginTop:14}}>
              <PostureRow icon={ShChk} ok label="mTLS to control plane" detail="All agents present client cert · 0 fallbacks"/>
              <PostureRow icon={KeyRound} ok label="Tenant signing key rotation" detail="Last rotated 41 days ago · auto-rotate at 90"/>
              <PostureRow icon={GlbIcon} ok label="DNS pinning" detail="api.vyuu.ai → 4 A records · DNSSEC valid"/>
              <PostureRow icon={ActX} ok label="Audit shipping" detail="Streaming to Splunk-llp · last batch 12 s ago"/>
              <PostureRow icon={AlertX} warn label="SSO is not connected" detail="Admins are managed manually · click Configure to fix"/>
            </div>
          </div>
        </div>
      </Card>

      {/* Region health table */}
      <Card padded={false}>
        <div style={{padding:'14px 20px', borderBottom:`1px solid ${theme.line}`, display:'flex', justifyContent:'space-between', alignItems:'center'}}>
          <div style={{fontFamily:theme.serif, fontSize:16, color:theme.ink, fontWeight:500}}>Control-plane regions</div>
          <div style={{fontSize:11.5, color:theme.muted}}>Health probe · refreshed every 30 s</div>
        </div>
        <table style={{width:'100%', borderCollapse:'collapse', fontSize:13}}>
          <thead><tr style={{borderBottom:`1px solid ${theme.line}`}}>
            {['','Region','Server ID','Role','Status','Latency','Uptime (30d)','Agents','Version','Cert',''].map((h,i)=>(
              <th key={i} style={{padding:'12px 16px', textAlign:'left', fontSize:10.5, letterSpacing:1.5, color:theme.muted, fontWeight:600, textTransform:'uppercase', fontFamily:theme.sans}}>{h}</th>
            ))}
          </tr></thead>
          <tbody>
            {REGIONS.map(r => (
              <tr key={r.id} style={{borderBottom:`1px solid ${theme.lineSoft}`}}>
                <td style={{padding:'14px 16px'}}><StatDot status={r.status==='healthy'?'online':r.status==='degraded'?'idle':'stale'}/></td>
                <td style={{padding:'14px 16px', color:theme.ink, fontWeight:500}}>{r.name}</td>
                <td style={{padding:'14px 16px', fontFamily:theme.mono, fontSize:12, color:theme.muted}}>{r.id}</td>
                <td style={{padding:'14px 16px'}}>
                  {r.primary ? <Pill tone="orange">Primary</Pill> : <Pill tone="neutral">Standby</Pill>}
                </td>
                <td style={{padding:'14px 16px'}}><Pill tone={tone(r.status)}>{r.status.toUpperCase()}</Pill></td>
                <td style={{padding:'14px 16px', fontFamily:theme.mono, fontSize:12, color:theme.muted}}>{r.latency}</td>
                <td style={{padding:'14px 16px', fontFamily:theme.mono, fontSize:12, color:theme.ink}}>{r.uptime}</td>
                <td style={{padding:'14px 16px', fontFamily:theme.mono, fontSize:12, color:theme.ink}}>{r.agents}</td>
                <td style={{padding:'14px 16px', fontFamily:theme.mono, fontSize:12, color:theme.muted}}>{r.version}</td>
                <td style={{padding:'14px 16px', fontSize:11.5, color:theme.muted}}>{r.cert}</td>
                <td style={{padding:'14px 16px'}}>
                  <button onClick={()=>alert(`Stub: open detail for ${r.id}.`)} style={{background:'transparent', border:'none', color:theme.orangeDeep, cursor:'pointer'}}><CRX size={14}/></button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>

      {/* Latency strip — fake 30d sparkline */}
      <Card style={{marginTop:16}}>
        <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:12}}>
          <h3 style={{fontFamily:theme.serif, fontSize:18, margin:0, color:theme.ink, fontWeight:500}}>Control-plane latency · 30 days</h3>
          <Pill tone="neutral">p95 / p99</Pill>
        </div>
        <svg viewBox="0 0 600 140" style={{width:'100%', height:140}}>
          {[28, 56, 84, 112].map(y => <line key={y} x1="0" y1={y} x2="600" y2={y} stroke={theme.lineSoft} strokeDasharray="2 4"/>)}
          <path d="M0 90 L40 86 L80 84 L120 88 L160 70 L200 66 L240 72 L280 60 L320 64 L360 56 L400 60 L440 52 L480 58 L520 50 L560 54 L600 48"
            fill="none" stroke={theme.orangeDeep} strokeWidth="2"/>
          <path d="M0 110 L40 108 L80 106 L120 110 L160 100 L200 94 L240 96 L280 88 L320 92 L360 84 L400 86 L440 78 L480 82 L520 74 L560 76 L600 72"
            fill="none" stroke={theme.ocean} strokeWidth="1.5" strokeDasharray="3 3"/>
        </svg>
        <div style={{display:'flex', gap:14, marginTop:8, fontSize:11.5, color:theme.muted}}>
          <span><span style={{display:'inline-block', width:10, height:2, background:theme.orangeDeep, marginRight:6, verticalAlign:'middle'}}/>p95</span>
          <span><span style={{display:'inline-block', width:10, height:2, background:theme.ocean, marginRight:6, verticalAlign:'middle'}}/>p99</span>
          <span style={{marginLeft:'auto'}}>SLA target: p99 ≤ 250 ms</span>
        </div>
      </Card>
    </div>
  );
};

const IdRow = ({label, value, mono, onCopy, copied}) => (
  <div style={{display:'grid', gridTemplateColumns:'160px 1fr auto', gap:10, alignItems:'center'}}>
    <span style={{fontSize:11, color:theme.muted, textTransform:'uppercase', letterSpacing:1.2, fontWeight:600}}>{label}</span>
    <span style={{color:theme.ink, fontFamily: mono ? theme.mono : theme.sans, fontSize: mono ? 12.5 : 13}}>{value}</span>
    {onCopy && <button onClick={onCopy} style={{background:'transparent', border:`1px solid ${theme.line}`, borderRadius:6, padding:'3px 8px', color:theme.muted, fontSize:10.5, cursor:'pointer', display:'inline-flex', gap:4, alignItems:'center'}}>{copied ? '✓' : <CpyX size={11}/>} {copied?'Copied':'Copy'}</button>}
  </div>
);

const PostureRow = ({icon:Icon, ok, warn, label, detail}) => {
  const ink = ok ? theme.orangeDeep : warn ? theme.amberInk : theme.terracottaInk;
  const bg = ok ? theme.orangeSoft : warn ? theme.amberSoft : theme.terracottaSoft;
  return (
    <div style={{display:'flex', alignItems:'flex-start', gap:12, padding:'10px 12px', border:`1px solid ${theme.line}`, borderRadius:8}}>
      <div style={{width:28, height:28, borderRadius:7, background:bg, display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0}}>
        <Icon size={14} color={ink} strokeWidth={1.8}/>
      </div>
      <div style={{flex:1}}>
        <div style={{fontSize:12.5, color:theme.ink, fontWeight:600}}>{label}</div>
        <div style={{fontSize:11.5, color:theme.muted, marginTop:2, lineHeight:1.4}}>{detail}</div>
      </div>
    </div>
  );
};

// ─────────────────────────────────────────────────────────────────
// Audit Log (Settings → Audit Log)
// ─────────────────────────────────────────────────────────────────
const AUDIT_LOG = [
  { ts:'2026-04-26 10:42:18', actor:'krishna@llp.in', actorRole:'Super Admin', action:'policy.publish', target:'Prompt Protection bundle', detail:'Published v23 (3 rules changed, 1 new)', ip:'10.42.8.14', result:'ok' },
  { ts:'2026-04-26 10:31:09', actor:'arjun.d@llp.in', actorRole:'Policy Editor', action:'policy.edit', target:'Block prod credentials (rule #3)', detail:'Pattern updated · added DATABASE_URL', ip:'10.42.7.22', result:'ok' },
  { ts:'2026-04-26 09:14:41', actor:'krishna@llp.in', actorRole:'Super Admin', action:'token.issue', target:'tok_8K2pX', detail:'Default · macOS+Linux · 24 hr · unlimited', ip:'10.42.8.14', result:'ok' },
  { ts:'2026-04-26 08:58:02', actor:'meera.nair@llp.in', actorRole:'Security Admin', action:'mcp.approve', target:'jira (Atlassian) v1.0.4', detail:'Promoted from registry · scope: All projects', ip:'10.42.6.18', result:'ok' },
  { ts:'2026-04-26 08:12:55', actor:'sundar.v@llp.in', actorRole:'Policy Editor', action:'rule.create.draft', target:'Rate-limit jira bulk create', detail:'Saved as draft · not yet enabled', ip:'10.42.7.30', result:'ok' },
  { ts:'2026-04-25 22:17:30', actor:'system', actorRole:'system', action:'token.expire', target:'tok_R7vL0', detail:'Reached usage cap (150/150)', ip:'—', result:'ok' },
  { ts:'2026-04-25 19:04:11', actor:'rhea.b@llp.in', actorRole:'Auditor (read)', action:'login.fail', target:'admin console', detail:'MFA missing · IdP rejected', ip:'10.42.5.7', result:'fail' },
  { ts:'2026-04-25 16:43:08', actor:'meera.nair@llp.in', actorRole:'Security Admin', action:'admin.invite', target:'sundar.v@llp.in', detail:'Role: Policy Editor · scope MCP Security', ip:'10.42.6.18', result:'ok' },
  { ts:'2026-04-25 14:22:51', actor:'arjun.d@llp.in', actorRole:'Policy Editor', action:'rule.toggle', target:'Block GSTIN bulk export', detail:'Disabled (was active)', ip:'10.42.7.22', result:'ok' },
  { ts:'2026-04-24 11:08:14', actor:'krishna@llp.in', actorRole:'Super Admin', action:'connector.add', target:'Anthropic Claude (sonnet-4-5)', detail:'Configured as primary escalation', ip:'10.42.8.14', result:'ok' },
];

const ACTION_TONES = {
  'policy.publish':'orange', 'policy.edit':'ocean',
  'rule.create':'orange', 'rule.create.draft':'neutral', 'rule.toggle':'amber',
  'token.issue':'ocean', 'token.revoke':'terracotta', 'token.expire':'neutral',
  'mcp.approve':'orange', 'mcp.block':'terracotta',
  'admin.invite':'orange', 'admin.remove':'terracotta',
  'login.fail':'terracotta', 'connector.add':'ocean',
};

const AuditLog = () => {
  const [filter, setFilter] = React.useState('all');
  const [search, setSearch] = React.useState('');
  const filters = ['all','policy','rule','token','mcp','admin','login.fail'];
  const filtered = AUDIT_LOG.filter(e =>
    (filter==='all' || e.action.startsWith(filter)) &&
    (!search || (e.actor + e.target + e.detail).toLowerCase().includes(search.toLowerCase()))
  );

  return (
    <div>
      <SectionTitle eyebrow="Settings · Audit Log" title="Every admin action, immutable & shippable"
        actions={<>
          <Button small icon={FltX} onClick={()=>alert('Stub: advanced filter drawer.')}>Advanced filter</Button>
          <Button small icon={DLX} onClick={()=>alert('Stub: download CSV (last 90 days).')}>Export CSV</Button>
          <Button small primary icon={ArrowDownToLine} onClick={()=>alert('Stub: configure SIEM stream (Splunk / Elastic / Datadog).')}>Stream to SIEM</Button>
        </>}/>

      <div style={{display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:14, marginBottom:20}}>
        <KPI label="Events · 30d" value="2,184" delta="across 14 admin users" tone="orange"/>
        <KPI label="Failed logins · 7d" value="3" delta="↑ 1 vs prior 7d" tone="amber"/>
        <KPI label="Destructive ops · 7d" value="2" delta="token revokes, admin removals" tone="terracotta"/>
        <KPI label="SIEM lag" value="12 s" delta="Splunk-llp · healthy" tone="orange"/>
      </div>

      <div style={{display:'flex', gap:10, marginBottom:14, alignItems:'center', flexWrap:'wrap'}}>
        <div style={{position:'relative', flex:'1 1 320px', maxWidth:480}}>
          <FileSearch size={14} color={theme.muted} style={{position:'absolute', left:12, top:10}}/>
          <input value={search} onChange={e=>setSearch(e.target.value)} placeholder="Search actor, target, detail…" style={{
            width:'100%', padding:'8px 12px 8px 34px', border:`1px solid ${theme.line}`, borderRadius:8,
            fontFamily:theme.sans, fontSize:13, color:theme.ink, background:theme.panel, outline:'none',
          }}/>
        </div>
        <div style={{display:'flex', gap:6, flexWrap:'wrap'}}>
          {filters.map(f => (
            <button key={f} onClick={()=>setFilter(f)} style={{
              padding:'6px 12px', borderRadius:999, cursor:'pointer',
              border:`1px solid ${filter===f?theme.orangeDeep:theme.line}`,
              background: filter===f?theme.orangeDeep:theme.panel,
              color: filter===f?theme.onPrimary:theme.ink,
              fontSize:11.5, fontWeight:500, fontFamily:theme.sans,
            }}>{f === 'all' ? 'All' : f}</button>
          ))}
        </div>
      </div>

      <Card padded={false}>
        <table style={{width:'100%', borderCollapse:'collapse', fontSize:13}}>
          <thead><tr style={{borderBottom:`1px solid ${theme.line}`}}>
            {['Time','Actor','Action','Target','Detail','IP','Result',''].map((h,i)=>(
              <th key={i} style={{padding:'12px 16px', textAlign:'left', fontSize:10.5, letterSpacing:1.5, color:theme.muted, fontWeight:600, textTransform:'uppercase', fontFamily:theme.sans}}>{h}</th>
            ))}
          </tr></thead>
          <tbody>
            {filtered.map((e, i) => (
              <tr key={i} style={{borderBottom:`1px solid ${theme.lineSoft}`}}>
                <td style={{padding:'14px 16px', fontFamily:theme.mono, fontSize:11.5, color:theme.muted, whiteSpace:'nowrap'}}>{e.ts}</td>
                <td style={{padding:'14px 16px'}}>
                  <div style={{color:e.actor==='system'?theme.muted:theme.ink, fontWeight:500, fontSize:12.5, fontFamily: e.actor==='system'?theme.mono:theme.sans, fontStyle:e.actor==='system'?'italic':'normal'}}>{e.actor}</div>
                  <div style={{fontSize:11, color:theme.muted}}>{e.actorRole}</div>
                </td>
                <td style={{padding:'14px 16px'}}>
                  <Pill tone={ACTION_TONES[e.action] || 'neutral'}>{e.action}</Pill>
                </td>
                <td style={{padding:'14px 16px', color:theme.ink, fontFamily:theme.mono, fontSize:12}}>{e.target}</td>
                <td style={{padding:'14px 16px', color:theme.muted, fontSize:12, maxWidth:340}}>{e.detail}</td>
                <td style={{padding:'14px 16px', fontFamily:theme.mono, fontSize:11.5, color:theme.muted}}>{e.ip}</td>
                <td style={{padding:'14px 16px'}}>
                  {e.result==='ok'
                    ? <Pill tone="orange">OK</Pill>
                    : <Pill tone="terracotta">FAIL</Pill>}
                </td>
                <td style={{padding:'14px 16px'}}>
                  <button onClick={()=>alert(`Stub: open audit event detail.\n\n${e.ts}\n${e.actor} → ${e.action}\nTarget: ${e.target}\nDetail: ${e.detail}`)} style={{background:'transparent', border:'none', color:theme.muted, cursor:'pointer'}}><EyeX size={14}/></button>
                </td>
              </tr>
            ))}
            {filtered.length===0 && (
              <tr><td colSpan={8} style={{padding:'48px 16px', textAlign:'center', color:theme.muted, fontSize:12.5}}>No audit events match the current filter.</td></tr>
            )}
          </tbody>
        </table>
      </Card>

      <Card style={{marginTop:16, background:theme.orangeMist, borderColor:theme.orangeSoft}}>
        <div style={{display:'flex', gap:14, alignItems:'flex-start'}}>
          <ShChk size={20} color={theme.orangeDeep} strokeWidth={1.8}/>
          <div>
            <div style={{fontFamily:theme.serif, fontSize:15, color:theme.ink, fontWeight:500, marginBottom:4}}>Tamper-evident · WORM-backed</div>
            <div style={{fontSize:12.5, color:theme.muted, lineHeight:1.55}}>Audit events are hash-chained and shipped to your SIEM in near real-time. Vyuu retains a 7-year copy in object storage with object-lock enabled. Every export is signed.</div>
          </div>
        </div>
      </Card>
    </div>
  );
};

// ─────────────────────────────────────────────────────────────────
// Policy History drawer — used by both Prompt + Invocation policies
// ─────────────────────────────────────────────────────────────────
const PolicyHistoryDrawer = ({rule, onClose, kind='prompt'}) => {
  if (!rule) return null;
  const isBundle = !!rule.all;
  const ruleVersion = rule.version || 1;
  const ink = kind === 'invocation' ? theme.oceanInk : theme.orangeDeep;

  // Generate fake revision list — 1..ruleVersion (or 1..18 for bundle)
  const max = isBundle ? (kind==='invocation' ? 18 : 23) : ruleVersion;
  const revisions = Array.from({length: Math.min(max, 8)}, (_, i) => {
    const v = max - i;
    const authors = ['krishna@llp.in','meera.nair@llp.in','arjun.d@llp.in','sundar.v@llp.in'];
    const author = authors[v % authors.length];
    const summaries = [
      'Pattern broadened to catch newer formats',
      'Action tightened from warn → redact',
      'Scope expanded to Engineering group',
      'Tool glob updated · added merge_*',
      'Predicate refined · external_domain check',
      'Initial draft created',
    ];
    return {
      v, author,
      ts: i===0 ? '2 hr ago' : i===1 ? 'yesterday' : `${i*2} days ago`,
      summary: summaries[i % summaries.length],
      isCurrent: i===0,
    };
  });

  return (
    <Drawer open={!!rule} onClose={onClose} width={620}>
      <DrawerHeader onClose={onClose}
        eyebrow={isBundle ? `${kind==='invocation'?'Invocation':'Prompt Protection'} · Bundle history` : `${kind==='invocation'?'Invocation':'Prompt'} rule history`}
        title={isBundle ? rule.name : rule.name}
        actions={!isBundle && <Button small icon={RotateCcw} onClick={()=>alert(`Stub: would roll ${rule.name} back to a prior version.`)}>Roll back…</Button>}/>
      <div style={{flex:1, overflow:'auto', padding:24}}>
        <div style={{display:'flex', gap:14, alignItems:'center', padding:'12px 14px', background:theme.panel, border:`1px solid ${theme.line}`, borderRadius:10, marginBottom:18}}>
          <GitBranch size={16} color={ink}/>
          <div style={{flex:1, fontSize:12.5, color:theme.muted}}>
            {isBundle
              ? <>Bundles are versioned as a whole. Every publish creates an immutable revision. <strong style={{color:theme.ink}}>{max}</strong> revisions on file.</>
              : <>This rule is on revision <strong style={{color:theme.ink, fontFamily:theme.mono}}>v{ruleVersion}</strong>. Edits create a new revision; agents pick up changes within 60 s of publish.</>}
          </div>
        </div>

        <div style={{borderLeft:`2px solid ${theme.lineSoft}`, paddingLeft:18, marginLeft:6}}>
          {revisions.map(r => (
            <div key={r.v} style={{position:'relative', paddingBottom:18}}>
              <div style={{position:'absolute', left:-26, top:4, width:14, height:14, borderRadius:999, background:r.isCurrent?ink:theme.panel, border:`2px solid ${r.isCurrent?ink:theme.line}`, boxShadow:`0 0 0 3px ${theme.bg}`}}/>
              <div style={{display:'flex', alignItems:'center', gap:10, marginBottom:4}}>
                <span style={{fontFamily:theme.mono, fontSize:13, color:ink, fontWeight:600}}>v{r.v}</span>
                {r.isCurrent && <Pill tone={kind==='invocation'?'ocean':'orange'}>Current</Pill>}
                <span style={{fontSize:11.5, color:theme.muted}}>{r.ts}</span>
              </div>
              <div style={{fontSize:13, color:theme.ink, marginBottom:3}}>{r.summary}</div>
              <div style={{fontSize:11.5, color:theme.muted, fontFamily:theme.mono}}>{r.author}</div>
              {!r.isCurrent && (
                <div style={{display:'flex', gap:6, marginTop:8}}>
                  <button onClick={()=>alert(`Stub: would diff v${r.v} ↔ v${max}.`)} style={{padding:'4px 10px', border:`1px solid ${theme.line}`, borderRadius:6, background:theme.panel, color:theme.ink, fontSize:11, cursor:'pointer'}}>Diff vs current</button>
                  <button onClick={()=>alert(`Stub: would restore v${r.v}.`)} style={{padding:'4px 10px', border:`1px solid ${theme.line}`, borderRadius:6, background:theme.panel, color:theme.ink, fontSize:11, cursor:'pointer'}}>Restore</button>
                </div>
              )}
            </div>
          ))}
        </div>
      </div>
      <div style={{padding:'14px 24px', borderTop:`1px solid ${theme.line}`, background:theme.panel, display:'flex', justifyContent:'flex-end', gap:8}}>
        <Button small onClick={onClose}>Close</Button>
      </div>
    </Drawer>
  );
};

Object.assign(window, {ServerHealth, AuditLog, PolicyHistoryDrawer});
