import type { CaseError, TurnState } from '../hooks/useRunSession'
import ChatBubble from './ChatBubble'
import { colors } from '../tokens'

interface TurnListProps {
  turns: TurnState[]
  errors?: CaseError[]
  showRoundLabel?: boolean
  gap?: number
}

/**
 * Renders a list of conversation turns as chat bubbles.
 * Consolidates the previously duplicated turn-rendering logic from CaseBlock
 * and CaseDetail (and eventually Reports).
 */
export default function TurnList({ turns, errors = [], showRoundLabel = true, gap = 4 }: TurnListProps) {
  return (
    <>
      {turns.map((t) => (
        <div key={t.roundIndex} style={{ marginBottom: gap }}>
          {showRoundLabel && (
            <div style={{ fontSize: 11, color: colors.textMuted, margin: '4px 0 6px' }}>
              第 {t.roundIndex} 轮
              {t.latency_ms != null && (
                <span style={{ marginLeft: 8, color: colors.primary }}>{t.latency_ms}ms</span>
              )}
            </div>
          )}
          {t.message && <ChatBubble role="user" content={t.message} />}
          {t.error ? (
            <ChatBubble role="system" content={`发送失败: ${t.error}`} />
          ) : t.pending ? (
            <ChatBubble role="agent" content={null} pending />
          ) : t.reply ? (
            <ChatBubble role="agent" content={t.reply} />
          ) : null}
        </div>
      ))}
      {errors.filter((e) => e.round == null).map((e, i) => (
        <ChatBubble key={i} role="system" content={e.message} />
      ))}
    </>
  )
}
