import { describe, it, expect, vi, beforeEach } from 'vitest'

vi.mock('../../assets/modules/mobile-menu.js', () => ({
    initMobileMenu: vi.fn(),
}))

vi.mock('../../assets/modules/tabs.js', () => ({
    initTabs: vi.fn(),
}))

import { initMobileMenu } from '../../assets/modules/mobile-menu.js'
import { initTabs } from '../../assets/modules/tabs.js'

describe('app.js', () => {
    beforeEach(() => {
        vi.clearAllMocks()
    })

    it('calls initMobileMenu and initTabs on DOMContentLoaded', async () => {
        await import('../../assets/app.js')
        document.dispatchEvent(new Event('DOMContentLoaded'))

        expect(initMobileMenu).toHaveBeenCalled()
        expect(initTabs).toHaveBeenCalled()
    })

    it('data-confirm prevents submit when cancelled', async () => {
        document.body.innerHTML = '<form data-confirm="Sure?"><button type="submit">Go</button></form>'

        await import('../../assets/app.js')
        document.dispatchEvent(new Event('DOMContentLoaded'))

        globalThis.confirm = vi.fn().mockReturnValue(false)

        const form = document.querySelector('form')
        const event = new Event('submit', { cancelable: true })
        form.dispatchEvent(event)

        expect(globalThis.confirm).toHaveBeenCalledWith('Sure?')
        expect(event.defaultPrevented).toBe(true)
    })

    it('data-confirm allows submit when confirmed', async () => {
        document.body.innerHTML = '<form data-confirm="Sure?"><button type="submit">Go</button></form>'

        await import('../../assets/app.js')
        document.dispatchEvent(new Event('DOMContentLoaded'))

        globalThis.confirm = vi.fn().mockReturnValue(true)

        const form = document.querySelector('form')
        const event = new Event('submit', { cancelable: true })
        form.dispatchEvent(event)

        expect(globalThis.confirm).toHaveBeenCalledWith('Sure?')
        expect(event.defaultPrevented).toBe(false)
    })
})
