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

describe('admin.js', () => {
    beforeEach(() => {
        document.body.innerHTML = ''
        vi.restoreAllMocks()
        globalThis.confirm = vi.fn()
    })

    it('prevents form submit when confirm is cancelled', async () => {
        document.body.innerHTML = `
            <form data-confirm="Are you sure?">
                <button type="submit">Delete</button>
            </form>
        `

        globalThis.confirm.mockReturnValue(false)

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

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

        expect(globalThis.confirm).toHaveBeenCalledWith('Are you sure?')
        expect(event.defaultPrevented).toBe(true)
    })

    it('allows form submit when confirm is accepted', async () => {
        document.body.innerHTML = `
            <form data-confirm="Are you sure?">
                <button type="submit">Delete</button>
            </form>
        `

        globalThis.confirm.mockReturnValue(true)

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

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

        expect(globalThis.confirm).toHaveBeenCalledWith('Are you sure?')
        expect(event.defaultPrevented).toBe(false)
    })

    it('does nothing on forms without data-confirm', async () => {
        document.body.innerHTML = `
            <form>
                <button type="submit">Submit</button>
            </form>
        `

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

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

        expect(globalThis.confirm).not.toHaveBeenCalled()
        expect(event.defaultPrevented).toBe(false)
    })
})
