import { describe, it, expect } from 'vitest'
import { render, screen } from '@testing-library/react'
import { CategoryLegend } from './category-legend'

const noColors = () => undefined

describe('<CategoryLegend>', () => {
  it('renders nothing when series is empty', () => {
    const { container } = render(
      <CategoryLegend series={[]} colorAt={noColors} />,
    )
    expect(container.firstChild).toBeNull()
  })

  it('renders one item per series with its name', () => {
    render(
      <CategoryLegend
        series={[{ name: '2024' }, { name: '2025' }]}
        colorAt={(i) => (i === 0 ? 'rgb(1, 1, 1)' : 'rgb(2, 2, 2)')}
      />,
    )
    expect(screen.getByText('2024')).toBeTruthy()
    expect(screen.getByText('2025')).toBeTruthy()
  })

  it('per-series color override (series[i].color) wins over colorAt(i)', () => {
    const { container } = render(
      <CategoryLegend
        series={[{ name: 'S1', color: 'rgb(99, 0, 0)' }]}
        colorAt={() => 'rgb(0, 0, 0)'}
      />,
    )
    const dot = Array.from(container.querySelectorAll('div')).find(
      (d) => (d as HTMLElement).style.backgroundColor === 'rgb(99, 0, 0)',
    )
    expect(dot).toBeTruthy()
  })

  it('falls back to colorAt(i) when series[i].color is absent', () => {
    const { container } = render(
      <CategoryLegend
        series={[{ name: 'S1' }]}
        colorAt={() => 'rgb(7, 7, 7)'}
      />,
    )
    const dot = Array.from(container.querySelectorAll('div')).find(
      (d) => (d as HTMLElement).style.backgroundColor === 'rgb(7, 7, 7)',
    )
    expect(dot).toBeTruthy()
  })
})
