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

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

import PdfViewer from './PdfViewer'

describe('PdfViewer', () => {
  const items = [
    { src: 'https://cdn.example.com/one.pdf#page=3' },
    { src: 'https://cdn.example.com/two.pdf', filename: 'second.pdf' },
  ]

  it('renders nothing with no active document', () => {
    const { container } = renderWithProviders(
      <PdfViewer open onClose={vi.fn()} items={[]} />
    )
    expect(container.firstChild).toBeNull()
  })

  it('merges viewer parameters into existing fragments', () => {
    renderWithProviders(<PdfViewer open onClose={vi.fn()} items={[items[0]]} />)
    const iframe = screen.getByTitle('one.pdf')
    expect(iframe).toHaveAttribute(
      'src',
      'https://cdn.example.com/one.pdf#page=3&toolbar=0&navpanes=0'
    )
    expect(iframe).toHaveAttribute(
      'sandbox',
      'allow-scripts allow-forms allow-popups allow-downloads'
    )
  })

  it('uses filename precedence and navigates stacked documents', () => {
    renderWithProviders(
      <PdfViewer open onClose={vi.fn()} items={items} initialIndex={1} />
    )
    expect(screen.getByRole('dialog')).toHaveAttribute(
      'aria-label',
      'second.pdf'
    )
    expect(screen.getByText('2 / 2')).toBeInTheDocument()
    fireEvent.click(screen.getByRole('button', { name: 'Previous document' }))
    expect(screen.getByTitle('one.pdf')).toBeInTheDocument()
  })
})
