// Graph Explorer + Observability (Usage/Logs/Quality) + Home + API + Settings

const { useState: useGx } = React;

function GraphPage({ openEntity }) {
  const [tab, setTab] = useGx('entities');
  return (
    <div style={{ display: 'flex', height: '100%' }}>
      {/* Left sidebar */}
      <aside style={{ width: 240, borderRight: '1px solid var(--border-subtle)', padding: '24px 16px', overflowY: 'auto' }}>
        <div className="t-micro text-tertiary" style={{ marginBottom: 8 }}>Graph</div>
        {[
          ['entities', 'Entities', '34.2k'],
          ['relationships', 'Relationships', '128k'],
          ['documents', 'Documents', '12.8k'],
          ['chunks', 'Chunks', '1.24M'],
        ].map(([id, label, count]) => (
          <button key={id} onClick={() => setTab(id)} style={{
            display: 'flex', alignItems: 'center', gap: 10, width: '100%',
            padding: '7px 10px', borderRadius: 6,
            background: tab === id ? 'var(--selected)' : 'transparent',
            color: tab === id ? 'var(--text-primary)' : 'var(--text-secondary)',
            fontSize: 13, fontWeight: tab === id ? 500 : 400,
          }}>
            <span style={{ flex: 1, textAlign: 'left' }}>{label}</span>
            <span className="mono-sm mono text-tertiary">{count}</span>
          </button>
        ))}

        <div className="t-micro text-tertiary" style={{ marginTop: 24, marginBottom: 8 }}>Saved views</div>
        {['Customers', 'Deals Q4', 'Engineers'].map(s => (
          <button key={s} style={{ display: 'block', width: '100%', textAlign: 'left', padding: '6px 10px', fontSize: 13, color: 'var(--text-secondary)' }}>• {s}</button>
        ))}

        <div className="t-micro text-tertiary" style={{ marginTop: 24, marginBottom: 8 }}>Type filter</div>
        {[['Org', true], ['Person', true], ['Product', false], ['Team', false], ['Document', false]].map(([t, on]) => (
          <label key={t} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '4px 10px', fontSize: 13, cursor: 'pointer' }}>
            <span style={{ width: 14, height: 14, borderRadius: 3, border: `1.5px solid ${on ? 'var(--accent)' : 'var(--border-strong)'}`, background: on ? 'var(--accent)' : 'transparent', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              {on && <Icons.Check size={9} style={{ color: 'var(--on-accent)' }}/>}
            </span>
            {t}
          </label>
        ))}
      </aside>

      {/* Content */}
      <div style={{ flex: 1, padding: '24px 32px', overflowY: 'auto' }}>
        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between' }}>
          <div>
            <h1 className="t-h1" style={{ margin: 0 }}>Entities</h1>
            <div className="text-secondary t-body mt-4">34,211 entities inferred across 6 sources.</div>
          </div>
          <div className="segmented">
            <button className="active">Explorer</button>
            <button>Retrieval preview</button>
          </div>
        </div>

        <div style={{ display: 'flex', gap: 10, marginTop: 20, alignItems: 'center' }}>
          <div style={{ position: 'relative', flex: 1, maxWidth: 380 }}>
            <Icons.Search size={13} style={{ position: 'absolute', left: 12, top: 10, color: 'var(--text-tertiary)' }}/>
            <input className="input" placeholder="Search entities…" style={{ paddingLeft: 34 }}/>
          </div>
          <button className="btn">Type: all <Icons.ChevronD size={11}/></button>
          <button className="btn">Source: all <Icons.ChevronD size={11}/></button>
          <button className="btn">Confidence &gt; 0.8 <Icons.ChevronD size={11}/></button>
        </div>

        <div className="card" style={{ marginTop: 16, overflow: 'hidden' }}>
          <table className="parcle">
            <thead>
              <tr>
                <th style={{ width: 70 }}>Type</th>
                <th>Name</th>
                <th style={{ width: 140 }}>Source</th>
                <th style={{ width: 100 }}>Confidence</th>
                <th style={{ width: 90 }}>Edges</th>
                <th style={{ width: 80 }}></th>
              </tr>
            </thead>
            <tbody>
              {ENTITIES.map((e, i) => (
                <tr key={i} onClick={() => openEntity(e)}>
                  <td><span className="chip" style={{ fontSize: 10, height: 20 }}>{e.type}</span></td>
                  <td style={{ fontWeight: 500, display: 'flex', alignItems: 'center', gap: 8 }}>
                    {e.name}
                    {e.isNew && <span className="chip accent" style={{ fontSize: 10, height: 18 }}>new</span>}
                  </td>
                  <td><div style={{ display: 'flex', alignItems: 'center', gap: 6 }}><VendorLogo vendor={e.source} size={16} radius={4}/><span className="mono-sm mono text-secondary">{VENDORS[e.source].name}</span></div></td>
                  <td>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                      <div style={{ width: 36, height: 4, background: 'var(--border-subtle)', borderRadius: 2, overflow: 'hidden' }}>
                        <div style={{ width: `${e.conf * 100}%`, height: '100%', background: e.conf >= 0.9 ? 'var(--success)' : e.conf >= 0.8 ? 'var(--accent)' : 'var(--warning)' }}/>
                      </div>
                      <span className="mono-sm mono">{e.conf.toFixed(2)}</span>
                    </div>
                  </td>
                  <td><span className="mono-sm mono text-secondary">{e.edges}</span></td>
                  <td><Icons.ChevronR size={13} style={{ color: 'var(--text-tertiary)' }}/></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 12, fontSize: 12 }}>
          <span className="mono-sm mono text-tertiary">1–16 of 34,211</span>
          <div style={{ display: 'flex', gap: 4 }}>
            <button className="btn sm">‹</button>
            <button className="btn sm">1</button>
            <button className="btn sm" style={{ background: 'var(--selected)' }}>2</button>
            <button className="btn sm">3</button>
            <button className="btn sm">›</button>
          </div>
        </div>
      </div>
    </div>
  );
}

// Entity drawer — resolves the clicked id against the live /skill/graph snapshot
// and renders the REAL node (aliases, properties, columns, connections, raw
// DTO). Non-graph ids (e.g. demo Person/Deal entities) fall back to a minimal
// card so nothing crashes.
const ENTITY_ICON_BY_TYPE = { table: 'Table', column: 'Table', document: 'Doc', chunk: 'Doc', concept: 'Sparkle' };
const EDGE_VERB = { mapping: 'maps to', dependency: 'depends on', relation: 'related', category: 'category', structure: 'links' };

function DrawerShell({ onClose, children }) {
  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,.25)', zIndex: 90, display: 'flex', justifyContent: 'flex-end' }}>
      <div onClick={e => e.stopPropagation()} style={{
        width: 640, height: '100%', background: 'var(--surface)',
        borderLeft: '1px solid var(--border)', boxShadow: 'var(--shadow-1)',
        display: 'flex', flexDirection: 'column',
        animation: 'slideInR 240ms cubic-bezier(.2,.8,.2,1)'
      }}>
        {children}
      </div>
    </div>
  );
}

