import { describe, expect, it, vi } from 'vitest'

import { fireEvent, renderWithProviders, screen } from '../../../test/utils'

import ImageViewer from './ImageViewer'

describe('ImageViewer', () => {
  const items = [
    { src: 'https://cdn.example.com/one.jpg', alt: 'One' },
    { src: 'https://cdn.example.com/two.jpg', filename: 'two.png' },
  ]

  it('renders nothing without an active item', () => {
    const { container } = renderWithProviders(
      <ImageViewer open onClose={vi.fn()} items={[]} />
    )
    expect(container.firstChild).toBeNull()
  })

  it('gates the image on open and resolves filename labels', () => {
    const { rerender } = renderWithProviders(
      <ImageViewer open={false} onClose={vi.fn()} items={[items[0]]} />
    )
    expect(screen.queryByRole('img')).toBeNull()
    expect(screen.getByTestId('image-viewer')).toHaveAttribute(
      'aria-label',
      'one.jpg'
    )
    expect(
      screen
        .getByTestId('image-viewer')
        .querySelector('button[aria-label="Download one.jpg"]')
    ).toBeInTheDocument()
    rerender(<ImageViewer open onClose={vi.fn()} items={[items[0]]} />)
    expect(screen.getByRole('img')).toHaveAttribute('alt', 'One')
    expect(screen.getByRole('img')).toHaveAttribute('draggable', 'false')
  })

  it('renders counter and navigation only for multiple items', () => {
    renderWithProviders(
      <ImageViewer open onClose={vi.fn()} items={items} initialIndex={99} />
    )
    expect(screen.getByText('2 / 2')).toBeInTheDocument()
    expect(
      screen.getByRole('button', { name: 'Previous image' })
    ).toBeInTheDocument()
    expect(screen.getByRole('img')).toHaveAttribute('src', items[1].src)
    fireEvent.click(screen.getByRole('button', { name: 'Previous image' }))
    expect(screen.getByText('1 / 2')).toBeInTheDocument()
    expect(screen.getByRole('img')).toHaveAttribute('src', items[0].src)
  })
})
