/* OpenMAO docs site — brand-faithful docs shell rendering the REAL doc content
   from the repo (NORTH_STAR.md, VOCABULARY.md, README quickstart).
   The repo ships these as Markdown; no docs website exists. This is the shell. */
const { useState, useEffect } = React;
const MARK_L = "/assets/openmao-mark.png";
const MARK_D = "/assets/openmao-mark-transparent.png";

const ICON_CACHE = {};
function iconSvg(name, size) {
  const key = name + ":" + size;
  if (ICON_CACHE[key] != null) return ICON_CACHE[key];
  let html = "";
  if (window.lucide) {
    const tmp = document.createElement("span");
    tmp.innerHTML = '<i data-lucide="' + name + '"></i>';
    document.body.appendChild(tmp);
    window.lucide.createIcons();
    const svg = tmp.querySelector("svg");
    if (svg) { svg.setAttribute("width", size); svg.setAttribute("height", size); html = svg.outerHTML; }
    document.body.removeChild(tmp);
  }
  ICON_CACHE[key] = html;
  return html;
}
function Icon({ name, size, cls }) {
  return <span className={cls} style={{ display: "inline-flex", alignItems: "center" }} dangerouslySetInnerHTML={{ __html: iconSvg(name, size || 16) }} />;
}

const NAV = [
  { grp: "Overview", items: [["north-star", "North Star"], ["readme", "Introduction"]] },
  { grp: "Concepts", items: [["vocabulary", "Vocabulary"], ["flywheel", "The Flywheel"], ["autonomy", "The Autonomy Dial"]] },
  { grp: "Guides", items: [["quickstart", "Quickstart"], ["console", "Operator Console"]] },
  { grp: "Reference", items: [["contracts", "Contract Models"], ["cli", "CLI"]] },
];

/* ---- Page renderers: real repo content ---- */
function NorthStar() {
  return (
    <div className="doc">
      <h1>North Star</h1>
      <p className="doc-lede">Why OpenMAO exists and where it is going. The canonical direction document — read this first.</p>
      <blockquote>Organizations that run themselves, accountably.</blockquote>
      <p>OpenMAO is the open, self-hostable substrate for self-correcting organizations, where the human role can recede from operator to board as the system earns trust. The human does not disappear; the human moves up: from doing the work, to approving the work, to governing the organization that does the work.</p>
      <div className="callout"><span className="ci"><Icon name="compass" size={18} /></span><p>The one-line litmus for every decision: does this strengthen an organization's ability to run itself accountably, and does it earn autonomy on audited evidence rather than assume it?</p></div>
      <h2 id="flywheel">The Flywheel</h2>
      <p>OpenMAO is one mechanism seen from several sides. The product is the loop, not the parts.</p>
      <table className="doc-table">
        <thead><tr><th>Stage</th><th>Role in the loop</th></tr></thead>
        <tbody>
          <tr><td>Governance &amp; enforcement</td><td>Makes actions safe, bounded, and non-bypassable for real side effects.</td></tr>
          <tr><td>Institutional memory</td><td>Promotes evidence-backed knowledge into collective truth. The compounding asset.</td></tr>
          <tr><td>Self-correction</td><td>Turns memory and outcomes into better future decisions.</td></tr>
          <tr><td>Self-learning</td><td>Improves the organization's own roles, policies, workflows, and capabilities.</td></tr>
          <tr><td>Audit &amp; world model</td><td>Records what happened, replayably, as the evidence base for trust.</td></tr>
        </tbody>
      </table>
      <h2 id="principles">Principles</h2>
      <ul>
        <li><strong>Accountability before autonomy.</strong> Build audit, enforcement, and reversibility before widening the dial.</li>
        <li><strong>Enforcement, not etiquette.</strong> Real side effects are governed only when the perimeter is non-bypassable.</li>
        <li><strong>Integrate, do not fuse.</strong> External frameworks are interchangeable workers under OpenMAO authority.</li>
        <li><strong>The organization owns its asset.</strong> Memory, structure, and audit history stay portable and self-hostable.</li>
      </ul>
    </div>
  );
}

