// Retrievals / Provenance + Retrieval detail drawer

const { useState: useRt } = React;

function RetrievalsPage({ openDetail }) {
  const [filter, setFilter] = useRt('all');
  return (
    <div style={{ padding: '32px 32px 80px', maxWidth: 1280, margin: '0 auto' }}>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 8 }}>
        <div>
          <h1 className="t-h1" style={{ margin: 0 }}>Retrievals</h1>
          <div className="text-secondary t-body mt-4">Full audit trail of what the AI was shown.</div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <button className="btn sm">Export CSV</button>
          <button className="btn sm accent">Open playground →</button>
        </div>
      </div>

      {/* Sub nav */}
      <div style={{ marginTop: 24, display: 'flex', gap: 0, borderBottom: '1px solid var(--border-subtle)' }}>
        {['Retrievals', 'Usage', 'Logs', 'Quality'].map((t, i) => (
          <button key={t} style={{
            padding: '10px 16px',
            borderBottom: `2px solid ${i === 0 ? 'var(--text-primary)' : 'transparent'}`,
            fontSize: 13, fontWeight: i === 0 ? 500 : 400,
            color: i === 0 ? 'var(--text-primary)' : 'var(--text-secondary)',
            marginBottom: -1,
          }}>{t}</button>
        ))}
      </div>

      {/* Filters */}
      <div style={{ display: 'flex', gap: 10, alignItems: 'center', marginTop: 20 }}>
        <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>
        <button className="btn">All statuses <Icons.ChevronD size={11}/></button>
        <div style={{ flex: 1 }}/>
        <span className="mono-sm mono text-tertiary">14,889 results</span>
      </div>

      {/* Table */}
      <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>}
                    {r.sources.length > 3 && <span className="mono-sm mono text-tertiary">+{r.sources.length - 3}</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>
    </div>
  );
}

function StatusGlyph({ status }) {
  if (status === 'ok')          return <div style={{ width: 20, height: 20, borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'var(--success-bg)' }}><Icons.Check size={11} style={{ color: 'var(--success)' }}/></div>;
  if (status === 'noresult')    return <div style={{ width: 20, height: 20, borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'var(--warning-bg)' }}><Icons.AlertTri size={11} style={{ color: 'var(--warning)' }}/></div>;
  if (status === 'thumbs_up')   return <Icons.Thumbs size={14} style={{ color: 'var(--success)' }}/>;
  if (status === 'thumbs_down') return <Icons.ThumbsDown size={14} style={{ color: 'var(--error)' }}/>;
  return <StatusDot size={8}/>;
}

function CitationPill({ cited }) {
  const [n, m] = cited.split(' of ').map(x => parseInt(x, 10));
  const ratio = m > 0 ? n / m : 0;
  const color = n === 0 ? 'var(--text-tertiary)' : ratio === 1 ? 'var(--success)' : ratio >= 0.5 ? 'var(--text-primary)' : 'var(--warning)';
  return (
    <span className="mono-sm mono" style={{ color, fontWeight: 500 }}>{cited}</span>
  );
}

