// SETTINGS PLATFORM — Data & Retention · Audit · Compliance · Custom Fields · Templates · Import/Export · System Health
const Ts_g = window.ArbiterTokens;

function SettingsDataRetention({ data }) {
  const stg = window.__stg;
  const ret = data.dataRetention;
  const holds = data.legalHolds;
  const exports = data.exports;
  const Card = window.SettingsSectionCard;
  const infra = window.__stg_infra || {};
  const toast = (infra.useToast && infra.useToast()) || { push: () => {} };

  const activeHolds = holds.filter(h => h.status === 'active').length;

  // #7 — dry-run preview state
  const [dryRun, setDryRun] = React.useState(null);
  const [dryPolicy, setDryPolicy] = React.useState(null);
  // #8 — legal hold custodian workflow
  const [custodianHold, setCustodianHold] = React.useState(null);

  function runDryRun(policy) {
    setDryPolicy(policy);
    setDryRun({ status: 'running', policy: policy.resource });
    setTimeout(() => {
      // Synthesize deterministic counts from resource string
      const seed = policy.resource.length * 13;
      const eligible = 1820 + (seed % 800);
      const heldBack = Math.floor(eligible * 0.12);
      const toDelete = eligible - heldBack;
      const sizeGb = ((toDelete * 0.18) + (seed % 40)).toFixed(1);
      setDryRun({
        status: 'ready',
        policy: policy.resource,
        retention: policy.retention,
        cutoff: '2021-04-23',
        scanned: eligible * 4,
        eligible,
        heldBack,
        toDelete,
        sizeGb,
        byType: [
          { k: 'Drafts > 5y',           n: Math.floor(toDelete * 0.46) },
          { k: 'Superseded versions',    n: Math.floor(toDelete * 0.28) },
          { k: 'Closed matter records',  n: Math.floor(toDelete * 0.19) },
          { k: 'Orphaned uploads',       n: Math.floor(toDelete * 0.07) },
        ],
        sample: [
          { id: 'DOC-84102', kind: 'Draft pleading',      matter: 'MTR-2019-0412', lastTouched: '2020-08-14', action: 'delete' },
          { id: 'DOC-84099', kind: 'Email attachment v2', matter: 'MTR-2019-0412', lastTouched: '2020-08-12', action: 'delete' },
          { id: 'DOC-84087', kind: 'Signed contract',     matter: 'MTR-2019-0401', lastTouched: '2020-07-30', action: 'hold',   holdId: 'LH-2023-014' },
          { id: 'DOC-84055', kind: 'Memo',                matter: 'MTR-2018-0887', lastTouched: '2020-06-19', action: 'delete' },
          { id: 'DOC-84041', kind: 'Evidence bundle',     matter: 'MTR-2019-0018', lastTouched: '2020-06-02', action: 'hold',   holdId: 'LH-2022-003' },
        ],
      });
    }, 900);
  }

  return (
    <div>
      <div style={stg.stripKpi}>
        <div style={stg.stat}><span style={stg.statLabel}>Retention policies</span><span style={stg.statValue}>{ret.length}</span></div>
        <div style={stg.stat}><span style={stg.statLabel}>Legal holds</span><span style={stg.statValue}>{holds.length}</span><span style={stg.statDelta}>{activeHolds} active</span></div>
        <div style={stg.stat}><span style={stg.statLabel}>Pending exports</span><span style={stg.statValue}>{exports.filter(e => e.status !== 'ready').length}</span></div>
        <div style={stg.stat}><span style={stg.statLabel}>Hold-override policies</span><span style={stg.statValue}>{ret.filter(r => r.holdOverride).length}</span></div>
        <div style={stg.stat}><span style={stg.statLabel}>Custodians under hold</span><span style={{ ...stg.statValue, color: stg.amber }}>108</span></div>
        <div style={stg.stat}><span style={stg.statLabel}>Data volume held</span><span style={stg.statValue}>1.8 TB</span></div>
      </div>

      <Card title={`Retention policies · ${ret.length}`} action={<button style={stg.btnSecondary}>+ Policy</button>}>
        <div style={stg.tableWrap}>
        <table style={stg.tableFixed}>
          <thead>
            <tr>
              <th style={stg.th}>Resource</th>
              <th style={stg.th}>Retention</th>
              <th style={stg.th}>Policy basis</th>
              <th style={stg.th}>Legal hold override</th>
              <th style={stg.th}></th>
            </tr>
          </thead>
          <tbody>
            {ret.map(r => (
              <tr key={r.id}>
                <td style={{ ...stg.td, fontWeight: 600 }}>{r.resource}</td>
                <td style={{ ...stg.td, fontFamily: Ts_g.font.mono, color: stg.steelDeep, fontWeight: 600 }}>{r.retention}</td>
                <td style={{ ...stg.td, fontSize: '11px', color: Ts_g.color.text.secondary }}>{r.policy}</td>
                <td style={stg.td}>
                  <span style={{ ...stg.tag, ...stg.statusPill(r.holdOverride ? 'info' : 'pending') }}>{r.holdOverride ? 'Suspends retention' : 'No override'}</span>
                </td>
                <td style={{ ...stg.td, textAlign: 'right', whiteSpace: 'nowrap' }}>
                  <button style={stg.btnGhost} onClick={() => runDryRun(r)}>◎ Dry-run</button>
                  <button style={stg.btnGhost}>Edit</button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
        </div>
      </Card>

      {/* #7 — Dry-run preview modal */}
      {dryRun && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 9996, background: 'rgba(15,23,42,0.4)', display: 'flex', justifyContent: 'center', alignItems: 'flex-start', paddingTop: '48px' }} onClick={() => setDryRun(null)}>
          <div onClick={e => e.stopPropagation()} style={{ width: '820px', maxWidth: '94%', maxHeight: '86vh', background: '#fff', borderRadius: '8px', boxShadow: '0 16px 48px rgba(0,0,0,0.2)', display: 'flex', flexDirection: 'column' }}>
            <div style={{ padding: '16px 20px', borderBottom: `1px solid ${Ts_g.color.border.light}`, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <div>
                <div style={{ fontSize: '10px', fontWeight: 700, color: Ts_g.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.08em' }}>Retention dry-run</div>
                <div style={{ fontSize: '14px', fontWeight: 700, marginTop: '2px' }}>{dryRun.policy}</div>
                {dryRun.status === 'ready' && <div style={{ fontSize: '11px', color: Ts_g.color.text.tertiary, marginTop: '2px' }}>Retention = {dryRun.retention} · cutoff = {dryRun.cutoff} · no records modified</div>}
              </div>
              <button onClick={() => setDryRun(null)} style={{ background: 'none', border: 'none', fontSize: '18px', cursor: 'pointer' }}>×</button>
            </div>
            {dryRun.status === 'running' ? (
              <div style={{ padding: '80px 20px', textAlign: 'center' }}>
                <div style={{ fontSize: '24px' }}></div>
                <div style={{ fontSize: '12px', color: Ts_g.color.text.secondary, marginTop: '8px' }}>Scanning … this is read-only</div>
              </div>
            ) : (
              <div style={{ flex: 1, overflowY: 'auto' }}>
                <div style={{ padding: '16px 20px', display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '10px' }}>
                  <div style={stg.stat}><span style={stg.statLabel}>Scanned</span><span style={stg.statValue}>{dryRun.scanned.toLocaleString()}</span></div>
                  <div style={stg.stat}><span style={stg.statLabel}>Eligible</span><span style={stg.statValue}>{dryRun.eligible.toLocaleString()}</span></div>
                  <div style={stg.stat}><span style={stg.statLabel}>Held back</span><span style={{ ...stg.statValue, color: stg.amber }}>{dryRun.heldBack.toLocaleString()}</span><span style={stg.statDelta}>legal holds</span></div>
                  <div style={stg.stat}><span style={stg.statLabel}>Would delete</span><span style={{ ...stg.statValue, color: stg.crimson }}>{dryRun.toDelete.toLocaleString()}</span><span style={stg.statDelta}>{dryRun.sizeGb} GB</span></div>
                </div>
                <div style={{ padding: '0 20px 16px' }}>
                  <div style={stg.sectionLabel}>Breakdown</div>
                  <div style={{ marginTop: '6px' }}>
                    {dryRun.byType.map(b => {
                      const pct = Math.round((b.n / dryRun.toDelete) * 100);
                      return (
                        <div key={b.k} style={{ display: 'flex', alignItems: 'center', gap: '10px', padding: '4px 0', fontSize: '11px' }}>
                          <span style={{ width: '200px', color: Ts_g.color.text.secondary }}>{b.k}</span>
                          <div style={{ flex: 1, height: '6px', background: Ts_g.color.border.light, borderRadius: '3px', overflow: 'hidden' }}>
                            <div style={{ width: `${pct}%`, height: '100%', background: stg.steelDeep }} />
                          </div>
                          <span style={{ width: '60px', fontFamily: Ts_g.font.mono, fontWeight: 700, textAlign: 'right' }}>{b.n.toLocaleString()}</span>
                          <span style={{ width: '40px', fontFamily: Ts_g.font.mono, color: Ts_g.color.text.tertiary, textAlign: 'right' }}>{pct}%</span>
                        </div>
                      );
                    })}
                  </div>
                </div>
                <div style={{ padding: '0 20px 16px' }}>
                  <div style={stg.sectionLabel}>Sample · first 5 of {dryRun.toDelete.toLocaleString()}</div>
                  <table style={{ ...stg.tableFixed, marginTop: '6px' }}>
                    <thead>
                      <tr>
                        <th style={stg.th}>Record</th>
                        <th style={stg.th}>Kind</th>
                        <th style={stg.th}>Matter</th>
                        <th style={stg.th}>Last touched</th>
                        <th style={stg.th}>Action</th>
                      </tr>
                    </thead>
                    <tbody>
                      {dryRun.sample.map(s => (
                        <tr key={s.id}>
                          <td style={{ ...stg.td, fontFamily: Ts_g.font.mono, fontWeight: 700, color: stg.steelDeep }}>{s.id}</td>
                          <td style={{ ...stg.td, fontSize: '11px' }}>{s.kind}</td>
                          <td style={{ ...stg.td, fontFamily: Ts_g.font.mono, fontSize: '11px', color: Ts_g.color.text.secondary }}>{s.matter}</td>
                          <td style={{ ...stg.td, fontFamily: Ts_g.font.mono, fontSize: '11px', color: Ts_g.color.text.tertiary }}>{s.lastTouched}</td>
                          <td style={stg.td}>
                            {s.action === 'delete'
                              ? <span style={{ ...stg.tag, ...stg.statusPill('fail') }}>delete</span>
                              : <span style={{ ...stg.tag, ...stg.statusPill('info'), fontFamily: Ts_g.font.mono }}>hold · {s.holdId}</span>}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>
            )}
            <div style={{ padding: '12px 20px', borderTop: `1px solid ${Ts_g.color.border.light}`, background: Ts_g.color.bg.secondary, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <span style={{ fontSize: '11px', color: Ts_g.color.text.tertiary }}>Dry-run does not modify records. Live application requires a 2-person review.</span>
              <div style={{ display: 'flex', gap: '6px' }}>
                <button style={stg.btnGhost} onClick={() => toast.push({ kind: 'info', title: 'Report exported', message: 'retention-dryrun.csv' })}>Export report</button>
                <button style={stg.btnSecondary} onClick={() => setDryRun(null)}>Close</button>
                <button style={stg.btnPrimary} onClick={() => { toast.push({ kind: 'info', title: 'Review requested', message: 'Partner approval pending' }); setDryRun(null); }} disabled={dryRun.status !== 'ready'}>Request 2-person review →</button>
              </div>
            </div>
          </div>
        </div>
      )}

      <Card title={`Legal holds · ${holds.length}`} action={<button style={stg.btnPrimary}>+ Issue hold</button>}>
        <div style={stg.tableWrap}>
        <table style={stg.tableFixed}>
          <thead>
            <tr>
              <th style={stg.th}>Hold ID</th>
              <th style={stg.th}>Matter</th>
              <th style={stg.th}>Scope</th>
              <th style={stg.th}>Issued</th>
              <th style={stg.th}>Issued by</th>
              <th style={{ ...stg.th, textAlign: 'right' }}>Acks</th>
              <th style={stg.th}>Status</th>
              <th style={stg.th}></th>
            </tr>
          </thead>
          <tbody>
            {holds.map(h => (
              <tr key={h.id}>
                <td style={{ ...stg.td, fontFamily: Ts_g.font.mono, fontWeight: 700, color: stg.steelDeep }}>{h.id}</td>
                <td style={{ ...stg.td, fontWeight: 600 }}>{h.matter}</td>
                <td style={{ ...stg.td, fontSize: '11px', color: Ts_g.color.text.secondary }}>{h.scope}</td>
                <td style={{ ...stg.td, fontFamily: Ts_g.font.mono, fontSize: '11px' }}>{h.issued}</td>
                <td style={{ ...stg.td, fontSize: '11px', color: Ts_g.color.text.secondary }}>{h.issuedBy}</td>
                <td style={{ ...stg.td, textAlign: 'right' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '6px', justifyContent: 'flex-end' }}>
                    <div style={{ width: '60px', height: '5px', background: Ts_g.color.border.light, borderRadius: '3px', overflow: 'hidden' }}>
                      <div style={{ width: `${h.ackPct}%`, height: '100%', background: h.ackPct === 100 ? stg.emerald : stg.amber }} />
                    </div>
                    <span style={{ fontFamily: Ts_g.font.mono, fontWeight: 700, fontSize: '11px' }}>{h.ackPct}%</span>
                  </div>
                </td>
                <td style={stg.td}><span style={{ ...stg.tag, ...stg.statusPill(h.status === 'active' ? 'info' : 'pending') }}>{h.status}</span></td>
                <td style={{ ...stg.td, textAlign: 'right', whiteSpace: 'nowrap' }}>
                  <button style={stg.btnGhost} onClick={() => setCustodianHold(h)}>Custodians →</button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
        </div>
      </Card>

      {/* #8 — Legal-hold custodian workflow drawer */}
      {custodianHold && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 9996, background: 'rgba(15,23,42,0.4)', display: 'flex', justifyContent: 'flex-end' }} onClick={() => setCustodianHold(null)}>
          <div onClick={e => e.stopPropagation()} style={{ width: '560px', maxWidth: '100%', height: '100%', background: '#fff', boxShadow: '-8px 0 24px rgba(0,0,0,0.15)', display: 'flex', flexDirection: 'column' }}>
            <div style={{ padding: '14px 18px', borderBottom: `1px solid ${Ts_g.color.border.light}`, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <div>
                <div style={{ fontSize: '10px', fontWeight: 700, color: Ts_g.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.08em' }}>Custodian workflow</div>
                <div style={{ fontSize: '14px', fontWeight: 700, marginTop: '2px' }}>{custodianHold.id} · {custodianHold.matter}</div>
                <div style={{ fontSize: '11px', color: Ts_g.color.text.tertiary, marginTop: '2px' }}>Scope: {custodianHold.scope}</div>
              </div>
              <button onClick={() => setCustodianHold(null)} style={{ background: 'none', border: 'none', fontSize: '18px', cursor: 'pointer' }}>×</button>
            </div>
            <div style={{ padding: '12px 18px', background: Ts_g.color.bg.secondary, borderBottom: `1px solid ${Ts_g.color.border.light}`, display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '8px' }}>
              <div><div style={stg.statLabel}>Custodians</div><div style={{ fontSize: '16px', fontWeight: 800, fontFamily: Ts_g.font.mono }}>18</div></div>
              <div><div style={stg.statLabel}>Acknowledged</div><div style={{ fontSize: '16px', fontWeight: 800, fontFamily: Ts_g.font.mono, color: stg.emerald }}>{Math.round(18 * custodianHold.ackPct / 100)}</div></div>
              <div><div style={stg.statLabel}>Pending</div><div style={{ fontSize: '16px', fontWeight: 800, fontFamily: Ts_g.font.mono, color: stg.amber }}>{18 - Math.round(18 * custodianHold.ackPct / 100)}</div></div>
              <div><div style={stg.statLabel}>Reminders sent</div><div style={{ fontSize: '16px', fontWeight: 800, fontFamily: Ts_g.font.mono }}>42</div></div>
            </div>
            <div style={{ padding: '12px 18px', borderBottom: `1px solid ${Ts_g.color.border.light}`, display: 'flex', gap: '6px', flexWrap: 'wrap' }}>
              <button style={stg.btnPrimary} onClick={() => toast.push({ kind: 'success', title: 'Reminder dispatched', message: 'Sent to 7 pending custodians' })}>↻ Send reminder to pending</button>
              <button style={stg.btnSecondary} onClick={() => toast.push({ kind: 'success', title: 'Release notice drafted', message: 'Awaiting partner sign-off' })}>Release notice…</button>
              <button style={stg.btnSecondary} onClick={() => toast.push({ kind: 'info', title: 'Export queued', message: 'hold-custodians.csv' })}>Export roster</button>
            </div>
            <div style={{ flex: 1, overflowY: 'auto' }}>
              <table style={stg.tableFixed}>
                <thead>
                  <tr>
                    <th style={stg.th}>Custodian</th>
                    <th style={stg.th}>Dept</th>
                    <th style={stg.th}>Notice sent</th>
                    <th style={stg.th}>Ack</th>
                    <th style={stg.th}>Reminders</th>
                    <th style={stg.th}></th>
                  </tr>
                </thead>
                <tbody>
                  {[
                    { id: 1, name: 'Rachel Kim',     dept: 'Litigation',   sent: '2026-04-02', ack: '2026-04-02', rem: 0 },
                    { id: 2, name: 'Marcus Orellana', dept: 'Litigation',   sent: '2026-04-02', ack: '2026-04-03', rem: 1 },
                    { id: 3, name: 'Priya Shah',     dept: 'Corporate',    sent: '2026-04-02', ack: null,         rem: 4 },
                    { id: 4, name: 'Daniel Ochoa',   dept: 'Litigation',   sent: '2026-04-02', ack: '2026-04-04', rem: 2 },
                    { id: 5, name: 'Sofia Alvarez',  dept: 'Paralegal',    sent: '2026-04-02', ack: '2026-04-02', rem: 0 },
                    { id: 6, name: 'Ken Yamada',     dept: 'IT',           sent: '2026-04-02', ack: null,         rem: 5 },
                    { id: 7, name: 'Elena Wirth',    dept: 'Compliance',   sent: '2026-04-02', ack: '2026-04-03', rem: 1 },
                  ].map(c => (
                    <tr key={c.id}>
                      <td style={{ ...stg.td, fontWeight: 600 }}>{c.name}</td>
                      <td style={{ ...stg.td, fontSize: '11px', color: Ts_g.color.text.secondary }}>{c.dept}</td>
                      <td style={{ ...stg.td, fontFamily: Ts_g.font.mono, fontSize: '11px', color: Ts_g.color.text.tertiary }}>{c.sent}</td>
                      <td style={stg.td}>
                        {c.ack
                          ? <span style={{ ...stg.tag, ...stg.statusPill('ok'), fontFamily: Ts_g.font.mono }}>{c.ack}</span>
                          : <span style={{ ...stg.tag, ...stg.statusPill('pending') }}>pending</span>}
                      </td>
                      <td style={{ ...stg.td, textAlign: 'center', fontFamily: Ts_g.font.mono, fontWeight: 700, color: c.rem >= 3 ? stg.crimson : c.rem > 0 ? stg.amber : Ts_g.color.text.tertiary }}>{c.rem}</td>
                      <td style={{ ...stg.td, textAlign: 'right', whiteSpace: 'nowrap' }}>
                        {!c.ack && <button style={stg.btnGhost} onClick={() => toast.push({ kind: 'success', title: `Nudged ${c.name}` })}>Nudge</button>}
                        <button style={stg.btnGhost}>Audit</button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      )}

      <Card title={`Data exports · ${exports.length}`} action={<button style={stg.btnPrimary}>+ Request export</button>}>
        <div style={stg.tableWrap}>
        <table style={stg.tableFixed}>
          <thead>
            <tr>
              <th style={stg.th}>Export ID</th>
              <th style={stg.th}>Kind</th>
              <th style={stg.th}>Scope</th>
              <th style={stg.th}>Requested</th>
              <th style={stg.th}>By</th>
              <th style={{ ...stg.th, textAlign: 'right' }}>Size</th>
              <th style={stg.th}>Status</th>
              <th style={stg.th}></th>
            </tr>
          </thead>
          <tbody>
            {exports.map(e => (
              <tr key={e.id}>
                <td style={{ ...stg.td, fontFamily: Ts_g.font.mono, fontWeight: 700, color: stg.steelDeep }}>{e.id}</td>
                <td style={{ ...stg.td, fontWeight: 600 }}>{e.kind}</td>
                <td style={{ ...stg.td, fontSize: '11px', color: Ts_g.color.text.secondary }}>{e.scope}</td>
                <td style={{ ...stg.td, fontFamily: Ts_g.font.mono, fontSize: '11px', color: Ts_g.color.text.tertiary }}>{e.requested}</td>
                <td style={{ ...stg.td, fontSize: '11px', color: Ts_g.color.text.secondary }}>{e.requestedBy}</td>
                <td style={{ ...stg.td, textAlign: 'right', fontFamily: Ts_g.font.mono, fontWeight: 600 }}>{e.size}</td>
                <td style={stg.td}>
                  <span style={{ ...stg.tag, ...stg.statusPill(e.status === 'ready' ? 'ok' : e.status === 'processing' ? 'info' : 'pending') }}>{e.status}</span>
                </td>
                <td style={{ ...stg.td, textAlign: 'right' }}>{e.status === 'ready' ? <button style={stg.btnGhost}>Download</button> : <button style={stg.btnGhost}>Details</button>}</td>
              </tr>
            ))}
          </tbody>
        </table>
        </div>
      </Card>
    </div>
  );
}

function SettingsAuditLog({ data }) {
  const stg = window.__stg;
  const ev = data.auditEvents;
  const Card = window.SettingsSectionCard;
  const { useState } = React;
  const infra = window.__stg_infra || {};
  const toast = (infra.useToast && infra.useToast()) || { push: () => {} };
  const AuditDrawer = infra.AuditDrawer || (() => null);
  const sampleHistory = infra.sampleHistory || [];

  const [search, setSearch] = useState('');
  const [sev, setSev] = useState('all');
  const [selected, setSelected] = useState(null);  // #14 — deep-link drill
  const [exportOpen, setExportOpen] = useState(false);
  const [siemOpen, setSiemOpen] = useState(false);

  // #12 — scheduled exports state
  const [schedules, setSchedules] = useState([
    { id: 'SCH-001', kind: 'CSV',      target: 'sftp://audit.saadein.law/daily/',          cadence: 'Daily · 02:00 UTC',  filter: 'severity ≥ warn',     last: '8h ago',  status: 'ok'    },
    { id: 'SCH-002', kind: 'JSONL',    target: 's3://arbiter-audit-archive/weekly/',       cadence: 'Weekly · Sunday 04:00', filter: 'all events',          last: '3d ago',  status: 'ok'    },
    { id: 'SCH-003', kind: 'Splunk HEC',target:'https://splunk.saadein.law:8088/services', cadence: 'Real-time',             filter: 'severity ≥ warn',     last: '14s ago', status: 'ok'    },
    { id: 'SCH-004', kind: 'Sentinel', target: 'Log Analytics · ArbiterAudit_CL',          cadence: 'Real-time',             filter: 'authn + authz only',  last: '7s ago',  status: 'ok'    },
    { id: 'SCH-005', kind: 'CSV',      target: 'mail: compliance@saadein.law',             cadence: 'Monthly · 1st',         filter: 'privileged actions',  last: 'pending', status: 'pending' },
  ]);

  const filtered = ev.filter(e => {
    if (sev !== 'all' && e.severity !== sev) return false;
    if (search) {
      const q = search.toLowerCase();
      return e.actor.toLowerCase().includes(q) || e.action.toLowerCase().includes(q) || (e.target || '').toLowerCase().includes(q);
    }
    return true;
  });

  // #14 — deep-link resolver: action → primary surface
  // URLs must match canonical sub-IDs in STG_GROUPS (SettingsPlatform.jsx)
  function resolveDeepLink(e) {
    const a = e.action || '';
    if (a.includes('user.'))     return { url: '#/settings/firm/users',             label: 'Open in Users' };
    if (a.includes('role.'))     return { url: '#/settings/firm/roles',             label: 'Open in Roles' };
    if (a.includes('security.') || a.includes('mfa.') || a.includes('sso.'))
                                 return { url: '#/settings/security/security',      label: 'Open in Security' };
    if (a.includes('integration.') || a.includes('webhook.'))
                                 return { url: '#/settings/integrations/integrations', label: 'Open in Integrations' };
    if (a.includes('retention.') || a.includes('hold.'))
                                 return { url: '#/settings/data/retention',         label: 'Open in Retention' };
    if (a.includes('billing.'))  return { url: '#/settings/system/billing',         label: 'Open in Billing' };
    return { url: '#/settings/security/audit', label: 'Copy link' };
  }

  function triggerScheduleNow(s) {
    setSchedules(ss => ss.map(x => x.id === s.id ? { ...x, status: 'running', last: 'just now' } : x));
    setTimeout(() => {
      setSchedules(ss => ss.map(x => x.id === s.id ? { ...x, status: 'ok', last: 'just now' } : x));
      toast.push({ kind: 'success', title: `${s.id} exported`, message: `${s.kind} → ${s.target.slice(0, 36)}${s.target.length > 36 ? '…' : ''}` });
    }, 900);
  }

  return (
    <div>
      <div style={stg.stripKpi}>
        <div style={stg.stat}><span style={stg.statLabel}>Events today</span><span style={stg.statValue}>{data.kpis.auditEventsToday.toLocaleString()}</span></div>
        <div style={stg.stat}><span style={stg.statLabel}>High severity</span><span style={{ ...stg.statValue, color: stg.amber }}>{ev.filter(e => e.severity === 'high').length}</span></div>
        <div style={stg.stat}><span style={stg.statLabel}>Warn</span><span style={stg.statValue}>{ev.filter(e => e.severity === 'warn').length}</span></div>
        <div style={stg.stat}><span style={stg.statLabel}>Info</span><span style={stg.statValue}>{ev.filter(e => e.severity === 'info').length}</span></div>
        <div style={stg.stat}><span style={stg.statLabel}>Retention</span><span style={stg.statValue}>5 yrs</span><span style={stg.statDelta}>immutable + hashed</span></div>
        <div style={stg.stat}><span style={stg.statLabel}>Scheduled exports</span><span style={{ ...stg.statValue, color: stg.emerald }}>{schedules.filter(s => s.status === 'ok').length}</span><span style={stg.statDelta}>of {schedules.length}</span></div>
      </div>

      <div style={{ display: 'flex', gap: '8px', marginBottom: '12px', flexWrap: 'wrap' }}>
        <input placeholder="Filter actor, action, target…" value={search} onChange={e => setSearch(e.target.value)} style={{ ...stg.input, width: '300px' }} />
        {['all','high','warn','info'].map(s => (
          <button key={s} onClick={() => setSev(s)}
            style={{ ...stg.btnSecondary, textTransform: 'capitalize', background: sev === s ? stg.steelDeep : Ts_g.color.bg.card, color: sev === s ? '#fff' : Ts_g.color.text.secondary, borderColor: sev === s ? stg.steelDeep : Ts_g.color.border.medium }}>{s}</button>
        ))}
        <div style={{ flex: 1 }} />
        <button style={stg.btnSecondary} onClick={() => toast.push({ kind: 'info', title: 'Live stream opened', message: 'Tailing audit.events (WebSocket)' })}>● Stream live</button>
        <button style={stg.btnSecondary} onClick={() => setExportOpen(true)}>⇣ Export / Schedule</button>
        <button style={stg.btnSecondary} onClick={() => setSiemOpen(true)}>SIEM forwarders</button>
      </div>

      <div style={stg.card}>
        <div style={stg.tableWrap}>
        <table style={stg.tableFixed}>
          <thead>
            <tr>
              <th style={stg.th}>Timestamp</th>
              <th style={stg.th}>Actor</th>
              <th style={stg.th}>Action</th>
              <th style={stg.th}>Target</th>
              <th style={stg.th}>IP</th>
              <th style={stg.th}>Severity</th>
              <th style={stg.th}></th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(e => {
              const dl = resolveDeepLink(e);
              return (
                <tr key={e.id} style={{ cursor: 'pointer' }} onClick={() => setSelected(e)}>
                  <td style={{ ...stg.td, fontFamily: Ts_g.font.mono, fontSize: '11px', color: Ts_g.color.text.tertiary }}>{e.ts}</td>
                  <td style={{ ...stg.td, fontWeight: 600 }}>{e.actor}</td>
                  <td style={{ ...stg.td, fontFamily: Ts_g.font.mono, fontSize: '11px', color: stg.steelDeep }}>{e.action}</td>
                  <td style={{ ...stg.td, fontSize: '11px', color: Ts_g.color.text.secondary }}>{e.target}</td>
                  <td style={{ ...stg.td, fontFamily: Ts_g.font.mono, fontSize: '10px', color: Ts_g.color.text.tertiary }}>{e.ip}</td>
                  <td style={stg.td}>
                    <span style={{ ...stg.tag, ...stg.statusPill(e.severity === 'high' ? 'fail' : e.severity === 'warn' ? 'warn' : 'info') }}>{e.severity}</span>
                  </td>
                  <td style={{ ...stg.td, textAlign: 'right', whiteSpace: 'nowrap' }}>
                    <a href={dl.url} onClick={(ev2) => { ev2.stopPropagation(); }}
                       style={{ fontSize: '11px', color: stg.steelDeep, textDecoration: 'none', padding: '2px 6px', borderRadius: '3px', background: stg.steelBg, fontWeight: 600 }}>
                      {dl.label} →
                    </a>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
        </div>
      </div>

      {/* #14 — Event detail drawer with deep-link to originating surface */}
      {selected && (
        <AuditDrawer
          open={!!selected}
          onClose={() => setSelected(null)}
          entry={{
            title: selected.action,
            subtitle: `${selected.actor} · ${selected.ts}`,
            fields: [
              { label: 'Actor',    value: selected.actor },
              { label: 'Action',   value: selected.action, mono: true },
              { label: 'Target',   value: selected.target || '—' },
              { label: 'IP',       value: selected.ip || '—', mono: true },
              { label: 'Severity', value: selected.severity },
              { label: 'Event ID', value: selected.id, mono: true },
              { label: 'Trace ID', value: 't_' + String(selected.id).padStart(10, '0'), mono: true },
              { label: 'Deep link', value: resolveDeepLink(selected).url, mono: true, linkHref: resolveDeepLink(selected).url },
            ],
          }}
          history={sampleHistory}
        />
      )}

      {/* #12 — Scheduled export management */}
      {exportOpen && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 9996, background: 'rgba(15,23,42,0.4)', display: 'flex', justifyContent: 'center', alignItems: 'flex-start', paddingTop: '60px' }} onClick={() => setExportOpen(false)}>
          <div onClick={e => e.stopPropagation()} style={{ width: '780px', maxWidth: '94%', background: '#fff', borderRadius: '8px', boxShadow: '0 16px 48px rgba(0,0,0,0.2)' }}>
            <div style={{ padding: '16px 20px', borderBottom: `1px solid ${Ts_g.color.border.light}`, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <div>
                <div style={{ fontSize: '14px', fontWeight: 700 }}>Export & schedule audit log</div>
                <div style={{ fontSize: '11px', color: Ts_g.color.text.tertiary, marginTop: '2px' }}>One-time export now, or schedule to CSV / JSONL / SIEM / mail</div>
              </div>
              <button onClick={() => setExportOpen(false)} style={{ background: 'none', border: 'none', fontSize: '18px', cursor: 'pointer' }}>×</button>
            </div>
            <div style={{ padding: '14px 20px', borderBottom: `1px solid ${Ts_g.color.border.light}`, display: 'flex', gap: '10px', flexWrap: 'wrap', alignItems: 'center' }}>
              <span style={stg.sectionLabel}>One-time export</span>
              <select style={{ ...stg.select, width: '130px' }}><option>CSV</option><option>JSONL</option><option>Parquet</option></select>
              <input type="date" style={{ ...stg.input, width: '160px' }} defaultValue="2026-04-01" />
              <span style={{ fontSize: '11px', color: Ts_g.color.text.tertiary }}>to</span>
              <input type="date" style={{ ...stg.input, width: '160px' }} defaultValue="2026-04-23" />
              <select style={{ ...stg.select, width: '160px' }}><option>All events</option><option>severity ≥ warn</option><option>Privileged actions</option></select>
              <button style={stg.btnPrimary} onClick={() => { toast.push({ kind: 'success', title: 'Export queued', message: 'EXP-10241 — you will be emailed when ready' }); setExportOpen(false); }}>Queue export</button>
            </div>
            <div style={{ padding: '6px 0' }}>
              <div style={{ padding: '8px 20px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <span style={stg.sectionLabel}>Scheduled exports · {schedules.length}</span>
                <button style={stg.btnSecondary}>+ Add schedule</button>
              </div>
              <table style={stg.tableFixed}>
                <thead>
                  <tr>
                    <th style={stg.th}>ID</th>
                    <th style={stg.th}>Kind</th>
                    <th style={stg.th}>Target</th>
                    <th style={stg.th}>Cadence</th>
                    <th style={stg.th}>Filter</th>
                    <th style={stg.th}>Last run</th>
                    <th style={stg.th}>Status</th>
                    <th style={stg.th}></th>
                  </tr>
                </thead>
                <tbody>
                  {schedules.map(s => (
                    <tr key={s.id}>
                      <td style={{ ...stg.td, fontFamily: Ts_g.font.mono, fontWeight: 700, color: stg.steelDeep }}>{s.id}</td>
                      <td style={{ ...stg.td, fontWeight: 600 }}>{s.kind}</td>
                      <td style={{ ...stg.td, fontFamily: Ts_g.font.mono, fontSize: '10px', maxWidth: '220px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', color: Ts_g.color.text.secondary }}>{s.target}</td>
                      <td style={{ ...stg.td, fontSize: '11px', color: Ts_g.color.text.secondary }}>{s.cadence}</td>
                      <td style={{ ...stg.td, fontSize: '11px', color: Ts_g.color.text.secondary }}>{s.filter}</td>
                      <td style={{ ...stg.td, fontSize: '11px', fontFamily: Ts_g.font.mono, color: Ts_g.color.text.tertiary }}>{s.last}</td>
                      <td style={stg.td}><span style={{ ...stg.tag, ...stg.statusPill(s.status === 'ok' ? 'ok' : s.status === 'running' ? 'info' : 'pending') }}>{s.status}</span></td>
                      <td style={{ ...stg.td, textAlign: 'right', whiteSpace: 'nowrap' }}>
                        <button style={stg.btnGhost} onClick={() => triggerScheduleNow(s)}>Run now</button>
                        <button style={stg.btnGhost}>Edit</button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      )}

      {/* #12 — SIEM forwarders panel */}
      {siemOpen && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 9996, background: 'rgba(15,23,42,0.4)', display: 'flex', justifyContent: 'flex-end' }} onClick={() => setSiemOpen(false)}>
          <div onClick={e => e.stopPropagation()} style={{ width: '480px', maxWidth: '100%', height: '100%', background: '#fff', boxShadow: '-8px 0 24px rgba(0,0,0,0.15)', display: 'flex', flexDirection: 'column' }}>
            <div style={{ padding: '14px 18px', borderBottom: `1px solid ${Ts_g.color.border.light}`, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <div>
                <div style={{ fontSize: '10px', fontWeight: 700, color: Ts_g.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.08em' }}>SIEM forwarders</div>
                <div style={{ fontSize: '14px', fontWeight: 700, marginTop: '2px' }}>Real-time audit stream targets</div>
              </div>
              <button onClick={() => setSiemOpen(false)} style={{ background: 'none', border: 'none', fontSize: '18px', cursor: 'pointer' }}>×</button>
            </div>
            <div style={{ flex: 1, overflowY: 'auto', padding: '14px 18px' }}>
              {[
                { name: 'Splunk HEC',        vendor: 'Splunk Cloud',     endpoint: 'https://splunk.saadein.law:8088/services/collector', lag: '14s', events7d: 1_842_003, on: true },
                { name: 'Microsoft Sentinel',vendor: 'Azure Log Analytics', endpoint: 'workspaceId: b6c9d4e2-…',                         lag: '7s',  events7d: 1_841_998, on: true  },
                { name: 'Datadog',           vendor: 'Datadog SaaS',      endpoint: 'https://http-intake.logs.datadoghq.com/api/v2/logs', lag: '—',  events7d: 0,          on: false },
                { name: 'Sumo Logic',        vendor: 'Sumo Logic',        endpoint: 'https://collectors.sumologic.com/receiver/…',       lag: '—',  events7d: 0,          on: false },
                { name: 'S3 archive',        vendor: 'AWS S3 · WORM',     endpoint: 's3://arbiter-audit-archive/',                        lag: '3h', events7d: 1_842_003, on: true  },
              ].map(f => (
                <div key={f.name} style={{ padding: '12px 0', borderBottom: `1px solid ${Ts_g.color.border.light}` }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '4px' }}>
                    <div style={{ fontSize: '13px', fontWeight: 700, color: Ts_g.color.text.primary }}>{f.name}</div>
                    <span style={{ ...stg.tag, ...stg.statusPill(f.on ? 'ok' : 'pending') }}>{f.on ? 'Streaming' : 'Disabled'}</span>
                  </div>
                  <div style={{ fontSize: '11px', color: Ts_g.color.text.tertiary }}>{f.vendor}</div>
                  <div style={{ fontFamily: Ts_g.font.mono, fontSize: '10px', color: Ts_g.color.text.secondary, marginTop: '4px', wordBreak: 'break-all' }}>{f.endpoint}</div>
                  <div style={{ display: 'flex', gap: '14px', marginTop: '6px', fontSize: '11px', color: Ts_g.color.text.tertiary }}>
                    <span>Lag: <span style={{ fontFamily: Ts_g.font.mono, color: f.on && f.lag !== '—' ? stg.emerald : Ts_g.color.text.tertiary }}>{f.lag}</span></span>
                    <span>7d: <span style={{ fontFamily: Ts_g.font.mono, fontWeight: 600, color: Ts_g.color.text.primary }}>{f.events7d.toLocaleString()}</span></span>
                  </div>
                  <div style={{ display: 'flex', gap: '6px', marginTop: '8px' }}>
                    <button style={stg.btnGhost}>Test connection</button>
                    <button style={stg.btnGhost}>Edit</button>
                    <button style={stg.btnGhost}>{f.on ? 'Disable' : 'Enable'}</button>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

function SettingsCompliance({ data }) {
  const stg = window.__stg;
  const comp = data.compliance;
  const Card = window.SettingsSectionCard;

  const certified = comp.filter(c => c.status === 'certified').length;
  const compliant = comp.filter(c => c.status === 'compliant').length;
  const inProgress = comp.filter(c => c.status === 'in-progress').length;
  const avg = Math.round(comp.filter(c => c.score != null).reduce((s, c) => s + c.score, 0) / comp.filter(c => c.score != null).length);

  const statusColor = (s) =>
    s === 'certified'   ? stg.statusPill('ok')
    : s === 'compliant' ? stg.statusPill('ok')
    : s === 'in-progress' ? stg.statusPill('info')
    : stg.statusPill('pending');

  return (
    <div>
      <div style={stg.stripKpi}>
        <div style={stg.stat}><span style={stg.statLabel}>Frameworks</span><span style={stg.statValue}>{comp.length}</span></div>
        <div style={stg.stat}><span style={stg.statLabel}>Certified</span><span style={{ ...stg.statValue, color: stg.emerald }}>{certified}</span></div>
        <div style={stg.stat}><span style={stg.statLabel}>Compliant</span><span style={stg.statValue}>{compliant}</span></div>
        <div style={stg.stat}><span style={stg.statLabel}>In progress</span><span style={{ ...stg.statValue, color: stg.blue }}>{inProgress}</span></div>
        <div style={stg.stat}><span style={stg.statLabel}>Avg score</span><span style={{ ...stg.statValue, color: stg.emerald }}>{avg}</span></div>
        <div style={stg.stat}><span style={stg.statLabel}>Evidence room</span><span style={{ ...stg.statValue, fontSize: '14px', marginTop: '4px' }}>Active</span></div>
      </div>

      <div style={stg.cardGrid(320)}>
        {comp.map(c => (
          <div key={c.id} style={{ ...stg.card, marginBottom: 0, margin: '4px' }}>
            <div style={{ padding: '14px 16px', borderBottom: `1px solid ${Ts_g.color.border.light}` }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '6px' }}>
                <div style={{ fontSize: '13px', fontWeight: 700, color: Ts_g.color.text.primary }}>{c.framework}</div>
                <span style={{ ...stg.tag, ...statusColor(c.status) }}>{c.status}</span>
              </div>
              <div style={{ fontSize: '11px', color: Ts_g.color.text.tertiary }}>Scope: {c.scope}</div>
            </div>
            <div style={{ padding: '12px 16px', display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '10px' }}>
              <div>
                <div style={stg.sectionLabel}>Score</div>
                <div style={{ fontSize: '20px', fontWeight: 800, color: c.score == null ? Ts_g.color.text.tertiary : c.score >= 95 ? stg.emerald : c.score >= 80 ? stg.steelDeep : stg.amber, fontFamily: Ts_g.font.mono }}>{c.score == null ? '—' : c.score}</div>
              </div>
              <div>
                <div style={stg.sectionLabel}>Next audit</div>
                <div style={{ fontSize: '11px', fontWeight: 600, color: Ts_g.color.text.primary, marginTop: '4px', fontFamily: Ts_g.font.mono }}>{c.next}</div>
              </div>
              <div>
                <div style={stg.sectionLabel}>Auditor</div>
                <div style={{ fontSize: '11px', fontWeight: 600, color: Ts_g.color.text.primary, marginTop: '4px' }}>{c.auditor}</div>
              </div>
            </div>
            <div style={{ padding: '10px 16px', borderTop: `1px solid ${Ts_g.color.border.light}`, display: 'flex', gap: '6px' }}>
              <button style={stg.btnGhost}>Evidence →</button>
              <button style={stg.btnGhost}>Controls →</button>
              <div style={{ flex: 1 }} />
              <button style={stg.btnSecondary}>Report</button>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function SettingsCustomFields({ data }) {
  const stg = window.__stg;
  const cf = data.customFields;
  const Card = window.SettingsSectionCard;
  const { useState } = React;
  const [tab, setTab] = useState('matters');
  const fields = cf[tab];

  const typeStyle = (t) => {
    const map = {
      select: { bg: 'rgba(71,85,105,0.10)', color: '#475569', icon: '▾' },
      text:   { bg: 'rgba(71,85,105,0.10)', color: '#475569', icon: 'Aa' },
      number: { bg: 'rgba(37,99,235,0.10)', color: '#2563EB', icon: '#' },
      currency: { bg: 'rgba(5,150,105,0.10)', color: '#059669', icon: '$' },
      boolean: { bg: 'rgba(124,58,237,0.10)', color: '#7C3AED', icon: '◐' },
      user:   { bg: 'rgba(13,148,136,0.10)', color: '#0D9488', icon: '◉' },
    };
    return map[t] || map.text;
  };

  return (
    <div>
      <div style={{ display: 'flex', gap: '6px', marginBottom: '14px' }}>
        {Object.keys(cf).map(t => (
          <button key={t} onClick={() => setTab(t)}
            style={{ padding: '6px 14px', borderRadius: '14px', border: `1px solid ${tab === t ? stg.steelDeep : Ts_g.color.border.light}`, background: tab === t ? stg.steelBg : Ts_g.color.bg.card, color: tab === t ? stg.steelDeep : Ts_g.color.text.secondary, fontSize: '12px', fontWeight: 600, cursor: 'pointer', fontFamily: Ts_g.font.family, textTransform: 'capitalize' }}>
            {t} · {cf[t].length}
          </button>
        ))}
      </div>

      <Card title={`Fields for ${tab}`} action={<button style={stg.btnPrimary}>+ Field</button>}>
        <div style={stg.tableWrap}>
        <table style={stg.tableFixed}>
          <thead>
            <tr>
              <th style={stg.th}>Field ID</th>
              <th style={stg.th}>Label</th>
              <th style={stg.th}>Type</th>
              <th style={stg.th}>Options / Default</th>
              <th style={stg.th}>Required</th>
              <th style={stg.th}></th>
            </tr>
          </thead>
          <tbody>
            {fields.map(f => {
              const ts = typeStyle(f.type);
              return (
                <tr key={f.id}>
                  <td style={{ ...stg.td, fontFamily: Ts_g.font.mono, fontWeight: 700, color: stg.steelDeep, fontSize: '11px' }}>{f.id}</td>
                  <td style={{ ...stg.td, fontWeight: 600 }}>{f.label}</td>
                  <td style={stg.td}><span style={{ ...stg.tag, background: ts.bg, color: ts.color }}>{ts.icon} {f.type}</span></td>
                  <td style={{ ...stg.td, fontSize: '11px', color: Ts_g.color.text.secondary, maxWidth: '320px' }}>
                    {f.options ? f.options.join(' · ') : f.default != null ? `default: ${String(f.default)}` : '—'}
                  </td>
                  <td style={stg.td}>{f.required ? <span style={{ ...stg.tag, ...stg.statusPill('info') }}>required</span> : <span style={{ color: Ts_g.color.text.tertiary, fontSize: '11px' }}>optional</span>}</td>
                  <td style={{ ...stg.td, textAlign: 'right' }}>
                    <button style={stg.btnGhost}>Edit</button>
                    <button style={stg.btnDanger}>Delete</button>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
        </div>
      </Card>
    </div>
  );
}

function SettingsTemplates({ data }) {
  const stg = window.__stg;
  const tpl = data.templates;
  const Card = window.SettingsSectionCard;
  const { useState } = React;
  const [cat, setCat] = useState('All');
  const cats = ['All', ...new Set(tpl.map(t => t.category))];
  const list = cat === 'All' ? tpl : tpl.filter(t => t.category === cat);
  const totalUses = tpl.reduce((s, t) => s + t.usage, 0);

  return (
    <div>
      <div style={stg.stripKpi}>
        <div style={stg.stat}><span style={stg.statLabel}>Templates</span><span style={stg.statValue}>{tpl.length}</span></div>
        <div style={stg.stat}><span style={stg.statLabel}>Categories</span><span style={stg.statValue}>{cats.length - 1}</span></div>
        <div style={stg.stat}><span style={stg.statLabel}>Total uses</span><span style={stg.statValue}>{totalUses.toLocaleString()}</span></div>
        <div style={stg.stat}><span style={stg.statLabel}>Most used</span><span style={{ ...stg.statValue, fontSize: '13px', marginTop: '4px' }}>{tpl.reduce((m, t) => t.usage > (m?.usage || 0) ? t : m, null)?.name.split(' — ')[0] || tpl[0].name}</span></div>
      </div>

      <div style={{ display: 'flex', gap: '6px', marginBottom: '12px', flexWrap: 'wrap' }}>
        {cats.map(c => (
          <button key={c} onClick={() => setCat(c)}
            style={{ padding: '5px 12px', borderRadius: '14px', border: `1px solid ${cat === c ? stg.steelDeep : Ts_g.color.border.light}`, background: cat === c ? stg.steelBg : Ts_g.color.bg.card, color: cat === c ? stg.steelDeep : Ts_g.color.text.secondary, fontSize: '11px', fontWeight: 500, cursor: 'pointer' }}>
            {c}
          </button>
        ))}
        <div style={{ flex: 1 }} />
        <button style={stg.btnSecondary}>Import from Word</button>
        <button style={stg.btnPrimary}>+ New template</button>
      </div>

      <div style={stg.cardGrid(300)}>
        {list.map(t => (
          <div key={t.id} style={{ ...stg.card, marginBottom: 0, margin: '4px' }}>
            <div style={{ padding: '14px 16px', borderBottom: `1px solid ${Ts_g.color.border.light}`, background: `linear-gradient(135deg, ${stg.steelBg} 0%, transparent 100%)` }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '6px' }}>
                <span style={{ ...stg.tag, background: stg.steelBg, color: stg.steelDeep }}>{t.category}</span>
                <span style={{ ...stg.tag, background: Ts_g.color.bg.secondary, color: Ts_g.color.text.tertiary, fontFamily: Ts_g.font.mono }}>{t.format.toUpperCase()}</span>
              </div>
              <div style={{ fontSize: '13px', fontWeight: 700, color: Ts_g.color.text.primary }}>{t.name}</div>
            </div>
            <div style={{ padding: '12px 16px', display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '10px' }}>
              <div>
                <div style={stg.sectionLabel}>Words</div>
                <div style={{ fontSize: '14px', fontWeight: 700, color: Ts_g.color.text.primary, fontFamily: Ts_g.font.mono }}>{t.words.toLocaleString()}</div>
              </div>
              <div>
                <div style={stg.sectionLabel}>Used</div>
                <div style={{ fontSize: '14px', fontWeight: 700, color: stg.steelDeep, fontFamily: Ts_g.font.mono }}>{t.usage}×</div>
              </div>
              <div>
                <div style={stg.sectionLabel}>Updated</div>
                <div style={{ fontSize: '11px', fontWeight: 600, color: Ts_g.color.text.secondary, marginTop: '4px', fontFamily: Ts_g.font.mono }}>{t.updated}</div>
              </div>
            </div>
            <div style={{ padding: '10px 16px', borderTop: `1px solid ${Ts_g.color.border.light}`, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <span style={{ fontSize: '10px', color: Ts_g.color.text.tertiary }}>by {t.author}</span>
              <div>
                <button style={stg.btnGhost}>Preview</button>
                <button style={stg.btnSecondary}>Edit</button>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function SettingsImportExport({ data }) {
  const stg = window.__stg;
  const jobs = data.importJobs;
  const Card = window.SettingsSectionCard;

  const completed = jobs.filter(j => j.status === 'completed').length;
  const running = jobs.filter(j => j.status === 'running').length;
  const queued = jobs.filter(j => j.status === 'queued').length;

  const statusStyle = (s) =>
    s === 'completed' ? stg.statusPill('ok')
    : s === 'running' ? stg.statusPill('info')
    : s === 'queued'  ? stg.statusPill('pending')
    : stg.statusPill('warn');

  return (
    <div>
      <div style={stg.stripKpi}>
        <div style={stg.stat}><span style={stg.statLabel}>Import jobs</span><span style={stg.statValue}>{jobs.length}</span></div>
        <div style={stg.stat}><span style={stg.statLabel}>Completed</span><span style={{ ...stg.statValue, color: stg.emerald }}>{completed}</span></div>
        <div style={stg.stat}><span style={stg.statLabel}>Running</span><span style={{ ...stg.statValue, color: stg.blue }}>{running}</span></div>
        <div style={stg.stat}><span style={stg.statLabel}>Queued</span><span style={stg.statValue}>{queued}</span></div>
        <div style={stg.stat}><span style={stg.statLabel}>Total rows imported</span><span style={stg.statValue}>{(jobs.reduce((s, j) => s + j.rows, 0) / 1e6).toFixed(2)}M</span></div>
      </div>

      <div style={stg.split(360)}>
        <Card title="Start a new import">
          <div style={{ padding: '16px', display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(160px, 1fr))', gap: '10px' }}>
            {[
              { l: 'CSV bulk users',    d: 'Add or update users in bulk' },
              { l: 'PST / Outlook',      d: 'Ingest custodian mailboxes' },
              { l: 'iManage / NetDocs',  d: 'Sync document libraries' },
              { l: 'CLIO / MyCase',      d: 'Historical practice data' },
              { l: 'Custom CSV',         d: 'Matters, contacts, time entries' },
              { l: 'SharePoint folder',  d: 'Matter-scoped document pull' },
            ].map(s => (
              <button key={s.l} style={{
                textAlign: 'left', padding: '12px', borderRadius: '6px',
                border: `1px solid ${Ts_g.color.border.light}`, background: Ts_g.color.bg.secondary,
                cursor: 'pointer', fontFamily: Ts_g.font.family,
              }}>
                <div style={{ fontSize: '12px', fontWeight: 700, color: Ts_g.color.text.primary, marginBottom: '2px' }}>{s.l}</div>
                <div style={{ fontSize: '10px', color: Ts_g.color.text.tertiary }}>{s.d}</div>
              </button>
            ))}
          </div>
        </Card>

        <Card title="Start an export">
          <div style={{ padding: '16px', display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(160px, 1fr))', gap: '10px' }}>
            {[
              { l: 'Full firm snapshot', d: 'All matters, all data' },
              { l: 'Matter export',       d: 'Single matter ZIP / JSON' },
              { l: 'Subject Access (SAR)',d: 'GDPR/CCPA data subject export' },
              { l: 'Audit log',           d: 'Any date range, CSV' },
              { l: 'Custom SQL',          d: 'Run a read-only query' },
              { l: 'Warehouse tap',       d: 'Open a Snowflake share' },
            ].map(s => (
              <button key={s.l} style={{
                textAlign: 'left', padding: '12px', borderRadius: '6px',
                border: `1px solid ${Ts_g.color.border.light}`, background: Ts_g.color.bg.secondary,
                cursor: 'pointer', fontFamily: Ts_g.font.family,
              }}>
                <div style={{ fontSize: '12px', fontWeight: 700, color: Ts_g.color.text.primary, marginBottom: '2px' }}>{s.l}</div>
                <div style={{ fontSize: '10px', color: Ts_g.color.text.tertiary }}>{s.d}</div>
              </button>
            ))}
          </div>
        </Card>
      </div>

      <Card title={`Import jobs · ${jobs.length}`}>
        <div style={stg.tableWrap}>
        <table style={stg.tableFixed}>
          <thead>
            <tr>
              <th style={stg.th}>Job ID</th>
              <th style={stg.th}>Source</th>
              <th style={{ ...stg.th, textAlign: 'right' }}>Rows</th>
              <th style={stg.th}>Started</th>
              <th style={stg.th}>Finished</th>
              <th style={{ ...stg.th, textAlign: 'right' }}>Errors</th>
              <th style={stg.th}>Status</th>
              <th style={stg.th}></th>
            </tr>
          </thead>
          <tbody>
            {jobs.map(j => (
              <tr key={j.id}>
                <td style={{ ...stg.td, fontFamily: Ts_g.font.mono, fontWeight: 700, color: stg.steelDeep }}>{j.id}</td>
                <td style={{ ...stg.td, fontWeight: 600 }}>{j.source}</td>
                <td style={{ ...stg.td, textAlign: 'right', fontFamily: Ts_g.font.mono, fontWeight: 700 }}>{j.rows.toLocaleString()}</td>
                <td style={{ ...stg.td, fontFamily: Ts_g.font.mono, fontSize: '11px', color: Ts_g.color.text.tertiary }}>{j.started}</td>
                <td style={{ ...stg.td, fontFamily: Ts_g.font.mono, fontSize: '11px', color: Ts_g.color.text.tertiary }}>{j.finished}</td>
                <td style={{ ...stg.td, textAlign: 'right', fontFamily: Ts_g.font.mono, color: j.errors > 0 ? stg.amber : Ts_g.color.text.tertiary }}>{j.errors}</td>
                <td style={stg.td}><span style={{ ...stg.tag, ...statusStyle(j.status) }}>{j.status}</span></td>
                <td style={{ ...stg.td, textAlign: 'right' }}><button style={stg.btnGhost}>Logs</button></td>
              </tr>
            ))}
          </tbody>
        </table>
        </div>
      </Card>
    </div>
  );
}

function SettingsSystem({ data }) {
  const stg = window.__stg;
  const sh = data.systemHealth;
  const Card = window.SettingsSectionCard;
  const [timelineIncident, setTimelineIncident] = React.useState(null);

  const allOk    = sh.services.filter(s => s.status === 'ok').length;
  const degraded = sh.services.filter(s => s.status === 'degraded').length;
  const down     = sh.services.filter(s => s.status === 'down').length;
  const avg      = (sh.services.reduce((s, x) => s + x.uptime90, 0) / sh.services.length).toFixed(3);

  const bar = (pct, color) => (
    <div style={{ height: '6px', borderRadius: '3px', background: Ts_g.color.border.light, overflow: 'hidden' }}>
      <div style={{ width: `${Math.min(pct, 100)}%`, height: '100%', background: color }} />
    </div>
  );

  const statusColor = (s) => s === 'ok' ? stg.emerald : s === 'degraded' ? stg.amber : stg.crimson;

  return (
    <div>
      <div style={stg.stripKpi}>
        <div style={stg.stat}><span style={stg.statLabel}>Services</span><span style={stg.statValue}>{sh.services.length}</span></div>
        <div style={stg.stat}><span style={stg.statLabel}>Healthy</span><span style={{ ...stg.statValue, color: stg.emerald }}>{allOk}</span></div>
        <div style={stg.stat}><span style={stg.statLabel}>Degraded</span><span style={{ ...stg.statValue, color: stg.amber }}>{degraded}</span></div>
        <div style={stg.stat}><span style={stg.statLabel}>Down</span><span style={{ ...stg.statValue, color: stg.crimson }}>{down}</span></div>
        <div style={stg.stat}><span style={stg.statLabel}>Uptime 90d</span><span style={stg.statValue}>{avg}%</span></div>
        <div style={stg.stat}><span style={stg.statLabel}>Primary region</span><span style={{ ...stg.statValue, fontSize: '13px', marginTop: '4px' }}>{sh.regions.find(r => r.primary).id}</span></div>
      </div>

      <Card title={`Service status · ${sh.services.length}`} action={<button style={stg.btnSecondary}>Public status page ↗</button>}>
        <div style={stg.tableWrap}>
        <table style={stg.tableFixed}>
          <thead>
            <tr>
              <th style={stg.th}></th>
              <th style={stg.th}>Service</th>
              <th style={{ ...stg.th, textAlign: 'right' }}>p95 latency</th>
              <th style={stg.th}>Uptime 90d</th>
              <th style={stg.th}>Status</th>
              <th style={stg.th}>Note</th>
            </tr>
          </thead>
          <tbody>
            {sh.services.map(s => (
              <tr key={s.id}>
                <td style={{ ...stg.td, width: '24px' }}>
                  <div style={{ width: '10px', height: '10px', borderRadius: '50%', background: statusColor(s.status), boxShadow: `0 0 0 3px ${statusColor(s.status)}22` }} />
                </td>
                <td style={{ ...stg.td, fontWeight: 600 }}>{s.label} <span style={{ marginLeft: '8px', color: Ts_g.color.text.tertiary, fontSize: '11px', fontFamily: Ts_g.font.mono }}>{s.id}</span></td>
                <td style={{ ...stg.td, textAlign: 'right', fontFamily: Ts_g.font.mono, fontWeight: 600, color: s.latencyP95 > 200 ? stg.amber : Ts_g.color.text.primary }}>{s.latencyP95} ms</td>
                <td style={{ ...stg.td, fontFamily: Ts_g.font.mono, fontSize: '11px' }}>{s.uptime90}%</td>
                <td style={stg.td}><span style={{ ...stg.tag, ...stg.statusPill(s.status === 'ok' ? 'ok' : s.status === 'degraded' ? 'warn' : 'fail') }}>{s.status}</span></td>
                <td style={{ ...stg.td, fontSize: '11px', color: Ts_g.color.text.tertiary }}>{s.note || '—'}</td>
              </tr>
            ))}
          </tbody>
        </table>
        </div>
      </Card>

      <div style={stg.split(400)}>
        <Card title={`Quotas · ${sh.quotas.length}`}>
          <div style={{ padding: '12px 16px' }}>
            {sh.quotas.map(q => {
              const pct = Math.round((q.used / q.cap) * 100);
              const color = pct > 85 ? stg.amber : pct > 95 ? stg.crimson : stg.steel;
              return (
                <div key={q.id} style={{ padding: '8px 0', borderBottom: `1px solid ${Ts_g.color.border.light}` }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '4px' }}>
                    <span style={{ fontSize: '12px', fontWeight: 600, color: Ts_g.color.text.primary }}>{q.label}</span>
                    <span style={{ fontSize: '11px', fontFamily: Ts_g.font.mono, color: Ts_g.color.text.secondary }}>{q.used.toLocaleString()} / {q.cap.toLocaleString()}</span>
                  </div>
                  {bar(pct, color)}
                </div>
              );
            })}
          </div>
        </Card>

        <Card title={`Regions · ${sh.regions.length}`}>
          <div style={{ padding: '12px 16px' }}>
            {sh.regions.map(r => (
              <div key={r.id} style={{ padding: '10px 0', borderBottom: `1px solid ${Ts_g.color.border.light}`, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <div>
                  <div style={{ fontSize: '12px', fontWeight: 700, color: Ts_g.color.text.primary }}>{r.label} {r.primary && <span style={{ ...stg.tag, ...stg.statusPill('info'), marginLeft: '6px' }}>primary</span>}</div>
                  <div style={{ fontSize: '10px', color: Ts_g.color.text.tertiary, fontFamily: Ts_g.font.mono }}>{r.id}</div>
                </div>
                <div style={{ minWidth: '140px', display: 'flex', alignItems: 'center', gap: '8px' }}>
                  <div style={{ flex: 1, height: '6px', background: Ts_g.color.border.light, borderRadius: '3px', overflow: 'hidden' }}>
                    <div style={{ width: `${r.traffic}%`, height: '100%', background: stg.steelDeep }} />
                  </div>
                  <span style={{ fontSize: '11px', fontFamily: Ts_g.font.mono, fontWeight: 700 }}>{r.traffic}%</span>
                </div>
              </div>
            ))}
          </div>
        </Card>
      </div>

      <Card title={`Recent incidents · ${sh.incidents.length}`} action={<button style={stg.btnGhost}>All incidents →</button>}>
        <div style={stg.tableWrap}>
        <table style={stg.tableFixed}>
          <thead>
            <tr>
              <th style={stg.th}>Incident</th>
              <th style={stg.th}>Date</th>
              <th style={stg.th}>Title</th>
              <th style={stg.th}>Severity</th>
              <th style={{ ...stg.th, textAlign: 'right' }}>Duration</th>
              <th style={stg.th}>Post-mortem</th>
              <th style={stg.th}></th>
            </tr>
          </thead>
          <tbody>
            {sh.incidents.map(i => (
              <tr key={i.id}>
                <td style={{ ...stg.td, fontFamily: Ts_g.font.mono, fontWeight: 700, color: stg.steelDeep }}>{i.id}</td>
                <td style={{ ...stg.td, fontFamily: Ts_g.font.mono, fontSize: '11px' }}>{i.date}</td>
                <td style={{ ...stg.td, fontWeight: 600 }}>{i.title}</td>
                <td style={stg.td}><span style={{ ...stg.tag, ...stg.statusPill(i.severity === 'high' ? 'fail' : i.severity === 'med' ? 'warn' : 'info') }}>{i.severity}</span></td>
                <td style={{ ...stg.td, textAlign: 'right', fontFamily: Ts_g.font.mono }}>{i.durationMin}m</td>
                <td style={stg.td}>{i.postMortem ? <button style={stg.btnGhost}>Read →</button> : '—'}</td>
                <td style={{ ...stg.td, textAlign: 'right' }}><button style={stg.btnGhost} onClick={() => setTimelineIncident(i)}>Correlate →</button></td>
              </tr>
            ))}
          </tbody>
        </table>
        </div>
      </Card>

      {/* #32 — Incident timeline with service-status overlay */}
      <IncidentTimelineCard services={sh.services} incidents={sh.incidents} timelineIncident={timelineIncident} setTimelineIncident={setTimelineIncident} />
    </div>
  );
}

// #32 — Correlation state hoist
function _SettingsSystemPatch() { return null; }
// IncidentTimelineCard pulls its state from parent via props to avoid re-render loops
function IncidentTimelineCard({ services, incidents, timelineIncident, setTimelineIncident }) {
  const stg = window.__stg;
  const Card = window.SettingsSectionCard;

  // 24h timeline — synthesize per-service status samples (72 buckets at 20-min granularity)
  const BUCKETS = 72;
  const seriesFor = React.useCallback((svc) => {
    const arr = [];
    // seed deterministic from id
    let seed = Array.from(svc.id).reduce((a, c) => a + c.charCodeAt(0), 0);
    for (let i = 0; i < BUCKETS; i++) {
      seed = (seed * 1103515245 + 12345) & 0x7fffffff;
      const roll = (seed % 1000) / 1000;
      let status = 'ok';
      // overlay incidents onto this service
      for (const inc of incidents) {
        const ih = (inc.startBucket != null ? inc.startBucket : (Array.from(inc.id).reduce((a,c)=>a+c.charCodeAt(0),0) % BUCKETS));
        const dur = Math.max(1, Math.round((inc.durationMin || 30) / 20));
        if (i >= ih && i < ih + dur && (inc.services || []).includes(svc.id)) {
          status = inc.severity === 'high' ? 'down' : 'degraded';
        }
      }
      if (status === 'ok' && roll < 0.015) status = 'degraded';
      arr.push(status);
    }
    // mutate current service status into most-recent bucket
    if (svc.status === 'degraded') arr[BUCKETS - 1] = 'degraded';
    if (svc.status === 'down')     arr[BUCKETS - 1] = 'down';
    return arr;
  }, [incidents]);

  // augment incidents with services affected + startBucket (deterministic)
  const inc24 = React.useMemo(() => incidents.slice(0, 4).map((i, idx) => ({
    ...i,
    startBucket: 12 + idx * 14,
    services: [services[idx % services.length].id, services[(idx + 3) % services.length].id].filter((v, k, a) => a.indexOf(v) === k),
  })), [incidents, services]);

  const cellColor = (st) => st === 'ok' ? '#34D399' : st === 'degraded' ? '#F59E0B' : '#DC2626';

  return (
    <Card title="Incident timeline · last 24h" action={<span style={{ fontSize: '11px', color: Ts_g.color.text.tertiary }}>hover a cell for details · click a band to jump to the incident</span>}>
      <div style={{ padding: '10px 16px 6px', overflowX: 'auto' }}>
        <div style={{ position: 'relative', minWidth: `${BUCKETS * 10 + 180}px` }}>
          {/* hour ticks */}
          <div style={{ display: 'flex', marginLeft: '180px', fontSize: '9px', fontFamily: Ts_g.font.mono, color: Ts_g.color.text.tertiary, marginBottom: '4px' }}>
            {Array.from({ length: 13 }).map((_, i) => (
              <div key={i} style={{ flex: 1, textAlign: 'center' }}>{String(-24 + i * 2).padStart(3, ' ')}h</div>
            ))}
          </div>
          {/* incident bands */}
          <div style={{ position: 'relative', height: '18px', marginLeft: '180px', background: Ts_g.color.bg.secondary, borderRadius: '3px', marginBottom: '6px' }}>
            {inc24.map(i => {
              const dur = Math.max(1, Math.round((i.durationMin || 30) / 20));
              return (
                <div key={i.id}
                  onClick={() => setTimelineIncident(i)}
                  title={`${i.id} · ${i.title} · ${i.severity} · ${i.durationMin}m`}
                  style={{
                    position: 'absolute', top: 0, bottom: 0,
                    left: `${(i.startBucket / BUCKETS) * 100}%`,
                    width: `${(dur / BUCKETS) * 100}%`,
                    background: i.severity === 'high' ? '#DC262633' : i.severity === 'med' ? '#F59E0B33' : '#3B82F633',
                    borderLeft: `2px solid ${i.severity === 'high' ? '#DC2626' : i.severity === 'med' ? '#F59E0B' : '#3B82F6'}`,
                    fontSize: '10px', fontFamily: Ts_g.font.mono, fontWeight: 700,
                    color: i.severity === 'high' ? '#DC2626' : i.severity === 'med' ? '#92400E' : '#1E3A8A',
                    padding: '1px 4px', overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis', cursor: 'pointer',
                  }}>
                  {i.id}
                </div>
              );
            })}
          </div>
          {/* per-service rows */}
          {services.map(svc => {
            const row = seriesFor(svc);
            return (
              <div key={svc.id} style={{ display: 'flex', alignItems: 'center', padding: '2px 0' }}>
                <div style={{ width: '180px', fontSize: '11px', display: 'flex', alignItems: 'center', gap: '6px', paddingRight: '10px' }}>
                  <div style={{ width: '8px', height: '8px', borderRadius: '50%', background: svc.status === 'ok' ? stg.emerald : svc.status === 'degraded' ? stg.amber : stg.crimson }} />
                  <span style={{ fontWeight: 600, color: Ts_g.color.text.primary, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{svc.label}</span>
                  <span style={{ fontFamily: Ts_g.font.mono, fontSize: '9px', color: Ts_g.color.text.tertiary, marginLeft: 'auto' }}>{svc.uptime90}%</span>
                </div>
                <div style={{ flex: 1, display: 'flex', gap: '1px' }}>
                  {row.map((st, i) => (
                    <div key={i}
                      title={`${svc.label} · t-${Math.round((BUCKETS - i) * 20 / 60 * 10) / 10}h · ${st}`}
                      style={{ flex: 1, height: '10px', borderRadius: '1px', background: cellColor(st) }} />
                  ))}
                </div>
              </div>
            );
          })}
        </div>
      </div>
      <div style={{ padding: '10px 16px', borderTop: `1px solid ${Ts_g.color.border.light}`, background: Ts_g.color.bg.secondary, display: 'flex', alignItems: 'center', gap: '14px', flexWrap: 'wrap', fontSize: '11px', color: Ts_g.color.text.tertiary }}>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: '4px' }}><div style={{ width: '10px', height: '10px', borderRadius: '2px', background: '#34D399' }} /> OK</span>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: '4px' }}><div style={{ width: '10px', height: '10px', borderRadius: '2px', background: '#F59E0B' }} /> Degraded</span>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: '4px' }}><div style={{ width: '10px', height: '10px', borderRadius: '2px', background: '#DC2626' }} /> Down</span>
        <div style={{ flex: 1 }} />
        <span>Buckets: 20-min · Service = Azure Container Apps revision health + synthetic probes</span>
      </div>

      {/* incident focus drawer */}
      {timelineIncident && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 9996, background: 'rgba(15,23,42,0.4)', display: 'flex', justifyContent: 'flex-end' }} onClick={() => setTimelineIncident(null)}>
          <div onClick={e => e.stopPropagation()} style={{ width: '520px', maxWidth: '100%', height: '100%', background: '#fff', boxShadow: '-8px 0 24px rgba(0,0,0,0.15)', display: 'flex', flexDirection: 'column' }}>
            <div style={{ padding: '14px 18px', borderBottom: `1px solid ${Ts_g.color.border.light}`, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <div>
                <div style={{ fontSize: '10px', fontWeight: 700, color: Ts_g.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.08em' }}>Incident timeline</div>
                <div style={{ fontSize: '14px', fontWeight: 700, marginTop: '2px' }}>{timelineIncident.id} · {timelineIncident.title}</div>
                <div style={{ fontSize: '11px', color: Ts_g.color.text.tertiary, marginTop: '2px' }}>{timelineIncident.date} · severity {timelineIncident.severity} · {timelineIncident.durationMin}m</div>
              </div>
              <button onClick={() => setTimelineIncident(null)} style={{ background: 'none', border: 'none', fontSize: '18px', cursor: 'pointer' }}>×</button>
            </div>
            <div style={{ flex: 1, overflowY: 'auto', padding: '14px 18px' }}>
              <div style={stg.sectionLabel}>Impacted services</div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: '4px', marginTop: '6px', marginBottom: '14px' }}>
                {(timelineIncident.services || []).map(sid => {
                  const s = services.find(x => x.id === sid);
                  return <span key={sid} style={{ ...stg.tag, background: stg.steelBg, color: stg.steelDeep, fontFamily: Ts_g.font.mono }}>{s ? s.label : sid}</span>;
                })}
              </div>
              <div style={stg.sectionLabel}>Event chain</div>
              <div style={{ borderLeft: `2px solid ${Ts_g.color.border.light}`, paddingLeft: '12px', marginLeft: '4px', marginTop: '8px' }}>
                {[
                  { t: 'T+00m',  k: 'trigger', m: 'First error: 5xx spike detected by synthetic probe', src: 'probes.saadein.law' },
                  { t: 'T+01m',  k: 'page',    m: 'PagerDuty alert routed to platform-oncall', src: 'pd.policy/platform' },
                  { t: 'T+03m',  k: 'ack',     m: 'Acknowledged by @kris.ochoa', src: 'pager ack' },
                  { t: 'T+06m',  k: 'deploy',  m: 'Revision rollback initiated (prev: 0.18.42 → current: 0.18.41)', src: 'Azure Container Apps' },
                  { t: 'T+09m',  k: 'autn',    m: 'IAM login-failure rate normalized (p95 from 1.2s → 180ms)', src: 'svc-iam' },
                  { t: 'T+12m',  k: 'resolve', m: 'Synthetic probe green for 3 consecutive windows', src: 'probes.saadein.law' },
                  { t: 'T+' + (timelineIncident.durationMin || 15) + 'm', k: 'close', m: 'Incident closed; post-mortem scheduled', src: 'IR process' },
                ].map((e, i) => {
                  const color = e.k === 'trigger' ? stg.crimson : e.k === 'resolve' || e.k === 'close' ? stg.emerald : stg.steelDeep;
                  return (
                    <div key={i} style={{ position: 'relative', paddingLeft: '14px', paddingBottom: '10px' }}>
                      <div style={{ position: 'absolute', left: '-7px', top: '3px', width: '10px', height: '10px', borderRadius: '50%', background: color, border: '2px solid #fff', boxShadow: `0 0 0 1px ${color}55` }} />
                      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: '8px' }}>
                        <span style={{ fontFamily: Ts_g.font.mono, fontSize: '11px', fontWeight: 700, color }}>{e.t}</span>
                        <span style={{ ...stg.tag, background: Ts_g.color.bg.secondary, color: Ts_g.color.text.secondary, fontFamily: Ts_g.font.mono, fontSize: '9px' }}>{e.k}</span>
                      </div>
                      <div style={{ fontSize: '12px', color: Ts_g.color.text.primary, marginTop: '2px' }}>{e.m}</div>
                      <div style={{ fontSize: '10px', color: Ts_g.color.text.tertiary, fontFamily: Ts_g.font.mono, marginTop: '2px' }}>{e.src}</div>
                    </div>
                  );
                })}
              </div>
            </div>
            <div style={{ padding: '12px 18px', borderTop: `1px solid ${Ts_g.color.border.light}`, background: Ts_g.color.bg.secondary, display: 'flex', gap: '6px', justifyContent: 'flex-end' }}>
              <button style={stg.btnGhost}>Open App Insights ↗</button>
              <button style={stg.btnSecondary}>Copy permalink</button>
              <button style={stg.btnPrimary}>Post-mortem →</button>
            </div>
          </div>
        </div>
      )}
    </Card>
  );
}

window.SettingsDataRetention = SettingsDataRetention;
window.SettingsAuditLog = SettingsAuditLog;
window.SettingsCompliance = SettingsCompliance;
window.SettingsCustomFields = SettingsCustomFields;
window.SettingsTemplates = SettingsTemplates;
window.SettingsImportExport = SettingsImportExport;
window.SettingsSystem = SettingsSystem;