function EntityDrawer({ entity, onClose }) {
  const [snap, setSnap] = useGx(null);
  const [loadErr, setLoadErr] = useGx(false);
  React.useEffect(() => {
    if (typeof fetchGraphSnapshotCached !== 'function') { setLoadErr(true); return; }
    let cancelled = false;
    fetchGraphSnapshotCached().then(s => { if (!cancelled) setSnap(s); }).catch(() => { if (!cancelled) setLoadErr(true); });
    const unsub = typeof subscribeGraphSnapshot === 'function'
      ? subscribeGraphSnapshot(s => { if (!cancelled) setSnap(s); })
      : null;
    return () => { cancelled = true; if (unsub) unsub(); };
  }, []);

  const resolved = React.useMemo(() => {
    if (!entity || !entity.id || !snap) return null;
    const nodes = allGraphNodes(snap);
    const idx = buildGraphNodeIndex(nodes);
    const node = idx.get(entity.id);
    if (!node) return null;
    const { outByNode, inByNode } = buildGraphAdjacency(allGraphEdges(snap));
    return { node, idx, outE: outByNode.get(node.id) || [], inE: inByNode.get(node.id) || [] };
  }, [entity, snap]);

  if (!entity) return null;

  // Resolved to a real knowledge-graph node → show its live data.
  if (resolved) {
    return <DrawerShell onClose={onClose}><GraphEntityBody resolved={resolved} onClose={onClose}/></DrawerShell>;
  }
  // Has a graph-style id and the snapshot is still loading → wait (not failed).
  if (entity.id && !snap && !loadErr) {
    return <DrawerShell onClose={onClose}><UnknownEntityBody entity={entity} loading={true} onClose={onClose}/></DrawerShell>;
  }
  // Not a knowledge-graph node (no id, id not in graph, or load failed) →
  // fall back to the cross-source entity drawer (people / orgs / deals demo).
  if (typeof SourceEntityDrawer === 'function') {
    return <SourceEntityDrawer entity={entity} onClose={onClose}/>;
  }
  return <DrawerShell onClose={onClose}><UnknownEntityBody entity={entity} loading={false} onClose={onClose}/></DrawerShell>;
}

