// API Keys management + documentation page

function ApiPage({ theme, isMobile }) {
  const t = theme;
  const [keys, setKeys] = React.useState([]);
  const [newKeyName, setNewKeyName] = React.useState('');
  const [createdKey, setCreatedKey] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [tab, setTab] = React.useState('keys'); // 'keys' | 'docs'

  React.useEffect(() => {
    fetch('/api/keys', { credentials: 'include' }).then(r => r.json()).then(data => {
      if (Array.isArray(data)) setKeys(data);
      setLoading(false);
    }).catch(() => setLoading(false));
  }, []);

  const createKey = async () => {
    if (!newKeyName.trim()) return;
    const res = await fetch('/api/keys', {
      method: 'POST', credentials: 'include',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ name: newKeyName.trim() }),
    });
    const data = await res.json();
    if (data.key) {
      setCreatedKey(data);
      setNewKeyName('');
      // Refresh list
      fetch('/api/keys', { credentials: 'include' }).then(r => r.json()).then(d => { if (Array.isArray(d)) setKeys(d); });
    }
  };

  const revokeKey = async (id) => {
    await fetch(`/api/keys/${id}`, { method: 'DELETE', credentials: 'include' });
    setKeys(prev => prev.map(k => k.id === id ? { ...k, revoked: 1 } : k));
  };

  const copyKey = () => {
    if (createdKey?.key) navigator.clipboard.writeText(createdKey.key);
  };

  const px = isMobile ? 16 : 32;
  const mono = { fontFamily: t.fontMono, fontSize: 12 };
  const baseUrl = window.location.origin;

  return React.createElement('div', { style: { flex: 1, overflowY: 'auto', padding: `24px ${px}px`, paddingBottom: 80 } },
    React.createElement('div', { style: { maxWidth: 800, margin: '0 auto' } },
      // Header
      React.createElement('div', { style: { fontFamily: t.fontDisplay, fontWeight: t.weightHeading, fontSize: 22, marginBottom: 4 } }, 'API'),
      React.createElement('div', { style: { fontSize: 13, color: t.fg2, marginBottom: 20 } },
        'Programmatic access to agents-control. Use API keys to let scripts or AI agents manage your machines, sessions, and autonomous agents.'
      ),

      // Tabs
      React.createElement('div', { style: { display: 'flex', gap: 4, marginBottom: 20, borderBottom: `1px solid ${t.line}`, paddingBottom: 0 } },
        ['keys', 'docs'].map(id =>
          React.createElement('button', {
            key: id, onClick: () => setTab(id),
            style: {
              padding: '8px 16px', background: 'transparent', border: 'none', borderBottom: tab === id ? `2px solid ${t.accent}` : '2px solid transparent',
              color: tab === id ? t.fg : t.fg2, cursor: 'pointer', fontFamily: t.fontSans, fontSize: 13, fontWeight: tab === id ? 600 : 400,
            }
          }, id === 'keys' ? 'API Keys' : 'Documentation')
        )
      ),

      tab === 'keys' && React.createElement(ApiKeysTab, { t, keys, newKeyName, setNewKeyName, createKey, revokeKey, createdKey, setCreatedKey, copyKey, loading, mono }),
      tab === 'docs' && React.createElement(ApiDocsTab, { t, baseUrl, mono }),
    )
  );
}

