import { describe, test, expect, vi } from 'vitest'
import { render, screen, fireEvent } from '@testing-library/react'
import { Group } from './group'

describe('Group', () => {
  const mockOptions = [
    { id: 'basemap1', label: 'Basemap 1', icon: 'icon1.png' },
    { id: 'basemap2', label: 'Basemap 2', icon: 'icon2.png' },
  ]

  const mockOnChange = vi.fn()

  test('should render all provided basemap options', () => {
    render(
      <Group values={mockOptions} selected={null} onChange={mockOnChange} />,
    )

    mockOptions.forEach((option) => {
      expect(screen.getByText(option.label)).toBeDefined()
      expect(screen.getByLabelText(option.label)).toBeDefined() // Button has aria-label equal to option.label
      expect(screen.getByLabelText(option.label + ' icon')).toBeDefined() // Image has aria-label equal to option.label + ' icon'
    })
  })

  test('should mark selected option correctly', () => {
    render(
      <Group
        values={mockOptions}
        selected='basemap1'
        onChange={mockOnChange}
      />,
    )

    const selectedImg = screen.getByLabelText('Basemap 1 icon') // The img element
    expect(selectedImg.getAttribute('data-active')).toBe('true')

    const nonSelectedImg = screen.getByLabelText('Basemap 2 icon') // The img element
    expect(nonSelectedImg.getAttribute('data-active')).toBe('false')
  })

  test('should call onChange with correct ID when an option is clicked', () => {
    render(
      <Group values={mockOptions} selected={null} onChange={mockOnChange} />,
    )

    const button = screen.getByLabelText('Basemap 2')
    fireEvent.click(button)

    expect(mockOnChange).toHaveBeenCalledTimes(1)
    expect(mockOnChange).toHaveBeenCalledWith('basemap2')
  })
})
