import { fireEvent, render, screen } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { PlanRunListRow } from './PlanRunListRow'
import { planRunListRowFixture } from './fixtures/plans'

describe('PlanRunListRow', () => {
  beforeEach(() => {
    vi.useFakeTimers()
    vi.setSystemTime(Date.UTC(2026, 6, 18, 12))
  })
  afterEach(() => vi.useRealTimers())

  it('renders verified run chips and absolute-time tooltip data', () => {
    render(
      <PlanRunListRow
        {...planRunListRowFixture}
        selected
        onSelect={vi.fn()}
      />,
    )

    expect(screen.getByText('running')).toBeInTheDocument()
    expect(screen.getByTestId('status-chip')).toHaveAttribute('data-status-category', 'running')
    expect(screen.getByText('run #28')).toBeInTheDocument()
    expect(screen.getByText('4/6 tasks')).toBeInTheDocument()
    expect(screen.getByText('2 active agents')).toBeInTheDocument()
    expect(screen.getByText('4m ago')).toHaveAttribute(
      'data-tipb',
      '2026-07-18T11:56:00.000Z',
    )
    expect(screen.getByRole('button', { name: 'Select Optimize data integrity' })).toHaveAttribute(
      'aria-pressed',
      'true',
    )
    expect(screen.getByRole('article')).toHaveClass('shrink-0')
  })

  it('omits absent sequence and zero active-agent values', () => {
    render(
      <PlanRunListRow
        {...planRunListRowFixture}
        seq={undefined}
        activeAgents={0}
        selected={false}
        onSelect={vi.fn()}
      />,
    )

    expect(screen.queryByText(/run #/)).not.toBeInTheDocument()
    expect(screen.queryByText(/active agent/)).not.toBeInTheDocument()
  })

  it('selects from the row button while Open remains navigation', () => {
    const onSelect = vi.fn()
    render(
      <PlanRunListRow
        {...planRunListRowFixture}
        selected={false}
        onSelect={onSelect}
      />,
    )

    fireEvent.click(screen.getByRole('button', { name: 'Select Optimize data integrity' }))
    expect(onSelect).toHaveBeenCalledTimes(1)
    const open = screen.getByRole('link', { name: 'Open' })
    expect(open).toHaveAttribute('href', '/plans/opt-data-integrity')
    expect(onSelect).toHaveBeenCalledTimes(1)
  })

  it('omits the timestamp instead of crashing when updatedAtMs is not finite', () => {
    render(
      <PlanRunListRow
        {...planRunListRowFixture}
        updatedAtMs={Number.NaN}
        selected={false}
        onSelect={vi.fn()}
      />,
    )

    expect(screen.queryByRole('time')).not.toBeInTheDocument()
    expect(screen.getByText('4/6 tasks')).toBeInTheDocument()
  })
})