function ApiKeysTab({ t, keys, newKeyName, setNewKeyName, createKey, revokeKey, createdKey, setCreatedKey, copyKey, loading, mono }) {
  return React.createElement(React.Fragment, null,
    // Created key banner
    createdKey && React.createElement('div', { style: {
      padding: 16, background: `${t.accent}12`, border: `1px solid ${t.accent}40`, borderRadius: t.radius, marginBottom: 16,
    } },
      React.createElement('div', { style: { fontSize: 13, fontWeight: 600, color: t.accent, marginBottom: 8 } }, 'API Key Created'),
      React.createElement('div', { style: { fontSize: 12, color: t.fg2, marginBottom: 8 } }, 'Copy this key now. It will not be shown again.'),
      React.createElement('div', { style: { display: 'flex', gap: 8, alignItems: 'center' } },
        React.createElement('code', { style: { ...mono, flex: 1, padding: '8px 10px', background: t.bg, borderRadius: t.radius, border: `1px solid ${t.line}`, color: t.fg, wordBreak: 'break-all' } }, createdKey.key),
        React.createElement('button', { onClick: copyKey, style: { padding: '8px 12px', background: t.accent, color: t.bg, border: 'none', borderRadius: t.radius, cursor: 'pointer', fontSize: 12, fontWeight: 600, whiteSpace: 'nowrap' } }, 'Copy'),
      ),
      React.createElement('button', { onClick: () => setCreatedKey(null), style: { marginTop: 8, padding: '4px 8px', background: 'transparent', border: 'none', color: t.fg3, cursor: 'pointer', fontSize: 11 } }, 'Dismiss'),
    ),

    // Create new key
    React.createElement('div', { style: { display: 'flex', gap: 8, marginBottom: 20 } },
      React.createElement('input', {
        value: newKeyName, onChange: e => setNewKeyName(e.target.value),
        onKeyDown: e => { if (e.key === 'Enter') createKey(); },
        placeholder: 'Key name (e.g. "my-bot")',
        style: { flex: 1, padding: '8px 12px', background: t.panel, border: `1px solid ${t.line}`, borderRadius: t.radius, color: t.fg, fontFamily: t.fontSans, fontSize: 13, outline: 'none' },
      }),
      React.createElement('button', { onClick: createKey, disabled: !newKeyName.trim(), style: {
        padding: '8px 16px', background: newKeyName.trim() ? t.accent : t.panel2, color: newKeyName.trim() ? t.bg : t.fg3,
        border: 'none', borderRadius: t.radius, cursor: newKeyName.trim() ? 'pointer' : 'not-allowed', fontSize: 13, fontWeight: 600, whiteSpace: 'nowrap',
      } }, 'Create Key'),
    ),

    // Keys list
    loading
      ? React.createElement('div', { style: { color: t.fg3, fontSize: 13 } }, 'Loading...')
      : keys.length === 0
        ? React.createElement('div', { style: { color: t.fg3, fontSize: 13, padding: 20, textAlign: 'center' } }, 'No API keys yet. Create one to get started.')
        : React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 4 } },
          keys.map(k =>
            React.createElement('div', { key: k.id, style: {
              display: 'flex', alignItems: 'center', gap: 12, padding: '10px 12px',
              background: k.revoked ? `${t.err}08` : t.panel, border: `1px solid ${k.revoked ? t.err + '30' : t.line}`, borderRadius: t.radius,
            } },
              React.createElement('div', { style: { flex: 1 } },
                React.createElement('div', { style: { fontSize: 13, fontWeight: 500, color: k.revoked ? t.fg3 : t.fg, textDecoration: k.revoked ? 'line-through' : 'none' } }, k.name),
                React.createElement('div', { style: { ...mono, color: t.fg3, marginTop: 2 } },
                  k.key_prefix, ' — ', k.last_used_at ? `used ${timeAgo(k.last_used_at)}` : 'never used',
                ),
              ),
              !k.revoked && React.createElement('button', { onClick: () => revokeKey(k.id), style: {
                padding: '4px 10px', background: 'transparent', border: `1px solid ${t.err}40`, borderRadius: t.radius,
                color: t.err, cursor: 'pointer', fontSize: 11, fontWeight: 500,
              } }, 'Revoke'),
              k.revoked && React.createElement('span', { style: { fontSize: 11, color: t.err, ...mono } }, 'revoked'),
            )
          )
        ),
  );
}