function Vocabulary() {
  return (
    <div className="doc">
      <h1>Vocabulary</h1>
      <p className="doc-lede">OpenMAO uses native names for its organizational substrate. This page maps product vocabulary to the contract model names.</p>
      <h2 id="types">Canonical types</h2>
      <table className="doc-table">
        <thead><tr><th>Concept</th><th>Type</th><th>Notes</th></tr></thead>
        <tbody>
          <tr><td>Organization</td><td><code>Organization</code></td><td>Holds mission, vision, values, goals, and <code>autonomy_level</code>.</td></tr>
          <tr><td>Unit of work</td><td><code>WorkItem</code></td><td>Accountable: owner, reviewer, criteria, risk, gates.</td></tr>
          <tr><td>Delegated task</td><td><code>TaskEnvelope</code></td><td>Bounded handoff between spine and agent.</td></tr>
          <tr><td>Capability</td><td><code>Capability</code></td><td>Governed declaration of a tool action with schema, risk, approval.</td></tr>
          <tr><td>Memory entry</td><td><code>MemoryEntry</code></td><td>Scope is <code>individual</code> or <code>collective</code>.</td></tr>
          <tr><td>Approval</td><td><code>ApprovalRequest</code></td><td>Resumes a run or applies without a run.</td></tr>
          <tr><td>Audit event</td><td><code>Event</code></td><td>Workspace-local <code>seq</code>, optional <code>run_seq</code>.</td></tr>
          <tr><td>Operational view</td><td><code>WorldModelSnapshot</code></td><td>Materialized projection from events; cache only.</td></tr>
        </tbody>
      </table>
      <h2 id="splits">Notable splits</h2>
      <h3 id="task-split">Task → WorkItem + TaskEnvelope</h3>
      <p>OpenMAO splits "task" into two types because they answer different questions. <code>WorkItem</code> is <em>what</em> must be done and outlives any single attempt; <code>TaskEnvelope</code> is <em>how</em> a piece of work is handed to an agent for one run.</p>
      <div className="callout warn"><span className="ci"><Icon name="git-fork" size={18} /></span><p>One <code>WorkItem</code> can produce many <code>TaskEnvelope</code>s across retries or re-delegations.</p></div>
      <h3 id="event-split">WorldModelEvent → Event + WorldModelSnapshot</h3>
      <p><code>Event</code> is the durable atomic record of something that happened. <code>WorldModelSnapshot</code> is a materialized projection over events — a cache, never a source of truth. The world model never writes events.</p>
    </div>
  );
}

function Quickstart() {
  return (
    <div className="doc">
      <h1>Quickstart</h1>
      <p className="doc-lede">Spin up a small organization, run a two-agent workflow, pause for approval, and resume from durable state — no API keys, no real LLM calls, no hosted services.</p>
      <h2 id="requirements">Requirements</h2>
      <p>Node.js 22+, npm, and <code>make</code>.</p>
      <h2 id="run">Run to approval</h2>
      <div className="codeblock">
        <div><span className="pmt">$</span> make install      <span className="c"># install dependencies</span></div>
        <div><span className="pmt">$</span> make demo         <span className="c"># run until it pauses for approval</span></div>
        <div style={{ marginTop: 8 }} className="c">run_id: run_99999999999999999999999999999999</div>
        <div>status: <span className="warn">suspended_approval</span></div>
        <div className="c">approval_id: approval_11111111111111111111111111111111</div>
      </div>
      <div className="callout"><span className="ci"><Icon name="info" size={18} /></span><p>The run pauses at a non-bypassable governance gate. Nothing is promoted to collective memory until a human approves.</p></div>
      <h2 id="approve">Approve and resume</h2>
      <div className="codeblock">
        <div><span className="pmt">$</span> make demo-approve <span className="c"># approve and resume from durable state</span></div>
        <div style={{ marginTop: 8 }}>status: <span className="ok">completed</span></div>
        <div className="c">collective_memory_id: mem_cccccccccccccccccccccccccccccccc</div>
      </div>
      <h2 id="console">Open the console</h2>
      <p>The operator console runs on <code>127.0.0.1</code> and prompts for the token the server prints.</p>
      <div className="codeblock"><div><span className="pmt">$</span> make console</div><div className="c"># → http://127.0.0.1:8000/console</div></div>
    </div>
  );
}

const PAGES = {
  "north-star": { title: "North Star", grp: "Overview", render: NorthStar, toc: [["flywheel", "The Flywheel"], ["principles", "Principles"]] },
  vocabulary: { title: "Vocabulary", grp: "Concepts", render: Vocabulary, toc: [["types", "Canonical types"], ["splits", "Notable splits"]] },
  quickstart: { title: "Quickstart", grp: "Guides", render: Quickstart, toc: [["requirements", "Requirements"], ["run", "Run to approval"], ["approve", "Approve and resume"], ["console", "Open the console"]] },
};
const ORDER = ["north-star", "vocabulary", "quickstart"];

