// Retrieval detail drawer (opened from Observability → Retrievals)

const { useState: useRt, useEffect: useRtEffect } = React;

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)' }}/>;
  if (status === 'error')       return <Icons.X size={14} style={{ color: 'var(--error)' }}/>;
  if (status === 'clarify')     return <span className="mono-sm mono text-tertiary" style={{ fontWeight: 600 }}>?</span>;
  return <StatusDot size={8}/>;
}

// Retrieval detail drawer — always a real audit row, fetching the full trace
// from /skill/retrievals/{turn_id}.
function RetrievalDrawer({ open, retrieval, onClose }) {
  if (!open || !retrieval) return null;
  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)'
      }}>
        <RetrievalDetail retrieval={retrieval} onClose={onClose}/>
      </div>
    </div>
  );
}

function RetrievalDetail({ retrieval, onClose }) {
  const [det, setDet] = useRt(null);
  const [error, setError] = useRt(null);

  useRtEffect(() => {
    let alive = true;
    setDet(null); setError(null);
    ParcleRetrievalsAPI.detail(retrieval.turn_id)
      .then(d => { if (alive) setDet(d); })
      .catch(e => { if (alive) setError((e && e.message) || 'request failed'); });
    return () => { alive = false; };
  }, [retrieval.turn_id]);

  // The list row already carries the summary fields, so the drawer renders
  // instantly and only the trace waits on the detail fetch.
  const r = det || retrieval;
  const steps = det && det.response ? (det.response.steps || []) : null;
  const when = new Date(r.created_at);

  return (
    <>
      <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 }}>#{r.turn_id}</div>
          <StatusGlyph status={rtvStatusKey(r.status)}/>
          <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">{isNaN(when.getTime()) ? '—' : when.toLocaleString()}</span>
          <span className="mono-sm mono text-secondary">{rtvLatency(r.latency_ms)}</span>
          {r.confidence != null && <span className="mono-sm mono text-secondary">conf {r.confidence.toFixed(2)}</span>}
          <span className="mono-sm mono text-tertiary">{r.status}</span>
        </div>
      </div>

      <div style={{ flex: 1, overflowY: 'auto', padding: 24 }}>
        <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 }}>
          "{r.query}"
        </div>

        {r.answer && (
          <div style={{ marginTop: 20 }}>
            <div className="t-micro text-tertiary">
              {r.status === 'clarify' ? 'Agent asked to clarify' : "Agent's answer"}
            </div>
            <div style={{ marginTop: 6, padding: 14, background: 'var(--surface)', border: '1px solid var(--border-subtle)', borderRadius: 8, fontSize: 13, lineHeight: '22px', whiteSpace: 'pre-wrap' }}>
              {r.answer}
            </div>
          </div>
        )}

        {r.sources && r.sources.length > 0 && (
          <div style={{ marginTop: 24 }}>
            <div className="t-micro text-tertiary" style={{ marginBottom: 8 }}>Sources</div>
            <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
              {r.sources.map((s, i) => (
                <span key={i} className="chip accent">{s.type} · {s.name || s.id}</span>
              ))}
            </div>
          </div>
        )}

        {error && (
          <div className="t-small" style={{ marginTop: 24, color: 'var(--error)' }}>
            Couldn't load the full trace — {error}
          </div>
        )}
        {!det && !error && (
          <div className="t-small text-tertiary" style={{ marginTop: 24 }}>Loading trace…</div>
        )}
        {steps && steps.length > 0 && (
          <div style={{ marginTop: 24 }}>
            <div className="t-h3">Agent trace · {steps.length} step{steps.length === 1 ? '' : 's'}</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginTop: 12 }}>
              {steps.map((s, i) => <RetrievalStepCard key={i} step={s} idx={i + 1}/>)}
            </div>
          </div>
        )}
      </div>
    </>
  );
}

function RetrievalStepCard({ step, idx }) {
  const failed = step.status === 'failed';
  const sql = step.data && step.data.sql;
  return (
    <div style={{
      padding: 14,
      border: '1px solid var(--border-subtle)',
      borderLeft: `3px solid ${failed ? 'var(--error)' : 'var(--border)'}`,
      background: 'var(--surface)',
      borderRadius: 8,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        <span className="mono-sm mono" style={{ fontWeight: 500, color: failed ? 'var(--error)' : 'var(--text-secondary)' }}>
          {idx} · {step.title || step.id}
        </span>
        <div style={{ flex: 1 }}/>
        <span className="mono-sm mono text-tertiary">{step.status}</span>
      </div>
      {step.thought && (
        <div className="t-small text-secondary" style={{ marginTop: 8, fontStyle: 'italic' }}>{step.thought}</div>
      )}
      {step.message && (
        <div className="mono" style={{ marginTop: 8, fontSize: 11, color: 'var(--text-secondary)', whiteSpace: 'pre-wrap', maxHeight: 140, overflowY: 'auto' }}>
          {step.message}
        </div>
      )}
      {sql && (
        <div className="mono" style={{ marginTop: 8, fontSize: 11, padding: 10, background: 'var(--bg)', borderRadius: 6, whiteSpace: 'pre-wrap' }}>
          {sql}
        </div>
      )}
    </div>
  );
}

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