import { useState, useCallback } from "react";

// ─────────────────────────────────────────────────────────────
// PRIMORDIAL CALCULUS · PRE-CARCERAL DUE-PROCESS INTEGRITY LAYER
// HIR × OAM APPLICATION · Created from Collin D. Weber's OSF Package
// ─────────────────────────────────────────────────────────────

const THREAT_CATEGORIES = [
  {
    id: "warrant",
    label: "Warrant Integrity",
    code: "WI",
    oamPressures: [
      { key: "I_oam", label: "Institutional Penetration", desc: "Bureaucratic rubber-stamp displacing judicial scrutiny of probable cause" },
      { key: "K", label: "Compliance Rigidity", desc: "System resists scrutiny of warrant basis; deviation from template is penalized" },
      { key: "R_oam", label: "Ideological Saturation", desc: "Pre-conviction narrative embedded in warrant language before any finding" },
    ],
    hirChecks: [
      { key: "H", label: "Honesty", question: "Does the warrant affidavit accurately reflect the actual factual basis, free from exaggeration or omission?" },
      { key: "I_hir", label: "Integrity", question: "Is the stated basis structurally consistent with the supporting documents and timeline?" },
      { key: "R_hir", label: "Respect", question: "Were the subject's Fourth Amendment protections meaningfully preserved — not merely formally invoked?" },
    ],
    description: "Warrants become degraded when institutional pressure (high I_oam) and compliance rigidity (high K) replace genuine judicial review. The HIR check restores Honesty to the factual basis, Integrity to internal consistency, and Respect to the constitutional threshold.",
  },
  {
    id: "report",
    label: "Police Report Fidelity",
    code: "RF",
    oamPressures: [
      { key: "D", label: "Accumulated Degradation", desc: "Sedimented departmental norms normalizing selective or misleading documentation" },
      { key: "Ac", label: "Alchemical Continuity (loss)", desc: "Depletion of the living capacity for honest judgment — replaced by template-filling" },
      { key: "M", label: "Coercive Enforcement Index", desc: "Narrative shaped by enforcement outcome desired rather than events witnessed" },
    ],
    hirChecks: [
      { key: "H", label: "Honesty", question: "Does the written report faithfully reflect what was observed, without omission of exculpatory detail?" },
      { key: "I_hir", label: "Integrity", question: "Are the sequence of events, timings, and officer roles internally consistent throughout?" },
      { key: "F", label: "Fidelity", question: "Does the report maintain stable truth-alignment — consistent language for comparable events across the document?" },
    ],
    description: "Report degradation occurs when accumulated departmental norms (high D) and depleted human judgment (low Ac) convert documentation into enforcement narrative. Honesty, Integrity, and Fidelity are the restorative checks.",
  },
  {
    id: "bodycam",
    label: "Bodycam Discrepancy",
    code: "BD",
    oamPressures: [
      { key: "M", label: "Coercive Enforcement Index", desc: "Footage disabled, lost, or withheld under enforcement pressure" },
      { key: "K", label: "Compliance Rigidity", desc: "Institutional resistance to accountability via visual record" },
      { key: "D", label: "Accumulated Degradation", desc: "Pattern of bodycam failures in high-stakes encounters signals systemic degradation" },
    ],
    hirChecks: [
      { key: "H", label: "Honesty", question: "Is the visual record complete, unedited, and consistent with what the written report claims occurred?" },
      { key: "F", label: "Fidelity", question: "Where footage exists, does it maintain stable correspondence with the written timeline and witness accounts?" },
      { key: "C", label: "Cohesion", question: "Do all video sources (body, dash, surveillance) fit together without unexplained gaps or contradictions?" },
    ],
    description: "Bodycam discrepancies sit at the intersection of coercive enforcement pressure (high M) and compliance rigidity (high K). Fidelity and Cohesion checks detect where visual and written records diverge — a critical signal of record tampering or selective documentation.",
  },
  {
    id: "evidence",
    label: "Evidence Gap Analysis",
    code: "EG",
    oamPressures: [
      { key: "N", label: "Social Harm / Agency Loss", desc: "The subject's capacity to contest evidence is already eroded before any proceeding" },
      { key: "G_oam", label: "Agency Erosion Multiplier", desc: "Each unexplained gap compounds the subject's downstream agency loss" },
      { key: "I_oam", label: "Institutional Penetration", desc: "Chain-of-custody procedures replaced by pro forma documentation" },
    ],
    hirChecks: [
      { key: "I_hir", label: "Integrity", question: "Is the chain of custody complete, documented, and internally consistent from collection to courtroom?" },
      { key: "C", label: "Cohesion", question: "Does the full evidence set cohere — no missing items, unexplained absences, or late-appearing materials?" },
      { key: "R_hir", label: "Respect", question: "Was the subject's right to contest evidence preserved — through timely disclosure and proper preservation?" },
    ],
    description: "Evidence gaps compound agency loss (high N) through the agency erosion multiplier (G_oam), which magnifies the effect of each gap downstream. Integrity and Cohesion checks map the structural completeness of the evidentiary record.",
  },
  {
    id: "criminalization",
    label: "Wrongful Criminalization Risk",
    code: "WC",
    oamPressures: [
      { key: "D", label: "Accumulated Degradation", desc: "Full OAM trajectory: each prior degradation (D) compounds into terminal system failure" },
      { key: "N", label: "Social Harm / Agency Loss", desc: "Subject's independent agency within the proceeding is fully eroded" },
      { key: "Ac", label: "Alchemical Continuity (loss)", desc: "Human judgment displaced at every node; the person becomes a case number" },
    ],
    hirChecks: [
      { key: "H", label: "Honesty", question: "Across all record sources, is there a consistent, honest account — or does the picture only cohere under a prosecutorial frame?" },
      { key: "C", label: "Cohesion", question: "Does the totality of the record cohere without reliance on assumption, inference, or template-filling?" },
      { key: "Rn", label: "Resonance", question: "Is the cumulative documentary record sufficient to support a fair proceeding — or has degradation made resonance impossible?" },
    ],
    description: "Wrongful criminalization is the terminal OAM state: D accumulated, N maximized, Ac depleted. The Resonance (Rn) check is the final gateway — it asks whether the full record, after all degradation pressures, can still support due process.",
  },
];

