// AUTOMATION PLATFORM — Governance sub-platform
// Views: Versions · Approvals · Policy · RBAC · Compliance · IaC
const { useState: useGovState } = React;
const Tgov = window.ArbiterTokens;

const GOV_VIEWS = [
  { id: 'versions',   label: 'Versions / Change Log' },
  { id: 'approvals',  label: 'Approvals' },
  { id: 'policy',     label: 'Policy Engine' },
  { id: 'rbac',       label: 'RBAC / Tenancy' },
  { id: 'compliance', label: 'Compliance' },
  { id: 'iac',        label: 'IaC Export' },
];

function GBadge({ color, bg, children, mono = false }) {
  return <span style={{ display: 'inline-flex', alignItems: 'center', padding: '2px 8px', borderRadius: '10px', fontSize: '10px', fontWeight: 700, background: bg, color, fontFamily: mono ? Tgov.font.mono : Tgov.font.family }}>{children}</span>;
}

// ─── VERSIONS ─────────────────────────────────────────────────────────────────
function GovVersions({ data }) {
  const au = window.__au;
  const [typeFilter, setTypeFilter] = useGovState('All');
  const types = ['All', ...new Set(data.versions.map(v => v.type))];
  const rows = data.versions.filter(v => typeFilter === 'All' || v.type === typeFilter);
  const k = data.governanceKpis;

  const statusStyle = (s) => {
    if (s === 'Published')    return { bg: au.emeraldBg, color: au.emerald };
    if (s === 'Draft')         return { bg: Tgov.color.bg.secondary, color: Tgov.color.text.secondary };
    if (s === 'Rolled Back')   return { bg: au.crimsonBg, color: au.crimson };
    if (s === 'Pending Approval') return { bg: au.amberBg, color: au.amber };
    return { bg: Tgov.color.bg.secondary, color: Tgov.color.text.secondary };
  };

  return (
    <div>
      <div style={{ ...au.card, borderLeft: `3px solid ${au.cobalt}`, background: au.cobaltBg }}>
        <div style={{ padding: '12px 16px' }}>
          <div style={{ fontSize: '12px', fontWeight: 700, color: au.cobalt, textTransform: 'uppercase', letterSpacing: '0.08em' }}>◆ Change log — {k.versionsTracked} versions tracked · {k.pendingChanges} pending</div>
          <div style={{ fontSize: '11px', color: Tgov.color.text.secondary, marginTop: '4px', lineHeight: 1.55 }}>
            Every workflow, trigger, integration, and script change is versioned with diffs. Rollback, compare, or publish drafts via partner sign-off.
          </div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '14px' }}>
        <div style={au.stat}><span style={au.statLabel}>Versions tracked</span><span style={au.statValue}>{k.versionsTracked}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Pending changes</span><span style={{ ...au.statValue, color: au.amber }}>{k.pendingChanges}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Published (30d)</span><span style={{ ...au.statValue, color: au.emerald }}>{rows.filter(r => r.status === 'Published').length}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Rolled back</span><span style={{ ...au.statValue, color: au.crimson }}>{rows.filter(r => r.status === 'Rolled Back').length}</span></div>
      </div>

      <div style={au.card}>
        <div style={au.cardH}>
          <span>Change log — {rows.length} of {data.versions.length}</span>
          <div style={{ display: 'flex', gap: '6px' }}>
            <select value={typeFilter} onChange={e => setTypeFilter(e.target.value)} style={{ padding: '3px 8px', fontSize: '11px', border: `1px solid ${Tgov.color.border.light}`, borderRadius: '5px', background: Tgov.color.bg.card, color: Tgov.color.text.secondary }}>
              {types.map(t => <option key={t}>Type: {t}</option>)}
            </select>
            <button style={au.btnSecondary}>Compare versions</button>
            <button style={au.btnSecondary}>Rollback</button>
          </div>
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={au.th}>Ver ID</th>
              <th style={au.th}>Artifact</th>
              <th style={au.th}>Type</th>
              <th style={au.th}>Version</th>
              <th style={au.th}>Changed</th>
              <th style={au.th}>Author</th>
              <th style={au.th}>Diff</th>
              <th style={au.th}>Status</th>
              <th style={au.th}>Approved by</th>
              <th style={au.th}>Summary</th>
            </tr>
          </thead>
          <tbody>
            {rows.map(v => {
              const ss = statusStyle(v.status);
              return (
                <tr key={v.id}>
                  <td style={{ ...au.td, fontFamily: Tgov.font.mono, fontWeight: 700, color: au.cobalt }}>{v.id}</td>
                  <td style={{ ...au.td, color: Tgov.color.text.primary, fontWeight: 600 }}>{v.artifact}</td>
                  <td style={au.td}><GBadge color={au.violet} bg={au.violetBg}>{v.type}</GBadge></td>
                  <td style={{ ...au.td, fontFamily: Tgov.font.mono, fontWeight: 700, color: Tgov.color.text.primary }}>{v.version}</td>
                  <td style={{ ...au.td, fontFamily: Tgov.font.mono, fontSize: '11px', color: Tgov.color.text.tertiary }}>{v.changedOn}</td>
                  <td style={{ ...au.td, color: Tgov.color.text.secondary, fontSize: '11px' }}>{v.changedBy}</td>
                  <td style={au.td}>
                    <span style={{ fontFamily: Tgov.font.mono, color: au.emerald, fontWeight: 600, fontSize: '11px' }}>+{v.linesAdded}</span>
                    <span style={{ color: Tgov.color.text.tertiary, margin: '0 4px' }}>·</span>
                    <span style={{ fontFamily: Tgov.font.mono, color: au.crimson, fontWeight: 600, fontSize: '11px' }}>-{v.linesRemoved}</span>
                  </td>
                  <td style={au.td}><GBadge color={ss.color} bg={ss.bg}>{v.status}</GBadge></td>
                  <td style={{ ...au.td, color: Tgov.color.text.tertiary, fontSize: '11px' }}>{v.approvedBy || '—'}</td>
                  <td style={{ ...au.td, color: Tgov.color.text.secondary, fontSize: '11px', maxWidth: '320px' }}>{v.summary}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// ─── APPROVALS ────────────────────────────────────────────────────────────────
function GovApprovals({ data }) {
  const au = window.__au;
  const k = data.governanceKpis;
  const rows = data.approvals;

  const stageStyle = (s) => {
    if (s === 'approved') return { color: au.emerald, icon: 'ok' };
    if (s === 'rejected') return { color: au.crimson, icon: 'x' };
    if (s === 'pending')  return { color: au.amber,   icon: '●' };
    return { color: Tgov.color.text.tertiary, icon: '○' };
  };

  const riskStyle = (r) => {
    if (r === 'High')   return { bg: au.crimsonBg, color: au.crimson };
    if (r === 'Medium') return { bg: au.amberBg, color: au.amber };
    return { bg: au.emeraldBg, color: au.emerald };
  };

  return (
    <div>
      <div style={{ ...au.card, borderLeft: `3px solid ${au.amber}`, background: au.amberBg }}>
        <div style={{ padding: '12px 16px' }}>
          <div style={{ fontSize: '12px', fontWeight: 700, color: au.amber, textTransform: 'uppercase', letterSpacing: '0.08em' }}>◆ Approval chains — {k.approvalsInQueue} in queue</div>
          <div style={{ fontSize: '11px', color: Tgov.color.text.secondary, marginTop: '4px', lineHeight: 1.55 }}>
            Multi-stage sign-off for privileged actions: deploy trigger, publish workflow, rotate secret, enable integration. {k.approvalsSlaBreached} approval(s) past SLA.
          </div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '14px' }}>
        <div style={au.stat}><span style={au.statLabel}>In queue</span><span style={au.statValue}>{k.approvalsInQueue}</span></div>
        <div style={au.stat}><span style={au.statLabel}>SLA breached</span><span style={{ ...au.statValue, color: au.crimson }}>{k.approvalsSlaBreached}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Approved (shown)</span><span style={{ ...au.statValue, color: au.emerald }}>{rows.filter(r => r.status === 'Approved').length}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Rejected (shown)</span><span style={{ ...au.statValue, color: au.crimson }}>{rows.filter(r => r.status === 'Rejected').length}</span></div>
      </div>

      <div style={au.card}>
        <div style={au.cardH}>
          <span>Approval queue</span>
          <button style={au.btnPrimary}>+ New approval chain</button>
        </div>
        <div style={{ padding: '8px 0' }}>
          {rows.map(a => {
            const risk = riskStyle(a.risk);
            const slaColor = a.slaLeftHr <= 4 ? au.crimson : a.slaLeftHr <= 12 ? au.amber : au.emerald;
            return (
              <div key={a.id} style={{ padding: '12px 16px', borderBottom: `1px solid ${Tgov.color.border.light}`, display: 'grid', gridTemplateColumns: '100px 1fr auto auto', gap: '14px', alignItems: 'center' }}>
                <span style={{ fontFamily: Tgov.font.mono, fontWeight: 700, color: au.cobalt, fontSize: '11px' }}>{a.id}</span>
                <div>
                  <div style={{ fontSize: '12px', fontWeight: 600, color: Tgov.color.text.primary }}>{a.subject}</div>
                  <div style={{ fontSize: '10px', color: Tgov.color.text.tertiary, marginTop: '2px' }}>Requested by <b>{a.requestedBy}</b> · {a.requestedOn}</div>
                  <div style={{ display: 'flex', gap: '4px', marginTop: '8px', alignItems: 'center' }}>
                    {a.stages.map((s, i) => {
                      const ss = stageStyle(s.status);
                      return (
                        <React.Fragment key={i}>
                          <div style={{ display: 'flex', alignItems: 'center', gap: '4px', padding: '3px 8px', borderRadius: '10px', background: `${ss.color}14`, border: `1px solid ${ss.color}44` }}>
                            <span style={{ color: ss.color, fontWeight: 700, fontSize: '10px' }}>{ss.icon}</span>
                            <span style={{ fontSize: '10px', color: Tgov.color.text.secondary, fontWeight: 500 }}>{s.role}:</span>
                            <span style={{ fontSize: '10px', color: Tgov.color.text.primary, fontWeight: 600 }}>{s.name}</span>
                          </div>
                          {i < a.stages.length - 1 && <span style={{ color: Tgov.color.text.tertiary }}>›</span>}
                        </React.Fragment>
                      );
                    })}
                  </div>
                </div>
                <div style={{ textAlign: 'right' }}>
                  <GBadge color={risk.color} bg={risk.bg}>{a.risk} RISK</GBadge>
                  <div style={{ marginTop: '4px', fontSize: '10px', color: slaColor, fontWeight: 700, fontFamily: Tgov.font.mono }}>
                    {a.slaLeftHr <= 0 ? 'SLA EXPIRED' : `${a.slaLeftHr}h left`}
                  </div>
                </div>
                <div>
                  <GBadge color={a.status === 'Approved' ? au.emerald : a.status === 'Rejected' ? au.crimson : au.amber}
                          bg={a.status === 'Approved' ? au.emeraldBg : a.status === 'Rejected' ? au.crimsonBg : au.amberBg}>
                    {a.status}
                  </GBadge>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

// ─── POLICY ───────────────────────────────────────────────────────────────────
function GovPolicy({ data }) {
  const au = window.__au;
  const k = data.governanceKpis;
  const rows = data.policies;

  const sevStyle = (s) => {
    if (s === 'Critical') return { bg: au.crimsonBg, color: au.crimson };
    if (s === 'High')     return { bg: au.orangeBg, color: au.orange };
    if (s === 'Medium')   return { bg: au.amberBg, color: au.amber };
    return { bg: Tgov.color.bg.secondary, color: Tgov.color.text.secondary };
  };

  return (
    <div>
      <div style={{ ...au.card, borderLeft: `3px solid ${au.violet}`, background: au.violetBg }}>
        <div style={{ padding: '12px 16px' }}>
          <div style={{ fontSize: '12px', fontWeight: 700, color: au.violet, textTransform: 'uppercase', letterSpacing: '0.08em' }}>◆ Policy engine — {k.policyRules} rules · {k.policyViolationsOpen} open violations</div>
          <div style={{ fontSize: '11px', color: Tgov.color.text.secondary, marginTop: '4px', lineHeight: 1.55 }}>
            Cross-cutting policies evaluated at save- and run-time. {k.policyViolations30d} violations fired in last 30d; all remediated.
          </div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '14px' }}>
        <div style={au.stat}><span style={au.statLabel}>Rules active</span><span style={au.statValue}>{rows.filter(r => r.enabled).length}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Open violations</span><span style={{ ...au.statValue, color: k.policyViolationsOpen === 0 ? au.emerald : au.amber }}>{k.policyViolationsOpen}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Violations (30d)</span><span style={au.statValue}>{k.policyViolations30d}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Objects evaluated</span><span style={au.statValue}>{rows.reduce((s, r) => s + r.matches, 0)}</span></div>
      </div>

      <div style={au.card}>
        <div style={au.cardH}>
          <span>Policy rules — {rows.length}</span>
          <div style={{ display: 'flex', gap: '6px' }}>
            <button style={au.btnSecondary}>Test policy</button>
            <button style={au.btnPrimary}>+ New rule</button>
          </div>
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={au.th}>ID</th>
              <th style={au.th}>Policy</th>
              <th style={au.th}>Category</th>
              <th style={au.th}>Severity</th>
              <th style={au.th}>Scope</th>
              <th style={{ ...au.th, textAlign: 'right' }}>Objects</th>
              <th style={{ ...au.th, textAlign: 'right' }}>Violations</th>
              <th style={au.th}>Enabled</th>
              <th style={au.th}>Last reviewed</th>
              <th style={au.th}>Note</th>
            </tr>
          </thead>
          <tbody>
            {rows.map(p => {
              const sev = sevStyle(p.severity);
              return (
                <tr key={p.id}>
                  <td style={{ ...au.td, fontFamily: Tgov.font.mono, fontWeight: 700, color: au.violet }}>{p.id}</td>
                  <td style={{ ...au.td, color: Tgov.color.text.primary, fontWeight: 600, fontSize: '12px', maxWidth: '280px' }}>{p.name}</td>
                  <td style={au.td}><GBadge color={au.cobalt} bg={au.cobaltBg}>{p.category}</GBadge></td>
                  <td style={au.td}><GBadge color={sev.color} bg={sev.bg}>{p.severity}</GBadge></td>
                  <td style={{ ...au.td, color: Tgov.color.text.secondary, fontSize: '11px' }}>{p.scope}</td>
                  <td style={{ ...au.td, textAlign: 'right', fontFamily: Tgov.font.mono, color: Tgov.color.text.primary, fontWeight: 700 }}>{p.matches}</td>
                  <td style={{ ...au.td, textAlign: 'right', fontFamily: Tgov.font.mono, fontWeight: 700, color: p.violations === 0 ? au.emerald : au.amber }}>{p.violations}</td>
                  <td style={au.td}>{p.enabled
                    ? <GBadge color={au.emerald} bg={au.emeraldBg}>ok on</GBadge>
                    : <GBadge color={Tgov.color.text.tertiary} bg={Tgov.color.bg.secondary}>off</GBadge>}</td>
                  <td style={{ ...au.td, fontFamily: Tgov.font.mono, fontSize: '11px', color: Tgov.color.text.tertiary }}>{p.lastReviewed}</td>
                  <td style={{ ...au.td, color: Tgov.color.text.secondary, fontSize: '11px', maxWidth: '280px' }}>{p.note}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// ─── RBAC ─────────────────────────────────────────────────────────────────────
function GovRBAC({ data }) {
  const au = window.__au;
  const k = data.governanceKpis;

  return (
    <div>
      <div style={{ ...au.card, borderLeft: `3px solid ${au.teal}`, background: au.tealBg }}>
        <div style={{ padding: '12px 16px' }}>
          <div style={{ fontSize: '12px', fontWeight: 700, color: au.teal, textTransform: 'uppercase', letterSpacing: '0.08em' }}>◆ RBAC & multi-tenancy — {data.rbacRoles.length} roles · {data.rbacTenants.length} workspaces</div>
          <div style={{ fontSize: '11px', color: Tgov.color.text.secondary, marginTop: '4px', lineHeight: 1.55 }}>
            Role-based access to workflows, triggers, and secrets. Workspaces isolate templates and runs per practice. {k.orphanPermissions} orphan permission(s) flagged.
          </div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '14px' }}>
        <div style={au.stat}><span style={au.statLabel}>Users with access</span><span style={au.statValue}>{k.usersWithAccess}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Privileged roles</span><span style={{ ...au.statValue, color: au.amber }}>{k.privilegedRoles}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Orphan perms</span><span style={{ ...au.statValue, color: k.orphanPermissions === 0 ? au.emerald : au.amber }}>{k.orphanPermissions}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Workspaces</span><span style={au.statValue}>{data.rbacTenants.length}</span></div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: '14px' }}>
        <div style={au.card}>
          <div style={au.cardH}>
            <span>Roles — {data.rbacRoles.length}</span>
            <button style={au.btnSecondary}>+ Role</button>
          </div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr>
                <th style={au.th}>ID</th>
                <th style={au.th}>Role</th>
                <th style={{ ...au.th, textAlign: 'right' }}>Users</th>
                <th style={{ ...au.th, textAlign: 'right' }}>Perms</th>
                <th style={au.th}>Scope</th>
                <th style={au.th}>Sensitive</th>
              </tr>
            </thead>
            <tbody>
              {data.rbacRoles.map(r => (
                <tr key={r.id}>
                  <td style={{ ...au.td, fontFamily: Tgov.font.mono, fontWeight: 700, color: au.teal }}>{r.id}</td>
                  <td style={{ ...au.td, color: Tgov.color.text.primary, fontWeight: 600 }}>{r.name}</td>
                  <td style={{ ...au.td, textAlign: 'right', fontFamily: Tgov.font.mono, fontWeight: 700 }}>{r.users}</td>
                  <td style={{ ...au.td, textAlign: 'right', fontFamily: Tgov.font.mono, color: Tgov.color.text.secondary }}>{r.permissions}</td>
                  <td style={{ ...au.td, color: Tgov.color.text.secondary, fontSize: '11px' }}>{r.scope}</td>
                  <td style={au.td}>{r.sensitive
                    ? <GBadge color={au.crimson} bg={au.crimsonBg}>privileged</GBadge>
                    : <GBadge color={Tgov.color.text.tertiary} bg={Tgov.color.bg.secondary}>standard</GBadge>}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        <div style={au.card}>
          <div style={au.cardH}>
            <span>Workspaces — {data.rbacTenants.length}</span>
            <button style={au.btnSecondary}>+ Workspace</button>
          </div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr>
                <th style={au.th}>Tenant</th>
                <th style={{ ...au.th, textAlign: 'right' }}>Users</th>
                <th style={{ ...au.th, textAlign: 'right' }}>Workflows</th>
                <th style={{ ...au.th, textAlign: 'right' }}>Integrations</th>
                <th style={{ ...au.th, textAlign: 'right' }}>Storage</th>
                <th style={au.th}>Owner</th>
              </tr>
            </thead>
            <tbody>
              {data.rbacTenants.map(t => (
                <tr key={t.id}>
                  <td style={{ ...au.td, color: Tgov.color.text.primary, fontWeight: 600 }}>{t.name} <span style={{ fontFamily: Tgov.font.mono, color: Tgov.color.text.tertiary, fontSize: '10px', fontWeight: 400 }}>{t.id}</span></td>
                  <td style={{ ...au.td, textAlign: 'right', fontFamily: Tgov.font.mono, fontWeight: 700 }}>{t.users}</td>
                  <td style={{ ...au.td, textAlign: 'right', fontFamily: Tgov.font.mono, color: Tgov.color.text.primary }}>{t.workflows} <span style={{ color: Tgov.color.text.tertiary, fontWeight: 400, fontSize: '10px' }}>({t.workflowsPrivate} pvt)</span></td>
                  <td style={{ ...au.td, textAlign: 'right', fontFamily: Tgov.font.mono, color: Tgov.color.text.secondary }}>{t.integrations}</td>
                  <td style={{ ...au.td, textAlign: 'right', fontFamily: Tgov.font.mono, color: Tgov.color.text.tertiary, fontSize: '11px' }}>{t.storage}</td>
                  <td style={{ ...au.td, color: Tgov.color.text.secondary, fontSize: '11px' }}>{t.owner}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

// ─── COMPLIANCE ───────────────────────────────────────────────────────────────
function GovCompliance({ data }) {
  const au = window.__au;
  const k = data.governanceKpis;
  const rows = data.complianceFrameworks;
  const totalControls = rows.reduce((s, r) => s + r.controlsTotal, 0);
  const passing = rows.reduce((s, r) => s + r.controlsPassing, 0);
  const coveragePct = Math.round((passing / totalControls) * 100);

  return (
    <div>
      <div style={{ ...au.card, borderLeft: `3px solid ${au.emerald}`, background: au.emeraldBg }}>
        <div style={{ padding: '12px 16px' }}>
          <div style={{ fontSize: '12px', fontWeight: 700, color: au.emerald, textTransform: 'uppercase', letterSpacing: '0.08em' }}>◆ Compliance posture — {coveragePct}% controls passing</div>
          <div style={{ fontSize: '11px', color: Tgov.color.text.secondary, marginTop: '4px', lineHeight: 1.55 }}>
            Automation platform controls mapped to SOC 2, ISO 27001/27701, SOX ITGC, HIPAA Security, NIST 800-53. {k.openFindings} open finding(s).
          </div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '14px' }}>
        <div style={au.stat}><span style={au.statLabel}>Frameworks</span><span style={au.statValue}>{rows.length}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Controls mapped</span><span style={au.statValue}>{totalControls}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Controls passing</span><span style={{ ...au.statValue, color: au.emerald }}>{passing}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Open findings</span><span style={{ ...au.statValue, color: k.openFindings === 0 ? au.emerald : au.amber }}>{k.openFindings}</span></div>
      </div>

      <div style={au.card}>
        <div style={au.cardH}>
          <span>Frameworks</span>
          <button style={au.btnSecondary}>Download audit evidence</button>
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={au.th}>ID</th>
              <th style={au.th}>Framework</th>
              <th style={au.th}>Controls</th>
              <th style={au.th}>Passing</th>
              <th style={au.th}>Findings</th>
              <th style={au.th}>Last audit</th>
              <th style={au.th}>Next audit</th>
              <th style={au.th}>Auditor</th>
              <th style={au.th}>Status</th>
            </tr>
          </thead>
          <tbody>
            {rows.map(f => {
              const pct = Math.round((f.controlsPassing / f.controlsTotal) * 100);
              return (
                <tr key={f.id}>
                  <td style={{ ...au.td, fontFamily: Tgov.font.mono, fontWeight: 700, color: au.emerald }}>{f.id}</td>
                  <td style={{ ...au.td, color: Tgov.color.text.primary, fontWeight: 600 }}>{f.name}</td>
                  <td style={{ ...au.td, fontFamily: Tgov.font.mono, color: Tgov.color.text.primary, fontWeight: 700 }}>{f.controlsTotal}</td>
                  <td style={au.td}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
                      <div style={{ width: '60px', height: '6px', background: Tgov.color.border.light, borderRadius: '3px', overflow: 'hidden' }}>
                        <div style={{ width: `${pct}%`, height: '100%', background: pct === 100 ? au.emerald : au.amber }} />
                      </div>
                      <span style={{ fontSize: '11px', fontFamily: Tgov.font.mono, fontWeight: 700, color: pct === 100 ? au.emerald : au.amber }}>{f.controlsPassing}/{f.controlsTotal}</span>
                    </div>
                  </td>
                  <td style={au.td}>{f.findings === 0
                    ? <GBadge color={au.emerald} bg={au.emeraldBg}>0</GBadge>
                    : <GBadge color={au.amber} bg={au.amberBg}>{f.findings}</GBadge>}</td>
                  <td style={{ ...au.td, fontFamily: Tgov.font.mono, fontSize: '11px', color: Tgov.color.text.tertiary }}>{f.lastAudit}</td>
                  <td style={{ ...au.td, fontFamily: Tgov.font.mono, fontSize: '11px', color: au.cobalt }}>{f.nextAudit}</td>
                  <td style={{ ...au.td, color: Tgov.color.text.secondary, fontSize: '11px' }}>{f.auditor}</td>
                  <td style={au.td}><GBadge color={au.emerald} bg={au.emeraldBg}>{f.status}</GBadge></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// ─── IaC ──────────────────────────────────────────────────────────────────────
function GovIaC({ data }) {
  const au = window.__au;
  const k = data.governanceKpis;
  const sample = `apiVersion: autoplatform.io/v1
kind: Workflow
metadata:
  name: MSJ-Opposition-Workflow
  version: v14
  tenant: Litigation
spec:
  owner: Litigation
  priority: P0
  sla:
    p95: 12h
    errorBudget: 84%
  steps:
    - name: research-memo
      type: script
      script: SC-014
    - name: outline
      type: human
      assignee: primary-associate
    - name: draft
      type: human
    - name: cite-check
      type: script
      script: SC-001
      retry:
        max: 5
        backoff: exponential
    - name: partner-review
      type: approval
      role: Partner
    - name: client-review
      type: human
    - name: revisions
      type: human
    - name: filing
      type: integration
      integration: INT-014-courtfiling
    - name: service
      type: integration`;

  return (
    <div>
      <div style={{ ...au.card, borderLeft: `3px solid ${au.slate}`, background: au.slateBg }}>
        <div style={{ padding: '12px 16px' }}>
          <div style={{ fontSize: '12px', fontWeight: 700, color: au.slate, textTransform: 'uppercase', letterSpacing: '0.08em' }}>◆ Configuration-as-code — GitOps for workflows, triggers, integrations</div>
          <div style={{ fontSize: '11px', color: Tgov.color.text.secondary, marginTop: '4px', lineHeight: 1.55 }}>
            {k.iacExports} export(s) · {k.iacImports} import(s). Every artifact round-trippable as YAML or JSON. Git-backed review with PR gates.
          </div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.1fr', gap: '14px' }}>
        <div style={au.card}>
          <div style={au.cardH}>
            <span>Recent exports — {data.iacExports.length}</span>
            <div style={{ display: 'flex', gap: '6px' }}>
              <button style={au.btnSecondary}>Export selected</button>
              <button style={au.btnPrimary}>⇣ Bulk export</button>
            </div>
          </div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr>
                <th style={au.th}>ID</th>
                <th style={au.th}>Artifact</th>
                <th style={au.th}>Type</th>
                <th style={au.th}>Format</th>
                <th style={au.th}>Exported</th>
                <th style={au.th}>By</th>
              </tr>
            </thead>
            <tbody>
              {data.iacExports.map(i => (
                <tr key={i.id}>
                  <td style={{ ...au.td, fontFamily: Tgov.font.mono, fontWeight: 700, color: au.slate }}>{i.id}</td>
                  <td style={{ ...au.td, color: Tgov.color.text.primary, fontWeight: 600, fontSize: '12px' }}>{i.artifact}</td>
                  <td style={au.td}><GBadge color={au.violet} bg={au.violetBg}>{i.type}</GBadge></td>
                  <td style={{ ...au.td, fontFamily: Tgov.font.mono, color: au.cobalt, fontWeight: 700 }}>{i.format}</td>
                  <td style={{ ...au.td, fontFamily: Tgov.font.mono, fontSize: '11px', color: Tgov.color.text.tertiary }}>{i.exportedOn}</td>
                  <td style={{ ...au.td, color: Tgov.color.text.secondary, fontSize: '11px' }}>{i.exportedBy}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        <div style={au.card}>
          <div style={au.cardH}>
            <span>Preview — MSJ-Opposition-Workflow.yml</span>
            <div style={{ display: 'flex', gap: '6px' }}>
              <button style={au.btnSecondary}>Copy</button>
              <button style={au.btnSecondary}>Open in Git</button>
            </div>
          </div>
          <pre style={{
            margin: 0, padding: '16px', background: '#0f172a', color: '#e2e8f0',
            fontSize: '11px', fontFamily: Tgov.font.mono, lineHeight: 1.65,
            overflow: 'auto', maxHeight: '560px',
          }}>{sample}</pre>
        </div>
      </div>
    </div>
  );
}

// ─── ROOT ─────────────────────────────────────────────────────────────────────
function AutoGovernance({ data }) {
  const au = window.__au;
  const [view, setView] = useGovState('versions');
  const renderView = () => {
    switch (view) {
      case 'versions':   return <GovVersions   data={data} />;
      case 'approvals':  return <GovApprovals  data={data} />;
      case 'policy':     return <GovPolicy     data={data} />;
      case 'rbac':       return <GovRBAC       data={data} />;
      case 'compliance': return <GovCompliance data={data} />;
      case 'iac':        return <GovIaC        data={data} />;
      default:           return <GovVersions   data={data} />;
    }
  };
  return (<div><AuSubNav views={GOV_VIEWS} active={view} onChange={setView} accent={au.cobalt} />{renderView()}</div>);
}

window.AutoGovernance = AutoGovernance;
