import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { initCart } from '../../assets/modules/cart.js'

function createBilletterie(billets, stockUrl = '') {
    let html = `<div id="billetterie"${stockUrl ? ` data-stock-url="${stockUrl}"` : ''}>`

    for (const b of billets) {
        html += `
            <div data-cart-item data-billet-id="${b.id}" data-price="${b.price}" data-max="${b.max}">
                <button data-cart-minus></button>
                <input data-cart-qty type="number" min="0" max="${b.max || 99}" value="0" readonly>
                <button data-cart-plus></button>
                <span data-cart-line-total></span>
                <p data-stock-label></p>
            </div>
        `
    }

    html += '<div id="cart-error" class="hidden"><p id="cart-error-text"></p></div>'
    html += '<span id="cart-total"></span><span id="cart-count"></span><button id="cart-checkout" disabled data-order-url="/order"></button></div>'
    document.body.innerHTML = html
}

describe('initCart', () => {
    beforeEach(() => {
        document.body.innerHTML = ''
    })

    it('does nothing without billetterie element', () => {
        expect(() => initCart()).not.toThrow()
    })

    it('does nothing without total element', () => {
        document.body.innerHTML = '<div id="billetterie"></div>'
        expect(() => initCart()).not.toThrow()
    })

    it('initializes with zero totals', () => {
        createBilletterie([{ id: 1, price: '10.00', max: 5 }])
        initCart()

        expect(document.getElementById('cart-total').textContent).toBe('0,00 \u20AC')
        expect(document.getElementById('cart-count').textContent).toBe('0')
        expect(document.getElementById('cart-checkout').disabled).toBe(true)
    })

    it('increments quantity on plus click', () => {
        createBilletterie([{ id: 1, price: '15.00', max: 10 }])
        initCart()

        document.querySelector('[data-cart-plus]').click()

        expect(document.querySelector('[data-cart-qty]').value).toBe('1')
        expect(document.querySelector('[data-cart-line-total]').textContent).toBe('15,00 \u20AC')
        expect(document.getElementById('cart-total').textContent).toBe('15,00 \u20AC')
        expect(document.getElementById('cart-count').textContent).toBe('1')
        expect(document.getElementById('cart-checkout').disabled).toBe(false)
    })

    it('decrements quantity on minus click', () => {
        createBilletterie([{ id: 1, price: '10.00', max: 5 }])
        initCart()

        document.querySelector('[data-cart-plus]').click()
        document.querySelector('[data-cart-plus]').click()
        document.querySelector('[data-cart-minus]').click()

        expect(document.querySelector('[data-cart-qty]').value).toBe('1')
        expect(document.getElementById('cart-total').textContent).toBe('10,00 \u20AC')
    })

    it('does not decrement below zero', () => {
        createBilletterie([{ id: 1, price: '10.00', max: 5 }])
        initCart()

        document.querySelector('[data-cart-minus]').click()

        expect(document.querySelector('[data-cart-qty]').value).toBe('0')
        expect(document.getElementById('cart-total').textContent).toBe('0,00 \u20AC')
    })

    it('respects max quantity', () => {
        createBilletterie([{ id: 1, price: '10.00', max: 2 }])
        initCart()

        document.querySelector('[data-cart-plus]').click()
        document.querySelector('[data-cart-plus]').click()
        document.querySelector('[data-cart-plus]').click()

        expect(document.querySelector('[data-cart-qty]').value).toBe('2')
        expect(document.getElementById('cart-total').textContent).toBe('20,00 \u20AC')
    })

    it('allows unlimited when max is 0', () => {
        createBilletterie([{ id: 1, price: '5.00', max: 0 }])
        initCart()

        for (let i = 0; i < 50; i++) {
            document.querySelector('[data-cart-plus]').click()
        }

        expect(document.querySelector('[data-cart-qty]').value).toBe('50')
        expect(document.getElementById('cart-total').textContent).toBe('250,00 \u20AC')
    })

    it('calculates total for multiple billets', () => {
        createBilletterie([
            { id: 1, price: '10.00', max: 5 },
            { id: 2, price: '25.00', max: 3 },
        ])
        initCart()

        const plusBtns = document.querySelectorAll('[data-cart-plus]')
        plusBtns[0].click()
        plusBtns[0].click()
        plusBtns[1].click()

        // 2 * 10 + 1 * 25 = 45
        expect(document.getElementById('cart-total').textContent).toBe('45,00 \u20AC')
        expect(document.getElementById('cart-count').textContent).toBe('3')
    })

    it('disables checkout when cart is empty again', () => {
        createBilletterie([{ id: 1, price: '10.00', max: 5 }])
        initCart()

        document.querySelector('[data-cart-plus]').click()
        expect(document.getElementById('cart-checkout').disabled).toBe(false)

        document.querySelector('[data-cart-minus]').click()
        expect(document.getElementById('cart-checkout').disabled).toBe(true)
    })

    it('posts cart data on checkout click', () => {
        const fetchMock = vi.fn().mockResolvedValue({
            ok: true,
            json: () => Promise.resolve({ redirect: '/commande/1/informations' }),
        })
        globalThis.fetch = fetchMock

        createBilletterie([
            { id: 1, price: '10.00', max: 5 },
            { id: 2, price: '20.00', max: 3 },
        ])
        initCart()

        const plusBtns = document.querySelectorAll('[data-cart-plus]')
        plusBtns[0].click()
        plusBtns[0].click()
        plusBtns[1].click()

        document.getElementById('cart-checkout').click()

        expect(fetchMock).toHaveBeenCalledWith('/order', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify([
                { billetId: '1', qty: 2 },
                { billetId: '2', qty: 1 },
            ]),
        })
    })

    it('redirects after successful checkout', async () => {
        const fetchMock = vi.fn().mockResolvedValue({
            ok: true,
            json: () => Promise.resolve({ redirect: '/commande/1/paiement' }),
        })
        globalThis.fetch = fetchMock
        globalThis.location = { href: '' }

        createBilletterie([{ id: 1, price: '10.00', max: 5 }])
        initCart()

        document.querySelector('[data-cart-plus]').click()
        document.getElementById('cart-checkout').click()

        await new Promise(r => setTimeout(r, 10))

        expect(globalThis.location.href).toBe('/commande/1/paiement')
    })

    it('does not redirect when response has no redirect', async () => {
        const fetchMock = vi.fn().mockResolvedValue({
            ok: true,
            json: () => Promise.resolve({}),
        })
        globalThis.fetch = fetchMock
        globalThis.location = { href: '/original' }

        createBilletterie([{ id: 1, price: '10.00', max: 5 }])
        initCart()

        document.querySelector('[data-cart-plus]').click()
        document.getElementById('cart-checkout').click()

        await new Promise(r => setTimeout(r, 10))

        expect(globalThis.location.href).toBe('/original')
    })

    it('re-enables button on fetch error', async () => {
        const fetchMock = vi.fn().mockRejectedValue(new Error('Network error'))
        globalThis.fetch = fetchMock

        createBilletterie([{ id: 1, price: '10.00', max: 5 }])
        initCart()

        document.querySelector('[data-cart-plus]').click()
        document.getElementById('cart-checkout').click()

        await new Promise(r => setTimeout(r, 10))

        const btn = document.getElementById('cart-checkout')
        expect(btn.disabled).toBe(false)
        expect(btn.textContent).toBe('Commander')
    })

    it('handles invalid price gracefully', () => {
        document.body.innerHTML = `
            <div id="billetterie">
                <div data-cart-item data-billet-id="1" data-price="invalid" data-max="5">
                    <button data-cart-minus></button>
                    <input data-cart-qty type="number" min="0" max="5" value="0" readonly>
                    <button data-cart-plus></button>
                    <span data-cart-line-total></span>
                </div>
                <span id="cart-total"></span><span id="cart-count"></span>
                <button id="cart-checkout" disabled data-order-url="/order"></button>
            </div>
        `
        initCart()

        document.querySelector('[data-cart-plus]').click()

        expect(document.getElementById('cart-total').textContent).toBe('0,00 \u20AC')
        expect(document.getElementById('cart-count').textContent).toBe('1')
    })

    it('works without checkout button', () => {
        document.body.innerHTML = `
            <div id="billetterie">
                <div data-cart-item data-billet-id="1" data-price="10" data-max="5">
                    <button data-cart-minus></button>
                    <input data-cart-qty type="number" min="0" max="5" value="0" readonly>
                    <button data-cart-plus></button>
                    <span data-cart-line-total></span>
                </div>
                <span id="cart-total"></span><span id="cart-count"></span>
            </div>
        `
        initCart()

        document.querySelector('[data-cart-plus]').click()

        expect(document.getElementById('cart-total').textContent).toBe('10,00 \u20AC')
        expect(document.getElementById('cart-count').textContent).toBe('1')
    })

    it('does not post when cart is empty on checkout', () => {
        const fetchMock = vi.fn()
        globalThis.fetch = fetchMock

        createBilletterie([{ id: 1, price: '10.00', max: 5 }])
        initCart()

        document.getElementById('cart-checkout').disabled = false
        document.getElementById('cart-checkout').click()

        expect(fetchMock).not.toHaveBeenCalled()
    })

    it('shows error message on HTTP error', async () => {
        const fetchMock = vi.fn().mockResolvedValue({ ok: false, status: 400 })
        globalThis.fetch = fetchMock

        createBilletterie([{ id: 1, price: '10.00', max: 5 }])
        initCart()

        document.querySelector('[data-cart-plus]').click()
        document.getElementById('cart-checkout').click()

        await new Promise(r => setTimeout(r, 10))

        const errorEl = document.getElementById('cart-error')
        expect(errorEl.classList.contains('hidden')).toBe(false)
        expect(document.getElementById('cart-error-text').textContent).toContain('erreur')
    })

    it('handles checkout without error elements', async () => {
        const fetchMock = vi.fn().mockRejectedValue(new Error('fail'))
        globalThis.fetch = fetchMock

        document.body.innerHTML = `
            <div id="billetterie">
                <div data-cart-item data-billet-id="1" data-price="10" data-max="5">
                    <button data-cart-minus></button>
                    <input data-cart-qty type="number" min="0" max="5" value="0" readonly>
                    <button data-cart-plus></button>
                    <span data-cart-line-total></span>
                </div>
                <span id="cart-total"></span><span id="cart-count"></span>
                <button id="cart-checkout" disabled data-order-url="/order"></button>
            </div>
        `
        initCart()

        document.querySelector('[data-cart-plus]').click()
        document.getElementById('cart-checkout').click()

        await new Promise(r => setTimeout(r, 10))

        expect(document.getElementById('cart-checkout').disabled).toBe(false)
    })

    it('hides error on new checkout attempt', async () => {
        const fetchMock = vi.fn().mockResolvedValue({
            ok: true,
            json: () => Promise.resolve({ redirect: '/ok' }),
        })
        globalThis.fetch = fetchMock
        globalThis.location = { href: '' }

        createBilletterie([{ id: 1, price: '10.00', max: 5 }])
        initCart()

        const errorEl = document.getElementById('cart-error')
        errorEl.classList.remove('hidden')

        document.querySelector('[data-cart-plus]').click()
        document.getElementById('cart-checkout').click()

        expect(errorEl.classList.contains('hidden')).toBe(true)
    })

    it('does not post without order url', () => {
        const fetchMock = vi.fn()
        globalThis.fetch = fetchMock

        document.body.innerHTML = `
            <div id="billetterie">
                <div data-cart-item data-billet-id="1" data-price="10" data-max="5">
                    <button data-cart-minus></button>
                    <input data-cart-qty type="number" min="0" max="5" value="0" readonly>
                    <button data-cart-plus></button>
                    <span data-cart-line-total></span>
                </div>
                <span id="cart-total"></span><span id="cart-count"></span>
                <button id="cart-checkout" disabled></button>
            </div>
        `
        initCart()

        document.querySelector('[data-cart-plus]').click()
        document.getElementById('cart-checkout').click()

        expect(fetchMock).not.toHaveBeenCalled()
    })
})

