// @vitest-environment jsdom
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent, waitFor } from '@testing-library/react'

const { logoutMock } = vi.hoisted(() => ({
  logoutMock: vi.fn().mockResolvedValue(undefined),
}))
vi.mock('@/actions/auth', () => ({ logoutAction: logoutMock }))

import { LogoutButton } from '@/components/mobile/logout-button'

beforeEach(() => {
  logoutMock.mockClear()
})

describe('LogoutButton', () => {
  it('toont initieel alleen de Uitloggen-knop, geen dialog', () => {
    render(<LogoutButton />)
    expect(screen.getByRole('button', { name: /Uitloggen/ })).toBeTruthy()
    expect(screen.queryByText(/Weet je zeker/)).toBeNull()
  })

  it('opent AlertDialog bij klikken op de knop', () => {
    render(<LogoutButton />)
    fireEvent.click(screen.getByRole('button', { name: /Uitloggen/ }))
    expect(screen.getByText('Uitloggen?')).toBeTruthy()
    expect(screen.getByText(/Weet je zeker/)).toBeTruthy()
  })

  it('roept logoutAction aan op bevestigen', async () => {
    const { container } = render(<LogoutButton />)
    fireEvent.click(screen.getByRole('button', { name: /Uitloggen/ }))
    // Het body-portal wordt buiten container gerenderd; query op document.body.
    const allButtons = Array.from(document.body.querySelectorAll('button'))
    const confirmBtn = allButtons.find(b => b.textContent?.trim() === 'Uitloggen' && !container.contains(b)) ?? allButtons[allButtons.length - 1]
    fireEvent.click(confirmBtn)
    await waitFor(() => expect(logoutMock).toHaveBeenCalledTimes(1))
  })

  it('roept logoutAction NIET aan bij annuleren', () => {
    render(<LogoutButton />)
    fireEvent.click(screen.getByRole('button', { name: /Uitloggen/ }))
    fireEvent.click(screen.getByText('Annuleren'))
    expect(logoutMock).not.toHaveBeenCalled()
  })
})
