import { describe, it, expect, vi } from 'vitest'
import { render, screen, fireEvent } from '@testing-library/svelte'
import AlertModal from './AlertModal.svelte'

describe('AlertModal', () => {
  it('renders nothing when open is false', () => {
    render(AlertModal, {
      props: { open: false, title: 'Notice', message: 'Hello' },
    })
    expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument()
  })

  it('renders title and message when open', () => {
    render(AlertModal, {
      props: {
        open: true,
        title: 'Error',
        message: 'Something went wrong.',
      },
    })
    expect(screen.getByRole('alertdialog')).toBeInTheDocument()
    expect(screen.getByText('Error')).toBeInTheDocument()
    expect(screen.getByText('Something went wrong.')).toBeInTheDocument()
  })

  it('calls onClose when OK is clicked', async () => {
    const onClose = vi.fn()
    render(AlertModal, {
      props: {
        open: true,
        title: 'Notice',
        message: 'Done.',
        okLabel: 'OK',
        onClose,
      },
    })
    await fireEvent.click(screen.getByRole('button', { name: 'OK' }))
    expect(onClose).toHaveBeenCalledTimes(1)
  })

  it('calls onClose on Escape key', async () => {
    const onClose = vi.fn()
    render(AlertModal, {
      props: { open: true, title: 'Notice', message: 'Hi', onClose },
    })
    const dialog = screen.getByRole('alertdialog')
    await fireEvent.keyDown(dialog, { key: 'Escape' })
    expect(onClose).toHaveBeenCalledTimes(1)
  })

  it('calls onClose on Enter key', async () => {
    const onClose = vi.fn()
    render(AlertModal, {
      props: { open: true, title: 'Notice', message: 'Hi', onClose },
    })
    const dialog = screen.getByRole('alertdialog')
    await fireEvent.keyDown(dialog, { key: 'Enter' })
    expect(onClose).toHaveBeenCalledTimes(1)
  })

  it('calls onClose when backdrop is clicked', async () => {
    const onClose = vi.fn()
    const { container } = render(AlertModal, {
      props: { open: true, title: 'Notice', message: 'Hi', onClose },
    })
    const backdrop = container.querySelector('.modal-backdrop')
    expect(backdrop).toBeTruthy()
    await fireEvent.click(backdrop)
    expect(onClose).toHaveBeenCalledTimes(1)
  })
})
