import { describe, it, expect, vi } from 'vitest'
import { render, screen, fireEvent } from '@testing-library/svelte'
import QuestionEditor from './QuestionEditor.svelte'

describe('QuestionEditor', () => {
  it('renders question index and prompt placeholder', () => {
    const question = { prompt: '', explanation: '', answers: [''], correct_answer_indices: [0] }
    render(QuestionEditor, { props: { question, index: 0 } })
    expect(screen.getByText('Question 1')).toBeInTheDocument()
    expect(screen.getByPlaceholderText('Prompt')).toBeInTheDocument()
    expect(screen.getByPlaceholderText('Explanation (optional)')).toBeInTheDocument()
    expect(screen.getByPlaceholderText('Answer 1')).toBeInTheDocument()
  })

  it('calls onRemove when Remove question is clicked', async () => {
    const question = { prompt: '', explanation: '', answers: [''], correct_answer_indices: [0] }
    const onRemove = vi.fn()
    render(QuestionEditor, { props: { question, index: 0, onRemove } })
    await fireEvent.click(screen.getByTitle('Remove question'))
    expect(onRemove).toHaveBeenCalledTimes(1)
  })

  it('adds answer row when Add answer is clicked', async () => {
    const question = { prompt: '', explanation: '', answers: [''], correct_answer_indices: [0] }
    render(QuestionEditor, { props: { question, index: 0 } })
    expect(screen.getByPlaceholderText('Answer 1')).toBeInTheDocument()
    await fireEvent.click(screen.getByRole('button', { name: '+ Add answer' }))
    expect(screen.getByPlaceholderText('Answer 2')).toBeInTheDocument()
  })

  it('shows remove answer button when there is more than one answer', () => {
    const question = {
      prompt: '',
      explanation: '',
      answers: ['A', 'B'],
      correct_answer_indices: [0],
    }
    render(QuestionEditor, { props: { question, index: 0 } })
    const removeButtons = screen.getAllByTitle('Remove answer')
    expect(removeButtons.length).toBeGreaterThanOrEqual(1)
  })

  it('updates answer text on input', async () => {
    const question = { prompt: '', explanation: '', answers: [''], correct_answer_indices: [0] }
    render(QuestionEditor, { props: { question, index: 0 } })
    const input = screen.getByPlaceholderText('Answer 1')
    await fireEvent.input(input, { target: { value: 'New answer' } })
    expect(question.answers[0]).toBe('New answer')
  })

  it('toggles correct checkbox', async () => {
    const question = { prompt: '', explanation: '', answers: ['A', 'B'], correct_answer_indices: [0] }
    render(QuestionEditor, { props: { question, index: 0 } })
    const checkboxes = screen.getAllByRole('checkbox')
    expect(checkboxes.length).toBeGreaterThanOrEqual(2)
    await fireEvent.click(checkboxes[1])
    expect(question.correct_answer_indices).toContain(1)
  })
})
