import { assetUrl } from '@/commons/assets'

const game1MusicUrl = assetUrl('game1.mp3')
const game2MusicUrl = assetUrl('game2.mp3')
const game4MusicUrl = assetUrl('cmyf-bgm.mp3')
const game5MusicUrl = assetUrl('qcnf-bgm.mp3')
const game6MusicUrl = assetUrl('game6.mp3')
const go321 = assetUrl('321go.mp3')
const applause = assetUrl('applause.mp3')

let backgroundMusic: HTMLAudioElement | null = null
let countdownTemplate: HTMLAudioElement | null = null
let pendingCountdownRetry: (() => void) | null = null
let applausePlayed = false
const countdownAudios = new Set<HTMLAudioElement>()



export function stopAllMusic() {
    stopApplauseMusic();
    stopGame1Music();
    stopGame2Music();
    // stopGame3Music();
    stopGame4Music();
    stopGame5Music();
    stopGame6Music();
    backgroundMusic = null;
}

function getBackgroundMusic(music: string, force: boolean = false, loop: boolean = true) {
    console.log('[Music] getBackgroundMusic called, music:', music, 'force:', force, 'current backgroundMusic:', backgroundMusic?.src)
    
    // 检查当前背景音乐是否是同一首（比较路径末尾，处理相对路径和完整URL的情况）
    const isSameMusic = backgroundMusic && 
        (backgroundMusic.src === music || backgroundMusic.src.endsWith(music));
    
    // 只有在需要切换不同音乐或强制重建时才停止并重建
    if (force || (!backgroundMusic || !isSameMusic)) {
        console.log('[Music] 重建背景音乐, 原因:', force ? '强制重建' : backgroundMusic ? '音乐URL变更' : '无现有音乐')
        if (backgroundMusic) {
            stopAllMusic();
        }
        backgroundMusic = new Audio(music)
        backgroundMusic.loop = loop
        backgroundMusic.preload = 'auto'
        backgroundMusic.volume = 0.6
        if (!loop) {
            backgroundMusic.addEventListener('ended', () => {
                if (!backgroundMusic || !backgroundMusic.src.endsWith(music)) {
                    return
                }
                backgroundMusic.pause()
                backgroundMusic.currentTime = 0
                backgroundMusic = null
            }, { once: true })
        }
        backgroundMusic.load()
        console.log('[Music] 新背景音乐创建完成:', backgroundMusic.src)
    }

    return backgroundMusic
}

//播放庆祝音乐
export async function playApplauseMusic() {
    if (applausePlayed) return

    const audio = getBackgroundMusic(applause, false, false)
    audio.loop = false

    try {
        applausePlayed = true
        await audio.play()
        window.removeEventListener('pointerdown', playApplauseMusic)
        window.removeEventListener('keydown', playApplauseMusic)
    } catch {
        applausePlayed = false
        window.removeEventListener('pointerdown', playApplauseMusic)
        window.removeEventListener('keydown', playApplauseMusic)
        window.addEventListener('pointerdown', playApplauseMusic, { once: true })
        window.addEventListener('keydown', playApplauseMusic, { once: true })
    }
}

export function stopApplauseMusic() {
    applausePlayed = false
    window.removeEventListener('pointerdown', playApplauseMusic)
    window.removeEventListener('keydown', playApplauseMusic)
    // 只有当当前播放的是喝彩音乐时才暂停，避免误伤背景音乐
    if (backgroundMusic && backgroundMusic.src.endsWith(applause)) {
        console.log('[Music] 停止喝彩音乐')
        backgroundMusic.pause()
    } else {
        console.log('[Music] stopApplauseMusic 被调用，但当前播放的不是喝彩音乐，不暂停')
    }
}


export async function playGame1Music() {
    const audio = getBackgroundMusic(game1MusicUrl)

    try {
        await audio.play()
        window.removeEventListener('pointerdown', playGame1Music)
        window.removeEventListener('keydown', playGame1Music)
    } catch {
        window.addEventListener('pointerdown', playGame1Music, { once: true })
        window.addEventListener('keydown', playGame1Music, { once: true })
    }
}

export function stopGame1Music() {
    window.removeEventListener('pointerdown', playGame1Music)
    window.removeEventListener('keydown', playGame1Music)
    backgroundMusic?.pause()
}

export async function playGame2Music() {
    const audio = getBackgroundMusic(game2MusicUrl)

    try {
        await audio.play()
        window.removeEventListener('pointerdown', playGame2Music)
        window.removeEventListener('keydown', playGame2Music)
    } catch {
        window.addEventListener('pointerdown', playGame2Music, { once: true })
        window.addEventListener('keydown', playGame2Music, { once: true })
    }
}

