import { describe, it, expect } from 'vitest'
import { render, screen } from '@testing-library/react'
import { FormulaUI } from './formula-ui'

describe('<FormulaUI>', () => {
  it('renders a single KPI value', () => {
    render(<FormulaUI items={[{ value: 1234 }]} />)
    expect(screen.getByText('1234')).toBeTruthy()
  })

  it('applies a formatter to the value', () => {
    render(
      <FormulaUI
        items={[{ value: 1234 }]}
        formatter={(n) => `$${n.toLocaleString('en-US')}`}
      />,
    )
    expect(screen.getByText('$1,234')).toBeTruthy()
  })

  it('renders prefix and suffix when provided', () => {
    render(<FormulaUI items={[{ value: 99, prefix: 'USD', suffix: '/mo' }]} />)
    expect(screen.getByText('USD')).toBeTruthy()
    expect(screen.getByText('99')).toBeTruthy()
    expect(screen.getByText('/mo')).toBeTruthy()
  })

  it('renders multiple items side-by-side', () => {
    render(
      <FormulaUI
        items={[
          { value: 100, suffix: 'rev' },
          { value: 25, suffix: 'cogs' },
          { value: 75, suffix: 'gp' },
        ]}
      />,
    )
    expect(screen.getByText('100')).toBeTruthy()
    expect(screen.getByText('25')).toBeTruthy()
    expect(screen.getByText('75')).toBeTruthy()
  })

  it('renders nothing visible when items is empty', () => {
    const { container } = render(<FormulaUI items={[]} />)
    // Root <Box> exists, but it has no item children.
    expect(container.querySelectorAll('[role]').length).toBe(0)
  })

  it('renders a series avatar with the first letter of the name', () => {
    render(
      <FormulaUI
        items={[{ value: 1, series: { name: 'Revenue', color: '#1E5BB5' } }]}
      />,
    )
    expect(screen.getByLabelText('Revenue').textContent).toBe('R')
  })

  it('renders the note when provided', () => {
    render(<FormulaUI items={[{ value: 1, note: 'Last 7 days' }]} />)
    expect(screen.getByText('Last 7 days')).toBeTruthy()
  })

  it('renders a delta chip with severity-based styling', () => {
    const { container } = render(
      <FormulaUI items={[{ value: 1, delta: { value: -0.123 } }]} />,
    )
    // MUI's `severity='error'` → `MuiChip-colorError` class.
    expect(container.querySelector('.MuiChip-colorError')).toBeTruthy()
  })

  it('uses the explicit delta label when provided', () => {
    render(
      <FormulaUI
        items={[
          {
            value: 1,
            delta: { value: 0.05, label: 'better than yesterday' },
          },
        ]}
      />,
    )
    expect(screen.getByText('better than yesterday')).toBeTruthy()
  })

  it('omits avatar / note / delta when fields are absent', () => {
    const { container } = render(<FormulaUI items={[{ value: 42 }]} />)
    expect(container.querySelector('[role="img"]')).toBeNull()
    expect(container.querySelector('.MuiChip-root')).toBeNull()
    expect(container.querySelector('p')).toBeNull()
  })
})
