'use client'

import { useEffect, useRef } from 'react'
import type { AdvisorTurn } from './useAdvisorStream'
import { StickyQuestion } from './StickyQuestion'
import { TurnView } from './TurnView'
import { AdvisorEmptyState } from './EmptyState'

/**
 * The Evidence Workspace body: a pinned "last question" + a scrollable history of turns, each
 * showing the answer alongside its sources / figures / footnotes. Scroll up to revisit a past
 * answer with its full evidence.
 */
export function EvidenceWorkspace({
  turns,
  exampleQuestions,
  onExample,
}: {
  turns: AdvisorTurn[]
  exampleQuestions: string[]
  onExample: (q: string) => void
}) {
  const endRef = useRef<HTMLDivElement>(null)
  const latest = turns[turns.length - 1]

  // Scroll to the newest turn when a question is added (not on every streamed token,
  // so the user can scroll up to review history while the answer streams).
  useEffect(() => {
    endRef.current?.scrollIntoView({ behavior: 'smooth' })
  }, [turns.length])

  if (turns.length === 0) {
    return (
      <div className="flex-1 overflow-y-auto bg-gray-50">
        <AdvisorEmptyState exampleQuestions={exampleQuestions} onExampleClick={onExample} />
      </div>
    )
  }

  return (
    <div className="flex-1 overflow-y-auto bg-gray-50">
      {latest && <StickyQuestion question={latest.question} />}
      <div className="space-y-4 p-4">
        {turns.map((t, i) => (
          <TurnView key={t.id} turn={t} showQuestion={i !== turns.length - 1} />
        ))}
        <div ref={endRef} />
      </div>
    </div>
  )
}
