import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { fireEvent, render, screen } from '@testing-library/react'
import { Provider } from '../provider/widget-provider'
import { clearAllWidgetStores } from '../stores'
import { Range } from './range'
import type { RangeWidgetData } from './types'

beforeEach(() => clearAllWidgetStores())
afterEach(() => clearAllWidgetStores())

describe('<Range> bridge', () => {
  it('renders two-thumb sliders for each row', () => {
    const data: RangeWidgetData = [
      { min: 0, max: 100, value: [25, 75] },
      { min: 0, max: 50, value: [10, 40] },
    ]
    render(
      <Provider id='rng-1' data={data}>
        <Range />
      </Provider>,
    )
    // Two items × two thumbs each = 4.
    expect(screen.getAllByRole('slider').length).toBe(4)
  })

  it('defaults a row without `value` to [min, max]', () => {
    const data: RangeWidgetData = [{ min: 10, max: 90 }]
    render(
      <Provider id='rng-2' data={data}>
        <Range />
      </Provider>,
    )
    const sliders = screen.getAllByRole('slider')
    expect(sliders[0]?.getAttribute('aria-valuenow')).toBe('10')
    expect(sliders[1]?.getAttribute('aria-valuenow')).toBe('90')
  })

  it('fires onChange with item index and the new tuple', () => {
    const onChange = vi.fn()
    const data: RangeWidgetData = [{ min: 0, max: 100, value: [25, 75] }]
    render(
      <Provider id='rng-3' data={data}>
        <Range onChange={onChange} />
      </Provider>,
    )
    const sliders = screen.getAllByRole('slider')
    fireEvent.change(sliders[0]!, { target: { value: '60' } })
    expect(onChange).toHaveBeenCalled()
    const call = onChange.mock.calls[0] as [number, readonly [number, number]]
    expect(call[0]).toBe(0)
    expect(Array.isArray(call[1])).toBe(true)
    expect(call[1]).toHaveLength(2)
  })

  it('honours per-item disabled', () => {
    const data: RangeWidgetData = [
      { min: 0, max: 100, value: [25, 75], disabled: true },
    ]
    render(
      <Provider id='rng-4' data={data}>
        <Range />
      </Provider>,
    )
    const sliders = screen.getAllByRole('slider')
    expect((sliders[0] as HTMLInputElement).disabled).toBe(true)
    expect((sliders[1] as HTMLInputElement).disabled).toBe(true)
  })
})
