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

import { PktBackLink } from './BackLink'

expect.extend(toHaveNoViolations)

describe('PktBackLink', () => {
  it('renders with default text and href', async () => {
    const { getByRole } = render(<PktBackLink />)
    await window.customElements.whenDefined('pkt-backlink')
    const link = getByRole('link')
    await expect(link.textContent).toBe('Forsiden')
    await expect(link.getAttribute('href')).toBe('/')
  })

  it('renders with custom text and href', async () => {
    const { getByRole } = render(<PktBackLink href="/custom-url" text="Custom Text" />)
    await window.customElements.whenDefined('pkt-backlink')
    const link = getByRole('link')
    await expect(link.textContent).toBe('Custom Text')
    await expect(link.getAttribute('href')).toBe('/custom-url')
  })

  it('calls onClick when clicked', async () => {
    const onClickMock = jest.fn()
    const { getByText } = render(<PktBackLink text="Back" onClick={onClickMock} />)
    await window.customElements.whenDefined('pkt-backlink')
    const link = getByText('Back')
    await fireEvent.click(link)

    await expect(onClickMock).toHaveBeenCalledTimes(1)
  })

  describe('accessibility', () => {
    it('renders with no wcag errors with axe', async () => {
      const { container } = render(<PktBackLink text="Tilbake" href="/" />)

      const results = await axe(container)

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