function GraphEntityBody({ resolved, onClose }) {
  const { node, idx, outE, inE } = resolved;
  const props = node.properties || {};
  const isConcept = node.category === 'concept';
  const typeLabel = node.type || node.category;
  const I = Icons[ENTITY_ICON_BY_TYPE[node.type] || ENTITY_ICON_BY_TYPE[node.category] || 'Box'] || Icons.Box;
  const synonyms = (node.synonyms || []).filter(s => s && s.state !== 'undo');
  const columns = Array.isArray(props.columns) ? props.columns : null;
  const created = (typeof formatRelativeTime === 'function' && node.created_at) ? formatRelativeTime(node.created_at) : node.created_at;

  const neighbors = [
    ...outE.map(e => ({ e, other: idx.get(e.target) })),
    ...inE.map(e => ({ e, other: idx.get(e.source) })),
  ].filter(x => x.other && x.other.state !== 'undo');

  return (
    <>
      <div style={{ padding: '20px 24px', borderBottom: '1px solid var(--border-subtle)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <span className="chip">{typeLabel}</span>
          {node.status === 'merged' && <span className="chip" style={{ color: 'var(--text-tertiary)' }}>merged</span>}
          {node.state === 'undo' && <span className="chip" style={{ color: 'var(--error)' }}>undone</span>}
          <div style={{ flex: 1 }}/>
          <button className="btn sm ghost" onClick={onClose}><Icons.X size={14}/></button>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginTop: 12 }}>
          <span style={{
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            width: 40, height: 40, borderRadius: 10, flexShrink: 0,
            background: 'var(--accent-muted)', color: 'var(--accent-text)',
          }}><I size={20}/></span>
          <div style={{ minWidth: 0 }}>
            <div className="t-h2" style={{ margin: 0 }}>{node.name}</div>
            <div className="mono-sm mono text-tertiary" style={{ marginTop: 2 }}>
              {node.id}{node.origin ? `  ·  ${node.origin}` : ''}{created ? `  ·  ${created}` : ''}
            </div>
          </div>
        </div>
      </div>

      <div style={{ flex: 1, overflowY: 'auto', padding: 24 }}>
        {props.description && (
          <div style={{ marginBottom: 20 }}>
            <div className="t-h3">Description</div>
            <div className="t-body text-secondary" style={{ marginTop: 6 }}>{props.description}</div>
          </div>
        )}
        {props.formula && (
          <div style={{ marginBottom: 20 }}>
            <div className="t-h3">Formula</div>
            <div className="mono-sm mono" style={{ marginTop: 6, background: 'var(--bg)', border: '1px solid var(--border-subtle)', borderRadius: 8, padding: '8px 10px' }}>{props.formula}</div>
          </div>
        )}

        {isConcept && (
          <div style={{ marginBottom: 20 }}>
            <div className="t-h3">Aliases <span className="mono-sm mono text-tertiary">· {synonyms.length}</span></div>
            <div style={{ display: 'flex', gap: 6, marginTop: 8, flexWrap: 'wrap' }}>
              {synonyms.length === 0
                ? <span className="t-small text-tertiary">No synonyms recorded.</span>
                : synonyms.map((s, i) => (
                    <span key={i} className="chip" title={`${s.origin || ''}${s.at ? ' · ' + s.at : ''}`}>{s.name}</span>
                  ))}
            </div>
          </div>
        )}

        {columns && (
          <div style={{ marginBottom: 20 }}>
            <div className="t-h3">Columns <span className="mono-sm mono text-tertiary">· {columns.length}</span></div>
            <div style={{ marginTop: 8, fontSize: 13 }}>
              {columns.slice(0, 60).map((c, i) => (
                <div key={i} style={{ display: 'flex', gap: 10, padding: '6px 0', borderBottom: '1px solid var(--border-subtle)' }}>
                  <span style={{ fontWeight: 500, minWidth: 0 }}>{c.name}</span>
                  {c.data_type && <span className="mono-sm mono text-tertiary">{c.data_type}</span>}
                  <div style={{ flex: 1 }}/>
                  {c.description && <span className="t-small text-secondary" style={{ maxWidth: 280, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{c.description}</span>}
                </div>
              ))}
              {columns.length > 60 && <div className="t-small text-tertiary" style={{ paddingTop: 8 }}>+{columns.length - 60} more columns</div>}
            </div>
          </div>
        )}

        <div style={{ marginBottom: 20 }}>
          <div className="t-h3">Connections <span className="mono-sm mono text-tertiary">· {neighbors.length}</span></div>
          <div style={{ marginTop: 8, display: 'flex', flexDirection: 'column', gap: 6 }}>
            {neighbors.length === 0
              ? <span className="t-small text-tertiary">No connected nodes.</span>
              : neighbors.slice(0, 50).map(({ e, other }, i) => (
                  <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '8px 10px', border: '1px solid var(--border-subtle)', borderRadius: 7 }}>
                    <span className="t-micro text-tertiary" style={{ minWidth: 64 }}>{e.relation || EDGE_VERB[e.type] || e.type}</span>
                    <span style={{ fontSize: 13, fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{other.name}</span>
                    {e.value && <span className="mono-sm mono text-tertiary">= {e.value}</span>}
                    <div style={{ flex: 1 }}/>
                    {typeof e.confidence === 'number' && <span className="mono-sm mono text-tertiary">{Math.round(e.confidence * 100)}%</span>}
                  </div>
                ))}
            {neighbors.length > 50 && <span className="t-small text-tertiary">+{neighbors.length - 50} more</span>}
          </div>
        </div>

        <div>
          <div className="t-h3">Raw node</div>
          <div style={{ marginTop: 8 }}>
            <CodeBlock language="json">{JSON.stringify(node, null, 2)}</CodeBlock>
          </div>
        </div>
      </div>
    </>
  );
}

function UnknownEntityBody({ entity, loading, onClose }) {
  const name = entity.name || entity.label || entity.id || 'Entity';
  const type = entity.type || entity.sub || 'Entity';
  return (
    <>
      <div style={{ padding: '20px 24px', borderBottom: '1px solid var(--border-subtle)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <span className="chip">{type}</span>
          <div style={{ flex: 1 }}/>
          <button className="btn sm ghost" onClick={onClose}><Icons.X size={14}/></button>
        </div>
        <div className="t-h1" style={{ marginTop: 10 }}>{name}</div>
        {entity.sub && <div className="text-secondary t-small mt-4">{entity.sub}</div>}
      </div>
      <div style={{ flex: 1, overflowY: 'auto', padding: 24 }}>
        <div className="t-small text-tertiary">
          {loading ? 'Loading graph…' : 'This entity is not in the current knowledge-graph snapshot.'}
        </div>
      </div>
    </>
  );
}
function KV2({ k, v }) {
  return <div style={{ display: 'flex', padding: '6px 0', borderBottom: '1px solid var(--border-subtle)' }}>
    <span className="text-tertiary" style={{ width: 120 }}>{k}</span>
    <span>{v}</span>
  </div>;
}

// Observability page with Usage/Logs/Quality tabs
function ObservabilityPage({ openDetail }) {
  const [tab, setTab] = useGx('retrievals');
  return (
    <div style={{ padding: '32px 32px 80px', maxWidth: 1280, margin: '0 auto' }}>
      <div>
        <h1 className="t-h1" style={{ margin: 0 }}>Observability</h1>
        <div className="text-secondary t-body mt-4">Retrieval audit trail, usage, logs and quality.</div>
      </div>
      <div style={{ marginTop: 24, display: 'flex', borderBottom: '1px solid var(--border-subtle)' }}>
        {[['retrievals','Retrievals'],['usage','Usage'],['logs','Logs'],['quality','Quality']].map(([id, label]) => (
          <button key={id} onClick={() => setTab(id)} style={{
            padding: '10px 16px', marginBottom: -1,
            borderBottom: `2px solid ${tab === id ? 'var(--text-primary)' : 'transparent'}`,
            fontSize: 13, fontWeight: tab === id ? 500 : 400,
            color: tab === id ? 'var(--text-primary)' : 'var(--text-secondary)',
          }}>{label}</button>
        ))}
      </div>
      <div style={{ marginTop: 24 }}>
        {tab === 'retrievals' && <RetrievalsTab openDetail={openDetail}/>}
        {tab === 'usage' && <UsageTab/>}
        {tab === 'logs' && <LogsPageTab/>}
        {tab === 'quality' && <QualityTab/>}
      </div>
    </div>
  );
}

function RetrievalsTab({ openDetail }) {
  return (
    <>
      <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
        <div style={{ position: 'relative', flex: 1, maxWidth: 380 }}>
          <Icons.Search size={13} style={{ position: 'absolute', left: 12, top: 10, color: 'var(--text-tertiary)' }}/>
          <input className="input" placeholder="Query text, entity, document…" style={{ paddingLeft: 34 }}/>
        </div>
        <button className="btn">Last 7d <Icons.ChevronD size={11}/></button>
        <button className="btn">All clients <Icons.ChevronD size={11}/></button>
        <div style={{ flex: 1 }}/>
        <span className="mono-sm mono text-tertiary">14,889 results</span>
      </div>
      <div className="card" style={{ marginTop: 16, overflow: 'hidden' }}>
        <table className="parcle">
          <thead>
            <tr>
              <th style={{ width: 40 }}></th>
              <th>Query</th>
              <th style={{ width: 140 }}>Client</th>
              <th style={{ width: 110 }}>Cited</th>
              <th style={{ width: 160 }}>Sources</th>
              <th style={{ width: 100 }}>Latency</th>
              <th style={{ width: 80 }}>Time</th>
            </tr>
          </thead>
          <tbody>
            {RETRIEVALS.map(r => (
              <tr key={r.id} onClick={() => openDetail(r)}>
                <td><StatusGlyph status={r.status}/></td>
                <td><span style={{ fontSize: 13 }}>{r.query}</span></td>
                <td><span className="mono-sm mono text-secondary">{r.client}</span></td>
                <td><CitationPill cited={r.cited}/></td>
                <td>
                  <div style={{ display: 'flex', gap: 4, alignItems: 'center' }}>
                    {r.sources.slice(0, 3).map(s => <VendorLogo key={s} vendor={s} size={18} radius={4}/>)}
                    {r.sources.length === 0 && <span className="mono-sm mono text-tertiary">—</span>}
                  </div>
                </td>
                <td><span className="mono-sm mono text-secondary">{r.latency}ms</span></td>
                <td><span className="mono-sm mono text-tertiary">{r.time}</span></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </>
  );
}

function UsageTab() {
  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 16 }}>
        <MetricCard label="Retrieval calls" value="182,443" spark={USAGE_SPARK} delta="+18.4%"/>
        <MetricCard label="Tokens embedded" value="41.2M" spark={EMBED_SPARK} delta="+12.1%"/>
        <MetricCard label="Storage indexed" value="1.24M items" spark={USAGE_SPARK.slice().reverse()} delta="+4.8%" subtle/>
      </div>

      <div className="card" style={{ padding: 24, marginTop: 24 }}>
        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 16 }}>
          <div>
            <div className="t-h3">Plan · Pro</div>
            <div className="t-small text-tertiary mt-4">500,000 retrieval calls included per month</div>
          </div>
          <button className="btn sm">Manage billing</button>
        </div>
        <Progress value={36} height={8}/>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 10 }}>
          <span className="mono-sm mono text-secondary">182k used · 36%</span>
          <span className="mono-sm mono text-tertiary">Resets in 11 days</span>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginTop: 24 }}>
        <div className="card" style={{ padding: 20 }}>
          <div className="t-h3" style={{ marginBottom: 12 }}>By endpoint</div>
          {[['/retrieve', 82], ['/entities', 11], ['/documents', 5], ['/graph', 2]].map(([k, v]) => (
            <div key={k} style={{ marginBottom: 10 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 4 }}>
                <span className="mono-sm mono">{k}</span>
                <span className="mono-sm mono text-secondary">{v}%</span>
              </div>
              <Progress value={v} height={3}/>
            </div>
          ))}
        </div>
        <div className="card" style={{ padding: 20 }}>
          <div className="t-h3" style={{ marginBottom: 12 }}>By key</div>
          {[['prod-agent', 73], ['ci-runner', 19], ['default', 7], ['default (auto)', 1]].map(([k, v]) => (
            <div key={k} style={{ marginBottom: 10 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 4 }}>
                <span className="mono-sm mono">{k}</span>
                <span className="mono-sm mono text-secondary">{v}%</span>
              </div>
              <Progress value={v} height={3}/>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function MetricCard({ label, value, spark, delta, subtle }) {
  return (
    <div className="card" style={{ padding: 20 }}>
      <div className="mono-sm mono text-tertiary">{label}</div>
      <div className="t-display" style={{ marginTop: 6 }}>{value}</div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 4 }}>
        {delta && <span className="mono-sm mono" style={{ color: subtle ? 'var(--text-secondary)' : 'var(--success)' }}>{delta}</span>}
        <span className="mono-sm mono text-tertiary">vs. prev 30d</span>
      </div>
      <div style={{ marginTop: 14 }}>
        <Sparkline data={spark} filled/>
      </div>
    </div>
  );
}

function LogsPageTab() {
  const [sel, setSel] = useGx(null);
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 520px', gap: 16, minHeight: 520 }}>
      <div className="card" style={{ overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
        <div style={{ padding: '10px 14px', borderBottom: '1px solid var(--border-subtle)', display: 'flex', gap: 10, alignItems: 'center' }}>
          <Icons.Search size={13} style={{ color: 'var(--text-tertiary)' }}/>
          <input placeholder="filter logs…" style={{ flex: 1, border: 'none', outline: 'none', background: 'transparent', fontSize: 12 }}/>
          <button className="btn sm ghost">errors only</button>
        </div>
        <div style={{ flex: 1, overflowY: 'auto' }}>
          {LOGS.map((l, i) => {
            const sc = l.status;
            const colr = sc >= 500 ? 'var(--error)' : sc >= 400 ? 'var(--warning)' : 'var(--success)';
            const isSel = sel === i;
            return (
              <div key={i} onClick={() => setSel(i)} style={{
                display: 'grid', gridTemplateColumns: '78px 48px 1fr 54px 60px',
                gap: 10, padding: '7px 14px',
                fontSize: 12, fontFamily: "'Geist Mono', monospace",
                background: isSel ? 'var(--selected)' : 'transparent',
                borderBottom: '1px solid var(--border-subtle)',
                cursor: 'pointer', alignItems: 'center',
              }}>
                <span className="text-tertiary">{l.t}</span>
                <span style={{ color: 'var(--text-secondary)' }}>{l.method}</span>
                <span>{l.path}</span>
                <span style={{ color: colr, fontWeight: 500 }}>{l.status}</span>
                <span className="text-tertiary" style={{ textAlign: 'right' }}>{l.ms}ms</span>
              </div>
            );
          })}
        </div>
      </div>

      <div className="card" style={{ padding: 20, display: 'flex', flexDirection: 'column', gap: 16 }}>
        <div>
          <div className="mono-sm mono text-tertiary">Trace</div>
          <div className="mono" style={{ fontSize: 13 }}>req_81a4f</div>
          <div className="t-h3 mt-8">POST /v1/retrieve</div>
          <div className="mono-sm mono text-secondary mt-4">200 OK · 148ms · pk_dev_***9f82</div>
        </div>
        <div>
          <div className="t-micro text-tertiary" style={{ marginBottom: 8 }}>Timeline</div>
          {[['embed', 18, 12], ['graph', 41, 28], ['retrieve', 42, 28], ['rerank', 47, 32]].map(([l, ms, w]) => (
            <div key={l} style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 4, fontSize: 12 }}>
              <span className="mono" style={{ width: 60, color: 'var(--text-secondary)' }}>{l}</span>
              <div style={{ flex: 1, height: 14, background: 'var(--bg)', borderRadius: 2, position: 'relative' }}>
                <div style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: `${w}%`, background: 'var(--accent)', borderRadius: 2 }}/>
              </div>
              <span className="mono text-tertiary" style={{ width: 50, textAlign: 'right' }}>{ms}ms</span>
            </div>
          ))}
        </div>
        <div>
          <div className="t-micro text-tertiary" style={{ marginBottom: 8 }}>Request</div>
          <CodeBlock language="json">{'{ "query": "pricing for enterprise", "mode": "hybrid", "k": 5 }'}</CodeBlock>
        </div>
      </div>
    </div>
  );
}

