// Knowledge Base screen — hybrid search, sources, index health, collections

const KB_SOURCES = [
  { id: 'docs',     name: 'Product Docs',    icon: 'book',   path: '/docs',              count: '1,284 pages',   fresh: 'synced 4m ago',  status: 'live'  },
  { id: 'runbooks', name: 'Runbooks',        icon: 'log',    path: 'ops/runbooks',       count: '96 docs',       fresh: 'synced 12m ago', status: 'live'  },
  { id: 'tickets',  name: 'Support Tickets', icon: 'layers', path: 'Tickets module',     count: '8,402 threads', fresh: 'syncing · 81%',  status: 'sync'  },
  { id: 'code',     name: 'Codebase',        icon: 'branch', path: '6 repositories',     count: '41,209 files',  fresh: 'synced 1h ago',  status: 'live'  },
  { id: 'api',      name: 'API Specs',       icon: 'box',    path: 'OpenAPI · 14 svc',   count: '912 endpoints', fresh: 'synced 22m ago', status: 'live'  },
  { id: 'changelog',name: 'Changelogs',      icon: 'clock',  path: 'releases/*',         count: '312 entries',   fresh: 'stale · 2d ago', status: 'warn'  },
];

const KB_RESULTS = [
  { score: 0.94, source: 'runbooks', sourceLabel: 'Runbook', path: 'ops/runbooks/db-partition-cutover.md',
    title: 'Partition cutover procedure',
    snippet: 'Switch read traffic to <mark>users_new</mark> in shadow mode, verify parity ≥ 99.99% across 50k probe queries, then promote writes. Roll back instantly if parity drops below threshold.' },
  { score: 0.89, source: 'code', sourceLabel: 'Code', path: 'migrator/src/cutover.ts · L142',
    title: 'cutover.promoteWrites()',
    snippet: 'Acquires advisory lock, flips routing flag, drains in-flight writes to legacy table, then re-points the connection pool. Emits <mark>cutover.completed</mark> on the audit bus.' },
  { score: 0.81, source: 'docs', sourceLabel: 'Docs', path: '/docs/migrations/zero-downtime',
    title: 'Zero-downtime migrations',
    snippet: 'A safe cutover happens in three phases — shadow, read-switch, write-switch. Each phase is independently reversible and gated behind an approval when the table affects billing.' },
  { score: 0.74, source: 'tickets', sourceLabel: 'Ticket', path: 'TKT-2218 · resolved',
    title: 'Cutover stalled on idx rebuild',
    snippet: 'Index <mark>idx_users_email</mark> rebuild took 3× baseline. Mitigation: build concurrently before the read-switch phase, not during.' },
];

const KB_COLLECTIONS = [
  { name: 'Incident response', docs: 42, color: 'var(--c-status-failed)' },
  { name: 'Onboarding',        docs: 31, color: 'var(--c-status-running)' },
  { name: 'Billing & payments',docs: 58, color: 'var(--c-status-review)' },
  { name: 'Security policies', docs: 27, color: 'var(--c-status-done)' },
];

const KB_RECENT = [
  'rollback steps for failed module install',
  'who owns the autoscaler config',
  'rate limits on the billing webhooks',
  'how to rotate KMS keys safely',
];

function KbScore({ score }) {
  return (
    <span className="kb-score" title={`hybrid relevance ${score}`}>
      <span className="kb-score-bar"><span style={{ width: `${score * 100}%` }} /></span>
      <span className="kb-score-num">{score.toFixed(2)}</span>
    </span>
  );
}

