// @vitest-environment happy-dom
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { mount } from '@vue/test-utils'
import DisplayPage from '../../src/components/DisplayPage.vue'

// Mock globale WebSocket per jsdom
class MockWebSocket {
    static OPEN = 1
    static CONNECTING = 0
    readyState = 0
    onopen = null
    onclose = null
    onmessage = null
    onerror = null
    send = vi.fn()
    close = vi.fn()
    constructor() {
        setTimeout(() => {
            this.readyState = 1
            if (this.onopen) this.onopen()
        }, 0)
    }
}

vi.stubGlobal('WebSocket', MockWebSocket)

// Mock requestFullscreen e speechSynthesis
vi.stubGlobal('speechSynthesis', {
    speak: vi.fn(),
    cancel: vi.fn(),
    getVoices: () => []
})

// happy-dom non implementa la riproduzione media: stub di play/pause/load
// così l'overlay time out può montare il <video> senza errori.
Object.defineProperty(HTMLMediaElement.prototype, 'play', { value: vi.fn().mockResolvedValue(undefined), writable: true })
Object.defineProperty(HTMLMediaElement.prototype, 'pause', { value: vi.fn(), writable: true })
Object.defineProperty(HTMLMediaElement.prototype, 'load', { value: vi.fn(), writable: true })

function mountDisplay() {
    return mount(DisplayPage, {
        global: {
            stubs: { 'w-app': true }
        }
    })
}

