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

describe('RunCommandBar', () => {
  it('disables unsupported controls with an explicit capability reason', () => {
    render(
      <RunCommandBar
        title="Run page v2"
        status="running"
        state="executing"
        seq={28}
        updatedAt="2026-07-18T12:00:00.000Z"
        capacity={<span>cursor</span>}
        coverage={<button type="button">Coverage</button>}
        controlReason="Run capabilities are not provided by this run."
      />,
    )

    expect(screen.getByRole('button', { name: 'Pause' })).toBeDisabled()
    expect(screen.getByRole('button', { name: 'Pause' })).toHaveAttribute(
      'data-tips',
      'Run capabilities are not provided by this run.',
    )
    expect(screen.getByRole('button', { name: 'Kill' })).toBeDisabled()
    expect(screen.getByText('seq 28')).toBeInTheDocument()
  })

  it('invokes supported pause and kill controls', () => {
    const onPause = vi.fn()
    const onKill = vi.fn()
    render(
      <RunCommandBar
        title="Run page v2"
        status="running"
        state="executing"
        updatedAt="2026-07-18T12:00:00.000Z"
        capacity={null}
        coverage={null}
        onPause={onPause}
        onKill={onKill}
      />,
    )

    fireEvent.click(screen.getByRole('button', { name: 'Pause' }))
    fireEvent.click(screen.getByRole('button', { name: 'Kill' }))
    fireEvent.click(screen.getByRole('button', { name: 'Confirm kill' }))
    expect(onPause).toHaveBeenCalledTimes(1)
    expect(onKill).toHaveBeenCalledTimes(1)
  })

  it('cancels a pending kill confirmation with Escape', () => {
    const onKill = vi.fn()
    render(<RunCommandBar title="Run" status="running" state="executing" updatedAt={null} capacity={null} coverage={null} onKill={onKill} />)
    fireEvent.click(screen.getByRole('button', { name: 'Kill' }))
    fireEvent.keyDown(window, { key: 'Escape' })
    expect(screen.getByRole('button', { name: 'Kill' })).toBeInTheDocument()
    expect(onKill).not.toHaveBeenCalled()
  })

  it('omits a missing update timestamp without fabricating a value', () => {
    render(
      <RunCommandBar
        title="Run page v2"
        status="failed"
        state="error"
        updatedAt={null}
        capacity={null}
        coverage={null}
      />,
    )

    expect(screen.queryByRole('time')).not.toBeInTheDocument()
    expect(screen.queryByText(/updated/)).not.toBeInTheDocument()
  })
})