const HIR_BASELINE = { H: 0.86, I_hir: 0.84, R_hir: 0.82, F: 0.85, C: 0.86, Rn: 0.85 };
const OAM_BASELINE = { I_oam: 0.12, K: 0.22, R_oam: 0.18, D: 0.05, M: 0.20, N: 0.15, G_oam: 1.015, Ac: 0.88 };
const OAM_CURRENT = { I_oam: 0.70, K: 0.65, R_oam: 0.75, D: 0.72, M: 0.45, N: 0.60, G_oam: 1.09, Ac: 0.42 };

function ScoreBar({ value, max = 1, invert = false, compact = false }) {
  const pct = Math.min(100, (value / max) * 100);
  const isGood = invert ? value < 0.4 : value > 0.6;
  const isMid = invert ? (value >= 0.4 && value <= 0.6) : (value >= 0.4 && value <= 0.6);
  const color = isGood ? "#4ade80" : isMid ? "#fbbf24" : "#f87171";
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
      <div style={{
        flex: 1, height: compact ? 4 : 6, background: "#1e293b", borderRadius: 3, overflow: "hidden"
      }}>
        <div style={{
          width: `${pct}%`, height: "100%",
          background: color, borderRadius: 3,
          transition: "width 0.4s ease"
        }} />
      </div>
      <span style={{ fontFamily: "'Courier New', monospace", fontSize: 11, color, minWidth: 32, textAlign: "right" }}>
        {value.toFixed(2)}
      </span>
    </div>
  );
}

