// @vitest-environment happy-dom
import { describe, expect, it, vi } from 'vitest'
import { fireEvent, render, screen } from '@testing-library/react'

/**
 * The shared admin Modal is built on Radix Dialog. These tests pin the
 * accessibility contract that the migration introduced: the surface is exposed
 * as a labelled dialog, the icon-only close control has an accessible name, and
 * Escape / close both fire `onClose`. Hand-rolled `<div>` overlays gave us none
 * of this.
 */

const { Modal } = await import('../../components/ui/Modal.js')

describe('Modal accessibility', () => {
  it('does not render content while closed', () => {
    render(
      <Modal open={false} onClose={() => {}} title="Edit page">
        <p>Body</p>
      </Modal>,
    )
    expect(screen.queryByRole('dialog')).toBeNull()
  })

  it('exposes a labelled dialog with an accessible close button', () => {
    render(
      <Modal open onClose={() => {}} title="Edit page">
        <p>Body</p>
      </Modal>,
    )
    // The title becomes the dialog's accessible name via aria-labelledby.
    expect(screen.getByRole('dialog', { name: 'Edit page' })).toBeTruthy()
    expect(screen.getByRole('button', { name: 'Close dialog' })).toBeTruthy()
  })

  it('fires onClose when the close button is activated', () => {
    const onClose = vi.fn()
    render(
      <Modal open onClose={onClose} title="Edit page">
        <p>Body</p>
      </Modal>,
    )
    fireEvent.click(screen.getByRole('button', { name: 'Close dialog' }))
    expect(onClose).toHaveBeenCalledTimes(1)
  })

  it('fires onClose when Escape is pressed', () => {
    const onClose = vi.fn()
    render(
      <Modal open onClose={onClose} title="Edit page">
        <p>Body</p>
      </Modal>,
    )
    fireEvent.keyDown(document.body, { key: 'Escape' })
    expect(onClose).toHaveBeenCalled()
  })
})
