import { describe, test, expect, vi } from 'vitest'
import { render, screen, fireEvent } from '@testing-library/react'
import { ChatFooter } from './chat-footer'

describe('ChatFooter', () => {
  const defaultProps = {
    value: '',
    onChange: vi.fn(),
    onSend: vi.fn(),
  }

  test('renders send button', () => {
    render(<ChatFooter {...defaultProps} />)
    expect(screen.getByLabelText('Send')).toBeTruthy()
  })

  test('send button is disabled when value is empty', () => {
    render(<ChatFooter {...defaultProps} />)
    expect(screen.getByLabelText('Send').hasAttribute('disabled')).toBeTruthy()
  })

  test('renders stop button when generating', () => {
    render(<ChatFooter {...defaultProps} isGenerating onStop={vi.fn()} />)
    expect(screen.getByLabelText('Stop')).toBeTruthy()
  })

  test('calls onChange when typing', () => {
    const onChange = vi.fn()
    render(<ChatFooter {...defaultProps} onChange={onChange} />)
    const input = screen.getByPlaceholderText('Type a message...')
    fireEvent.change(input, { target: { value: 'hello' } })
    expect(onChange).toHaveBeenCalledWith('hello')
  })

  const MODELS = [
    { value: 'gpt-4o', label: 'gpt-4o' },
    { value: 'gemini-2.5-pro', label: 'gemini-2.5-pro' },
  ]

  test('no model selector when models is empty/undefined', () => {
    render(<ChatFooter {...defaultProps} />)
    expect(screen.queryByLabelText('Select model')).toBeNull()
  })

  test('no model selector when only one model is available', () => {
    render(
      <ChatFooter
        {...defaultProps}
        models={[{ value: 'gpt-4o', label: 'gpt-4o' }]}
        selectedModel='gpt-4o'
      />,
    )
    expect(screen.queryByLabelText('Select model')).toBeNull()
  })

  test('renders the selected model label', () => {
    render(
      <ChatFooter {...defaultProps} models={MODELS} selectedModel='gpt-4o' />,
    )
    const trigger = screen.getByLabelText('Select model')
    expect(trigger.textContent).toContain('gpt-4o')
  })

  test('opens the menu and fires onModelChange', () => {
    const onModelChange = vi.fn()
    render(
      <ChatFooter
        {...defaultProps}
        models={MODELS}
        selectedModel='gpt-4o'
        onModelChange={onModelChange}
      />,
    )
    fireEvent.click(screen.getByLabelText('Select model'))
    fireEvent.click(screen.getByRole('menuitem', { name: 'gemini-2.5-pro' }))
    expect(onModelChange).toHaveBeenCalledWith('gemini-2.5-pro')
  })

  test('model selector is disabled while generating', () => {
    render(
      <ChatFooter
        {...defaultProps}
        models={MODELS}
        selectedModel='gpt-4o'
        isGenerating
        onStop={vi.fn()}
      />,
    )
    expect(
      screen.getByLabelText('Select model').hasAttribute('disabled'),
    ).toBeTruthy()
  })
})