function RatingInput({ value, onChange, label }) {
  const levels = [
    { v: 0.15, label: "CRITICAL" },
    { v: 0.35, label: "LOW" },
    { v: 0.55, label: "PARTIAL" },
    { v: 0.75, label: "ADEQUATE" },
    { v: 0.92, label: "HIGH" },
  ];
  return (
    <div style={{ display: "flex", gap: 4 }}>
      {levels.map(l => (
        <button
          key={l.v}
          onClick={() => onChange(l.v)}
          style={{
            flex: 1, padding: "3px 0", fontSize: 9, fontFamily: "'Courier New', monospace",
            fontWeight: 700, letterSpacing: "0.05em",
            background: Math.abs(value - l.v) < 0.05 ? "#0f172a" : "transparent",
            color: Math.abs(value - l.v) < 0.05
              ? (l.v > 0.6 ? "#4ade80" : l.v > 0.4 ? "#fbbf24" : "#f87171")
              : "#475569",
            border: Math.abs(value - l.v) < 0.05
              ? `1px solid ${l.v > 0.6 ? "#4ade80" : l.v > 0.4 ? "#fbbf24" : "#f87171"}`
              : "1px solid #1e293b",
            borderRadius: 2, cursor: "pointer", transition: "all 0.15s"
          }}
        >
          {l.label}
        </button>
      ))}
    </div>
  );
}

function ThreatPanel({ cat, scores, onScore }) {
  const [open, setOpen] = useState(false);
  const catScores = scores[cat.id] || {};
  const hirValues = cat.hirChecks.map(c => catScores[c.key] ?? 0.55);
  const avgHir = hirValues.reduce((a, b) => a + b, 0) / hirValues.length;
  const oamMagnitude = cat.oamPressures.reduce((sum, p) => sum + OAM_CURRENT[p.key] / (OAM_CURRENT[p.key] + 0.01), 0) / cat.oamPressures.length;
  const integrityScore = Math.max(0, avgHir - (oamMagnitude - 0.5) * 0.3);

  const statusColor = integrityScore > 0.65 ? "#4ade80" : integrityScore > 0.45 ? "#fbbf24" : "#f87171";
  const statusLabel = integrityScore > 0.65 ? "WITHIN BOUNDS" : integrityScore > 0.45 ? "FLAG FOR REVIEW" : "INTEGRITY BREACH";

  return (
    <div style={{
      border: `1px solid ${open ? "#334155" : "#1e293b"}`,
      borderRadius: 4, overflow: "hidden", marginBottom: 8,
      background: open ? "#0b1220" : "transparent",
      transition: "all 0.2s"
    }}>
      <div
        onClick={() => setOpen(!open)}
        style={{
          display: "flex", alignItems: "center", padding: "10px 14px",
          cursor: "pointer", gap: 12, userSelect: "none"
        }}
      >
        <span style={{
          fontFamily: "'Courier New', monospace", fontSize: 10, fontWeight: 700,
          color: "#475569", letterSpacing: "0.12em", minWidth: 28
        }}>{cat.code}</span>
        <span style={{ flex: 1, color: "#cbd5e1", fontSize: 12, fontFamily: "'Courier New', monospace", letterSpacing: "0.04em" }}>
          {cat.label}
        </span>
        <span style={{
          fontSize: 9, fontFamily: "'Courier New', monospace", fontWeight: 700,
          letterSpacing: "0.1em", color: statusColor,
          border: `1px solid ${statusColor}`, padding: "2px 6px", borderRadius: 2
        }}>{statusLabel}</span>
        <span style={{ color: "#475569", fontSize: 10, marginLeft: 4 }}>{open ? "▲" : "▼"}</span>
      </div>

      {open && (
        <div style={{ padding: "0 14px 14px", borderTop: "1px solid #1e293b" }}>
          <p style={{
            color: "#64748b", fontSize: 11, lineHeight: 1.6, margin: "10px 0 14px",
            fontFamily: "Georgia, serif", fontStyle: "italic"
          }}>{cat.description}</p>

          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
            {/* OAM Pressures */}
            <div>
              <div style={{
                fontFamily: "'Courier New', monospace", fontSize: 9, letterSpacing: "0.15em",
                color: "#f87171", marginBottom: 8, fontWeight: 700
              }}>OAM DEGRADATION PRESSURES</div>
              {cat.oamPressures.map(p => (
                <div key={p.key} style={{ marginBottom: 10 }}>
                  <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 3 }}>
                    <span style={{ color: "#94a3b8", fontSize: 10, fontFamily: "'Courier New', monospace" }}>{p.label}</span>
                    <span style={{ color: "#f87171", fontSize: 9, fontFamily: "'Courier New', monospace" }}>
                      {p.key}: {typeof OAM_CURRENT[p.key] === 'number' && OAM_CURRENT[p.key] <= 1 ? OAM_CURRENT[p.key].toFixed(2) : OAM_CURRENT[p.key]}
                    </span>
                  </div>
                  {OAM_CURRENT[p.key] <= 1 && <ScoreBar value={OAM_CURRENT[p.key]} invert compact />}
                  <div style={{ color: "#475569", fontSize: 9, marginTop: 3, fontFamily: "Georgia, serif" }}>{p.desc}</div>
                </div>
              ))}
            </div>

            {/* HIR Integrity Checks */}
            <div>
              <div style={{
                fontFamily: "'Courier New', monospace", fontSize: 9, letterSpacing: "0.15em",
                color: "#4ade80", marginBottom: 8, fontWeight: 700
              }}>HIR INTEGRITY CHECKS</div>
              {cat.hirChecks.map(c => (
                <div key={c.key} style={{ marginBottom: 12 }}>
                  <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 4 }}>
                    <span style={{ color: "#94a3b8", fontSize: 10, fontFamily: "'Courier New', monospace" }}>{c.label} ({c.key})</span>
                  </div>
                  <div style={{ color: "#64748b", fontSize: 9, marginBottom: 5, fontFamily: "Georgia, serif" }}>{c.question}</div>
                  <RatingInput
                    value={catScores[c.key] ?? 0.55}
                    onChange={v => onScore(cat.id, c.key, v)}
                  />
                </div>
              ))}

              <div style={{
                marginTop: 12, padding: "8px 10px",
                background: "#0f172a", border: `1px solid ${statusColor}`, borderRadius: 3
              }}>
                <div style={{ fontFamily: "'Courier New', monospace", fontSize: 9, color: "#475569", letterSpacing: "0.1em", marginBottom: 4 }}>
                  COMPUTED INTEGRITY · {cat.code}
                </div>
                <ScoreBar value={integrityScore} />
                <div style={{
                  fontFamily: "'Courier New', monospace", fontSize: 9, color: statusColor,
                  letterSpacing: "0.1em", marginTop: 6, fontWeight: 700
                }}>→ {statusLabel}</div>
              </div>
            </div>
          </div>

          {integrityScore <= 0.45 && (
            <div style={{
              marginTop: 12, padding: "10px 12px",
              background: "rgba(248, 113, 113, 0.06)", border: "1px solid rgba(248, 113, 113, 0.3)",
              borderRadius: 3
            }}>
              <div style={{ fontFamily: "'Courier New', monospace", fontSize: 9, color: "#f87171", fontWeight: 700, letterSpacing: "0.1em", marginBottom: 4 }}>
                ⚠ HUMAN REVIEW REQUIRED — NOT A LEGAL FINDING
              </div>
              <div style={{ color: "#94a3b8", fontSize: 10, lineHeight: 1.6, fontFamily: "Georgia, serif" }}>
                This layer flags degradation conditions for human review only. It does not determine guilt, innocence, or legal outcome. 
                A trained reviewer must assess whether documentary conditions warrant escalation. No automated adverse finding is generated.
              </div>
            </div>
          )}
        </div>
      )}
    </div>
  );
}