describe('DisplayPage.vue', () => {

    beforeEach(() => {
        vi.useFakeTimers()
    })

    afterEach(() => {
        vi.useRealTimers()
    })

    // =============================================
    // RENDERING PUNTEGGIO
    // =============================================
    describe('Rendering punteggio', () => {
        it('dovrebbe mostrare i nomi dei team', () => {
            const wrapper = mountDisplay()
            const text = wrapper.text()
            expect(text).toContain('Antoniana')
            expect(text).toContain('Guest')
        })

        it('dovrebbe mostrare punteggio iniziale 0-0', () => {
            const wrapper = mountDisplay()
            const punti = wrapper.findAll('.punt')
            expect(punti[0].text()).toBe('0')
            expect(punti[1].text()).toBe('0')
        })

        it('dovrebbe mostrare i set corretti', () => {
            const wrapper = mountDisplay()
            const text = wrapper.text()
            expect(text).toContain('set 0')
        })

        it('dovrebbe aggiornare il punteggio quando lo stato cambia', async () => {
            const wrapper = mountDisplay()
            // il punteggio si ricava dalla striscia: 15 punti home + 12 guest
            wrapper.vm.state.sp.striscia.at(-1).ris = 'h'.repeat(15) + 'g'.repeat(12)
            await wrapper.vm.$nextTick()
            const punti = wrapper.findAll('.punt')
            expect(punti[0].text()).toBe('15')
            expect(punti[1].text()).toBe('12')
        })
    })

    // =============================================
    // ORDINE TEAM
    // =============================================
    describe('Ordine team', () => {
        it('order=true → Home prima di Guest', () => {
            const wrapper = mountDisplay()
            const headers = wrapper.findAll('.hea')
            expect(headers[0].classes()).toContain('home')
            expect(headers[1].classes()).toContain('guest')
        })

        it('order=false → Guest prima di Home', async () => {
            const wrapper = mountDisplay()
            wrapper.vm.state.order = false
            await wrapper.vm.$nextTick()
            const headers = wrapper.findAll('.hea')
            expect(headers[0].classes()).toContain('guest')
            expect(headers[1].classes()).toContain('home')
        })
    })

    // =============================================
    // FORMAZIONE vs PUNTEGGIO
    // =============================================
    describe('visuForm toggle', () => {
        it('visuForm=false → mostra punteggio grande', () => {
            const wrapper = mountDisplay()
            expect(wrapper.find('.punteggio-container').exists()).toBe(true)
            expect(wrapper.find('.form').exists()).toBe(false)
        })

        it('visuForm=true → mostra formazione', async () => {
            const wrapper = mountDisplay()
            wrapper.vm.state.visuForm = true
            await wrapper.vm.$nextTick()
            expect(wrapper.findAll('.form').length).toBeGreaterThan(0)
            expect(wrapper.find('.punteggio-container').exists()).toBe(false)
        })

        it('formazione mostra 6 giocatori per team', async () => {
            const wrapper = mountDisplay()
            wrapper.vm.state.visuForm = true
            await wrapper.vm.$nextTick()
            const formDivs = wrapper.findAll('.formdiv')
            // 6 per home + 6 per guest = 12
            expect(formDivs).toHaveLength(12)
        })
    })

    // =============================================
    // STRISCIA
    // =============================================
    describe('visuStriscia toggle', () => {
        it('visuStriscia=true → mostra la striscia', () => {
            const wrapper = mountDisplay()
            expect(wrapper.find('.striscia').exists()).toBe(true)
        })

        it('visuStriscia=false → nasconde la striscia', async () => {
            const wrapper = mountDisplay()
            wrapper.vm.state.visuStriscia = false
            await wrapper.vm.$nextTick()
            expect(wrapper.find('.striscia').exists()).toBe(false)
        })
    })

    // =============================================
    // INDICATORE CONNESSIONE
    // =============================================
    describe('Indicatore connessione', () => {
        it('dovrebbe avere classe "disconnected" quando non connesso', () => {
            const wrapper = mountDisplay()
            const status = wrapper.find('.connection-status')
            expect(status.classes()).toContain('disconnected')
        })

        it('dovrebbe avere classe "connected" quando connesso', async () => {
            const wrapper = mountDisplay()
            wrapper.vm.wsConnected = true
            await wrapper.vm.$nextTick()
            const status = wrapper.find('.connection-status')
            expect(status.classes()).toContain('connected')
        })

        it('dovrebbe mostrare "Disconnesso" quando non connesso', () => {
            const wrapper = mountDisplay()
            const status = wrapper.find('.connection-status')
            expect(status.text()).toContain('Disconnesso')
        })
    })

    // =============================================
    // OVERLAY TIME OUT
    // =============================================
    describe('Overlay time out', () => {
        // Attiva il time out impostando lo stato come farebbe il server.
        async function attivaTimeout(wrapper, { team = 'home', video = null, startedAt = Date.now() } = {}) {
            wrapper.vm.state.timeoutTeam = team
            wrapper.vm.state.timeoutVideo = video
            wrapper.vm.state.timeoutStartedAt = startedAt
            wrapper.vm.state.timeout = true
            await wrapper.vm.$nextTick()
            await wrapper.vm.$nextTick()
        }

        it('non mostra l\'overlay quando il time out non è attivo', () => {
            const wrapper = mountDisplay()
            expect(wrapper.find('.timeout-overlay').exists()).toBe(false)
        })

        it('senza video mostra il placeholder con il nome della squadra', async () => {
            const wrapper = mountDisplay()
            await attivaTimeout(wrapper, { team: 'home', video: null })
            expect(wrapper.find('.timeout-overlay').exists()).toBe(true)
            const placeholder = wrapper.find('.timeout-placeholder')
            expect(placeholder.text()).toContain('TIME OUT')
            expect(placeholder.text()).toContain('Antoniana')
            expect(wrapper.find('.timeout-video').exists()).toBe(false)
        })

        it('con un video lo riproduce nell\'overlay', async () => {
            const wrapper = mountDisplay()
            await attivaTimeout(wrapper, { team: 'guest', video: 'a.mp4' })
            const video = wrapper.find('.timeout-video')
            expect(video.exists()).toBe(true)
            expect(video.element.src).toContain('/spot/a.mp4')
            expect(wrapper.find('.timeout-placeholder').exists()).toBe(false)
        })

        it('a fine video mostra il placeholder fino allo stop del server', async () => {
            const wrapper = mountDisplay()
            await attivaTimeout(wrapper, { video: 'a.mp4' })
            const video = wrapper.find('.timeout-video')
            video.element.onended()
            await wrapper.vm.$nextTick()
            expect(wrapper.find('.timeout-video').exists()).toBe(false)
            expect(wrapper.find('.timeout-placeholder').exists()).toBe(true)
        })

        it('il countdown parte da timeoutStartedAt', async () => {
            const wrapper = mountDisplay()
            await attivaTimeout(wrapper, { startedAt: Date.now() - 5000 })
            expect(wrapper.vm.timeoutRemaining).toBe(25)
            expect(wrapper.find('.timeout-countdown').text()).toBe('00:25')
        })

        it('timeoutFading è true solo con video oltre i 30s negli ultimi istanti', async () => {
            const wrapper = mountDisplay()
            await attivaTimeout(wrapper, { video: 'a.mp4', startedAt: Date.now() - 29500 })
            // video corto: mai dissolvenza
            wrapper.vm.spotVideoDuration = 20
            expect(wrapper.vm.timeoutFading).toBe(false)
            // video più lungo dei 30s: dissolvenza nell'ultimo secondo
            wrapper.vm.spotVideoDuration = 45
            expect(wrapper.vm.timeoutRemaining).toBe(1)
            expect(wrapper.vm.timeoutFading).toBe(true)
        })

        it('alla fine del time out l\'overlay scompare', async () => {
            const wrapper = mountDisplay()
            await attivaTimeout(wrapper)
            wrapper.vm.state.timeout = false
            await wrapper.vm.$nextTick()
            expect(wrapper.find('.timeout-overlay').exists()).toBe(false)
        })
    })

    // =============================================
    // ICONA SERVIZIO
    // =============================================
    describe('Icona servizio', () => {
        it('dovrebbe mostrare l\'icona servizio sul team home quando servHome=true', () => {
            const wrapper = mountDisplay()
            // v-show imposta display:none. In happy-dom controlliamo lo style.
            const imgs = wrapper.findAll('.serv-slot img')
            // Con state.order=true e servHome=true:
            // - la prima img (home) è visibile (no display:none)
            // - la seconda img (guest) ha display:none
            const homeStyle = imgs[0].attributes('style') || ''
            const guestStyle = imgs[1].attributes('style') || ''
            expect(homeStyle).not.toContain('display: none')
            expect(guestStyle).toContain('display: none')
        })
    })
})
