import { describe, it, expect } from 'vitest'
import { mount } from '@vue/test-utils'
import SelectBoxBase from '../src/canonical/SelectBoxBase.vue'

const options = [
  { label: 'Apple', value: 'a' },
  { label: 'Banana', value: 'b' },
]

describe('SelectBox a11y controls', () => {
  it('renders the multi-select chip remove control as a real <button> with aria-label', () => {
    const wrapper = mount(SelectBoxBase, {
      props: { multiple: true, options, modelValue: ['a'] },
    })
    const remove = wrapper.find('.select-chip__close')
    expect(remove.element.tagName).toBe('BUTTON')
    expect(remove.attributes('type')).toBe('button')
    expect(remove.attributes('aria-label')).toBe('Remove option')
  })

  it('emits update:modelValue removing the option when the chip remove button is activated', async () => {
    const wrapper = mount(SelectBoxBase, {
      props: { multiple: true, options, modelValue: ['a', 'b'] },
    })
    await wrapper.find('.select-chip__close').trigger('click')
    const emitted = wrapper.emitted('update:modelValue')
    expect(emitted).toBeTruthy()
    expect(emitted![0][0]).toEqual(['b'])
  })

  it('keyboard-activates the chip remove button (Enter on a native button fires click)', async () => {
    const wrapper = mount(SelectBoxBase, {
      props: { multiple: true, options, modelValue: ['a'] },
    })
    const remove = wrapper.find('.select-chip__close')
    // native <button> activates click via Enter/Space; assert it is focusable and click-driven
    await remove.trigger('keydown', { key: 'Enter' })
    await remove.trigger('click')
    expect(wrapper.emitted('update:modelValue')).toBeTruthy()
  })

  it('renders the single-value clear control as a real <button> with aria-label and clears on activate', async () => {
    const wrapper = mount(SelectBoxBase, {
      props: {
        feature: 'time',
        ux: 'click',
        options: [{ label: '09:00', value: '09:00' }],
        modelValue: '09:00',
      },
    })
    const clear = wrapper.find('.select-clear')
    expect(clear.element.tagName).toBe('BUTTON')
    expect(clear.attributes('type')).toBe('button')
    expect(clear.attributes('aria-label')).toBe('Clear value')
    await clear.trigger('click')
    const emitted = wrapper.emitted('update:modelValue')
    expect(emitted).toBeTruthy()
    expect(emitted![0][0]).toBe('')
  })

  it('does not toggle the dropdown open when activating an inner control (@click.stop)', async () => {
    const wrapper = mount(SelectBoxBase, {
      props: { multiple: true, options, modelValue: ['a'] },
    })
    await wrapper.find('.select-chip__close').trigger('click')
    expect(wrapper.find('.select-dropdown').exists()).toBe(false)
  })
})