function QualityTab() {
  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 16 }}>
        <MetricCard label="Answer coverage" value="94.2%" spark={COVERAGE_SPARK} delta="+1.2pp"/>
        <MetricCard label="Citations per answer" value="3.8" spark={USAGE_SPARK.slice(0,20)} delta="+0.4" subtle/>
        <MetricCard label="Avg retrieval latency" value="142ms" spark={LATENCY_SPARK} delta="−9ms"/>
      </div>

      <div className="card" style={{ padding: 24, marginTop: 24 }}>
        <div className="t-h3">Top "no-result" queries</div>
        <div className="t-small text-tertiary mt-4">Coverage = queries returning ≥ 1 result above threshold 0.6</div>
        <div style={{ marginTop: 16, display: 'flex', flexDirection: 'column', gap: 10 }}>
          {[
            ['q3 forecast', 34, ['CloudBin folder /Finance']],
            ['onboarding checklist', 22, ['PageVault space · People Ops']],
            ['dpa template', 18, ['PageVault space · Legal']],
            ['salary bands 2026', 14, ['CloudBin folder /HR-private']],
          ].map(([q, n, sugg]) => (
            <div key={q} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 14px', border: '1px solid var(--border-subtle)', borderRadius: 8 }}>
              <span className="mono-sm mono text-secondary" style={{ width: 40 }}>{n}×</span>
              <span style={{ flex: 1, fontSize: 13, fontWeight: 500 }}>"{q}"</span>
              <span className="t-small text-tertiary">suggest connecting</span>
              <button className="btn sm" style={{ color: 'var(--accent-text)' }}>{sugg[0]}</button>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

// Home
function HomePage({ setRoute }) {
  return (
    <div style={{ padding: '32px 32px 80px', maxWidth: 1080, margin: '0 auto' }}>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between' }}>
        <div>
          <h1 className="t-h1" style={{ margin: 0 }}>Welcome back, Maya</h1>
          <div className="text-secondary t-body mt-4">Here's what's happening across your org knowledge.</div>
        </div>
        <div className="mono-sm mono text-tertiary">April 21, 2026 · 10:42 UTC</div>
      </div>

      {/* Learnings digest */}
      <div style={{
        marginTop: 24, padding: '16px 20px',
        background: 'var(--accent-muted)',
        border: '1px solid transparent',
        borderRadius: 10,
        display: 'flex', alignItems: 'center', gap: 20,
      }}>
        <Icons.Sparkle size={16} style={{ color: 'var(--accent-text)' }}/>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 14, fontWeight: 500, color: 'var(--accent-text)' }}>Parcle has learned 6 new things today</div>
          <div className="mono-sm mono" style={{ color: 'var(--accent-text)', opacity: 0.8, marginTop: 2 }}>
            ◆ 2 new entities  ·  → 3 new relationships  ·  ≈ 1 de-duplication
          </div>
        </div>
        <button className="btn sm" style={{ background: 'var(--surface)', borderColor: 'transparent' }} onClick={() => setRoute('graph')}>Review all →</button>
      </div>

      {/* Status cards */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 16, marginTop: 24 }}>
        <StatusCard label="Sources connected" value="6" footer="All live · 1 partial" onClick={() => setRoute('connectors')}/>
        <StatusCard label="Retrieval calls · today" value="4,281" footer="+12% vs yesterday" onClick={() => setRoute('observability')}/>
        <StatusCard label="Latency p50" value="138ms" footer="−9ms vs 30d avg" onClick={() => setRoute('observability')}/>
      </div>

      {/* Recent retrievals */}
      <div style={{ marginTop: 32 }}>
        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 12 }}>
          <h2 className="t-h2" style={{ margin: 0 }}>Recent retrievals</h2>
          <button className="btn sm ghost" onClick={() => setRoute('observability')}>See all →</button>
        </div>
        <div className="card" style={{ overflow: 'hidden' }}>
          <table className="parcle">
            <tbody>
              {RETRIEVALS.slice(0, 5).map(r => (
                <tr key={r.id} onClick={() => setRoute('observability')}>
                  <td style={{ width: 36 }}><StatusGlyph status={r.status}/></td>
                  <td>{r.query}</td>
                  <td style={{ width: 120 }}><span className="mono-sm mono text-secondary">{r.client}</span></td>
                  <td style={{ width: 80 }}><CitationPill cited={r.cited}/></td>
                  <td style={{ width: 72 }}><span className="mono-sm mono text-tertiary">{r.time}</span></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* Shortcuts */}
      <div style={{ marginTop: 32 }}>
        <h2 className="t-h2" style={{ margin: 0, marginBottom: 12 }}>Shortcuts</h2>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }}>
          <ShortcutCard icon="Plus" title="Add a connector" desc="47 sources available" onClick={() => setRoute('connectors')}/>
          <ShortcutCard icon="Code" title="Try the API" desc="Playground with one-click cURL" onClick={() => setRoute('api')}/>
          <ShortcutCard icon="Key" title="Manage keys" desc="Rotate, scope or revoke" onClick={() => setRoute('settings')}/>
        </div>
      </div>
    </div>
  );
}
function StatusCard({ label, value, footer, onClick }) {
  return (
    <button onClick={onClick} className="card" style={{ padding: 20, textAlign: 'left' }}>
      <div className="mono-sm mono text-tertiary">{label}</div>
      <div className="t-display" style={{ marginTop: 6 }}>{value}</div>
      <div className="t-small text-secondary mt-4">{footer}</div>
    </button>
  );
}
function ShortcutCard({ icon, title, desc, onClick }) {
  const I = Icons[icon];
  return (
    <button onClick={onClick} className="card" style={{ padding: 18, textAlign: 'left', display: 'flex', gap: 14, alignItems: 'center' }}>
      <div style={{ width: 36, height: 36, borderRadius: 8, background: 'var(--accent-muted)', color: 'var(--accent-text)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><I size={16}/></div>
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 14, fontWeight: 500 }}>{title}</div>
        <div className="t-small text-tertiary mt-4">{desc}</div>
      </div>
      <Icons.ArrowR size={14} style={{ color: 'var(--text-tertiary)' }}/>
    </button>
  );
}

