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 { StackToggle } from './stack-toggle'

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

/**
 * Stack/Zoom/Brush share the same toggle wiring. This file is the exemplar.
 * The transforms themselves are tested in `transforms.test.ts` /
 * `…/zoom-toggle/transforms.test.ts` / `…/brush-toggle/transforms.test.ts`.
 */
describe('<StackToggle>', () => {
  it('starts disabled by default and uses the off-state label', () => {
    render(
      <Provider id='st1' data={[]}>
        <StackToggle />
      </Provider>,
    )
    const btn = screen.getByRole('button', { name: 'Stack series' })
    expect(btn.getAttribute('aria-pressed')).toBe('false')
  })

  it('toggles aria-pressed and label on click', () => {
    render(
      <Provider id='st2' data={[]}>
        <StackToggle />
      </Provider>,
    )
    fireEvent.click(screen.getByRole('button', { name: 'Stack series' }))
    const after = screen.getByRole('button', { name: 'Unstack series' })
    expect(after.getAttribute('aria-pressed')).toBe('true')
  })

  it('persists the enabled flag on the widget store under transformStates', () => {
    render(
      <Provider id='st3' data={[]}>
        <StackToggle />
      </Provider>,
    )
    fireEvent.click(screen.getByRole('button', { name: 'Stack series' }))
    expect(
      getWidgetStore('st3').getState().transformStates['stack-toggle']?.enabled,
    ).toBe(true)
  })

  it('initialEnabled=true mounts already-on', () => {
    render(
      <Provider id='st4' data={[]}>
        <StackToggle initialEnabled />
      </Provider>,
    )
    expect(
      screen
        .getByRole('button', { name: 'Unstack series' })
        .getAttribute('aria-pressed'),
    ).toBe('true')
  })
})
