import { fireEvent, render, screen } from '@testing-library/react'
import { describe, expect, it, vi } from 'vitest'
import type { UndoToastHandle } from './UndoToast'
import { AgentStatusBar } from './AgentStatusBar'
import { liveAgentIdentityFixture } from './fixtures/agent'

describe('AgentStatusBar', () => {
  it('queues restart for five seconds and supports undo or commit', () => {
    const onRestart = vi.fn()
    const toastUndo = vi.fn<UndoToastHandle['toastUndo']>()
    const toastHandle: UndoToastHandle = { toast: vi.fn(), toastUndo }

    render(
      <AgentStatusBar
        agent={liveAgentIdentityFixture}
        onRestart={onRestart}
        toastHandle={toastHandle}
        controls={{ mode: 'pause', unavailableReason: 'Observed attempt id is required.' }}
      />,
    )

    fireEvent.click(screen.getByRole('button', { name: 'Restart' }))
    expect(toastUndo).toHaveBeenCalledWith(
      'Restarting t4.2 — nothing sent yet.',
      expect.objectContaining({ seconds: 5, onCommit: onRestart }),
    )

    const options = toastUndo.mock.calls[0]?.[1]
    options?.onUndo()
    expect(onRestart).not.toHaveBeenCalled()
    options?.onCommit()
    expect(onRestart).toHaveBeenCalledTimes(1)
  })

  it('labels unsupported controls from explicit capability state', () => {
    const { rerender } = render(
      <AgentStatusBar
        agent={liveAgentIdentityFixture}
        onRestart={vi.fn()}
        toastHandle={{ toast: vi.fn(), toastUndo: vi.fn() }}
        controls={{ mode: 'pause', unavailableReason: 'Observed attempt id is required.' }}
      />,
    )

    for (const name of ['Pause', 'Kill']) {
      const button = screen.getByRole('button', { name })
      expect(button).toBeDisabled()
      expect(button).toHaveAttribute('data-tips', 'Observed attempt id is required.')
    }

    rerender(
      <AgentStatusBar
        agent={{ ...liveAgentIdentityFixture, live: false }}
        onRestart={vi.fn()}
        toastHandle={{ toast: vi.fn(), toastUndo: vi.fn() }}
        controls={{ mode: 'pause', unavailableReason: 'Observed attempt id is required.' }}
      />,
    )
    expect(screen.queryByRole('button', { name: 'Restart' })).not.toBeInTheDocument()
  })

  it('queues an enabled kill behind confirmation undo', () => {
    const onKill = vi.fn()
    const toastUndo = vi.fn<UndoToastHandle['toastUndo']>()
    render(<AgentStatusBar agent={liveAgentIdentityFixture} onRestart={vi.fn()} toastHandle={{ toast: vi.fn(), toastUndo }} controls={{ mode: 'pause', onKill }} />)
    fireEvent.click(screen.getByRole('button', { name: 'Kill' }))
    expect(toastUndo).toHaveBeenCalledWith('Killing t4.2 — nothing sent yet.', expect.objectContaining({ onCommit: onKill }))
  })
})
