import '@testing-library/jest-dom'

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

import { UserMenuItem } from '../header/types'
import { PktHeaderUserMenu } from './UserMenu'

expect.extend(toHaveNoViolations)

describe('PktHeaderUserMenu', () => {
  const mockUser = {
    name: 'Ola Nordmann',
  }

  const mockRepresenting = {
    name: 'Oslo Kommune',
    orgNumber: '123456789',
  }

  const menuItems: UserMenuItem[] = [
    { title: 'Profil', target: '/profil', iconName: 'user' },
    { title: 'Bookinger', target: '/bookinger', iconName: 'heart' },
    { title: 'Innstillinger', target: () => {}, iconName: 'settings' },
  ]

  it('has no a11y violations', async () => {
    const { container } = render(
      <PktHeaderUserMenu user={mockUser} representing={mockRepresenting} userMenu={menuItems} />,
    )
    const results = await axe(container)
    expect(results).toHaveNoViolations()
  })

  it('renders user section with default label when not provided', () => {
    render(<PktHeaderUserMenu user={mockUser} />)
    expect(screen.getByText('Pålogget som')).toBeInTheDocument()
    expect(screen.getByText('Ola Nordmann')).toBeInTheDocument()
  })

  it('renders representing section with default label when not provided', () => {
    render(<PktHeaderUserMenu user={mockUser} representing={mockRepresenting} />)
    expect(screen.getByText('Representerer')).toBeInTheDocument()
    expect(screen.getByText('Oslo Kommune')).toBeInTheDocument()
    expect(screen.getByText('Org.nr. 123456789')).toBeInTheDocument()
  })

  it('renders provided links as list items', () => {
    render(<PktHeaderUserMenu user={mockUser} userMenu={menuItems} />)
    expect(screen.getByRole('navigation')).toHaveClass('pkt-user-menu')
    const lists = screen.getAllByRole('list')
    expect(lists.length).toBeGreaterThan(1)
    expect(screen.getAllByRole('listitem').length).toBeGreaterThan(0)
    expect(screen.getByText('Profil')).toBeInTheDocument()
    expect(screen.getByText('Innstillinger')).toBeInTheDocument()
  })

  it('calls logoutOnClick when logout button is rendered and clicked', () => {
    const onLogout = vi.fn()
    render(<PktHeaderUserMenu user={mockUser} logoutOnClick={onLogout} />)
    const logoutButton = screen.getByText('Logg ut')
    fireEvent.click(logoutButton)
    expect(onLogout).toHaveBeenCalled()
  })

  it('supports button-type menu items and triggers their onClick', () => {
    const onClick = vi.fn()
    const items: UserMenuItem[] = [{ title: 'Konto', target: onClick, iconName: 'user' }]
    render(<PktHeaderUserMenu user={mockUser} userMenu={items} />)
    const btn = screen.getByText('Konto')
    fireEvent.click(btn)
    expect(onClick).toHaveBeenCalled()
  })
})