function Docs() {
  const [theme, setTheme] = useState("light");
  const [page, setPage] = useState("north-star");
  const [navOpen, setNavOpen] = useState(false);
  useEffect(() => { document.documentElement.setAttribute("data-theme", theme); }, [theme]);
  useEffect(() => { window.scrollTo({ top: 0 }); }, [page]);
  useEffect(() => { document.body.style.overflow = navOpen ? "hidden" : ""; }, [navOpen]);

  const cur = PAGES[page] || PAGES["north-star"];
  const idx = ORDER.indexOf(page);
  const prev = idx > 0 ? ORDER[idx - 1] : null;
  const next = idx < ORDER.length - 1 ? ORDER[idx + 1] : null;
  const real = !!PAGES[page];
  let label = cur.title, grp = cur.grp;
  if (!real) {
    for (const g of NAV) for (const [id, lab] of g.items) if (id === page) { label = lab; grp = g.grp; }
  }

  return (
    <div className="docs">
      <div className="docs-top">
        <button className="docs-burger btn btn-sm" onClick={() => setNavOpen(true)} aria-label="Open navigation"><Icon name="menu" size={18} /></button>
        <a className="brand" href="/" style={{ textDecoration: "none", color: "inherit" }}><img src={theme === "dark" ? MARK_D : MARK_L} alt="" />OpenMAO <span className="tag">docs</span></a>
        <div className="docs-search"><Icon name="search" size={14} /><span className="docs-search-label">Search the docs</span><span className="k">⌘K</span></div>
        <button className="btn btn-sm" onClick={() => setTheme(theme === "dark" ? "light" : "dark")}><Icon name={theme === "dark" ? "sun" : "moon"} size={15} /></button>
        <a className="ghbtn" href="https://github.com/aeonbilal/OpenMAO" target="_blank" rel="noopener">GitHub ↗</a>
      </div>

      <div className="docs-layout">
        <div className={"docs-scrim" + (navOpen ? " show" : "")} onClick={() => setNavOpen(false)} />
        <aside className={"docs-side" + (navOpen ? " open" : "")}>
          <div className="docs-side-head">
            <span className="docs-side-title">Documentation</span>
            <button className="docs-side-close" onClick={() => setNavOpen(false)} aria-label="Close navigation"><Icon name="x" size={18} /></button>
          </div>
          {NAV.map((g) => (
            <div className="grp" key={g.grp}>
              <div className="grp-t">{g.grp}</div>
              {g.items.map(([id, label]) => (
                <a key={id} className={page === id ? "on" : ""} onClick={() => { setPage(id); setNavOpen(false); }}>{label}</a>
              ))}
            </div>
          ))}
          <a className="docs-side-gh" href="https://github.com/aeonbilal/OpenMAO" target="_blank" rel="noopener">GitHub ↗</a>
        </aside>

        <main className="docs-main">
          <div className="crumbs">Docs <span className="sep">/</span> {grp} <span className="sep">/</span> {label}</div>
          {real ? <cur.render /> : (
            <div className="doc">
              <h1>{label}</h1>
              <div className="callout warn"><span className="ci"><Icon name="construction" size={18} /></span><p>This page isn't part of the kit. See the real source in the repo — <code>docs/</code> and <code>ts/src/contracts/models.ts</code>.</p></div>
            </div>
          )}
          <div className="doc-foot">
            {prev ? <a onClick={() => setPage(prev)}><div className="dir">← Previous</div><div className="ttl">{PAGES[prev].title}</div></a> : <span />}
            {next ? <a className="next" onClick={() => setPage(next)}><div className="dir">Next →</div><div className="ttl">{PAGES[next].title}</div></a> : <span />}
          </div>
        </main>

        <aside className="docs-toc">
          <div className="toc-t">On this page</div>
          {(cur.toc || []).map(([id, label]) => (
            <a key={id} href={"#" + id} onClick={(e) => { e.preventDefault(); const el = document.getElementById(id); if (el) el.scrollIntoView({ behavior: "smooth", block: "start" }); }}>{label}</a>
          ))}
          <div className="edit"><a href="https://github.com/aeonbilal/OpenMAO/tree/main/docs" target="_blank" rel="noopener"><Icon name="pencil" size={13} /> Edit this page</a></div>
        </aside>
      </div>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<Docs />);