describe('stock polling', () => {
    beforeEach(() => {
        document.body.innerHTML = ''
    })

    function mockStock(stock) {
        return vi.fn().mockResolvedValue({
            json: () => Promise.resolve(stock),
        })
    }

    it('polls stock URL and updates labels for out of stock', async () => {
        const fetchMock = mockStock({ 1: 0 })
        globalThis.fetch = fetchMock
        globalThis.setInterval = (fn) => { fn(); return 1 }

        createBilletterie([{ id: 1, price: '10.00', max: 5 }], '/stock')
        initCart()

        document.querySelector('[data-cart-plus]').click()
        document.querySelector('[data-cart-plus]').click()

        await new Promise(r => setTimeout(r, 20))

        expect(fetchMock).toHaveBeenCalledWith('/stock')
        expect(document.querySelector('[data-stock-label]').innerHTML).toContain('Rupture')
        expect(document.querySelector('[data-cart-qty]').value).toBe('0')
    })

    it('polls stock URL and shows low stock warning', async () => {
        globalThis.fetch = mockStock({ 1: 5 })
        globalThis.setInterval = (fn) => { fn(); return 1 }

        createBilletterie([{ id: 1, price: '10.00', max: 20 }], '/stock')
        initCart()

        await new Promise(r => setTimeout(r, 20))

        expect(document.querySelector('[data-stock-label]').innerHTML).toContain('Plus que')
    })

    it('polls stock URL and shows normal stock', async () => {
        globalThis.fetch = mockStock({ 1: 50 })
        globalThis.setInterval = (fn) => { fn(); return 1 }

        createBilletterie([{ id: 1, price: '10.00', max: 100 }], '/stock')
        initCart()

        await new Promise(r => setTimeout(r, 20))

        expect(document.querySelector('[data-stock-label]').innerHTML).toContain('disponible')
    })

    it('clamps qty when stock decreases below current selection', async () => {
        globalThis.fetch = mockStock({ 1: 2 })
        globalThis.setInterval = (fn) => { fn(); return 1 }

        createBilletterie([{ id: 1, price: '10.00', max: 10 }], '/stock')
        initCart()

        for (let i = 0; i < 5; i++) {
            document.querySelector('[data-cart-plus]').click()
        }

        await new Promise(r => setTimeout(r, 20))

        expect(document.querySelector('[data-cart-qty]').value).toBe('2')
    })

    it('does not poll without stock URL', () => {
        const fetchMock = vi.fn()
        globalThis.fetch = fetchMock
        const origSetInterval = globalThis.setInterval
        const intervalSpy = vi.fn()
        globalThis.setInterval = intervalSpy

        createBilletterie([{ id: 1, price: '10.00', max: 5 }])
        initCart()

        expect(intervalSpy).not.toHaveBeenCalled()
        globalThis.setInterval = origSetInterval
    })

    it('handles stock poll fetch error gracefully', async () => {
        globalThis.fetch = vi.fn().mockRejectedValue(new Error('Network'))
        globalThis.setInterval = (fn) => { fn(); return 1 }

        createBilletterie([{ id: 1, price: '10.00', max: 5 }], '/stock')
        initCart()

        await new Promise(r => setTimeout(r, 20))

        // No crash, label unchanged
        expect(document.querySelector('[data-stock-label]').innerHTML).toBe('')
    })

    it('skips billet not in stock response', async () => {
        globalThis.fetch = mockStock({ 999: 10 })
        globalThis.setInterval = (fn) => { fn(); return 1 }

        createBilletterie([{ id: 1, price: '10.00', max: 5 }], '/stock')
        initCart()

        await new Promise(r => setTimeout(r, 20))

        // Label unchanged — billet 1 not in response
        expect(document.querySelector('[data-stock-label]').innerHTML).toBe('')
    })

    it('handles out of stock when qty already zero', async () => {
        globalThis.fetch = mockStock({ 1: 0 })
        globalThis.setInterval = (fn) => { fn(); return 1 }

        createBilletterie([{ id: 1, price: '10.00', max: 5 }], '/stock')
        initCart()

        // Don't click +, qty stays at 0

        await new Promise(r => setTimeout(r, 20))

        expect(document.querySelector('[data-stock-label]').innerHTML).toContain('Rupture')
        expect(document.querySelector('[data-cart-qty]').value).toBe('0')
    })

    it('shows singular place for stock of 1', async () => {
        globalThis.fetch = mockStock({ 1: 1 })
        globalThis.setInterval = (fn) => { fn(); return 1 }

        createBilletterie([{ id: 1, price: '10.00', max: 5 }], '/stock')
        initCart()

        await new Promise(r => setTimeout(r, 20))

        const label = document.querySelector('[data-stock-label]')
        expect(label.innerHTML).toContain('Plus que 1 place !')
        expect(label.innerHTML).not.toContain('places')
    })

    it('shows singular for stock of exactly 1 in normal range', async () => {
        globalThis.fetch = mockStock({ 1: 50 })
        globalThis.setInterval = (fn) => { fn(); return 1 }

        createBilletterie([{ id: 1, price: '10.00', max: 100 }], '/stock')
        initCart()

        await new Promise(r => setTimeout(r, 20))

        const label = document.querySelector('[data-stock-label]')
        expect(label.innerHTML).toContain('50 places disponibles')
    })

    it('handles item without stock-label element', async () => {
        globalThis.fetch = mockStock({ 1: 5 })
        globalThis.setInterval = (fn) => { fn(); return 1 }

        // Create billetterie without data-stock-label
        document.body.innerHTML = `
            <div id="billetterie" data-stock-url="/stock">
                <div data-cart-item data-billet-id="1" data-price="10.00" data-max="20">
                    <button data-cart-minus></button>
                    <input data-cart-qty type="number" min="0" max="20" value="0" readonly>
                    <button data-cart-plus></button>
                    <span data-cart-line-total></span>
                </div>
                <span id="cart-total"></span><span id="cart-count"></span>
            </div>
        `
        initCart()

        await new Promise(r => setTimeout(r, 20))

        // No crash, max updated
        expect(document.querySelector('[data-cart-item]').dataset.max).toBe('5')
    })
})
