import { describe, it, expect } from 'vitest'
import { mountSuspended } from '@nuxt/test-utils/runtime'
import AppSelect from './AppSelect.vue'

const options = [
  { value: 'a', label: 'Option A' },
  { value: 'b', label: 'Option B' },
]

describe('AppSelect', () => {
  it('shows the placeholder when no option is selected', async () => {
    const wrapper = await mountSuspended(AppSelect, {
      props: { modelValue: '', options, placeholder: 'Pick one' },
    })
    expect(wrapper.text()).toContain('Pick one')
  })

  it('shows the label of the selected option', async () => {
    const wrapper = await mountSuspended(AppSelect, {
      props: { modelValue: 'b', options },
    })
    expect(wrapper.text()).toContain('Option B')
  })

  it('opens the option list on trigger click and closes after selecting', async () => {
    const wrapper = await mountSuspended(AppSelect, {
      props: { modelValue: '', options },
    })
    expect(wrapper.find('.app-select-list').exists()).toBe(false)

    await wrapper.find('.app-select-trigger').trigger('click')
    expect(wrapper.find('.app-select-list').exists()).toBe(true)

    await wrapper.findAll('.app-select-option')[1].trigger('click')
    expect(wrapper.find('.app-select-list').exists()).toBe(false)
  })

  it('emits update:modelValue with the selected option value', async () => {
    const wrapper = await mountSuspended(AppSelect, {
      props: { modelValue: '', options },
    })
    await wrapper.find('.app-select-trigger').trigger('click')
    await wrapper.findAll('.app-select-option')[1].trigger('click')

    expect(wrapper.emitted('update:modelValue')?.[0]).toEqual(['b'])
  })

  it('closes the list on Escape', async () => {
    const wrapper = await mountSuspended(AppSelect, {
      props: { modelValue: '', options },
    })
    await wrapper.find('.app-select-trigger').trigger('click')
    expect(wrapper.find('.app-select-list').exists()).toBe(true)

    await document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }))
    await wrapper.vm.$nextTick()
    expect(wrapper.find('.app-select-list').exists()).toBe(false)
  })

  it('closes the list on an outside click', async () => {
    const wrapper = await mountSuspended(AppSelect, {
      props: { modelValue: '', options },
      attachTo: document.body,
    })
    await wrapper.find('.app-select-trigger').trigger('click')
    expect(wrapper.find('.app-select-list').exists()).toBe(true)

    document.body.dispatchEvent(new MouseEvent('click', { bubbles: true }))
    await wrapper.vm.$nextTick()
    expect(wrapper.find('.app-select-list').exists()).toBe(false)
  })
})
