import { describe, it, expect, beforeEach, afterEach } from 'vitest'
import { fireEvent, render, screen } from '@testing-library/react'
import { Provider } from '../../provider/widget-provider'
import { clearAllWidgetStores, getWidgetStore } from '../../stores'
import { ChangeColumn } from './change-column'
import type { ChangeColumnWidgetState } from './types'

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

const ITEMS = [
  { id: 'a', label: 'Alpha' },
  { id: 'b', label: 'Beta' },
  { id: 'c', label: 'Gamma' },
]

describe('<ChangeColumn>', () => {
  it('renders nothing when fewer than two columns are provided', () => {
    const { container } = render(
      <Provider id='cc1' data={[]}>
        <ChangeColumn columns={[ITEMS[0]!]} />
      </Provider>,
    )
    expect(container.querySelector('button')).toBeNull()
  })

  it('renders the trigger and opens the menu listing every column in order', () => {
    render(
      <Provider id='cc2' data={[]}>
        <ChangeColumn columns={ITEMS} labels={{ trigger: 'Reorder' }} />
      </Provider>,
    )
    fireEvent.click(screen.getByLabelText('Reorder'))
    const items = screen.getAllByRole('menuitem')
    expect(items.map((el) => el.textContent)).toEqual([
      'Alpha',
      'Beta',
      'Gamma',
    ])
  })

  it('uses columnOrder from the store when present', () => {
    render(
      <Provider id='cc3' data={[]}>
        <ChangeColumn columns={ITEMS} labels={{ trigger: 'Reorder' }} />
      </Provider>,
    )
    getWidgetStore('cc3').setState({
      columnOrder: ['c', 'a', 'b'],
    } as Partial<ChangeColumnWidgetState>)
    fireEvent.click(screen.getByLabelText('Reorder'))
    const items = screen.getAllByRole('menuitem')
    expect(items.map((el) => el.textContent)).toEqual([
      'Gamma',
      'Alpha',
      'Beta',
    ])
  })
})
