import { render, screen, fireEvent } from '@testing-library/react'
import { ConversationTimeline } from '../session/ConversationTimeline'
import type { ChatMessageData } from '../chat/types'

beforeAll(() => {
  Element.prototype.scrollIntoView = jest.fn()
})

const entries: ChatMessageData[] = [
  { id: '1', role: 'assistant', content: 'Started the task' },
  { id: '2', role: 'tool', kind: 'tool', toolName: 'bash', content: 'npm test' },
  { id: '3', role: 'user', content: 'Focus on the billing page' },
]

describe('ConversationTimeline', () => {
  it('renders the timeline entries', () => {
    render(<ConversationTimeline entries={entries} />)
    expect(screen.getByText('Started the task')).toBeInTheDocument()
    expect(screen.getByText('npm test')).toBeInTheDocument()
    expect(screen.getByText('Focus on the billing page')).toBeInTheDocument()
  })

  it('renders header title, status label, and a progress bar', () => {
    render(<ConversationTimeline entries={entries} title="Session goal" statusLabel="Connected" progressPercent={42} />)
    expect(screen.getByText('Session goal')).toBeInTheDocument()
    expect(screen.getByText('Connected')).toBeInTheDocument()
    const bar = screen.getByRole('progressbar')
    expect(bar).toHaveAttribute('aria-valuenow', '42')
  })

  it('sends composed text via onSend', () => {
    const onSend = jest.fn()
    render(<ConversationTimeline entries={entries} onSend={onSend} />)
    const textarea = screen.getByRole('textbox')
    fireEvent.change(textarea, { target: { value: 'steer left' } })
    fireEvent.keyDown(textarea, { key: 'Enter' })
    expect(onSend).toHaveBeenCalledWith('steer left')
  })

  it('does not render a composer when onSend is omitted', () => {
    render(<ConversationTimeline entries={entries} />)
    expect(screen.queryByRole('textbox')).not.toBeInTheDocument()
  })

  it('renders a "Load earlier messages" control when hasMore', () => {
    const onLoadMore = jest.fn()
    render(<ConversationTimeline entries={entries} hasMore onLoadMore={onLoadMore} />)
    fireEvent.click(screen.getByRole('button', { name: /load earlier messages/i }))
    expect(onLoadMore).toHaveBeenCalledTimes(1)
  })

  it('shows the working indicator when isLoading', () => {
    render(<ConversationTimeline entries={entries} isLoading />)
    expect(screen.getByTestId('chat-working-indicator')).toBeInTheDocument()
  })
})
