// Platform Admin AI Context governance
function AIContextPage({ initialSection = "rules" }) {
  const [section, setSection] = useState(initialSection || "rules");
  const [ruleStatus, setRuleStatus] = useState("Active");
  const [memoryStatus, setMemoryStatus] = useState("Candidate");
  const [auditOpen, setAuditOpen] = useState(false);

  const tabs = [
    { k: "rules", label: "Rules", icon: <I.shield size={15}/> },
    { k: "knowledge", label: "Knowledge Base", icon: <I.book size={15}/> },
    { k: "memory", label: "Memory", icon: <I.brain size={15}/> },
    { k: "retrieval", label: "Retrieval Config", icon: <I.cog size={15}/> },
  ];

  const rules = [
    {
      id: "R-PB-001",
      name: "Lead escalation threshold",
      type: "Guardrail",
      source: "APP RULES workbook",
      status: ruleStatus,
      priority: "Blocking",
      applied: "18 protocols",
      updated: "Jun 24",
      condition: "Pb above clinical threshold or trend rising across retests",
      recommendation: "Require mentor review before protocol is marked ready.",
      note: "Generated guardrail source requires rebuild until rule registry migration is complete.",
    },
    {
      id: "DOM-CU-007",
      name: "Copper-zinc monitoring",
      type: "Domain rule",
      source: "recommendation_rules",
      status: "Active",
      priority: "Standard",
      applied: "43 protocols",
      updated: "Jun 21",
      condition: "Cu/Zn ratio is elevated or increasing with copper symptoms.",
      recommendation: "Monitor copper load, avoid aggressive zinc escalation without tolerance review.",
      note: "DB-backed semantic retrieval rule; changes apply to the next protocol run after save.",
    },
    {
      id: "DOM-SLOW2-014",
      name: "Slow 2 adrenal pacing",
      type: "Domain rule",
      source: "recommendation_rules",
      status: "Draft",
      priority: "Review",
      applied: "0 protocols",
      updated: "Today",
      condition: "Slow 2 pattern with low sodium and potassium plus fatigue.",
      recommendation: "Favor staged mineral support and conservative adrenal stimulation.",
      note: "Draft from mentor review; not active in retrieval.",
    },
  ];

  const sources = [
    {
      name: "Lisa Pomeroy Protocol Handbook",
      scope: "Protocol KB",
      chunks: "148",
      embedding: "text-embedding-3-large · 3072",
      status: "Current",
      used: "96 protocol runs",
      updated: "Jun 25",
    },
    {
      name: "VERA practitioner transcripts",
      scope: "VERA KB",
      chunks: "312",
      embedding: "text-embedding-3-large · 3072",
      status: "Current",
      used: "214 VERA answers",
      updated: "Jun 23",
    },
    {
      name: "Supplement guardrails generated markdown",
      scope: "VERA KB",
      chunks: "29",
      embedding: "text-embedding-3-large · 3072",
      status: "Reindex queued",
      used: "41 VERA answers",
      updated: "Today",
    },
  ];

  const memories = [
    {
      title: "Selenium tolerance note",
      type: "Episodic",
      status: memoryStatus,
      source: "protocol_feedback · v3 · Amelia Hart",
      version: "Candidate",
      updated: "Today",
      text: "Client reported metallic taste above 150mcg selenium; use lower dose when selenium is recommended.",
    },
    {
      title: "Copper wording preference",
      type: "Semantic",
      status: "Active",
      source: "assistant_message_feedback · VERA",
      version: "v2",
      updated: "Jun 22",
      text: "When explaining copper monitoring, include retest rationale and avoid implying copper detox without practitioner confirmation.",
    },
    {
      title: "Lead escalation handling",
      type: "Semantic",
      status: "Active",
      source: "mentor note · red flag review",
      version: "v1",
      updated: "Jun 19",
      text: "Elevated lead protocols require mentor clearance before the ready action is available.",
    },
  ];

  const versions = [
    ["Active protocol recommender", "rules 10 · KB 5 · cases 5 · age ±5", "Published", "Jun 24"],
    ["VERA assistant", "limit 8 · min similarity 0.50", "Published", "Jun 23"],
    ["Protocol recommender draft", "rules 12 · KB 6 · cases 5 · age ±5", "Draft", "Today"],
  ];

  const auditEvents = [
    {
      id: "audit-1",
      type: "Publish",
      title: "Retrieval config published",
      target: "Protocol recommender config",
      actor: "Platform Admin",
      time: "Today, 10:42",
      version: "v1.4 -> v1.5",
      status: "Published",
      note: "Changed Rules top-k from 8 to 10. Applies to the next eligible protocol run.",
      before: "rules top-k 8 · KB 5 · cases 5 · age ±5",
      after: "rules top-k 10 · KB 5 · cases 5 · age ±5",
      provenance: "Settings > AI Context > Retrieval Config",
      impact: "Next protocol generation and case VERA retrieval use the updated rule count.",
      refs: ["vykon-protocol v1.5", "Audit event ctx_audit_2026_0629_1042"],
    },
    {
      id: "audit-2",
      type: "Knowledge Base",
      title: "Knowledge source reindexed",
      target: "Supplement guardrails generated markdown",
      actor: "Platform Admin",
      time: "Today, 09:58",
      version: "index 42 -> 43",
      status: "Reindexed",
      note: "Rebuilt VERA KB chunks after guardrail source refresh.",
      before: "29 chunks · reindex queued",
      after: "31 chunks · current",
      provenance: "Knowledge source upload and embedding job",
      impact: "VERA citations can now reference the refreshed guardrail chunks.",
      refs: ["embedding job emb_0629_0958", "VERA KB"],
    },
    {
      id: "audit-3",
      type: "Memory",
      title: "Memory approved",
      target: "Selenium tolerance note",
      actor: "Platform Admin",
      time: "Yesterday, 16:22",
      version: "Candidate -> v1",
      status: "Approved",
      note: "Approved candidate memory from protocol feedback for future case-aware retrieval.",
      before: "Candidate memory, not used in retrieval",
      after: "Active episodic memory with source provenance",
      provenance: "protocol_feedback · Amelia Hart · protocol v3",
      impact: "Future case-specific VERA answers can cite the selenium tolerance note.",
      refs: ["HTMA-2025-0112", "protocol_feedback row 42"],
    },
    {
      id: "audit-4",
      type: "Rules",
      title: "Rule activated",
      target: "R-PB-001 Lead escalation threshold",
      actor: "Platform Admin",
      time: "Jun 24, 14:06",
      version: "v1.3 -> v1.4",
      status: "Published",
      note: "Activated the lead escalation guardrail after mentor review.",
      before: "Draft guardrail, not blocking",
      after: "Active blocking guardrail",
      provenance: "APP RULES workbook + mentor red-flag review",
      impact: "Protocols with elevated lead require mentor clearance before ready state.",
      refs: ["R-PB-001", "HTMA-2025-0112"],
    },
    {
      id: "audit-5",
      type: "Rules",
      title: "Rule draft saved",
      target: "DOM-SLOW2-014 Slow 2 adrenal pacing",
      actor: "Platform Admin",
      time: "Jun 24, 11:31",
      version: "new draft",
      status: "Draft",
      note: "Created a new domain rule draft from mentor review notes.",
      before: "No domain rule",
      after: "Draft rule available for review",
      provenance: "mentor note · slow oxidation review",
      impact: "No runtime impact until published.",
      refs: ["DOM-SLOW2-014"],
    },
    {
      id: "audit-6",
      type: "Publish",
      title: "Rollback completed",
      target: "VERA assistant retrieval",
      actor: "Platform Admin",
      time: "Jun 23, 18:05",
      version: "v1.5 -> v1.4",
      status: "Rolled back",
      note: "Rolled back minimum similarity after lower-quality VERA source matches.",
      before: "limit 10 · min similarity 0.42",
      after: "limit 8 · min similarity 0.50",
      provenance: "Low-rated VERA answer review",
      impact: "VERA uses tighter retrieval until the next published config.",
      refs: ["assistant feedback batch fb_0623", "VERA assistant"],
    },
  ];

  const statusBadge = (status) => {
    const cls = status === "Active" || status === "Current" || status === "Published" ? "green" : status.includes("queued") || status === "Candidate" || status === "Draft" ? "amber" : "blue";
    return <span className={"badge " + cls}><span className="dot"></span>{status}</span>;
  };

  function GovernanceHeader() {
    return (
      <div className="ai-context-hero">
        <div>
          <div className="row" style={{gap: 8, marginBottom: 8}}>
            <span className="chip green"><I.shield size={11}/> Platform Admin</span>
            <span className="chip">A8 · AI Context and Knowledge Management</span>
          </div>
          <div className="page-title">AI Context</div>
          <div className="page-sub">Rules, knowledge sources, memory provenance, and retrieval configuration.</div>
        </div>
        <div className="row">
          <button className="btn" onClick={() => setAuditOpen(true)}><I.clock size={14}/> Audit log</button>
          <button className="btn primary"><I.check size={14}/> Publish changes</button>
        </div>
      </div>
    );
  }

  function OverviewStrip() {
    return (
      <div className="grid grid-4 ai-context-kpis">
        <div className="kpi">
          <div className="kpi-label">Rules tracked</div>
          <div className="kpi-val">213</div>
          <div className="kpi-trend">Guardrails and domain rules</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Knowledge chunks</div>
          <div className="kpi-val">489</div>
          <div className="kpi-trend up">2 sources current</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Memory candidates</div>
          <div className="kpi-val">7</div>
          <div className="kpi-trend warn">Require admin review</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Active config</div>
          <div className="kpi-val" style={{fontSize: 24}}>v1.4</div>
          <div className="kpi-trend">Applies next run</div>
        </div>
      </div>
    );
  }

  function RuleRegistry() {
    return (
      <div className="ai-context-grid">
        <div className="card">
          <div className="card-head">
            <div>
              <div className="card-title">Rule registry</div>
              <div className="card-sub">Guardrail and domain rules with where-used provenance</div>
            </div>
            <div className="row">
              <button className="btn sm"><I.filter size={12}/> Filter</button>
              <button className="btn sm primary"><I.plus size={12}/> New draft</button>
            </div>
          </div>
          <table className="tbl">
            <thead>
              <tr><th>Rule</th><th>Type</th><th>Status</th><th>Where used</th><th>Updated</th></tr>
            </thead>
            <tbody>
              {rules.map(rule => (
                <tr key={rule.id} className="row-click">
                  <td>
                    <div style={{fontWeight: 600}}>{rule.id}</div>
                    <div className="muted" style={{fontSize: 11.5}}>{rule.name}</div>
                  </td>
                  <td>{rule.type}</td>
                  <td>{statusBadge(rule.status)}</td>
                  <td className="muted">{rule.applied}</td>
                  <td className="muted">{rule.updated}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <div className="card card-pad ai-detail">
          <div className="row-between" style={{marginBottom: 14}}>
            <div>
              <div className="card-title">R-PB-001</div>
              <div className="muted" style={{fontSize: 12}}>Lead escalation threshold</div>
            </div>
            {statusBadge(ruleStatus)}
          </div>
          <div className="ai-field"><span>Source</span><strong>APP RULES workbook</strong></div>
          <div className="ai-field"><span>Condition</span><strong>Pb above clinical threshold or trend rising across retests</strong></div>
          <div className="ai-field"><span>Recommendation</span><strong>Require mentor review before protocol is marked ready.</strong></div>
          <div className="alert warn" style={{marginTop: 14}}>
            <I.warn size={16}/>
            <div>Direct activation depends on the generated guardrail registry decision.</div>
          </div>
          <div className="ai-timeline">
            <div><I.link size={13}/> Applied in HTMA-2025-0112 · protocol v3</div>
            <div><I.edit size={13}/> Version v1.4 saved Jun 24 by Platform Admin</div>
            <div><I.clock size={13}/> Next change requires audit note</div>
          </div>
          <div className="row" style={{gap: 8, marginTop: 16}}>
            <button className="btn sm" onClick={() => setRuleStatus(ruleStatus === "Active" ? "Inactive" : "Active")}>{ruleStatus === "Active" ? "Deactivate" : "Activate"}</button>
            <button className="btn sm primary"><I.edit size={12}/> Edit draft</button>
          </div>
        </div>
      </div>
    );
  }

  function KnowledgeBase() {
    return (
      <div className="ai-context-grid">
        <div className="card">
          <div className="card-head">
            <div>
              <div className="card-title">Knowledge sources</div>
              <div className="card-sub">Protocol KB and VERA KB stay separate</div>
            </div>
            <div className="row">
              <button className="btn sm"><I.upload size={12}/> Add source</button>
              <button className="btn sm primary"><I.refresh size={12}/> Reindex</button>
            </div>
          </div>
          <table className="tbl">
            <thead>
              <tr><th>Source</th><th>Scope</th><th>Chunks</th><th>Status</th><th>Used</th></tr>
            </thead>
            <tbody>
              {sources.map(source => (
                <tr key={source.name} className="row-click">
                  <td>
                    <div style={{fontWeight: 600}}>{source.name}</div>
                    <div className="muted" style={{fontSize: 11.5}}>{source.embedding}</div>
                  </td>
                  <td>{source.scope}</td>
                  <td>{source.chunks}</td>
                  <td>{statusBadge(source.status)}</td>
                  <td className="muted">{source.used}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <div className="card card-pad ai-detail">
          <div className="card-title" style={{marginBottom: 10}}>Source health</div>
          <div className="ai-source-health">
            <div><span>Embedding model</span><strong>text-embedding-3-large</strong></div>
            <div><span>Dimensions</span><strong>3072</strong></div>
            <div><span>Unreachable chunks</span><strong>0</strong></div>
            <div><span>Last reindex</span><strong>Today, 10:42</strong></div>
          </div>
          <div className="divider"></div>
          <div className="card-title" style={{fontSize: 14, marginBottom: 8}}>Where used</div>
          <div className="ai-timeline">
            <div><I.shield size={13}/> Retrieved in 96 protocol runs</div>
            <div><I.sparkle size={13}/> Cited in 214 VERA answers</div>
            <div><I.msg size={13}/> Low-rated VERA answer linked to chunk 42</div>
          </div>
          <div className="row" style={{gap: 8, marginTop: 16}}>
            <button className="btn sm"><I.doc size={12}/> Inspect chunks</button>
            <button className="btn sm primary"><I.refresh size={12}/> Reindex source</button>
          </div>
        </div>
      </div>
    );
  }

  function MemoryManagement() {
    return (
      <div className="ai-context-grid">
        <div className="card">
          <div className="card-head">
            <div>
              <div className="card-title">Memory entries</div>
              <div className="card-sub">Feedback is source provenance, not a new analytics flow</div>
            </div>
            <div className="row">
              <button className="btn sm"><I.filter size={12}/> Source</button>
              <button className="btn sm primary"><I.plus size={12}/> New memory</button>
            </div>
          </div>
          <table className="tbl">
            <thead>
              <tr><th>Memory</th><th>Type</th><th>Status</th><th>Source</th><th>Version</th></tr>
            </thead>
            <tbody>
              {memories.map(memory => (
                <tr key={memory.title} className="row-click">
                  <td>
                    <div style={{fontWeight: 600}}>{memory.title}</div>
                    <div className="muted" style={{fontSize: 11.5}}>{memory.text}</div>
                  </td>
                  <td>{memory.type}</td>
                  <td>{statusBadge(memory.status)}</td>
                  <td className="muted">{memory.source}</td>
                  <td>{memory.version}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <div className="card card-pad ai-detail">
          <div className="row-between" style={{marginBottom: 14}}>
            <div>
              <div className="card-title">Selenium tolerance note</div>
              <div className="muted" style={{fontSize: 12}}>Candidate · episodic memory</div>
            </div>
            {statusBadge(memoryStatus)}
          </div>
          <div className="ai-field"><span>Source</span><strong>protocol_feedback · protocol v3</strong></div>
          <div className="ai-field"><span>Attribution</span><strong>Linn · Jun 27</strong></div>
          <div className="ai-field"><span>Memory text</span><strong>Client reported metallic taste above 150mcg selenium.</strong></div>
          <div className="ai-timeline">
            <div><I.link size={13}/> Linked to HTMA-2025-0112 protocol feedback</div>
            <div><I.clock size={13}/> Candidate created from existing feedback source</div>
            <div><I.shield size={13}/> Requires Platform Admin approval</div>
          </div>
          <div className="row" style={{gap: 8, marginTop: 16}}>
            <button className="btn sm" onClick={() => setMemoryStatus("Rejected")}>Reject</button>
            <button className="btn sm primary" onClick={() => setMemoryStatus("Active")}><I.check size={12}/> Approve</button>
          </div>
        </div>
      </div>
    );
  }

  function RetrievalConfig() {
    return (
      <div className="ai-context-grid">
        <div className="card card-pad">
          <div className="row-between" style={{marginBottom: 16}}>
            <div>
              <div className="card-title">Protocol recommender config</div>
              <div className="muted" style={{fontSize: 12.5}}>Deployment: vykon-protocol v1.4</div>
            </div>
            {statusBadge("Published")}
          </div>
          <div className="config-grid">
            {[
              ["Rules top-k", "10"],
              ["KB max results", "5"],
              ["Similar cases top-k", "5"],
              ["Age tolerance", "5"],
            ].map(([label, value]) => (
              <label className="config-control" key={label}>
                <span>{label}</span>
                <input className="input" defaultValue={value}/>
              </label>
            ))}
          </div>
          <div className="divider"></div>
          <div className="row" style={{gap: 8, justifyContent: "flex-end"}}>
            <button className="btn sm">Save draft</button>
            <button className="btn sm primary">Publish</button>
          </div>
        </div>
        <div className="card">
          <div className="card-head">
            <div>
              <div className="card-title">Config versions</div>
              <div className="card-sub">Settings apply to the next eligible run</div>
            </div>
          </div>
          <table className="tbl">
            <thead>
              <tr><th>Config</th><th>Values</th><th>Status</th><th>Updated</th></tr>
            </thead>
            <tbody>
              {versions.map(row => (
                <tr key={row[0]} className="row-click">
                  <td>{row[0]}</td>
                  <td className="muted">{row[1]}</td>
                  <td>{statusBadge(row[2])}</td>
                  <td className="muted">{row[3]}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <div className="card card-pad ai-detail">
          <div className="card-title" style={{marginBottom: 10}}>VERA retrieval</div>
          <div className="config-grid single">
            <label className="config-control"><span>Retrieval limit</span><input className="input" defaultValue="8"/></label>
            <label className="config-control"><span>Min similarity</span><input className="input" defaultValue="0.50"/></label>
          </div>
          <div className="ai-timeline">
            <div><I.check size={13}/> Values within configured bounds</div>
            <div><I.clock size={13}/> Last published Jun 23 by Platform Admin</div>
            <div><I.refresh size={13}/> Rollback available to prior version</div>
          </div>
        </div>
      </div>
    );
  }

  function AuditLogDrawer({ onClose }) {
    const [filter, setFilter] = useState("All");
    const [expanded, setExpanded] = useState("audit-1");
    const filters = ["All", "Rules", "Knowledge Base", "Memory", "Retrieval", "Publish"];
    const visibleEvents = auditEvents.filter(event => {
      if (filter === "All") return true;
      if (filter === "Retrieval") return event.target.toLowerCase().includes("retrieval") || event.target.toLowerCase().includes("recommender config");
      return event.type === filter;
    });

    return (
      <div className="modal-backdrop" onClick={onClose} style={{justifyContent: "flex-end", padding: 0}}>
        <div className="side-panel ai-audit-panel" onClick={e => e.stopPropagation()}>
          <header>
            <div className="row" style={{gap: 10}}>
              <I.clock size={16}/>
              <div>
                <div style={{fontWeight: 700}}>AI Context Audit Log</div>
                <div className="muted" style={{fontSize: 12}}>History of rule, knowledge, memory, and retrieval changes.</div>
              </div>
            </div>
            <button className="icon-btn" onClick={onClose}><I.x size={16}/></button>
          </header>
          <div className="body ai-audit-body">
            <div className="ai-audit-filters">
              {filters.map(item => (
                <button
                  key={item}
                  className={"chip" + (filter === item ? " green" : "")}
                  onClick={() => setFilter(item)}
                >
                  {item}
                </button>
              ))}
            </div>

            <div className="ai-audit-list">
              {visibleEvents.map(event => {
                const isExpanded = expanded === event.id;
                return (
                  <div key={event.id} className={"ai-audit-event" + (isExpanded ? " expanded" : "")}>
                    <button className="ai-audit-event-head" onClick={() => setExpanded(isExpanded ? null : event.id)}>
                      <div>
                        <div className="row" style={{gap: 8, marginBottom: 5, flexWrap: "wrap"}}>
                          <span className="chip">{event.type}</span>
                          {statusBadge(event.status)}
                        </div>
                        <strong>{event.title}</strong>
                        <small>{event.target} · {event.version}</small>
                      </div>
                      <I.chevD size={15}/>
                    </button>
                    <div className="ai-audit-event-meta">
                      <span>{event.actor}</span>
                      <span>{event.time}</span>
                    </div>
                    <p>{event.note}</p>

                    {isExpanded && (
                      <div className="ai-audit-detail">
                        <div><span>Before</span><strong>{event.before}</strong></div>
                        <div><span>After</span><strong>{event.after}</strong></div>
                        <div><span>Provenance</span><strong>{event.provenance}</strong></div>
                        <div><span>Where-used impact</span><strong>{event.impact}</strong></div>
                        <div>
                          <span>References</span>
                          <div className="permission-tags">
                            {event.refs.map(ref => <em key={ref}>{ref}</em>)}
                          </div>
                        </div>
                        <div className="row" style={{gap: 8, marginTop: 4}}>
                          <button className="btn sm"><I.externalLink size={12}/> Open target</button>
                          <button className="btn sm"><I.doc size={12}/> View diff</button>
                          {event.status === "Published" && <button className="btn sm"><I.refresh size={12}/> Rollback</button>}
                        </div>
                      </div>
                    )}
                  </div>
                );
              })}
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="page ai-context-page" data-screen-label="AI Context">
      <GovernanceHeader/>
      <OverviewStrip/>

      <div className="ai-tabs" role="tablist" aria-label="AI Context sections">
        {tabs.map(tab => (
          <button
            key={tab.k}
            className={"ai-tab" + (section === tab.k ? " active" : "")}
            onClick={() => setSection(tab.k)}
          >
            {tab.icon}<span>{tab.label}</span>
          </button>
        ))}
      </div>

      {section === "rules" && <RuleRegistry/>}
      {section === "knowledge" && <KnowledgeBase/>}
      {section === "memory" && <MemoryManagement/>}
      {section === "retrieval" && <RetrievalConfig/>}
      {auditOpen && <AuditLogDrawer onClose={() => setAuditOpen(false)}/>}
    </div>
  );
}

Object.assign(window, { AIContextPage });
