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 { ShowAllToggle, setShowAll, SHOW_ALL_ID } from './show-all'

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

describe('setShowAll', () => {
  it('writes the flag under transformStates[SHOW_ALL_ID]', () => {
    render(
      <Provider id='sa1' data={[]}>
        <span />
      </Provider>,
    )
    setShowAll('sa1', true)
    expect(
      getWidgetStore('sa1').getState().transformStates[SHOW_ALL_ID]?.enabled,
    ).toBe(true)
    setShowAll('sa1', false)
    expect(
      getWidgetStore('sa1').getState().transformStates[SHOW_ALL_ID]?.enabled,
    ).toBe(false)
  })
})

describe('<ShowAllToggle>', () => {
  it('renders a collapse (✕) button', () => {
    render(
      <Provider id='sa2' data={[]}>
        <ShowAllToggle />
      </Provider>,
    )
    expect(screen.getByRole('button', { name: 'Show less' })).toBeTruthy()
  })

  it('clears the flag on click (collapses)', () => {
    render(
      <Provider id='sa3' data={[]}>
        <ShowAllToggle />
      </Provider>,
    )
    setShowAll('sa3', true)
    fireEvent.click(screen.getByRole('button', { name: 'Show less' }))
    expect(
      getWidgetStore('sa3').getState().transformStates[SHOW_ALL_ID]?.enabled,
    ).toBe(false)
  })
})
