import { fireEvent, render, screen } from '@testing-library/react'
import '@testing-library/jest-dom/vitest'
import React from 'react'
import { describe, expect, it, vi } from 'vitest'
import { HookControlToggle } from './HookControlToggle'

describe('HookControlToggle', () => {
  it('is pessimistic while pending and announces a failed update', () => {
    const onEnabledChange = vi.fn()
    const { rerender } = render(<HookControlToggle id="background-jobs-blocker" label="Block agent background jobs" hint="Disabling permits agent-initiated background commands." enabled pending error="Write failed" onEnabledChange={onEnabledChange} />)
    const input = screen.getByLabelText('Block agent background jobs')
    expect(input).toBeDisabled()
    expect(screen.getAllByText('Write failed').length).toBeGreaterThan(0)
    rerender(<HookControlToggle id="background-jobs-blocker" label="Block agent background jobs" hint="Disabling permits agent-initiated background commands." enabled pending={false} onEnabledChange={onEnabledChange} />)
    fireEvent.click(screen.getByLabelText('Block agent background jobs'))
    expect(onEnabledChange).toHaveBeenCalledWith(false)
  })

  it('links hint and error through aria-describedby', () => {
    render(<HookControlToggle id="background-jobs-blocker" label="Block agent background jobs" hint="Disabling permits agent-initiated background commands." enabled={false} pending={false} error="Write failed" onEnabledChange={vi.fn()} />)
    const input = screen.getByLabelText('Block agent background jobs')
    const describedBy = input.getAttribute('aria-describedby')?.split(/\s+/) ?? []
    expect(describedBy.length).toBeGreaterThanOrEqual(2)
    for (const id of describedBy) {
      expect(document.getElementById(id)).toBeTruthy()
    }
    expect(screen.getByText('Disabling permits agent-initiated background commands.')).toBeInTheDocument()
    expect(screen.getAllByText('Write failed').length).toBeGreaterThan(0)
  })

  it('retains the confirmed enabled state while pending', () => {
    render(<HookControlToggle id="background-jobs-blocker" label="Block agent background jobs" hint="Disabling permits agent-initiated background commands." enabled pending onEnabledChange={vi.fn()} />)
    expect(screen.getByLabelText('Block agent background jobs')).toBeChecked()
    expect(screen.getByLabelText('Block agent background jobs')).toBeDisabled()
  })
})