function ApiDocsTab({ t, baseUrl, mono }) {
  const codeBlock = (code) => React.createElement('pre', { style: {
    ...mono, padding: 14, background: t.bg, borderRadius: t.radius, border: `1px solid ${t.line}`,
    color: t.fg, overflowX: 'auto', whiteSpace: 'pre-wrap', wordBreak: 'break-word', lineHeight: 1.6, marginTop: 8, marginBottom: 16,
  } }, code);

  const h3 = (text) => React.createElement('div', { style: { fontFamily: t.fontDisplay, fontWeight: 600, fontSize: 15, marginTop: 24, marginBottom: 8, color: t.fg } }, text);
  const p = (text) => React.createElement('div', { style: { fontSize: 13, color: t.fg2, marginBottom: 8, lineHeight: 1.5 } }, text);
  const badge = (method, color) => React.createElement('span', { style: { ...mono, fontSize: 11, fontWeight: 700, color, marginRight: 8 } }, method);

  return React.createElement(React.Fragment, null,
    // Auth
    h3('Authentication'),
    p('All API requests require a Bearer token. Create an API key in the "API Keys" tab, then pass it in the Authorization header:'),
    codeBlock(`curl -H "Authorization: Bearer ac_your_key_here" ${baseUrl}/api/status`),

    // Status
    h3('Status'),
    React.createElement('div', { style: { marginBottom: 4 } }, badge('GET', '#61affe'), React.createElement('code', { style: mono }, '/api/status')),
    p('Get server status, counts, and version info.'),
    codeBlock(`curl -H "Authorization: Bearer $KEY" ${baseUrl}/api/status`),

    // Machines
    h3('Machines'),
    React.createElement('div', { style: { marginBottom: 4 } }, badge('GET', '#61affe'), React.createElement('code', { style: mono }, '/api/machines')),
    p('List all your machines with their sessions.'),
    codeBlock(`curl -H "Authorization: Bearer $KEY" ${baseUrl}/api/machines`),

    React.createElement('div', { style: { marginBottom: 4 } }, badge('POST', '#49cc90'), React.createElement('code', { style: mono }, '/api/machines')),
    p('Register a new machine.'),
    codeBlock(`curl -X POST -H "Authorization: Bearer $KEY" \\
  -H "Content-Type: application/json" \\
  -d '{"name": "my-server"}' \\
  ${baseUrl}/api/machines`),

    React.createElement('div', { style: { marginBottom: 4 } }, badge('DELETE', '#f93e3e'), React.createElement('code', { style: mono }, '/api/machines/:id')),
    p('Delete a machine and all its sessions.'),

    // Sessions
    h3('Sessions'),
    React.createElement('div', { style: { marginBottom: 4 } }, badge('GET', '#61affe'), React.createElement('code', { style: mono }, '/api/sessions')),
    p('List all sessions. Add ?archived=true for archived ones.'),

    React.createElement('div', { style: { marginBottom: 4 } }, badge('POST', '#49cc90'), React.createElement('code', { style: mono }, '/api/sessions')),
    p('Create a new session on a machine.'),
    codeBlock(`curl -X POST -H "Authorization: Bearer $KEY" \\
  -H "Content-Type: application/json" \\
  -d '{"machine_id": "uuid", "agent_type": "claude-code"}' \\
  ${baseUrl}/api/sessions`),

    React.createElement('div', { style: { marginBottom: 4 } }, badge('PATCH', '#fca130'), React.createElement('code', { style: mono }, '/api/sessions/:id')),
    p('Update a session (name, status, archived).'),
    codeBlock(`curl -X PATCH -H "Authorization: Bearer $KEY" \\
  -H "Content-Type: application/json" \\
  -d '{"name": "my-task", "archived": 0}' \\
  ${baseUrl}/api/sessions/:id`),

    React.createElement('div', { style: { marginBottom: 4 } }, badge('GET', '#61affe'), React.createElement('code', { style: mono }, '/api/sessions/:id/messages')),
    p('Get message history for a session. Supports ?limit=N and ?before=ID for pagination.'),

    React.createElement('div', { style: { marginBottom: 4 } }, badge('DELETE', '#f93e3e'), React.createElement('code', { style: mono }, '/api/sessions/:id')),
    p('Delete a session and its messages.'),

    // Agent Groups
    h3('Agent Groups'),
    React.createElement('div', { style: { marginBottom: 4 } }, badge('GET', '#61affe'), React.createElement('code', { style: mono }, '/api/agents/groups')),
    p('List all agent groups.'),
    codeBlock(`curl -H "Authorization: Bearer $KEY" ${baseUrl}/api/agents/groups`),

    React.createElement('div', { style: { marginBottom: 4 } }, badge('POST', '#49cc90'), React.createElement('code', { style: mono }, '/api/agents/groups')),
    p('Create a new group.'),
    codeBlock(`curl -X POST -H "Authorization: Bearer $KEY" \\
  -H "Content-Type: application/json" \\
  -d '{"name": "Trading", "color": "#4fc3f7"}' \\
  ${baseUrl}/api/agents/groups`),

    React.createElement('div', { style: { marginBottom: 4 } }, badge('PATCH', '#fca130'), React.createElement('code', { style: mono }, '/api/agents/groups/:id')),
    p('Update a group (name, color, position).'),

    React.createElement('div', { style: { marginBottom: 4 } }, badge('DELETE', '#f93e3e'), React.createElement('code', { style: mono }, '/api/agents/groups/:id')),
    p('Delete a group. Agents in the group are moved to ungrouped.'),

    // Autonomous Agents
    h3('Autonomous Agents'),
    React.createElement('div', { style: { marginBottom: 4 } }, badge('GET', '#61affe'), React.createElement('code', { style: mono }, '/api/agents')),
    p('List all autonomous agents.'),

    React.createElement('div', { style: { marginBottom: 4 } }, badge('POST', '#49cc90'), React.createElement('code', { style: mono }, '/api/agents')),
    p('Create a new autonomous agent.'),
    codeBlock(`curl -X POST -H "Authorization: Bearer $KEY" \\
  -H "Content-Type: application/json" \\
  -d '{
    "name": "Trading bot",
    "machine_id": "uuid",
    "prompt": "Analyze market data and report",
    "model": "claude-haiku-4-5-20251001",
    "group_id": "group-uuid-or-empty",
    "schedule_type": "interval",
    "schedule_interval": 900,
    "enabled": true
  }' \\
  ${baseUrl}/api/agents`),
    p('Available models: "" (default Opus 4.7), "claude-opus-4-6", "claude-sonnet-4-6", "claude-haiku-4-5-20251001"'),

    React.createElement('div', { style: { marginBottom: 4 } }, badge('PATCH', '#fca130'), React.createElement('code', { style: mono }, '/api/agents/:id')),
    p('Update an agent (name, prompt, model, group_id, schedule, enabled).'),

    React.createElement('div', { style: { marginBottom: 4 } }, badge('POST', '#49cc90'), React.createElement('code', { style: mono }, '/api/agents/:id/run')),
    p('Trigger an agent run manually.'),
    codeBlock(`curl -X POST -H "Authorization: Bearer $KEY" ${baseUrl}/api/agents/:id/run`),

    React.createElement('div', { style: { marginBottom: 4 } }, badge('POST', '#fca130'), React.createElement('code', { style: mono }, '/api/agents/:id/stop')),
    p('Stop a running agent.'),

    React.createElement('div', { style: { marginBottom: 4 } }, badge('GET', '#61affe'), React.createElement('code', { style: mono }, '/api/agents/:id/runs')),
    p('Get run history for an agent. Supports ?limit=N.'),

    React.createElement('div', { style: { marginBottom: 4 } }, badge('DELETE', '#f93e3e'), React.createElement('code', { style: mono }, '/api/agents/:id')),
    p('Delete an agent and all its runs.'),

    // Sending messages
    h3('Sending Messages (WebSocket)'),
    p('Messages are sent via WebSocket, not REST. Connect to the WS endpoint and authenticate:'),
    codeBlock(`const ws = new WebSocket("wss://${window.location.host}/ws");

// After connect, send hello
ws.send(JSON.stringify({
  type: "hello",
  protocolVersions: ["1.0", "1.1"],
  role: "web"
}));

// Subscribe to a session
ws.send(JSON.stringify({
  type: "subscribe_session",
  session_id: "session-uuid"
}));

// Send a message to the agent
ws.send(JSON.stringify({
  type: "send_message",
  session_id: "session-uuid",
  client_message_id: crypto.randomUUID(),
  content_encrypted: "Hello, please analyze the logs",
  sender_type: "user"
}));`),
    p('Stream events arrive as type: "stream_event" with the agent\'s response blocks.'),

    // API Keys
    h3('API Keys'),
    React.createElement('div', { style: { marginBottom: 4 } }, badge('GET', '#61affe'), React.createElement('code', { style: mono }, '/api/keys')),
    p('List your API keys (keys are masked).'),

    React.createElement('div', { style: { marginBottom: 4 } }, badge('POST', '#49cc90'), React.createElement('code', { style: mono }, '/api/keys')),
    p('Create a new API key. The full key is only returned once.'),
    codeBlock(`curl -X POST -H "Authorization: Bearer $KEY" \\
  -H "Content-Type: application/json" \\
  -d '{"name": "my-bot"}' \\
  ${baseUrl}/api/keys`),

    React.createElement('div', { style: { marginBottom: 4 } }, badge('DELETE', '#f93e3e'), React.createElement('code', { style: mono }, '/api/keys/:id')),
    p('Revoke an API key.'),

    // Example full workflow
    h3('Example: Full Workflow'),
    p('Create a session, send a message, and get the response — all from a script:'),
    codeBlock(`#!/bin/bash
KEY="ac_your_key"
BASE="${baseUrl}"

# 1. List machines
MACHINE=$(curl -s -H "Authorization: Bearer $KEY" $BASE/api/machines | jq -r '.[0].id')

# 2. Create a session
SESSION=$(curl -s -X POST -H "Authorization: Bearer $KEY" \\
  -H "Content-Type: application/json" \\
  -d "{\\\"machine_id\\\": \\\"$MACHINE\\\", \\\"agent_type\\\": \\\"claude-code\\\"}" \\
  $BASE/api/sessions | jq -r '.id')

echo "Session: $SESSION"

# 3. Connect via WebSocket to send messages
# (Use wscat, websocat, or a script)
# Messages are sent/received over WS for real-time streaming`),
  );
}

window.ApiPage = ApiPage;
