import { describe, it, expect, beforeEach } from 'vitest'
import { mountSuspended, registerEndpoint } from '@nuxt/test-utils/runtime'
import DefaultLayout from '../../app/layouts/default.vue'
import NavDrawer from '../../app/components/NavDrawer.vue'

const wait = (ms = 100) => new Promise(r => setTimeout(r, ms))

describe('default layout', () => {
  beforeEach(() => {
    registerEndpoint('/api/me', () => ({ id: '1', identifier: 'user', role: 'member', avatar_url: null }), { method: 'GET' })
  })

  it.each([
    ['KestrelOS header', 'KestrelOS'],
    ['drawer toggle', 'button[aria-label="Toggle navigation"]'],
  ])('renders %s', async (description, selector) => {
    const wrapper = await mountSuspended(DefaultLayout)
    if (selector.startsWith('button')) {
      expect(wrapper.find(selector).exists()).toBe(true)
    }
    else {
      expect(wrapper.text()).toContain(selector)
    }
  })

  it('renders NavDrawer', async () => {
    const wrapper = await mountSuspended(DefaultLayout)
    expect(wrapper.findComponent(NavDrawer).exists()).toBe(true)
  })

  it('renders user menu and sign out navigates home', async () => {
    registerEndpoint('/api/auth/logout', () => null, { method: 'POST' })
    const wrapper = await mountSuspended(DefaultLayout)
    await wait()
    const menuTrigger = wrapper.find('button[aria-label="User menu"]')
    await menuTrigger.trigger('click')
    await wait(50)
    const signOut = wrapper.find('button[role="menuitem"]')
    expect(signOut.text()).toContain('Sign out')
    await signOut.trigger('click')
    await wait()
    const router = useRouter()
    await router.isReady()
    expect(router.currentRoute.value.path).toBe('/')
  })
})