export default function App() {
  const [scores, setScores] = useState({});
  const [activeTab, setActiveTab] = useState("assess");

  const handleScore = useCallback((catId, key, val) => {
    setScores(prev => ({
      ...prev,
      [catId]: { ...(prev[catId] || {}), [key]: val }
    }));
  }, []);

  const computeOverall = () => {
    let total = 0, count = 0;
    THREAT_CATEGORIES.forEach(cat => {
      const catScores = scores[cat.id] || {};
      const hirValues = cat.hirChecks.map(c => catScores[c.key] ?? 0.55);
      const avgHir = hirValues.reduce((a, b) => a + b, 0) / hirValues.length;
      const oamMag = cat.oamPressures.reduce((sum, p) => sum + OAM_CURRENT[p.key] / (OAM_CURRENT[p.key] + 0.01), 0) / cat.oamPressures.length;
      total += Math.max(0, avgHir - (oamMag - 0.5) * 0.3);
      count++;
    });
    return total / count;
  };

  const overallScore = computeOverall();
  const breachCount = THREAT_CATEGORIES.filter(cat => {
    const catScores = scores[cat.id] || {};
    const hirValues = cat.hirChecks.map(c => catScores[c.key] ?? 0.55);
    const avgHir = hirValues.reduce((a, b) => a + b, 0) / hirValues.length;
    const oamMag = cat.oamPressures.reduce((sum, p) => sum + OAM_CURRENT[p.key] / (OAM_CURRENT[p.key] + 0.01), 0) / cat.oamPressures.length;
    return Math.max(0, avgHir - (oamMag - 0.5) * 0.3) <= 0.45;
  }).length;

  const tabs = [
    { id: "assess", label: "ASSESSMENT" },
    { id: "map", label: "HIR × OAM MAP" },
    { id: "guide", label: "FRAMEWORK" },
  ];

  return (
    <div style={{
      background: "#060d18",
      minHeight: "100vh",
      fontFamily: "'Courier New', monospace",
      color: "#cbd5e1",
      padding: "0 0 40px"
    }}>
      {/* Header */}
      <div style={{
        borderBottom: "1px solid #1e293b",
        padding: "20px 28px 16px",
        background: "linear-gradient(to bottom, #0a1628, #060d18)"
      }}>
        <div style={{ fontSize: 9, color: "#334155", letterSpacing: "0.2em", marginBottom: 6 }}>
          PRIMORDIAL CALCULUS · OSF CANONICAL PACKAGE v1.0 · COLLIN D. WEBER
        </div>
        <h1 style={{
          margin: 0, fontSize: 18, fontWeight: 700, letterSpacing: "0.06em",
          color: "#e2e8f0", lineHeight: 1.2
        }}>
          PRE-CARCERAL DUE-PROCESS INTEGRITY LAYER
        </h1>
        <div style={{ fontSize: 11, color: "#475569", marginTop: 4, letterSpacing: "0.06em" }}>
          HIR × OAM APPLICATION · DOCUMENTARY RECORD INTEGRITY ASSESSMENT
        </div>

        <div style={{
          display: "flex", gap: 20, marginTop: 16, flexWrap: "wrap"
        }}>
          {[
            { label: "BOUNDED", desc: "5 threat domains only" },
            { label: "NON-PUNITIVE", desc: "Flags only, no adverse findings" },
            { label: "HUMAN-REVIEWED", desc: "No automated outcomes" },
            { label: "NOT LEGAL ADVICE", desc: "Integrity assessment only" },
          ].map(c => (
            <div key={c.label} style={{ display: "flex", alignItems: "center", gap: 6 }}>
              <div style={{
                width: 6, height: 6, borderRadius: "50%", background: "#4ade80",
                boxShadow: "0 0 6px #4ade80"
              }} />
              <div>
                <div style={{ fontSize: 9, fontWeight: 700, color: "#4ade80", letterSpacing: "0.12em" }}>{c.label}</div>
                <div style={{ fontSize: 8, color: "#334155" }}>{c.desc}</div>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Tabs */}
      <div style={{ display: "flex", borderBottom: "1px solid #1e293b", padding: "0 28px" }}>
        {tabs.map(t => (
          <button key={t.id} onClick={() => setActiveTab(t.id)} style={{
            padding: "10px 14px", background: "none",
            border: "none", borderBottom: activeTab === t.id ? "2px solid #60a5fa" : "2px solid transparent",
            color: activeTab === t.id ? "#60a5fa" : "#475569",
            fontSize: 9, letterSpacing: "0.15em", cursor: "pointer", fontFamily: "'Courier New', monospace",
            fontWeight: 700, marginBottom: "-1px", transition: "all 0.15s"
          }}>{t.label}</button>
        ))}
      </div>

      <div style={{ padding: "20px 28px" }}>

        {/* ── ASSESSMENT TAB ── */}
        {activeTab === "assess" && (
          <div>
            {/* Status bar */}
            <div style={{
              display: "grid", gridTemplateColumns: "1fr 1fr 1fr",
              gap: 12, marginBottom: 20
            }}>
              <div style={{ padding: "12px 14px", background: "#0b1220", border: "1px solid #1e293b", borderRadius: 4 }}>
                <div style={{ fontSize: 8, color: "#475569", letterSpacing: "0.15em", marginBottom: 6 }}>RECORD RESONANCE (Rn)</div>
                <ScoreBar value={overallScore} />
                <div style={{ fontSize: 8, color: "#64748b", marginTop: 4 }}>
                  {overallScore > 0.65 ? "Record supports fair proceeding" : overallScore > 0.45 ? "Conditional — review required" : "Record integrity insufficient"}
                </div>
              </div>
              <div style={{ padding: "12px 14px", background: "#0b1220", border: "1px solid #1e293b", borderRadius: 4 }}>
                <div style={{ fontSize: 8, color: "#475569", letterSpacing: "0.15em", marginBottom: 8 }}>INTEGRITY BREACHES</div>
                <div style={{ fontSize: 28, fontWeight: 700, color: breachCount > 0 ? "#f87171" : "#4ade80", lineHeight: 1 }}>
                  {breachCount}
                </div>
                <div style={{ fontSize: 8, color: "#64748b", marginTop: 4 }}>of {THREAT_CATEGORIES.length} threat domains breached</div>
              </div>
              <div style={{ padding: "12px 14px", background: "#0b1220", border: "1px solid #1e293b", borderRadius: 4 }}>
                <div style={{ fontSize: 8, color: "#475569", letterSpacing: "0.15em", marginBottom: 6 }}>ROUTING STATUS</div>
                <div style={{
                  fontSize: 10, fontWeight: 700, letterSpacing: "0.1em",
                  color: breachCount === 0 ? "#4ade80" : breachCount <= 2 ? "#fbbf24" : "#f87171",
                  marginBottom: 4
                }}>
                  {breachCount === 0 ? "STANDARD PROCEEDING" : breachCount <= 2 ? "HUMAN REVIEW QUEUE" : "INTEGRITY HOLD"}
                </div>
                <div style={{ fontSize: 8, color: "#64748b", lineHeight: 1.5 }}>
                  {breachCount === 0
                    ? "No breaches flagged. Standard human review applies."
                    : breachCount <= 2
                    ? "Flagged conditions require trained human reviewer before proceeding."
                    : "Multiple breaches. Record should not advance without full integrity review."}
                </div>
              </div>
            </div>

            {THREAT_CATEGORIES.map(cat => (
              <ThreatPanel key={cat.id} cat={cat} scores={scores} onScore={handleScore} />
            ))}
          </div>
        )}

        {/* ── HIR × OAM MAP TAB ── */}
        {activeTab === "map" && (
          <div>
            <div style={{
              padding: "14px 16px", background: "#0b1220", border: "1px solid #1e293b",
              borderRadius: 4, marginBottom: 20
            }}>
              <div style={{ fontSize: 9, color: "#60a5fa", letterSpacing: "0.15em", fontWeight: 700, marginBottom: 8 }}>
                ARCHITECTURAL MAPPING STATEMENT
              </div>
              <p style={{ color: "#94a3b8", fontSize: 11, lineHeight: 1.7, margin: 0, fontFamily: "Georgia, serif" }}>
                OAM is the zero-tolerance hard-fault test built after HIR. In the pre-carceral context, OAM variables 
                map the pressures that degrade documentary integrity. HIR variables — Honesty, Integrity, Respect, 
                Fidelity, Cohesion, Resonance — provide the restorative baseline checks. This layer does not replace 
                legal process; it identifies where OAM degradation has made fair process structurally difficult.
              </p>
            </div>

            {/* The mapping table */}
            <div style={{ overflowX: "auto" }}>
              <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 10 }}>
                <thead>
                  <tr style={{ borderBottom: "1px solid #1e293b" }}>
                    {["THREAT", "DOMINANT OAM PRESSURES", "HIR RESTORATIVE CHECKS", "RESONANCE THRESHOLD"].map(h => (
                      <th key={h} style={{
                        textAlign: "left", padding: "8px 12px", color: "#475569",
                        fontSize: 8, letterSpacing: "0.12em", fontWeight: 700
                      }}>{h}</th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {THREAT_CATEGORIES.map((cat, i) => (
                    <tr key={cat.id} style={{ borderBottom: "1px solid #0f172a" }}>
                      <td style={{ padding: "10px 12px", verticalAlign: "top" }}>
                        <div style={{ color: "#e2e8f0", fontWeight: 700, letterSpacing: "0.04em" }}>{cat.code}</div>
                        <div style={{ color: "#64748b", fontSize: 9, marginTop: 2 }}>{cat.label}</div>
                      </td>
                      <td style={{ padding: "10px 12px", verticalAlign: "top" }}>
                        {cat.oamPressures.map(p => (
                          <div key={p.key} style={{ marginBottom: 5 }}>
                            <span style={{ color: "#f87171", fontSize: 9, fontWeight: 700 }}>{p.key}</span>
                            <span style={{ color: "#64748b", fontSize: 9 }}> · {p.label}</span>
                          </div>
                        ))}
                      </td>
                      <td style={{ padding: "10px 12px", verticalAlign: "top" }}>
                        {cat.hirChecks.map(c => (
                          <div key={c.key} style={{ marginBottom: 5 }}>
                            <span style={{ color: "#4ade80", fontSize: 9, fontWeight: 700 }}>{c.key}</span>
                            <span style={{ color: "#64748b", fontSize: 9 }}> · {c.label}</span>
                          </div>
                        ))}
                      </td>
                      <td style={{ padding: "10px 12px", verticalAlign: "top" }}>
                        <div style={{ color: "#60a5fa", fontSize: 9 }}>
                          {cat.id === "criminalization" ? "Rn > 0.65 required" : "F, C > 0.60 required"}
                        </div>
                        <div style={{ color: "#334155", fontSize: 9, marginTop: 2 }}>
                          Baseline: Rn ≈ 0.85 (pre-OAM)
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>

            {/* Equation block */}
            <div style={{
              marginTop: 20, padding: "16px", background: "#0b1220",
              border: "1px solid #1e293b", borderRadius: 4
            }}>
              <div style={{ fontSize: 9, color: "#475569", letterSpacing: "0.15em", marginBottom: 12 }}>
                CANONICAL EQUATIONS APPLIED · FROM OSF PACKAGE (Weber, 2026)
              </div>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
                <div>
                  <div style={{ fontSize: 9, color: "#4ade80", marginBottom: 8, fontWeight: 700 }}>HIR CONSTRUCTIVE SEQUENCE</div>
                  {[
                    "H + I → F (Fidelity)",
                    "R + I → C (Cohesion)",
                    "F + C → Rn (Resonance)",
                    "Rn[t+1] = Rn[t] + α(F[t]·C[t]) − δ",
                    "S_core = s(H, I, R, Rn, G)",
                  ].map(eq => (
                    <div key={eq} style={{ color: "#94a3b8", fontSize: 10, marginBottom: 6 }}>{eq}</div>
                  ))}
                </div>
                <div>
                  <div style={{ fontSize: 9, color: "#f87171", marginBottom: 8, fontWeight: 700 }}>OAM DEGRADATION EQUATIONS</div>
                  {[
                    "G_oam[t] = 1 + q·N[t]",
                    "N[t+1] = N[t] + (b·R·K·P[t] + g·R·K·I)·G_oam + …",
                    "D[t+1] = D[t] + a·R·K·I·P·N·E + …",
                    "E[t+1] = E[t] + m_eco·R·K·P + n_eco·N + …",
                    "PDIL integrity = f(HIR checks) − f(OAM pressures)",
                  ].map(eq => (
                    <div key={eq} style={{ color: "#94a3b8", fontSize: 10, marginBottom: 6 }}>{eq}</div>
                  ))}
                </div>
              </div>
            </div>
          </div>
        )}

        {/* ── FRAMEWORK TAB ── */}
        {activeTab === "guide" && (
          <div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, marginBottom: 20 }}>
              {[
                {
                  title: "WHAT THIS LAYER DOES",
                  color: "#60a5fa",
                  items: [
                    "Maps five documentary integrity threat domains to OAM degradation variables",
                    "Applies HIR restorative checks (H, I, R, F, C, Rn) against each threat",
                    "Computes a per-domain and overall resonance integrity score",
                    "Routes low-resonance records to human review queues",
                    "Provides structured language for reviewers — not legal conclusions",
                  ]
                },
                {
                  title: "WHAT THIS LAYER DOES NOT DO",
                  color: "#f87171",
                  items: [
                    "Determine guilt or innocence — that is never its function",
                    "Generate adverse legal findings against any party",
                    "Replace or supersede legal counsel, courts, or official review",
                    "Constitute legal advice of any kind",
                    "Operate without human review — no automated outcome is valid",
                  ]
                }
              ].map(block => (
                <div key={block.title} style={{
                  padding: "14px 16px", background: "#0b1220",
                  border: `1px solid #1e293b`, borderRadius: 4
                }}>
                  <div style={{ fontSize: 9, color: block.color, letterSpacing: "0.15em", fontWeight: 700, marginBottom: 10 }}>
                    {block.title}
                  </div>
                  {block.items.map((item, i) => (
                    <div key={i} style={{ display: "flex", gap: 8, marginBottom: 7 }}>
                      <span style={{ color: block.color, fontSize: 10, marginTop: 1 }}>›</span>
                      <span style={{ color: "#94a3b8", fontSize: 10, lineHeight: 1.5, fontFamily: "Georgia, serif" }}>{item}</span>
                    </div>
                  ))}
                </div>
              ))}
            </div>

            {/* Variable reference */}
            <div style={{
              padding: "14px 16px", background: "#0b1220",
              border: "1px solid #1e293b", borderRadius: 4, marginBottom: 16
            }}>
              <div style={{ fontSize: 9, color: "#475569", letterSpacing: "0.15em", fontWeight: 700, marginBottom: 12 }}>
                OAM VARIABLE REFERENCE · CURRENT SYSTEMIC ESTIMATES
              </div>
              <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 10 }}>
                {Object.entries(OAM_CURRENT).filter(([k]) => OAM_CURRENT[k] <= 1).map(([k, v]) => {
                  const labels = {
                    I_oam: "Institutional Penetration", K: "Compliance Rigidity",
                    R_oam: "Ideological Saturation", D: "Accumulated Degradation",
                    M: "Coercive Enforcement", N: "Agency Loss Index",
                    Ac: "Alchemical Continuity"
                  };
                  const isAc = k === "Ac";
                  const bad = isAc ? v < 0.5 : v > 0.5;
                  return (
                    <div key={k} style={{ padding: "8px 10px", background: "#060d18", borderRadius: 3, border: "1px solid #0f172a" }}>
                      <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 4 }}>
                        <span style={{ color: bad ? "#f87171" : "#4ade80", fontSize: 10, fontWeight: 700 }}>{k}</span>
                        <span style={{ color: bad ? "#f87171" : "#4ade80", fontSize: 9 }}>{v.toFixed(2)}</span>
                      </div>
                      <ScoreBar value={isAc ? v : v} invert={!isAc} compact />
                      <div style={{ color: "#334155", fontSize: 8, marginTop: 4 }}>{labels[k] || k}</div>
                      <div style={{ color: "#1e293b", fontSize: 8 }}>Baseline: {OAM_BASELINE[k]?.toFixed(2)}</div>
                    </div>
                  );
                })}
              </div>
            </div>

            <div style={{
              padding: "14px 16px", background: "#0a0f1a",
              border: "1px solid #1e293b", borderRadius: 4
            }}>
              <div style={{ fontSize: 9, color: "#475569", letterSpacing: "0.15em", fontWeight: 700, marginBottom: 8 }}>
                CANONICAL SOURCE
              </div>
              <p style={{ color: "#475569", fontSize: 9, lineHeight: 1.7, margin: 0, fontFamily: "Georgia, serif" }}>
                Framework derived exclusively from: Primordial Calculus OSF Canonical Package v1.0 + 018 
                (Weber, C.D., 2026). HIR as bedrock constructive triad (H + I → F; R + I → C; F + C → Rn). 
                OAM as the zero-tolerance hard-fault test built after HIR. Baseline calibration from 
                003_HIR_OAM_Historical_Baseline_Calibration_v0_1.txt (HIR/Rn ≈ 0.85; D ≈ 0.05). 
                This application is bounded to documentary integrity assessment and does not constitute 
                externally validated science. It inherits the package's provisional status accordingly.
              </p>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