// Retrieval detail drawer
function RetrievalDrawer({ open, retrieval, onClose }) {
  if (!open) return null;
  const r = retrieval || RETRIEVALS[0];
  const isNoResult = r.status === 'noresult';
  const det = r.id === 'req_81a4f' ? RETRIEVAL_DETAIL : {
    ...RETRIEVAL_DETAIL, id: r.id,
    query: r.query, client: r.client, time: r.time + ':02', latency: r.latency, key: r.key,
    chunks: isNoResult ? [] : RETRIEVAL_DETAIL.chunks.slice(0, parseInt(r.cited.split(' of ')[1]) || 3),
    answer: isNoResult ? null : RETRIEVAL_DETAIL.answer,
  };

  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: 720, 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)'
      }}>
        {/* Header */}
        <div style={{ padding: '20px 24px', borderBottom: '1px solid var(--border-subtle)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <div className="mono text-tertiary" style={{ fontSize: 12 }}>Retrieval</div>
            <div className="mono" style={{ fontSize: 13 }}>{det.id}</div>
            <div style={{ flex: 1 }}/>
            <button className="btn sm ghost" onClick={onClose}><Icons.X size={14}/></button>
          </div>
          <div style={{ display: 'flex', gap: 16, marginTop: 10 }}>
            <span className="mono-sm mono text-secondary">{det.time}</span>
            <span className="mono-sm mono text-secondary">{det.client}</span>
            <span className="mono-sm mono text-secondary">{det.latency}ms</span>
            <span className="mono-sm mono text-tertiary">{det.key}</span>
          </div>
        </div>

        <div style={{ flex: 1, overflowY: 'auto', padding: 24 }}>
          {/* Query */}
          <div className="t-micro text-tertiary">Query</div>
          <div className="t-h2" style={{ marginTop: 4, padding: '12px 16px', background: 'var(--bg)', borderRadius: 8, border: '1px solid var(--border-subtle)', fontWeight: 400 }}>
            "{det.query}"
          </div>

          {/* Answer */}
          {det.answer && (
            <div style={{ marginTop: 20 }}>
              <div className="t-micro text-tertiary">Agent's answer <span style={{ color: 'var(--text-tertiary)' }}>· captured via MCP</span></div>
              <div style={{ marginTop: 6, padding: 14, background: 'var(--surface)', border: '1px solid var(--border-subtle)', borderRadius: 8, fontSize: 13, lineHeight: '22px' }}>
                {det.answer}
              </div>
            </div>
          )}

          {/* No-result */}
          {isNoResult && (
            <div style={{ marginTop: 20, padding: 16, border: '1px solid var(--warning-bg)', background: 'var(--warning-bg)', borderRadius: 8 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <Icons.AlertTri size={14} style={{ color: 'var(--warning)' }}/>
                <span style={{ fontSize: 13, fontWeight: 500, color: 'var(--warning)' }}>No chunks above confidence threshold (0.6)</span>
              </div>
              <div className="t-small" style={{ marginTop: 6, color: 'var(--text-secondary)' }}>
                Top below-threshold result at conf 0.41 — consider broadening your coverage.
              </div>
              <div style={{ marginTop: 14 }}>
                <div className="t-micro text-tertiary" style={{ marginBottom: 6 }}>Suggestions</div>
                <ul style={{ margin: 0, paddingLeft: 18, fontSize: 13, lineHeight: '22px' }}>
                  <li>You don't have a Legal-scoped connector</li>
                  <li style={{ color: 'var(--accent-text)' }}><a>Connect Google Drive folder /Legal →</a></li>
                </ul>
              </div>
            </div>
          )}

          {/* Chunks */}
          {det.chunks.length > 0 && (
            <div style={{ marginTop: 24 }}>
              <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between' }}>
                <div className="t-h3">
                  {det.chunks.length} chunks returned · {det.chunks.filter(c => c.cited).length} cited in answer
                </div>
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginTop: 12 }}>
                {det.chunks.map(c => <ChunkCard key={c.idx} c={c}/>)}
              </div>
            </div>
          )}

          {/* Graph nodes */}
          <div style={{ marginTop: 24 }}>
            <div className="t-micro text-tertiary" style={{ marginBottom: 8 }}>Graph nodes touched</div>
            <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
              <span className="chip accent">◆ Pricing</span>
              <span className="chip accent">◆ Enterprise</span>
              <span className="chip accent">◆ Platform tier</span>
              <button className="btn sm ghost" style={{ color: 'var(--accent-text)' }}>Open in Graph →</button>
            </div>
          </div>

          {/* Feedback */}
          <div style={{ marginTop: 24, padding: 16, background: 'var(--bg)', borderRadius: 10, border: '1px solid var(--border-subtle)' }}>
            <div className="t-h3">Was this retrieval right?</div>
            <div style={{ display: 'flex', gap: 8, marginTop: 10 }}>
              <button className="btn"><Icons.Thumbs size={13}/> Accurate</button>
              <button className="btn"><Icons.ThumbsDown size={13}/> Missed / wrong</button>
              <button className="btn ghost">Add note</button>
            </div>
            <div className="t-small text-tertiary" style={{ marginTop: 10 }}>
              Your feedback trains retrieval quality. No model training data is sent externally.
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function ChunkCard({ c }) {
  const v = VENDORS[c.vendor];
  const cited = c.cited;
  return (
    <div style={{
      padding: 14,
      border: '1px solid var(--border-subtle)',
      borderLeft: `3px solid ${cited ? 'var(--success)' : 'var(--border)'}`,
      background: 'var(--surface)',
      borderRadius: 8,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
        <span className="mono-sm mono" style={{ color: cited ? 'var(--success)' : 'var(--text-tertiary)', fontWeight: 500 }}>
          {c.idx}/5 · {cited ? 'CITED' : 'not cited'}
        </span>
        <div style={{ flex: 1 }}/>
        <span className="mono-sm mono text-tertiary">conf {c.conf.toFixed(2)}</span>
      </div>
      <div className="mono" style={{ fontSize: 12, fontStyle: 'italic', color: 'var(--text-secondary)', marginBottom: 10 }}>
        {c.text}
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12, flexWrap: 'wrap' }}>
        <VendorLogo vendor={c.vendor} size={18} radius={4}/>
        <span style={{ fontWeight: 500 }}>{v.name}</span>
        <span className="text-tertiary">· {c.path}</span>
        {c.stale && <span className="chip warning" style={{ fontSize: 10, height: 20 }}><Icons.AlertTri size={10}/> stale 11mo</span>}
        <span style={{ flex: 1 }}/>
        <span className="mono-sm mono text-tertiary">Updated {c.updated}</span>
      </div>
      <div style={{ marginTop: 10 }}>
        <button className="btn sm" style={{ fontSize: 11, color: 'var(--accent-text)', borderColor: 'var(--accent-muted)' }}>
          Open in {v.name} <Icons.External size={11}/>
        </button>
      </div>
    </div>
  );
}

Object.assign(window, { RetrievalsPage, RetrievalDrawer });
