// ═══════════════════════════════════════════════════════════════════
// ASSET CLASSES — the platform's SPECIFICATION AXIS.
// One canonical class list (the ontology's six Asset class-field
// bundles, discriminated by A01 · ASSET_CLASS) that every spec layer
// extends over its universal core:
//   · Ontology         — the Asset's class-field datapoint bundle
//   · Datapoint Register — those same fields in the register
//   · Report Schema     — the RS-10/11/12 class extensions
//   · Workflow          — the steps the class-specific cards bind to
// A project is BOUND to exactly one class (A01); the binding selects
// which extension each layer applies. The security wrapper (C04 ·
// SECURITY_TYPE) is ORTHOGONAL — any class can be tokenized.
// ═══════════════════════════════════════════════════════════════════
(function () {
  const S = window.ONTOLOGY;
  const RS = window.REPORT_SCHEMA;
  const AC = window.AssetClass;

  // ── canonical registry: join report class ⇄ ontology bundle ⇄ projects
  // ── the axis index reads the ROOT class list from the ontology, then
  // joins what each aspect owns: report sections (Report Schema) and the
  // research branch (Workflow Templates, read live at render). Owns nothing.
  const CLASSES = ((S.ASSET_CLASSES) || []).map((c) => {
    const groups = (RS.groupsForClass(c.id) || []).filter((g) => g.classSpecific);
    const steps = [];
    groups.forEach((g) => g.subs.forEach((s) => s.cards.forEach(([, , st]) => { if (steps.indexOf(st) < 0) steps.push(st); })));
    const cards = groups.reduce((n, g) => n + g.subs.reduce((m, s) => m + s.cards.length, 0), 0);
    return { ...c, ontology: c.group, bundle: { label: c.name, group: c.group, codes: c.codes }, fieldCodes: c.codes, groups, steps, cards };
  });
  const byId = (id) => CLASSES.find((c) => c.id === id) || CLASSES[0];

  function projectsFor(classId) {
    const ps = (window.INTEL && window.INTEL.PROJECTS) || [];
    return ps.filter((p) => AC.of(p) === classId);
  }

  window.ASSET_AXIS = { CLASSES, byId, of: (p) => AC.of(p), set: (id, c) => AC.set(id, c), projectsFor };

  // ── shared bits ────────────────────────────────────────────────────
  const REQ_TONE = { Required: "accent", Recommended: "info", Optional: "neutral", Auto: "ok", Internal: "warn" };
  const STEP_LABEL = { parse: "01 · Parse", extract: "01 · Extract", kb: "01 · Knowledge Base", kg: "01 · Knowledge Graph", entity: "01 · Entity Registry", background: "02 · Background", crosscheck: "02 · Cross-check", market: "02 · Market", gaps: "02 · Gaps", compose: "03 · Compose", review: "03 · Review", publish: "03 · Publish" };
  const SLOT = [["subject", "Subject · RS-10"], ["instrument", "Instrument · RS-11"], ["underwriting", "Underwriting · RS-12"]];
  const mono = (s, extra) => <span style={{ fontFamily: "var(--mono)", fontSize: "8.5px", letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--ink-4)", ...extra }}>{s}</span>;
  const LAYER = [
    { k: "ontology", label: "Ontology", glyph: "⬡", note: "Asset class-field bundle" },
    { k: "register", label: "Datapoint Register", glyph: "☲", note: "those fields, in the register" },
    { k: "report", label: "Report Schema", glyph: "⊞", note: "RS-10 / 11 / 12 extensions" },
    { k: "workflow", label: "Workflow", glyph: "⟳", note: "3 dedicated phases · class-specialized" },
  ];

  function LinkBtn({ label, onClick }) {
    return (
      <button onClick={onClick} style={{ border: "1px solid var(--accent-bd)", background: "var(--accent-bg)", color: "var(--accent-lo)", borderRadius: "var(--r-2)", padding: "6px 11px", cursor: "pointer", fontFamily: "var(--mono)", fontSize: "9px", fontWeight: 600, letterSpacing: "0.06em", textTransform: "uppercase", whiteSpace: "nowrap" }}>{label}</button>
    );
  }

  // ═══ the platform page ═════════════════════════════════════════════
  function AssetClassesPage({ proj, go }) {
    const T = window.WORKFLOW_TEMPLATE;
    const research = (id) => (T && T.branchFor ? T.branchFor(id).length : 0);
    const liveTotal = CLASSES.reduce((n, x) => n + projectsFor(x.id).length, 0);
    const sec = (S.DISCRIMINATOR_VOCAB && S.DISCRIMINATOR_VOCAB.SECURITY_TYPE) || null;

    const Cell = ({ route, primary, sub, on }) => (
      <button onClick={() => go(route)} title="Open source ↗" style={{ display: "block", width: "100%", textAlign: "left", border: "none", background: on ? "var(--accent-bg)" : "var(--bg)", padding: "10px 12px", cursor: "pointer" }}
        onMouseEnter={(ev) => (ev.currentTarget.style.background = "var(--bg-2)")} onMouseLeave={(ev) => (ev.currentTarget.style.background = on ? "var(--accent-bg)" : "var(--bg)")}>
        <div style={{ fontSize: "var(--fs-xs)", color: "var(--ink-2)", lineHeight: 1.4 }}>{primary}</div>
        <div style={{ fontFamily: "var(--mono)", fontSize: "8.5px", color: "var(--ink-4)", marginTop: 3 }}>{sub} ↗</div>
      </button>
    );

    return (
      <div>
        <window.PageHead eyebrow="Platform · Specification axis" title="Asset Classes"
          sub="The index of the axis — for each class, what every specification layer contributes. This page owns no configuration: the cells summarize and link to the four sources of truth — the Ontology, the Datapoint Register, the Report Schema and the Workflow Templates. A project bound to a class inherits that whole column."
          right={<div style={{ textAlign: "right" }}>
            {mono(CLASSES.length + " classes · 4 sources of truth", { display: "block", marginBottom: 4, color: "var(--accent-lo)" })}
            {mono(liveTotal + " bound project" + (liveTotal === 1 ? "" : "s"))}
          </div>}>
        </window.PageHead>

        <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 1, background: "var(--rule)", border: "1px solid var(--rule-hard)", borderRadius: "var(--r-3)", overflow: "hidden", marginBottom: 12 }}>
          {[["⬡", "Ontology", "kgref", "Asset class-field bundle"], ["☲", "Datapoint Register", "kbref", "class-field datapoints"], ["⊞", "Report Schema", "rptref", "RS-10 / 11 / 12 extensions"], ["⟳", "Workflow Templates", "wftpl", "phase-02 research branch"]].map(([g, label, route, note]) => (
            <button key={route} onClick={() => go(route)} style={{ textAlign: "left", border: "none", background: "var(--bg)", padding: "12px 14px", cursor: "pointer" }}>
              <div style={{ display: "flex", alignItems: "center", gap: 7, marginBottom: 5 }}>
                <span style={{ fontSize: 13, color: "var(--accent-lo)" }}>{g}</span>
                <span style={{ fontFamily: "var(--ui-display)", fontWeight: 600, fontSize: "var(--fs-sm)", color: "var(--ink)" }}>{label}</span>
                <span style={{ marginLeft: "auto", fontFamily: "var(--mono)", fontSize: "10px", color: "var(--ink-4)" }}>↗</span>
              </div>
              <div style={{ fontFamily: "var(--mono)", fontSize: "8.5px", letterSpacing: "0.04em", color: "var(--ink-4)", lineHeight: 1.5 }}>source of truth</div>
              <div style={{ fontSize: "var(--fs-xs)", color: "var(--ink-3)", marginTop: 3, lineHeight: 1.4 }}>{note}</div>
            </button>
          ))}
        </div>
        {sec && (
          <div style={{ display: "flex", alignItems: "center", gap: 9, border: "1px dashed var(--rule-hard)", borderRadius: "var(--r-2)", background: "var(--bg-2)", padding: "9px 13px", marginBottom: 22 }}>
            <span style={{ fontFamily: "var(--mono)", fontSize: "9px", fontWeight: 600, letterSpacing: "0.06em", textTransform: "uppercase", color: "var(--ink-3)" }}>Orthogonal</span>
            <span style={{ fontFamily: "var(--mono)", fontSize: "9px", color: "var(--accent-lo)" }}>{sec.code} · SECURITY_TYPE</span>
            <span style={{ fontSize: "var(--fs-xs)", color: "var(--ink-3)" }}>the {sec.label} is chosen independently of the asset class — every class can be issued as a tokenized security.</span>
          </div>
        )}

        <window.SectionHead sub="each cell summarizes that source's contribution for the class and links to it — this page never duplicates the source">Axis Matrix</window.SectionHead>
        <div style={{ border: "1px solid var(--rule-hard)", borderRadius: "var(--r-3)", overflow: "hidden" }}>
          <div style={{ display: "grid", gridTemplateColumns: "200px repeat(4, 1fr) 96px", gap: 1, background: "var(--rule)" }}>
            {["Asset class", "Ontology", "Datapoint Register", "Report Schema", "Workflow Templates", "Projects"].map((h) => (
              <div key={h} style={{ background: "var(--bg-2)", padding: "8px 12px" }}><window.MonoLabel>{h}</window.MonoLabel></div>
            ))}
            {CLASSES.map((x) => {
              const bound = proj && AC.of(proj) === x.id;
              const xp = projectsFor(x.id);
              return (
                <React.Fragment key={x.id}>
                  <div style={{ background: bound ? "var(--accent-bg)" : "var(--bg)", padding: "10px 12px", borderLeft: bound ? "2px solid var(--accent)" : "2px solid transparent" }}>
                    <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                      <span style={{ fontSize: 14, color: "var(--accent-lo)" }}>{x.glyph}</span>
                      <span style={{ fontFamily: "var(--ui-display)", fontWeight: 600, fontSize: "var(--fs-sm)", color: "var(--ink)" }}>{x.name}</span>
                    </div>
                    {bound && <div style={{ marginTop: 4 }}><window.Pill tone="accent">bound · this project</window.Pill></div>}
                  </div>
                  <Cell route="kgref" on={bound} primary={x.bundle.label} sub={x.fieldCodes.length + " class fields"} />
                  <Cell route="kbref" on={bound} primary={"+" + x.fieldCodes.length + " class datapoints"} sub="in the register" />
                  <Cell route="rptref" on={bound} primary={"RS-10 / 11 / 12 · " + x.cards + " cards"} sub="3 class sections" />
                  <Cell route="wftpl" on={bound} primary={research(x.id) + " research tasks · phase 02"} sub="instantiated per project" />
                  <div style={{ background: bound ? "var(--accent-bg)" : "var(--bg)", padding: "10px 12px" }}>
                    {xp.length ? <window.Pill tone="ok">{xp.length} bound</window.Pill> : <window.Pill tone="neutral">template</window.Pill>}
                  </div>
                </React.Fragment>
              );
            })}
          </div>
        </div>

        <p style={{ margin: "14px 0 0", fontFamily: "var(--mono)", fontSize: "9px", letterSpacing: "0.06em", color: "var(--ink-4)", lineHeight: 1.7 }}>
          One canonical list, sourced from the ontology's A01 · ASSET_CLASS discriminator. To add a class you declare it in each source — its class-field bundle (Ontology · Datapoint Register), its three report sections (Report Schema) and its research branch (Workflow Templates) — then bind a project. This page only indexes them.
        </p>
      </div>
    );
  }

  // ═══ project-side strip — shows the bound class + applied extensions ═
  function ClassStrip({ proj, go }) {
    if (!proj) return null;
    const c = byId(AC.of(proj));
    const chip = (label) => <span style={{ fontFamily: "var(--mono)", fontSize: "8.5px", letterSpacing: "0.03em", color: "var(--ink-2)", border: "1px solid var(--rule)", background: "var(--bg)", borderRadius: "var(--r-1)", padding: "3px 7px", whiteSpace: "nowrap" }}>{label}</span>;
    return (
      <div style={{ display: "flex", alignItems: "center", gap: 12, flexWrap: "wrap", border: "1px solid var(--rule-hard)", borderLeft: "2px solid var(--accent)", borderRadius: "var(--r-2)", background: "var(--bg)", padding: "8px 13px", marginBottom: 16 }}>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 7 }}>
          <span style={{ fontFamily: "var(--mono)", fontSize: "8.5px", fontWeight: 600, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--ink-4)" }}>Asset class</span>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontFamily: "var(--ui-display)", fontWeight: 600, fontSize: "var(--fs-sm)", color: "var(--ink)" }}>
            <span style={{ color: "var(--accent-lo)" }}>{c.glyph}</span>{c.name}
          </span>
        </span>
        <span style={{ width: 1, height: 16, background: "var(--rule)" }}></span>
        <span style={{ fontFamily: "var(--mono)", fontSize: "8.5px", fontWeight: 600, letterSpacing: "0.06em", textTransform: "uppercase", color: "var(--ink-4)" }}>Specification applied</span>
        <span style={{ display: "inline-flex", gap: 6, flexWrap: "wrap" }}>
          {chip("Ontology · +" + c.fieldCodes.length + " fields")}
          {chip("Report · RS-10 / 11 / 12")}
          {chip("Workflow · " + c.steps.length + " steps")}
        </span>
        {go && (
          <button onClick={() => go("classes")} style={{ marginLeft: "auto", border: "1px solid var(--accent-bd)", background: "var(--accent-bg)", color: "var(--accent-lo)", borderRadius: "var(--r-2)", padding: "5px 10px", cursor: "pointer", fontFamily: "var(--mono)", fontSize: "8.5px", fontWeight: 600, letterSpacing: "0.06em", textTransform: "uppercase", whiteSpace: "nowrap" }}>View axis ↗</button>
        )}
      </div>
    );
  }

  window.AssetClassesPage = AssetClassesPage;
  window.ClassStrip = ClassStrip;
})();
