import { fireEvent, render, screen } from '@testing-library/react'
import { describe, expect, it, vi } from 'vitest'
import { CI_REPO_SUMMARIES } from './fixtures/ci-trains'
import { RepoCiStrip } from './RepoCiStrip'

describe('RepoCiStrip', () => {
  it('selects All by default and scopes it to null', () => {
    const onScope = vi.fn()
    render(<RepoCiStrip repos={CI_REPO_SUMMARIES} selectedRepo={null} onScope={onScope} />)

    const all = screen.getByRole('button', { name: 'All repositories' })
    expect(all).toHaveAttribute('aria-pressed', 'true')
    fireEvent.click(all)
    expect(onScope).toHaveBeenCalledWith(null)
  })

  it('marks and scopes only the exact selected repository', () => {
    const onScope = vi.fn()
    render(
      <RepoCiStrip
        repos={CI_REPO_SUMMARIES}
        selectedRepo="alexcodeplace/overdeck"
        onScope={onScope}
      />,
    )

    const first = screen.getByRole('button', { name: /alexcodeplace\/multideal/ })
    const selected = screen.getByRole('button', { name: /alexcodeplace\/overdeck/ })
    expect(screen.getByRole('button', { name: 'All repositories' })).toHaveAttribute('aria-pressed', 'false')
    expect(first).toHaveAttribute('aria-pressed', 'false')
    expect(selected).toHaveAttribute('aria-pressed', 'true')

    fireEvent.click(first)
    expect(onScope).toHaveBeenCalledWith('alexcodeplace/multideal')
  })

  it('renders All first and preserves repository input order', () => {
    render(<RepoCiStrip repos={[...CI_REPO_SUMMARIES].reverse()} selectedRepo={null} onScope={() => undefined} />)

    expect(screen.getAllByRole('button').map((button) => button.textContent)).toEqual([
      'All',
      expect.stringContaining('alexcodeplace/overdeck'),
      expect.stringContaining('alexcodeplace/multideal'),
    ])
  })

  it('renders a named gap state for an empty repository list', () => {
    render(<RepoCiStrip repos={[]} selectedRepo={null} onScope={() => undefined} />)
    expect(screen.getByRole('status')).toHaveTextContent('No repositories configured')
  })
})
