// API Reference with split-pane code
function APIRef() {
  const shell = useShell();
  const tocItems = [
    { id: 'admin', label: 'POST /api/admin' },
    { id: 'cs', label: 'POST /api/cs' },
    { id: 'sessions', label: 'GET /api/sessions' },
    { id: 'skills', label: 'GET /api/skills' },
    { id: 'webhook', label: 'POST /webhook/{channel}/{tenantId}' },
  ];

  return (
    <div className="app">
      <Topbar section="api" theme={shell.theme} setTheme={shell.setTheme} onSearch={() => shell.setSearchOpen(true)} onMenuToggle={() => shell.setMobileMenuOpen(true)} />
      <div className="main">
        <Sidebar activeId="api-admin" mobileOpen={shell.mobileMenuOpen} onMobileClose={() => shell.setMobileMenuOpen(false)} />
        <article className="content" style={{maxWidth:'none', paddingRight:40}}>
          <div className="crumbs">
            <a href="index.html">Docs</a>
            <span className="sep">/</span>
            <a href="#">API</a>
            <span className="sep">/</span>
            <span>Chat</span>
          </div>
          <div className="eyebrow">API Reference · v0</div>
          <h1 className="h1">Chat endpoints</h1>
          <p className="lede">
            Two streaming endpoints are available today: <code>/api/admin</code> for the tenant
            owner, <code>/api/cs</code> for customer-facing traffic. Both return Server-Sent Events
            so you can render partial text as the model generates it. These are the two built-in
            agents; support for additional tenant-defined agents and per-agent endpoints lands in a
            later phase — track progress in the <a className="inline" href="changelog.html">changelog</a>.
          </p>

          <hr className="rule" />

          {/* ───── ADMIN ───── */}
          <section id="admin" className="api-split">
            <div className="api-doc">
              <h2 className="h2" style={{margin:0}}>Chat with the Admin agent</h2>
              <p>Streams a reply from your owner-facing agent. Broad toolset — can read and write memory, manage skills, schedule crons, send on any connected channel.</p>
              <div className="endpoint">
                <span className="method post">POST</span>
                <span className="path">/api/admin</span>
              </div>
              <h4>Headers</h4>
              <div className="params">
                <div className="param">
                  <div className="param-head">
                    <span className="param-name">X-API-Key</span>
                    <span className="param-type">string</span>
                    <span className="param-req">required</span>
                  </div>
                  <p className="param-desc">Tenant-scoped key, beginning with <code>ck_live_</code>. Identifies both the tenant and the caller.</p>
                </div>
                <div className="param">
                  <div className="param-head">
                    <span className="param-name">Accept</span>
                    <span className="param-type">string</span>
                    <span className="param-opt">optional</span>
                  </div>
                  <p className="param-desc">Defaults to <code>text/event-stream</code>. Pass <code>application/json</code> for a single-shot non-streaming reply.</p>
                </div>
              </div>
              <h4>Body parameters</h4>
              <div className="params">
                <div className="param">
                  <div className="param-head">
                    <span className="param-name">message</span>
                    <span className="param-type">string</span>
                    <span className="param-req">required</span>
                  </div>
                  <p className="param-desc">The user's message. 1–32000 characters.</p>
                </div>
                <div className="param">
                  <div className="param-head">
                    <span className="param-name">contact_id</span>
                    <span className="param-type">string</span>
                    <span className="param-opt">optional</span>
                  </div>
                  <p className="param-desc">Continues an existing session. Omit to start a fresh one — a new <code>contact_id</code> is returned in the first event.</p>
                </div>
                <div className="param">
                  <div className="param-head">
                    <span className="param-name">attachments</span>
                    <span className="param-type">File[]</span>
                    <span className="param-opt">optional</span>
                  </div>
                  <p className="param-desc">Array of uploaded file references (from <code>POST /api/uploads</code>). Images, PDFs, and text are supported.</p>
                </div>
              </div>
              <h4>Streaming events</h4>
              <p>The response is a sequence of SSE events. Event types:</p>
              <ul>
                <li><code>session</code> — emitted once, contains <code>contact_id</code>.</li>
                <li><code>text_delta</code> — incremental text output.</li>
                <li><code>tool_call_start</code> / <code>tool_call_end</code> — the agent invoking any tool from its registry (e.g. <code>read</code>, <code>web_search</code>, <code>bash</code>, <code>message</code>, <code>load_skill</code>).</li>
                <li><code>done</code> — final event with token usage and finish reason.</li>
                <li><code>error</code> — emitted and stream closes. No fallback.</li>
              </ul>
            </div>
            <div className="api-side">
              <CodeBlock
                tabs={[
                  { label: 'curl', raw: `curl -N https://api.clawagen.com/api/admin \\\n  -H "X-API-Key: $CLAWAGEN_KEY" \\\n  -H "Content-Type: application/json" \\\n  -d '{\n    "message": "What did Jamie ask me yesterday?",\n    "contact_id": "sess_9f2m"\n  }'`,
                    code: `<span class="tok-com">$</span> curl -N https://api.clawagen.com/api/admin <span class="tok-pun">\\</span>
  -H <span class="tok-str">"X-API-Key: $CLAWAGEN_KEY"</span> <span class="tok-pun">\\</span>
  -H <span class="tok-str">"Content-Type: application/json"</span> <span class="tok-pun">\\</span>
  -d <span class="tok-str">'{
    "message": "What did Jamie ask me yesterday?",
    "contact_id": "sess_9f2m"
  }'</span>` },
                  { label: 'node', raw: `for await (const ev of c.chat.admin.stream({\n  message: 'What did Jamie ask me yesterday?',\n  contact_id: 'sess_9f2m',\n})) {\n  if (ev.type === 'text_delta') process.stdout.write(ev.delta);\n  if (ev.type === 'tool_call_start') console.log('\\n→', ev.name, ev.input);\n}`,
                    code: `<span class="tok-kw">for await</span> (<span class="tok-kw">const</span> <span class="tok-var">ev</span> <span class="tok-kw">of</span> c.chat.admin.<span class="tok-fn">stream</span>({
  message: <span class="tok-str">'What did Jamie ask me yesterday?'</span>,
  contact_id: <span class="tok-str">'sess_9f2m'</span>,
})) {
  <span class="tok-kw">if</span> (ev.type === <span class="tok-str">'text_delta'</span>) process.stdout.<span class="tok-fn">write</span>(ev.delta);
  <span class="tok-kw">if</span> (ev.type === <span class="tok-str">'tool_call_start'</span>) console.<span class="tok-fn">log</span>(<span class="tok-str">'\\n→'</span>, ev.name, ev.input);
}` },
                  { label: 'python', raw: `for ev in c.chat.admin.stream(message="What did Jamie ask me yesterday?", contact_id="sess_9f2m"):\n    if ev.type == "text_delta":\n        print(ev.delta, end="", flush=True)`,
                    code: `<span class="tok-kw">for</span> ev <span class="tok-kw">in</span> c.chat.admin.<span class="tok-fn">stream</span>(message=<span class="tok-str">"What did Jamie ask me yesterday?"</span>, contact_id=<span class="tok-str">"sess_9f2m"</span>):
    <span class="tok-kw">if</span> ev.type == <span class="tok-str">"text_delta"</span>:
        <span class="tok-fn">print</span>(ev.delta, end=<span class="tok-str">""</span>, flush=<span class="tok-kw">True</span>)` },
                ]}
              />
              <CodeBlock
                tabs={[{ label: 'SSE stream', raw: `event: session\ndata: {"contact_id":"sess_9f2m"}\n\nevent: text_delta\ndata: {"delta":"Jamie "}\n\nevent: tool_call_start\ndata: {"name":"bash","input":{"command":"tunder messages search jamie"}}\n\nevent: text_delta\ndata: {"delta":"asked about the Q2 deck."}\n\nevent: done\ndata: {"inputTokens":1842,"outputTokens":91,"finishReason":"stop"}`,
                  code: `event: <span class="tok-kw">session</span>
data: {<span class="tok-str">"contact_id"</span>:<span class="tok-str">"sess_9f2m"</span>}

event: <span class="tok-kw">text_delta</span>
data: {<span class="tok-str">"delta"</span>:<span class="tok-str">"Jamie "</span>}

event: <span class="tok-kw">tool_call_start</span>
data: {<span class="tok-str">"name"</span>:<span class="tok-str">"bash"</span>,<span class="tok-str">"input"</span>:{<span class="tok-str">"command"</span>:<span class="tok-str">"tunder messages search jamie"</span>}}

event: <span class="tok-kw">text_delta</span>
data: {<span class="tok-str">"delta"</span>:<span class="tok-str">"asked about the Q2 deck."</span>}

event: <span class="tok-kw">done</span>
data: {<span class="tok-str">"inputTokens"</span>:<span class="tok-num">1842</span>,<span class="tok-str">"outputTokens"</span>:<span class="tok-num">91</span>,<span class="tok-str">"finishReason"</span>:<span class="tok-str">"stop"</span>}` }]}
              />
            </div>
          </section>

          <hr className="rule" />

          {/* ───── CS ───── */}
          <section id="cs" className="api-split">
            <div className="api-doc">
              <h2 className="h2" style={{margin:0}}>Chat with the CS agent</h2>
              <p>Customer-facing endpoint. Restricted toolset — cannot modify tenant config, install skills, or send on arbitrary channels. Used by embedded web chat and by the channel dispatcher for inbound traffic.</p>
              <div className="endpoint">
                <span className="method post">POST</span>
                <span className="path">/api/cs</span>
              </div>
              <h4>Body parameters</h4>
              <div className="params">
                <div className="param">
                  <div className="param-head">
                    <span className="param-name">message</span>
                    <span className="param-type">string</span>
                    <span className="param-req">required</span>
                  </div>
                  <p className="param-desc">Same as <code>/api/admin</code>.</p>
                </div>
                <div className="param">
                  <div className="param-head">
                    <span className="param-name">sender</span>
                    <span className="param-type">string</span>
                    <span className="param-opt">optional</span>
                  </div>
                  <p className="param-desc">Stable identifier for the contact. Scopes memory and session to this sender only.</p>
                </div>
                <div className="param">
                  <div className="param-head">
                    <span className="param-name">channel</span>
                    <span className="param-type">enum</span>
                    <span className="param-opt">optional</span>
                  </div>
                  <p className="param-desc">One of <code>web</code>, <code>whatsapp</code>, <code>telegram</code>, <code>messenger</code>, <code>instagram</code>. Defaults to <code>web</code>.</p>
                </div>
              </div>
              <Callout type="warn" title="Enforcement is in progress">
                Per-agent tool restrictions are a work-in-progress. Until Phase 9 lands, treat CS access as if it had the same capabilities as Admin — gate via API-key scope, not endpoint choice.
              </Callout>
            </div>
            <div className="api-side">
              <CodeBlock
                tabs={[
                  { label: 'curl', raw: `curl -N https://api.clawagen.com/api/cs \\\n  -H "X-API-Key: $CLAWAGEN_KEY" \\\n  -H "Content-Type: application/json" \\\n  -d '{\n    "message": "Do you still have size M in stock?",\n    "sender": "wa:+15551234567",\n    "channel": "whatsapp"\n  }'`,
                    code: `<span class="tok-com">$</span> curl -N https://api.clawagen.com/api/cs <span class="tok-pun">\\</span>
  -H <span class="tok-str">"X-API-Key: $CLAWAGEN_KEY"</span> <span class="tok-pun">\\</span>
  -H <span class="tok-str">"Content-Type: application/json"</span> <span class="tok-pun">\\</span>
  -d <span class="tok-str">'{
    "message": "Do you still have size M in stock?",
    "sender": "wa:+15551234567",
    "channel": "whatsapp"
  }'</span>` },
                  { label: 'node', raw: `for await (const ev of c.chat.cs.stream({\n  message: 'Do you still have size M in stock?',\n  sender: 'wa:+15551234567',\n  channel: 'whatsapp',\n})) {\n  if (ev.type === 'text_delta') process.stdout.write(ev.delta);\n}`,
                    code: `<span class="tok-kw">for await</span> (<span class="tok-kw">const</span> <span class="tok-var">ev</span> <span class="tok-kw">of</span> c.chat.cs.<span class="tok-fn">stream</span>({
  message: <span class="tok-str">'Do you still have size M in stock?'</span>,
  sender: <span class="tok-str">'wa:+15551234567'</span>,
  channel: <span class="tok-str">'whatsapp'</span>,
})) {
  <span class="tok-kw">if</span> (ev.type === <span class="tok-str">'text_delta'</span>) process.stdout.<span class="tok-fn">write</span>(ev.delta);
}` },
                ]}
              />
            </div>
          </section>

          <hr className="rule" />

          {/* ───── LIST SESSIONS ───── */}
          <section id="sessions" className="api-split">
            <div className="api-doc">
              <h2 className="h2" style={{margin:0}}>List sessions</h2>
              <p>Returns the tenant's recent sessions, ordered by <code>updatedAt</code> descending. Session bodies are in <code>sessions/&#123;id&#125;.json</code> on the tenant filesystem.</p>
              <div className="endpoint">
                <span className="method get">GET</span>
                <span className="path">/api/sessions</span>
              </div>
              <h4>Query parameters</h4>
              <div className="params">
                <div className="param">
                  <div className="param-head">
                    <span className="param-name">limit</span>
                    <span className="param-type">integer</span>
                    <span className="param-opt">optional</span>
                  </div>
                  <p className="param-desc">1–100. Default 25.</p>
                </div>
                <div className="param">
                  <div className="param-head">
                    <span className="param-name">agent</span>
                    <span className="param-type">enum</span>
                    <span className="param-opt">optional</span>
                  </div>
                  <p className="param-desc"><code>admin</code> or <code>cs</code> today; this enum will expand as tenant-defined agents ship. Omit to return all.</p>
                </div>
              </div>
            </div>
            <div className="api-side">
              <CodeBlock
                tabs={[
                  { label: 'curl', raw: `curl "https://api.clawagen.com/api/sessions?limit=10&agent=admin" \\\n  -H "X-API-Key: $CLAWAGEN_KEY"`,
                    code: `<span class="tok-com">$</span> curl <span class="tok-str">"https://api.clawagen.com/api/sessions?limit=10&agent=admin"</span> <span class="tok-pun">\\</span>
  -H <span class="tok-str">"X-API-Key: $CLAWAGEN_KEY"</span>` },
                  { label: 'node', raw: `for await (const sess of c.sessions.list({ agent: 'admin' })) {\n  console.log(sess.id, sess.updatedAt);\n}`,
                    code: `<span class="tok-kw">for await</span> (<span class="tok-kw">const</span> <span class="tok-var">sess</span> <span class="tok-kw">of</span> c.sessions.<span class="tok-fn">list</span>({ agent: <span class="tok-str">'admin'</span> })) {
  console.<span class="tok-fn">log</span>(sess.id, sess.updatedAt);
}` },
                ]}
              />
            </div>
          </section>

          <hr className="rule" />

          {/* ───── LIST SKILLS ───── */}
          <section id="skills" className="api-split">
            <div className="api-doc">
              <h2 className="h2" style={{margin:0}}>List skills</h2>
              <p>Returns all skills for the tenant, parsed from each <code>SKILL.md</code>'s front-matter.</p>
              <div className="endpoint">
                <span className="method get">GET</span>
                <span className="path">/api/skills</span>
              </div>
              <Callout type="note" title="Source of truth is the filesystem">
                The skills index in <code>data.db</code> is a cache. To add a skill, drop a directory under <code>skills/</code> and either restart or hit <code>POST /api/skills/reindex</code>.
              </Callout>
            </div>
            <div className="api-side">
              <CodeBlock tabs={[
                { label: '200 Response', raw: `[\n  {\n    "name": "weekly-summary",\n    "description": "Summarize this week's inbox activity",\n    "trigger": "summarize my week",\n    "path": "skills/weekly-summary/SKILL.md"\n  }\n]`,
                  code: `[
  {
    <span class="tok-str">"name"</span>: <span class="tok-str">"weekly-summary"</span>,
    <span class="tok-str">"description"</span>: <span class="tok-str">"Summarize this week's inbox activity"</span>,
    <span class="tok-str">"trigger"</span>: <span class="tok-str">"summarize my week"</span>,
    <span class="tok-str">"path"</span>: <span class="tok-str">"skills/weekly-summary/SKILL.md"</span>
  }
]` },
              ]} />
            </div>
          </section>

          <hr className="rule" />

          {/* ───── WEBHOOK ───── */}
          <section id="webhook" className="api-split">
            <div className="api-doc">
              <h2 className="h2" style={{margin:0}}>Channel webhooks</h2>
              <p>Channel providers (Meta, Telegram, etc.) POST inbound messages to a per-tenant URL. ClawAgen verifies the signature, routes to the CS agent, and streams the reply back out.</p>
              <div className="endpoint">
                <span className="method post">POST</span>
                <span className="path">/webhook/<span className="var">{'{channel}'}</span>/<span className="var">{'{tenantId}'}</span></span>
              </div>
              <Callout type="danger" title="Signature required">
                Requests without a valid channel signature are rejected with <code>401</code>. Signature schemes vary: <code>X-Hub-Signature-256</code> for Meta, <code>X-Telegram-Bot-Api-Secret-Token</code> for Telegram.
              </Callout>
            </div>
            <div className="api-side">
              <CodeBlock tabs={[
                { label: 'set-webhook.sh', raw: `# WhatsApp Cloud — register the webhook URL in Meta's console:\n# https://api.clawagen.com/webhook/whatsapp/{tenantId}\n#\n# Telegram Bot API:\ncurl "https://api.telegram.org/bot$TG_TOKEN/setWebhook" \\\n  -d "url=https://api.clawagen.com/webhook/telegram/$TENANT_ID" \\\n  -d "secret_token=$TG_SECRET"`,
                  code: `<span class="tok-com"># WhatsApp Cloud — register the webhook URL in Meta's console:</span>
<span class="tok-com"># https://api.clawagen.com/webhook/whatsapp/{tenantId}</span>
<span class="tok-com">#</span>
<span class="tok-com"># Telegram Bot API:</span>
<span class="tok-com">$</span> curl <span class="tok-str">"https://api.telegram.org/bot$TG_TOKEN/setWebhook"</span> <span class="tok-pun">\\</span>
  -d <span class="tok-str">"url=https://api.clawagen.com/webhook/telegram/$TENANT_ID"</span> <span class="tok-pun">\\</span>
  -d <span class="tok-str">"secret_token=$TG_SECRET"</span>` },
              ]} />
            </div>
          </section>

          <Feedback />
          <PageFoot
            prev={{ label: 'Architecture', href: 'guide.html' }}
            next={{ label: 'Changelog', href: 'changelog.html' }}
          />
        </article>
        <TOC items={tocItems} />
      </div>
      <SearchOverlay open={shell.searchOpen} onClose={() => shell.setSearchOpen(false)} />
      <TweaksPanel visible={shell.tweaksVisible} theme={shell.theme} setTheme={shell.setTheme} />
    </div>
  );
}
ReactDOM.createRoot(document.getElementById('root')).render(<APIRef />);
