import { createRef } from 'react'
import { render, fireEvent } from '@testing-library/react'
import { axe, toHaveNoViolations } from 'jest-axe'
import { PktAlert } from './Alert'

import { cleanup } from '@testing-library/react'

import '@testing-library/jest-dom'

expect.extend(toHaveNoViolations)

afterEach(cleanup)

describe('PktAlert', () => {
  test('ref works correctly', async () => {
    const ref = createRef<HTMLElement>()
    const { unmount } = render(<PktAlert ref={ref}>Alert text</PktAlert>)
    await window.customElements.whenDefined('pkt-alert')
    expect(ref.current).toBeInstanceOf(HTMLElement)
    unmount()
    expect(ref.current).toBeNull()
  })

  test('calls onClose when close button is clicked', async () => {
    const onClose = jest.fn()
    const { getByLabelText } = render(
      <PktAlert closeAlert={true} onClose={onClose}>
        Hello World
      </PktAlert>,
    )
    await window.customElements.whenDefined('pkt-alert')
    fireEvent.click(getByLabelText('close'))
    expect(onClose).toHaveBeenCalledTimes(1)
  })

  test('renders with default role', async () => {
    const { getByRole } = render(<PktAlert>Alert text</PktAlert>)
    await window.customElements.whenDefined('pkt-alert')
    const alert = getByRole('status')
    expect(alert).toBeInTheDocument()
    expect(alert).toHaveAttribute('role', 'status')
  })

  test('renders with alert as role prop', async () => {
    const { getByRole } = render(<PktAlert role="alert">Alert text</PktAlert>)
    await window.customElements.whenDefined('pkt-alert')
    const alert = getByRole('alert')
    expect(alert).toBeInTheDocument()
    expect(alert).toHaveAttribute('role', 'alert')
  })

  describe('accessibility', () => {
    test('renders with no wcag errors with axe', async () => {
      const { container } = render(<PktAlert title="Error" skin="error"></PktAlert>)
      await window.customElements.whenDefined('pkt-alert')
      const results = await axe(container)

      expect(results).toHaveNoViolations()
    })
  })
})
