import { describe, expect, it } from 'vitest'
import { render, screen } from '@testing-library/react'
import { VirtualList } from './virtual'

describe('VirtualList', () => {
  it('renders a grid with the full row count exposed for screen readers, but windows the DOM', () => {
    const items = Array.from({ length: 100 }, (_, index) => `Row ${index}`)

    render(
      <VirtualList
        items={items}
        estimateSize={30}
        renderRow={(item) => <span>{item}</span>}
      />,
    )

    const grid = screen.getByRole('grid')
    expect(grid.getAttribute('aria-rowcount')).toBe('100')
    expect(screen.getByText('Row 0')).toBeTruthy()
    expect(screen.queryByText('Row 99')).toBeNull()
  })

  it('numbers each rendered row via aria-rowindex (1-based)', () => {
    const items = Array.from({ length: 5 }, (_, index) => `Row ${index}`)

    render(
      <VirtualList
        items={items}
        estimateSize={30}
        renderRow={(item) => <span>{item}</span>}
      />,
    )

    const rows = screen.getAllByRole('row')
    expect(rows.length).toBeGreaterThan(0)
    expect(rows[0]?.getAttribute('aria-rowindex')).toBe('1')
  })

  it('renders the empty slot and a zero-row grid when items is empty', () => {
    render(
      <VirtualList
        items={[]}
        estimateSize={30}
        renderRow={() => null}
        empty={<span>Nothing here</span>}
      />,
    )

    expect(screen.getByRole('grid').getAttribute('aria-rowcount')).toBe('0')
    expect(screen.getByText('Nothing here')).toBeTruthy()
  })

  it('mirrors to RTL when the document direction is rtl', () => {
    document.documentElement.dir = 'rtl'
    const items = ['a', 'b', 'c']

    render(
      <VirtualList items={items} estimateSize={30} renderRow={(item) => <span>{item}</span>} />,
    )

    expect(screen.getByRole('grid').getAttribute('dir')).toBe('rtl')
    document.documentElement.dir = 'ltr'
  })

  it('uses getRowKey to derive a stable key instead of the array index', () => {
    const items = [{ id: 'x' }, { id: 'y' }]

    render(
      <VirtualList
        items={items}
        estimateSize={30}
        getRowKey={(item) => item.id}
        renderRow={(item) => <span>{item.id}</span>}
      />,
    )

    expect(screen.getByText('x')).toBeTruthy()
    expect(screen.getByText('y')).toBeTruthy()
  })
})