// Personal Home — a lightweight dashboard over the two surfaces a personal user
// has: Connectors and Team Sync (My Cloud skills, devices/agents, auto-sync).
// Every tile deep-links into the page it summarizes. Data is live (the ts*
// helpers are de-org-scoped) with mock fallback, like the rest of the app.
function PersonalHomePage({ setRoute, session, sourcesPopulated }) {
  const acct = session && session.account;
  const name = acct && acct.email ? acct.email.split('@')[0] : 'there';
  const [devices, setDevices] = React.useState(null);
  const [skills, setSkills] = React.useState(null);
  const [agentsByDev, setAgentsByDev] = React.useState({});
  const [autoSync, setAutoSync] = React.useState(false);

  React.useEffect(() => {
    let cancelled = false;
    if (typeof tsGetAutoSync === 'function') {
      tsGetAutoSync(null).then(r => { if (!cancelled) setAutoSync(!!(r && r.enabled)); }).catch(() => {});
    }
    if (typeof tsListDevices === 'function') {
      tsListDevices(null).then(list => {
        if (cancelled) return;
        const visible = (list || []).filter(d => d.status !== 'removed');
        setDevices(visible);
        // Pull agents for the devices we'll show, for the per-device chips.
        visible.slice(0, 5).forEach(d => {
          tsListAgents(null, d.id)
            .then(ags => { if (!cancelled) setAgentsByDev(prev => ({ ...prev, [d.id]: ags || [] })); })
            .catch(() => {});
        });
      }).catch(() => { if (!cancelled) setDevices([]); });
    } else { setDevices([]); }
    if (typeof tsListUserSkills === 'function') {
      tsListUserSkills(null).then(s => { if (!cancelled) setSkills(s || []); }).catch(() => { if (!cancelled) setSkills([]); });
    } else { setSkills([]); }
    return () => { cancelled = true; };
  }, []);

  const connectorCount = sourcesPopulated && typeof CONNECTED_SOURCES !== 'undefined' && CONNECTED_SOURCES ? CONNECTED_SOURCES.length : 0;
  const devTotal = devices ? devices.length : null;
  const devOnline = devices ? devices.filter(d => d.status === 'online').length : null;
  const skillCount = skills ? skills.length : null;
  const skillName = (s) => (s.bundle && s.bundle.skill_name) || s.name || 'Skill';

  const summary = [
    devTotal != null ? `${devOnline} of ${devTotal} device${devTotal === 1 ? '' : 's'} online` : null,
    skillCount != null ? `${skillCount} cloud skill${skillCount === 1 ? '' : 's'}` : null,
    `auto-sync ${autoSync ? 'on' : 'off'}`,
  ].filter(Boolean).join('  ·  ');

  return (
    <div style={{ padding: '32px 32px 80px', maxWidth: 1080, margin: '0 auto' }}>
      <h1 className="t-h1" style={{ margin: 0 }}>Welcome back, {name}</h1>
      <div className="text-secondary t-body mt-4">{summary}</div>

      {/* Status cards */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))', gap: 16, marginTop: 24 }}>
        <StatusCard label="Connectors" value={connectorCount}
          footer={connectorCount ? 'sources connected' : 'No sources yet'} onClick={() => setRoute('connectors')} />
        <StatusCard label="My Cloud Skills" value={skillCount == null ? '—' : skillCount}
          footer={skillCount ? 'in your cloud' : 'Add from a folder'} onClick={() => setRoute('teamsync')} />
        <StatusCard label="Devices online" value={devTotal == null ? '—' : `${devOnline}/${devTotal}`}
          footer={devTotal ? 'agents reachable' : 'Install the daemon'} onClick={() => setRoute('teamsync')} />
        <StatusCard label="Auto-sync" value={autoSync ? 'On' : 'Off'}
          footer={autoSync ? 'skills kept in sync' : 'Turn on in Team Sync'} onClick={() => setRoute('teamsync')} />
      </div>

      {/* Your devices */}
      <div style={{ marginTop: 32 }}>
        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 12 }}>
          <h2 className="t-h2" style={{ margin: 0 }}>Your devices</h2>
          <button className="btn sm ghost" onClick={() => setRoute('teamsync')}>Manage →</button>
        </div>
        <div className="card" style={{ overflow: 'hidden' }}>
          {devices === null && <div style={{ padding: 16 }}><div className="skeleton" style={{ height: 48 }} /></div>}
          {devices && devices.length === 0 && (
            <button onClick={() => setRoute('teamsync')} style={{ width: '100%', textAlign: 'left', padding: '18px 16px', display: 'flex', alignItems: 'center', gap: 12, background: 'transparent' }}>
              <div style={{ width: 34, height: 34, borderRadius: 8, background: 'var(--accent-muted)', color: 'var(--accent-text)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icons.Box size={16} /></div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 14, fontWeight: 500 }}>No devices yet</div>
                <div className="t-small text-tertiary mt-4">Install the daemon to sync skills to your machines.</div>
              </div>
              <Icons.ArrowR size={14} style={{ color: 'var(--text-tertiary)' }} />
            </button>
          )}
          {devices && devices.length > 0 && devices.slice(0, 5).map((d, i) => {
            const ags = agentsByDev[d.id];
            const online = d.status === 'online';
            return (
              <button key={d.id} onClick={() => setRoute('teamsync')} style={{
                width: '100%', textAlign: 'left', padding: '12px 16px', display: 'flex', alignItems: 'center', gap: 12,
                background: 'transparent', borderTop: i ? '1px solid var(--border-subtle)' : 'none',
              }}>
                <span style={{ width: 8, height: 8, borderRadius: '50%', flexShrink: 0, background: online ? 'var(--success)' : 'var(--text-tertiary)' }} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{d.display_name}</div>
                  <div className="mono-sm mono text-tertiary">{(d.os || 'unknown')} · {online ? 'online' : 'offline'}</div>
                </div>
                {ags && ags.length > 0 && (
                  <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', justifyContent: 'flex-end' }}>
                    {ags.slice(0, 3).map(a => <span key={a.id} className="chip">{a.agent_type}</span>)}
                  </div>
                )}
                <Icons.ArrowR size={14} style={{ color: 'var(--text-tertiary)', flexShrink: 0 }} />
              </button>
            );
          })}
        </div>
      </div>

      {/* My Cloud Skills — only when the user has some */}
      {skills && skills.length > 0 && (
        <div style={{ marginTop: 32 }}>
          <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 12 }}>
            <h2 className="t-h2" style={{ margin: 0 }}>My Cloud Skills</h2>
            <button className="btn sm ghost" onClick={() => setRoute('teamsync')}>See all →</button>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(220px, 1fr))', gap: 10 }}>
            {skills.slice(0, 6).map(s => (
              <button key={s.id} onClick={() => setRoute('teamsync')} className="card" style={{ padding: '12px 14px', textAlign: 'left', display: 'flex', alignItems: 'center', gap: 10 }}>
                <div style={{ width: 30, height: 30, borderRadius: 8, background: 'var(--accent-muted)', color: 'var(--accent-text)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icons.Cloud size={15} /></div>
                <span style={{ fontSize: 13, fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{skillName(s)}</span>
              </button>
            ))}
          </div>
        </div>
      )}

      {/* Quick actions */}
      <div style={{ marginTop: 32 }}>
        <h2 className="t-h2" style={{ margin: 0, marginBottom: 12 }}>Quick actions</h2>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 12 }}>
          <ShortcutCard icon="Plus" title="Add a connector" desc="Connect a data source" onClick={() => setRoute('connectors')} />
          <ShortcutCard icon="Cloud" title="Add skills" desc="Upload from a folder or device" onClick={() => setRoute('teamsync')} />
          <ShortcutCard icon="Refresh" title={autoSync ? 'Auto-sync is on' : 'Turn on Auto-sync'} desc={autoSync ? 'Skills sync to all agents' : 'Keep every agent in sync'} onClick={() => setRoute('teamsync')} />
        </div>
      </div>
    </div>
  );
}

