import '@testing-library/jest-dom'

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

import { PktBackLink } from './BackLink'

expect.extend(toHaveNoViolations)

afterEach(cleanup)

describe('PktBackLink', () => {
  test('renders with default text and href', () => {
    const { getByRole } = render(<PktBackLink />)
    const link = getByRole('link')
    expect(link).toHaveTextContent('Forsiden')
    expect(link).toHaveAttribute('href', '/')
  })

  test('renders with custom text and href', () => {
    const { getByRole } = render(<PktBackLink href="/custom-url" text="Custom Text" />)
    const link = getByRole('link')
    expect(link).toHaveTextContent('Custom Text')
    expect(link).toHaveAttribute('href', '/custom-url')
  })

  test('calls onClick when clicked', () => {
    const onClickMock = vi.fn()
    const { getByText } = render(<PktBackLink text="Back" onClick={onClickMock} />)
    fireEvent.click(getByText('Back'))
    expect(onClickMock).toHaveBeenCalledTimes(1)
  })

  test('renders with default aria-label on nav', () => {
    const { container } = render(<PktBackLink />)
    const nav = container.querySelector('nav')
    expect(nav).toHaveAttribute('aria-label', 'Gå tilbake til forrige side')
  })

  test('renders with custom aria-label on nav', () => {
    const { container } = render(<PktBackLink ariaLabel="Tilbake til oversikt" />)
    const nav = container.querySelector('nav')
    expect(nav).toHaveAttribute('aria-label', 'Tilbake til oversikt')
  })

  test('forwards ref to nav element', () => {
    const ref = createRef<HTMLElement>()
    render(<PktBackLink ref={ref} />)
    expect(ref.current).toBeInstanceOf(HTMLElement)
    expect(ref.current?.tagName).toBe('NAV')
  })

  test('supports custom renderLink', () => {
    const { getByRole } = render(
      <PktBackLink
        href="/test"
        text="Tilbake"
        renderLink={({ href, className, children }) => (
          <button data-href={href} className={className}>
            {children}
          </button>
        )}
      />,
    )
    const button = getByRole('button')
    expect(button).toHaveAttribute('data-href', '/test')
    expect(button).toHaveTextContent('Tilbake')
  })

  describe('accessibility', () => {
    test('renders with no wcag errors with axe', async () => {
      const { container } = render(<PktBackLink text="Tilbake" href="/" />)
      const results = await axe(container)
      expect(results).toHaveNoViolations()
    })
  })
})