export function stopGame2Music() {
    window.removeEventListener('pointerdown', playGame2Music)
    window.removeEventListener('keydown', playGame2Music)
    backgroundMusic?.pause()
}

export async function playGame4Music() {
    console.log('[Music] playGame4Music called')
    const audio = getBackgroundMusic(game4MusicUrl)
    console.log('[Music] 播放音乐文件:', game4MusicUrl, '完整路径:', audio.src)
    console.log('[Music] audio element readyState:', audio.readyState, 'paused:', audio.paused, 'currentTime:', audio.currentTime)

    try {
        console.log('[Music] 尝试播放音乐...')
        await audio.play()
        console.log('[Music] 音乐播放成功！文件:', game4MusicUrl, 'paused:', audio.paused, 'currentTime:', audio.currentTime, 'duration:', audio.duration)
        
        // 添加延迟检查，看是否被其他代码暂停
        setTimeout(() => {
            console.log('[Music] 100ms后检查 - 文件:', game4MusicUrl, 'paused:', audio.paused, 'currentTime:', audio.currentTime)
        }, 100)
        
        window.removeEventListener('pointerdown', playGame4Music)
        window.removeEventListener('keydown', playGame4Music)
    } catch (error) {
        console.log('[Music] 音乐播放失败，注册交互监听器:', error)
        window.addEventListener('pointerdown', playGame4Music, { once: true })
        window.addEventListener('keydown', playGame4Music, { once: true })
    }
}

export function stopGame4Music() {
    window.removeEventListener('pointerdown', playGame4Music)
    window.removeEventListener('keydown', playGame4Music)
    backgroundMusic?.pause()
}

export async function playGame5Music() {
    const audio = getBackgroundMusic(game5MusicUrl)

    try {
        await audio.play()
        window.removeEventListener('pointerdown', playGame5Music)
        window.removeEventListener('keydown', playGame5Music)
    } catch {
        window.addEventListener('pointerdown', playGame5Music, { once: true })
        window.addEventListener('keydown', playGame5Music, { once: true })
    }
}

export function stopGame5Music() {
    window.removeEventListener('pointerdown', playGame5Music)
    window.removeEventListener('keydown', playGame5Music)
    backgroundMusic?.pause()
}

export async function playGame6Music() {
    const audio = getBackgroundMusic(game6MusicUrl)

    try {
        await audio.play()
        window.removeEventListener('pointerdown', playGame6Music)
        window.removeEventListener('keydown', playGame6Music)
    } catch {
        window.addEventListener('pointerdown', playGame6Music, { once: true })
        window.addEventListener('keydown', playGame6Music, { once: true })
    }
}

export function stopGame6Music() {
    window.removeEventListener('pointerdown', playGame6Music)
    window.removeEventListener('keydown', playGame6Music)
    backgroundMusic?.pause()
}

function getCountdownTemplate() {
    if (!countdownTemplate) {
        countdownTemplate = new Audio(go321)
        countdownTemplate.loop = false
        countdownTemplate.preload = 'auto'
        countdownTemplate.volume = 0.8
        countdownTemplate.load()
    }

    return countdownTemplate
}

function releaseCountdownAudio(audio: HTMLAudioElement) {
    audio.pause()
    audio.removeAttribute('src')
    audio.load()
    countdownAudios.delete(audio)
}

function clearCountdownRetry() {
    if (!pendingCountdownRetry) return

    window.removeEventListener('pointerdown', pendingCountdownRetry)
    window.removeEventListener('keydown', pendingCountdownRetry)
    pendingCountdownRetry = null
}

export async function playCountdownMusic() {
    const audio = getCountdownTemplate().cloneNode(true) as HTMLAudioElement
    audio.loop = false
    audio.volume = 1
    countdownAudios.add(audio)

    const release = () => releaseCountdownAudio(audio)
    audio.addEventListener('ended', release, { once: true })
    audio.addEventListener('error', release, { once: true })

    try {
        await audio.play()
        clearCountdownRetry()
    } catch {
        releaseCountdownAudio(audio)

        if (pendingCountdownRetry) return
        pendingCountdownRetry = () => {
            pendingCountdownRetry = null
            void playCountdownMusic()
        }
        window.addEventListener('pointerdown', pendingCountdownRetry, { once: true })
        window.addEventListener('keydown', pendingCountdownRetry, { once: true })
    }
}

export function stopCountdownMusic() {
    clearCountdownRetry()
    countdownAudios.forEach(releaseCountdownAudio)
}