// API Playground
function APIPage() {
  return (
    <div style={{ padding: '32px 32px 80px', maxWidth: 1280, margin: '0 auto' }}>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between' }}>
        <div>
          <h1 className="t-h1" style={{ margin: 0 }}>API Playground</h1>
          <div className="text-secondary t-body mt-4">Run retrievals against your live graph.</div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <button className="btn sm">Env: dev <Icons.ChevronD size={11}/></button>
          <button className="btn sm"><Icons.Key size={13}/> pk_dev_***9f82 <Icons.ChevronD size={11}/></button>
        </div>
      </div>

      <div style={{ marginTop: 20, display: 'flex', gap: 10, alignItems: 'center' }}>
        <button className="btn" style={{ minWidth: 180 }}>POST /v1/retrieve <Icons.ChevronD size={11}/></button>
        <div style={{ flex: 1 }}/>
        <button className="btn accent"><Icons.Play size={12}/> Run</button>
        <button className="btn">Copy as cURL</button>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginTop: 16 }}>
        <div className="card" style={{ padding: 16 }}>
          <div className="t-micro text-tertiary" style={{ marginBottom: 8 }}>Request</div>
          <CodeBlock language="json">{`{
  "query": "pricing for enterprise",
  "mode": "hybrid",
  "k": 5,
  "filters": {
    "source": ["pagevault", "cloudbin"]
  }
}`}</CodeBlock>
        </div>
        <div className="card" style={{ padding: 16 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
            <span className="t-micro text-tertiary">Response</span>
            <span className="mono-sm mono" style={{ color: 'var(--success)' }}>200 OK · 148ms</span>
          </div>
          <CodeBlock language="json">{`{
  "results": [
    {
      "chunk_id": "ch_a91f2e",
      "text": "Platform tier: $40,000/year…",
      "score": 0.93,
      "source": "pagevault",
      "entities": ["Anthropic", "Platform tier"]
    },
    { "chunk_id": "ch_b82c1d", "score": 0.89, "source": "cloudbin", ... }
  ],
  "latency_ms": 148
}`}</CodeBlock>
        </div>
      </div>

      <div className="card" style={{ marginTop: 16, padding: 20 }}>
        <div style={{ display: 'flex', gap: 32, flexWrap: 'wrap', alignItems: 'center' }}>
          <div>
            <div className="t-micro text-tertiary">Retrieved from</div>
            <div style={{ display: 'flex', gap: 8, marginTop: 6, alignItems: 'center' }}>
              <span className="chip"><VendorLogo vendor="pagevault" size={14} radius={3}/> PageVault · 2</span>
              <span className="chip"><VendorLogo vendor="cloudbin" size={14} radius={3}/> CloudBin · 1</span>
              <span className="chip"><VendorLogo vendor="chatroom" size={14} radius={3}/> ChatRoom · 1</span>
            </div>
          </div>
          <div>
            <div className="t-micro text-tertiary">Graph nodes touched</div>
            <div style={{ display: 'flex', gap: 6, marginTop: 6 }}>
              <span className="chip accent">◆ Pricing</span>
              <span className="chip accent">◆ Enterprise</span>
              <span className="chip accent">◆ Platform tier</span>
            </div>
          </div>
          <div style={{ flex: 1 }}/>
          <button className="btn sm">View this call in Retrievals →</button>
        </div>

        <div style={{ marginTop: 20 }}>
          <div className="t-micro text-tertiary" style={{ marginBottom: 8 }}>Latency breakdown</div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 2, height: 14, borderRadius: 3, overflow: 'hidden' }}>
            <div style={{ flex: 18, background: 'var(--accent)', opacity: 0.5 }}/>
            <div style={{ flex: 41, background: 'var(--accent)', opacity: 0.7 }}/>
            <div style={{ flex: 42, background: 'var(--accent)', opacity: 0.85 }}/>
            <div style={{ flex: 47, background: 'var(--accent)' }}/>
          </div>
          <div style={{ display: 'flex', gap: 18, marginTop: 8, fontSize: 11, fontFamily: "'Geist Mono', monospace", color: 'var(--text-secondary)' }}>
            <span>embed · 18ms</span>
            <span>graph · 41ms</span>
            <span>retrieve · 42ms</span>
            <span>rerank · 47ms</span>
          </div>
        </div>
      </div>
    </div>
  );
}

