/* @jsxRuntime classic */
/* @jsx React.createElement */
// Orchestra — Context Sources view  (R39 phase 1, task 86bak5e4v)
// Read-only visualisation of Agent → Skill → Source.
//
// Self-contained: loaded by index.html as its own <script type="text/babel">,
// exposes window.ContextSourcesPage, and is rendered by app.jsx's page switch.
// No editing, no persistence, no API calls, no live connectors — the source
// bindings below are a static phase-1 model. Agents/skills themselves come from
// the live /api/agents data (seed_agents) passed in as a prop; only the
// source bindings are hard-coded here.
// ─────────────────────────────────────────────────────────────────────────────

(function () {
  const { useState, useEffect, useMemo } = React;

  // ── Source catalog ────────────────────────────────────────────────────────
  // "native" = the in-app surface an agent type works in (its KB). "external" =
  // an outside system referenced as a secondary source. R42 builds the native
  // surfaces for real; R40 enforces boundaries; this pass only names them.
  const SOURCES = {
    "ns-req":       { id: "ns-req",       name: "Requirements & Documentation", kind: "native",
                      blurb: "The BA/enablement working surface — requirements, acceptance criteria, process docs." },
    "ns-design":    { id: "ns-design",    name: "Design & Architecture", kind: "native",
                      blurb: "Solution and data design surface — technical designs, schema, integration patterns." },
    "ns-tasks":     { id: "ns-tasks",     name: "Task Management", kind: "native",
                      blurb: "Build/test working surface — configuration, code, defects, test plans." },
    "ns-project":   { id: "ns-project",   name: "Project Management", kind: "native",
                      blurb: "Delivery surface — dependencies, risks, status, scope, release readiness." },
    "ns-analytics": { id: "ns-analytics", name: "Delivery Analytics", kind: "native",
                      blurb: "Workflow configuration and run history the meta-agents analyse." },
    // External secondaries (illustrative — show the shared-source / facet model).
    "ext-jira":     { id: "ext-jira",     name: "Jira", kind: "external",
                      blurb: "External project tracker. Referenced for dependencies and estimates." },
    "ext-sf":       { id: "ext-sf",       name: "Salesforce Org Metadata", kind: "external",
                      blurb: "The target org's schema, automations, and security model (read-only)." },
    "ext-conf":     { id: "ext-conf",     name: "Confluence", kind: "external",
                      blurb: "External knowledge base for process docs and published developer documentation." },
  };

  // Primary source per agent — the in-app native surface for that agent type.
  // Every skill of the agent inherits this as its primary (read+write) KB.
  const PRIMARY_BY_AGENT = {
    ba: "ns-req", trainer: "ns-req",
    sa: "ns-design", da: "ns-design",
    dev: "ns-tasks", qa: "ns-tasks",
    pm: "ns-project", exec: "ns-project", rm: "ns-project",
    advisor: "ns-analytics", finops: "ns-analytics",
  };
  const FALLBACK_PRIMARY = "ns-project";

  // Illustrative secondary sources, keyed by skill id. Direction is read |
  // write | read+write. Several sources are shared across skills at different
  // facets (e.g. Jira: dependency tracking vs. estimates) to show the model.
  const SECONDARY_BY_SKILL = {
    "ba-1":  [{ source: "ext-conf", direction: "read",  facet: "Existing process & requirement docs" }],
    "dev-3": [{ source: "ext-conf", direction: "write", facet: "Publish developer documentation" }],
    "sa-2":  [{ source: "ext-sf",   direction: "read",  facet: "Security model: profiles, permission sets, FLS" }],
    "da-1":  [{ source: "ext-sf",   direction: "read",  facet: "Object schema & relationships" }],
    "pm-1":  [{ source: "ext-jira", direction: "read",  facet: "Dependency & blocker tracking" }],
    "fin-2": [{ source: "ext-jira", direction: "read",  facet: "Effort estimates & actuals" }],
  };

  const DIR_BADGE = { "read": "badge-blue", "write": "badge-gold", "read+write": "badge-green" };

  // ── Derive the model from live agents + the static bindings ────────────────
  function buildModel(agents) {
    // skillSources: skillId -> [{ source, direction, facet, primary }]
    // sourceUsage:  sourceId -> [{ agentId, agentRole, skillId, skillName, facet, direction, primary }]
    const skillSources = {};
    const sourceUsage = {};
    (agents || []).forEach((agent) => {
      const primaryId = PRIMARY_BY_AGENT[agent.id] || FALLBACK_PRIMARY;
      (agent.skills || []).forEach((sk) => {
        const list = [];
        const primary = { source: SOURCES[primaryId], direction: "read+write",
                          facet: "Working knowledge base", primary: true };
        list.push(primary);
        (SECONDARY_BY_SKILL[sk.id] || []).forEach((b) => {
          if (SOURCES[b.source]) list.push({ source: SOURCES[b.source], direction: b.direction, facet: b.facet, primary: false });
        });
        skillSources[sk.id] = list;
        list.forEach((binding) => {
          (sourceUsage[binding.source.id] = sourceUsage[binding.source.id] || []).push({
            agentId: agent.id, agentRole: agent.role, skillId: sk.id, skillName: sk.name,
            facet: binding.facet, direction: binding.direction, primary: binding.primary,
          });
        });
      });
    });
    return { skillSources, sourceUsage };
  }

  // ── Small presentational helpers ───────────────────────────────────────────
  function DirBadge({ direction }) {
    return React.createElement("span", { className: `badge ${DIR_BADGE[direction] || "badge-gray"}` }, direction);
  }
  function KindBadge({ kind }) {
    return React.createElement("span", { className: `badge ${kind === "native" ? "badge-gray" : "badge-blue"}` }, kind);
  }

  // ── Component ──────────────────────────────────────────────────────────────
  function ContextSourcesPage({ agents }) {
    const [selAgentId, setSelAgentId] = useState(null);
    const [selSourceId, setSelSourceId] = useState(null);

    useEffect(() => { injectStyles(); }, []);

    const model = useMemo(() => buildModel(agents), [agents]);
    const selAgent = (agents || []).find((a) => a.id === selAgentId) || null;
    const selSource = selSourceId ? SOURCES[selSourceId] : null;

    const pickAgent = (id) => { setSelSourceId(null); setSelAgentId((cur) => (cur === id ? null : id)); };
    const pickSource = (id) => setSelSourceId(id);

    if (!agents || !agents.length) {
      return React.createElement("div", { className: "cs-root" },
        React.createElement("div", { className: "cs-empty" }, "No agents loaded."));
    }

    return (
      <div className="cs-root">
        <div className="cs-head">
          <div className="cs-title">Context Sources</div>
          <div className="cs-sub">
            A read-only map of <b>Agent → Skill → Source</b>. Each skill has one <b>primary source</b> (its
            knowledge base) plus any secondary sources. Select an agent to see its skills and their sources;
            select a source to see which skills use it and at what facet.
          </div>
          <div className="cs-legend">
            <div className="cs-legend-group">
              <span className="cs-legend-label">Direction</span>
              <DirBadge direction="read" /><DirBadge direction="write" /><DirBadge direction="read+write" />
            </div>
            <div className="cs-legend-group">
              <span className="cs-legend-label">Source</span>
              <KindBadge kind="native" /><KindBadge kind="external" />
              <span className="badge badge-gold">primary</span>
            </div>
          </div>
        </div>

        <div className="cs-layout">
          {/* Agents column */}
          <div className="cs-col-agents">
            {agents.map((agent) => {
              const primary = SOURCES[PRIMARY_BY_AGENT[agent.id] || FALLBACK_PRIMARY];
              return (
                <div key={agent.id}
                  className={`cs-agent ${agent.id === selAgentId && !selSource ? "active" : ""}`}
                  onClick={() => pickAgent(agent.id)}>
                  <div className="cs-agent-head">
                    <div className="agent-avatar" style={{ background: agent.color || "#273558", color: "#fff", width: 26, height: 26 }}>
                      {agent.initials || (agent.role || "").slice(0, 2).toUpperCase()}
                    </div>
                    <div className="cs-agent-name">{agent.role}</div>
                    {agent.meta && <span className="badge badge-blue" style={{ fontSize: "0.62rem" }}>Meta</span>}
                  </div>
                  <div className="cs-agent-meta">
                    {(agent.skills || []).length} skills · primary: {primary ? primary.name : "—"}
                  </div>
                </div>
              );
            })}
          </div>

          {/* Detail column */}
          <div className="cs-col-detail">
            {selSource
              ? renderSourceDetail(selSource, model, () => setSelSourceId(null), pickAgent)
              : selAgent
                ? renderAgentDetail(selAgent, model, pickSource)
                : renderDefault(model, pickSource)}
          </div>
        </div>
      </div>
    );
  }

  // ── Detail renderers ───────────────────────────────────────────────────────
  function SourceRow({ binding, onClick, selected }) {
    const cls = `cs-source ${binding.primary ? "primary" : ""} ${selected ? "sel" : ""}`;
    return (
      <div className={cls} onClick={onClick}>
        <div className="cs-source-main">
          <span className="cs-source-name">{binding.source.name}</span>
          <span className="cs-source-facet">· {binding.facet}</span>
        </div>
        <div className="cs-source-tags">
          {binding.primary && <span className="badge badge-gold">primary</span>}
          <KindBadge kind={binding.source.kind} />
          <DirBadge direction={binding.direction} />
        </div>
      </div>
    );
  }

  function renderAgentDetail(agent, model, pickSource) {
    return (
      <div>
        <div className="cs-detail-title">{agent.role} — skills &amp; sources</div>
        {(agent.skills || []).map((sk) => (
          <div key={sk.id} className="cs-skill">
            <div className="cs-skill-name">{sk.name}</div>
            {(model.skillSources[sk.id] || []).map((binding, i) => (
              <SourceRow key={i} binding={binding} onClick={() => pickSource(binding.source.id)} />
            ))}
          </div>
        ))}
      </div>
    );
  }

  function renderSourceDetail(source, model, onBack, pickAgent) {
    const usages = model.sourceUsage[source.id] || [];
    return (
      <div>
        <div className="cs-back">
          <button className="btn btn-outline btn-sm" onClick={onBack}>← Back</button>
        </div>
        <div className="row" style={{ gap: 8, flexWrap: "wrap" }}>
          <div className="cs-detail-title" style={{ margin: 0 }}>{source.name}</div>
          <KindBadge kind={source.kind} />
        </div>
        <div className="text-muted" style={{ marginTop: 6, marginBottom: 16, lineHeight: 1.5 }}>{source.blurb}</div>
        <div className="inspector-section-title">
          Used by {usages.length} skill{usages.length === 1 ? "" : "s"}
        </div>
        {usages.length === 0 && <div className="cs-empty">No skills use this source.</div>}
        {usages.map((u, i) => (
          <div key={i} className="cs-usage">
            <div className="row-between" style={{ alignItems: "flex-start", flexWrap: "wrap", gap: 8 }}>
              <div style={{ minWidth: 0 }}>
                <div style={{ fontSize: "0.84rem", fontWeight: 600 }}>{u.skillName}</div>
                <div className="text-xs" style={{ marginTop: 3, cursor: "pointer" }}
                  onClick={() => pickAgent(u.agentId)}>{u.agentRole}</div>
                <div className="cs-source-facet" style={{ marginTop: 5 }}>{u.facet}</div>
              </div>
              <div className="cs-source-tags">
                {u.primary && <span className="badge badge-gold">primary</span>}
                <DirBadge direction={u.direction} />
              </div>
            </div>
          </div>
        ))}
      </div>
    );
  }

  function renderDefault(model, pickSource) {
    const sources = Object.keys(SOURCES).map((id) => SOURCES[id]);
    return (
      <div>
        <div className="cs-empty" style={{ paddingBottom: 20 }}>
          Select an agent on the left to see its skills and their sources — or pick a source below.
        </div>
        <div className="inspector-section-title">All sources</div>
        {sources.map((src) => {
          const count = (model.sourceUsage[src.id] || []).length;
          return (
            <div key={src.id} className="cs-source" onClick={() => pickSource(src.id)}>
              <div className="cs-source-main">
                <span className="cs-source-name">{src.name}</span>
                <span className="cs-source-facet">· {count} skill{count === 1 ? "" : "s"}</span>
              </div>
              <div className="cs-source-tags"><KindBadge kind={src.kind} /></div>
            </div>
          );
        })}
      </div>
    );
  }

  // ── Scoped styles (matches app.jsx's CSS-injection pattern) ────────────────
  function injectStyles() {
    if (document.getElementById("cs-styles")) return;
    const el = document.createElement("style");
    el.id = "cs-styles";
    el.textContent = `
.cs-root { height:100%; overflow-y:auto; overflow-x:hidden; padding:24px; }
.cs-head { margin-bottom:18px; }
.cs-title { font-weight:600; font-size:1.05rem; }
.cs-sub { font-size:0.82rem; color:#748090; margin-top:5px; line-height:1.55; max-width:720px; }
.cs-sub b { color:#e8e6df; }
.cs-legend { display:flex; flex-wrap:wrap; gap:18px; align-items:center; margin-top:14px;
  padding:11px 14px; background:#0f1525; border:1px solid #1b2640; border-radius:10px; }
.cs-legend-group { display:flex; align-items:center; gap:7px; flex-wrap:wrap; }
.cs-legend-label { font-size:0.62rem; text-transform:uppercase; letter-spacing:0.09em; color:#344054; font-weight:600; }
.cs-layout { display:flex; gap:16px; align-items:flex-start; }
.cs-col-agents { width:300px; min-width:240px; flex-shrink:0; display:flex; flex-direction:column; gap:10px; }
.cs-col-detail { flex:1; min-width:0; }
.cs-agent { background:#0f1525; border:1px solid #1b2640; border-radius:10px; padding:12px 14px;
  cursor:pointer; transition:all 0.15s; }
.cs-agent:hover { border-color:#4a5568; }
.cs-agent.active { border-color:#c8a84a; }
.cs-agent-head { display:flex; align-items:center; gap:9px; }
.cs-agent-name { font-weight:600; font-size:0.88rem; }
.cs-agent-meta { font-size:0.74rem; color:#344054; margin-top:7px; }
.cs-detail-title { font-weight:600; font-size:0.95rem; margin-bottom:14px; }
.cs-skill { background:#0f1525; border:1px solid #1b2640; border-radius:10px; padding:14px; margin-bottom:12px; }
.cs-skill-name { font-weight:600; font-size:0.86rem; margin-bottom:10px; }
.cs-source { display:flex; align-items:center; justify-content:space-between; gap:10px; flex-wrap:wrap;
  background:#172038; border:1px solid #1b2640; border-radius:8px; padding:9px 11px; margin-bottom:7px;
  cursor:pointer; transition:all 0.15s; }
.cs-source:hover { border-color:#4a5568; }
.cs-source.primary { border-color:#c8a84a; background:rgba(200,168,74,0.06); }
.cs-source.sel { box-shadow:0 0 0 1px #c8a84a; }
.cs-source-main { display:flex; align-items:center; gap:7px; min-width:0; flex-wrap:wrap; }
.cs-source-name { font-size:0.83rem; font-weight:500; }
.cs-source-facet { font-size:0.75rem; color:#748090; }
.cs-source-tags { display:flex; gap:6px; align-items:center; flex-wrap:wrap; }
.cs-usage { background:#0f1525; border:1px solid #1b2640; border-radius:9px; padding:11px 13px; margin-bottom:8px; }
.cs-empty { padding:36px 20px; text-align:center; color:#344054; font-size:0.85rem; line-height:1.6; }
.cs-back { margin-bottom:14px; }
@media (max-width:900px) {
  .cs-root { padding:16px; }
  .cs-layout { flex-direction:column; }
  .cs-col-agents { width:100%; min-width:0; }
  .cs-col-detail { width:100%; }
}
`;
    document.head.appendChild(el);
  }

  // Expose for app.jsx's page switch (separate text/babel scripts don't share scope).
  window.ContextSourcesPage = ContextSourcesPage;
})();