function KnowledgeBase() {
  const [query, setQuery] = React.useState('how does partition cutover work');

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <h1 className="page-title">Knowledge Base</h1>
          <p className="page-sub">Hybrid vector + lexical index over docs, runbooks, tickets & code · queried by agents at dispatch time</p>
        </div>
        <div style={{ marginLeft: 'auto', display: 'flex', gap: 6 }}>
          <button className="btn ghost" type="button"><Icon name="box" size={12} />Add source</button>
          <button className="btn" type="button"><Icon name="refresh" size={12} />Rebuild index</button>
          <button className="btn primary" type="button"><Icon name="spark" size={12} />Ask agent</button>
        </div>
      </div>

      <div className="kpi-grid">
        <div className="kpi">
          <div className="kpi-label">Indexed docs</div>
          <div className="kpi-value">52,415</div>
          <div className="kpi-foot ok">▲ 1,204 this week</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Vectors</div>
          <div className="kpi-value">1.94M</div>
          <div className="kpi-foot">3,072-dim · ClickHouse</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Sources</div>
          <div className="kpi-value">6<span style={{ fontSize: 13, color: 'var(--c-text-3)', fontWeight: 400, marginLeft: 6 }}>connected</span></div>
          <div className="kpi-foot warn">1 stale · 1 syncing</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Index freshness</div>
          <div className="kpi-value">98.2%</div>
          <div className="kpi-foot ok"><span className="dot pulse" />rebuilt 4m ago</div>
        </div>
      </div>

      <div className="page-grid">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          {/* Search */}
          <div className="panel">
            <div className="kb-searchbar">
              <Icon name="search" size={16} />
              <input
                value={query}
                onChange={e => setQuery(e.target.value)}
                placeholder="Search the knowledge base…"
                spellCheck={false}
              />
              <span className="kb-mode">hybrid</span>
              <kbd className="kb-kbd">⏎</kbd>
            </div>
            <div className="kb-results-head">
              <span className="section-title" style={{ margin: 0 }}>4 results · 38ms</span>
              <span style={{ marginLeft: 'auto', display: 'flex', gap: 6 }}>
                <span className="chip chip-mono" style={{ height: 22 }}>vector 0.6</span>
                <span className="chip chip-mono" style={{ height: 22 }}>lexical 0.4</span>
              </span>
            </div>
            <div className="kb-results">
              {KB_RESULTS.map((r, i) => (
                <article className="kb-result" key={i}>
                  <div className="kb-result-top">
                    <span className={`kb-src-pill src-${r.source}`}>{r.sourceLabel}</span>
                    <span className="kb-result-title">{r.title}</span>
                    <KbScore score={r.score} />
                  </div>
                  <p className="kb-snippet" dangerouslySetInnerHTML={{ __html: r.snippet }} />
                  <div className="kb-result-foot">
                    <span className="kb-path">{r.path}</span>
                    <button className="btn sm ghost" type="button" style={{ marginLeft: 'auto' }}>
                      <Icon name="open" size={11} />Open
                    </button>
                  </div>
                </article>
              ))}
            </div>
          </div>

          {/* Sources */}
          <div className="panel">
            <div className="panel-head">
              <Icon name="database" size={14} />
              <span className="panel-title">Indexed sources</span>
              <button className="btn sm ghost" style={{ marginLeft: 'auto' }} type="button">
                <Icon name="refresh" size={11} />Sync all
              </button>
            </div>
            <div className="panel-body">
              {KB_SOURCES.map(s => (
                <div className="row" key={s.id}>
                  <div className="row-name">
                    <div className="icon-tile"><Icon name={s.icon} size={13} /></div>
                    <div>
                      <div>{s.name}</div>
                      <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10.5, color: 'var(--c-text-3)' }}>
                        {s.path} · {s.count}
                      </div>
                    </div>
                  </div>
                  <div className="row-meta">
                    {s.status === 'live' && <span className="badge live">live</span>}
                    {s.status === 'sync' && <span className="badge update">syncing</span>}
                    {s.status === 'warn' && <span className="badge review">stale</span>}
                  </div>
                  <div className="row-meta" style={{ minWidth: 92, textAlign: 'right' }}>{s.fresh}</div>
                </div>
              ))}
            </div>
          </div>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          {/* Index health */}
          <div className="panel">
            <div className="panel-head">
              <Icon name="zap" size={14} />
              <span className="panel-title">Index health</span>
              <span className="badge live" style={{ marginLeft: 'auto' }}>healthy</span>
            </div>
            <div className="panel-body" style={{ padding: '12px 14px', display: 'flex', flexDirection: 'column', gap: 10 }}>
              <div className="kb-stat"><span>Embedding model</span><b>text-embedding-3-large</b></div>
              <div className="kb-stat"><span>Dimensions</span><b>3,072</b></div>
              <div className="kb-stat"><span>Vector store</span><b>ClickHouse · hnsw</b></div>
              <div className="kb-stat"><span>Reranker</span><b>cohere-rerank-v3</b></div>
              <div style={{ marginTop: 4 }}>
                <div className="kb-stat" style={{ marginBottom: 4 }}><span>Tickets re-index</span><b style={{ color: 'var(--c-status-running)' }}>81%</b></div>
                <div className="card-progress" style={{ height: 5 }}><span style={{ width: '81%' }} /></div>
              </div>
            </div>
          </div>

          {/* Collections */}
          <div className="panel">
            <div className="panel-head">
              <Icon name="layers" size={14} />
              <span className="panel-title">Collections</span>
              <button className="btn sm ghost icon" style={{ marginLeft: 'auto' }} type="button"><Icon name="plus" size={13} /></button>
            </div>
            <div className="panel-body">
              {KB_COLLECTIONS.map((c, i) => (
                <div className="row" key={i} style={{ gridTemplateColumns: '1fr auto' }}>
                  <div className="row-name">
                    <span className="swatch" style={{ background: c.color, width: 10, height: 10, borderRadius: 3 }} />
                    <span>{c.name}</span>
                  </div>
                  <div className="row-meta">{c.docs} docs</div>
                </div>
              ))}
            </div>
          </div>

          {/* Recent queries */}
          <div className="panel">
            <div className="panel-head">
              <Icon name="search" size={14} />
              <span className="panel-title">Recent agent queries</span>
            </div>
            <div className="panel-body" style={{ padding: '6px 8px', display: 'flex', flexDirection: 'column', gap: 2 }}>
              {KB_RECENT.map((q, i) => (
                <button key={i} type="button" className="kb-recent" onClick={() => setQuery(q)}>
                  <Icon name="search" size={11} />
                  <span>{q}</span>
                  <Icon name="arrowRight" size={11} />
                </button>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

window.KnowledgeBase = KnowledgeBase;