function SettingsPage() {
  return (
    <div style={{ padding: '32px 32px 80px', maxWidth: 1080, margin: '0 auto' }}>
      <h1 className="t-h1" style={{ margin: 0 }}>Settings</h1>
      <div className="text-secondary t-body mt-4">Org, members, billing and API keys.</div>

      <div style={{ marginTop: 32 }}>
        <h2 className="t-h2" style={{ margin: 0, marginBottom: 12 }}>API Keys</h2>
        <div className="card" style={{ overflow: 'hidden' }}>
          <table className="parcle">
            <thead>
              <tr><th>Name</th><th>Prefix</th><th>Env</th><th>Origin</th><th>Created</th><th>Last used</th></tr>
            </thead>
            <tbody>
              {[
                { name: '(default)', prefix: 'pk_live_***_cc42', env: 'live', origin: 'Auto · Claude Code', created: 'Apr 20', used: 'now' },
                { name: '(default)', prefix: 'pk_live_***_ax91', env: 'live', origin: 'Auto · Codex', created: 'Apr 20', used: 'now' },
                { name: 'ci-runner',  prefix: 'pk_dev_3a11_bb', env: 'dev',  origin: 'Manual', created: 'Apr 7', used: '4h ago' },
                { name: 'prod-agent', prefix: 'pk_live_e7b_c1',  env: 'live', origin: 'Manual', created: 'Apr 15', used: 'now' },
              ].map((k, i) => (
                <tr key={i}>
                  <td style={{ fontWeight: 500 }}>{k.name}</td>
                  <td className="mono-sm mono text-secondary">{k.prefix}</td>
                  <td><span className="chip" style={{ fontSize: 10, height: 20 }}>{k.env}</span></td>
                  <td>
                    <span className={'chip ' + (k.origin.startsWith('Auto') ? 'accent' : '')} style={{ fontSize: 10, height: 20 }}>
                      {k.origin}
                    </span>
                  </td>
                  <td className="mono-sm mono text-tertiary">{k.created}</td>
                  <td className="mono-sm mono text-secondary">{k.used}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <div style={{ marginTop: 10, display: 'flex', gap: 8 }}>
          <button className="btn"><Icons.Plus size={13}/> New key</button>
          <span className="mono-sm mono text-tertiary" style={{ alignSelf: 'center', marginLeft: 'auto' }}>Rotation: every 90 days (recommended)</span>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { GraphPage, EntityDrawer, ObservabilityPage, HomePage, APIPage, SettingsPage });
