-- WoWTetris Core
-- A WoW-themed Tetris game addon with class ultimates

local addonName, addon = ...
WoWTetris = addon

-- Addon namespace
addon.name = addonName
addon.version = "3.5.0"

-- TEST MODE - Set to true to unlock all ultimates for testing
addon.testMode = false  -- SET TO true FOR TESTING

-- Default saved variables
local defaults = {
    highScore = 0,
    totalLinesCleared = 0,
    gamesPlayed = 0,
    selectedClass = nil,
    selectedRace = nil,
    selectedUltimateName = nil,
    classStats = {},  -- Per-class level tracking: classStats["WARRIOR"] = {level = 5, highScore = 1000, ...}
    keybinds = {
        moveLeft = "LEFT",
        moveRight = "RIGHT",
        softDrop = "DOWN",
        hardDrop = "SPACE",
        rotateClockwise = "UP",
        rotateCounterClockwise = "LCTRL",
        hold = "C",
        pause = "P",
        ultimate = "R",
        pvpAbility = "V",
        racialAbility = "B",
    },
    ghostPieceEnabled = true,
    soundEnabled = true,
    musicMuted = false,
    tutorialSeen = false,
    -- Currency
    coins = 0,
    pvpTokens = 0,
    -- Unlocks
    unlockedClasses = {},  -- Premium classes purchased
    unlockedUltimates = {},  -- Shop ultimates purchased: {WARRIOR = {6, 7}, ...}
    unlockedSabotages = {},  -- Shop sabotages purchased
    unlockedRaces = {},  -- Races purchased
    -- PvP Stats
    pvpWins = 0,
    pvpLosses = 0,
    pvpRating = 1000,  -- Starting rating (ELO-like)
}

-- Initialize class stats for a class (with optional race)
function addon:InitClassStats(classKey, raceKey)
    if not addon.db.classStats then
        addon.db.classStats = {}
    end
    -- Use class_race as key if race provided
    local key = classKey
    if raceKey then
        key = classKey .. "_" .. raceKey
    end
    if not addon.db.classStats[key] then
        addon.db.classStats[key] = {
            level = 1,
            totalXP = 0,
            highScore = 0,
            totalLines = 0,
            gamesPlayed = 0,
            race = raceKey,
        }
    end
    -- Ensure totalXP exists for existing saves
    if not addon.db.classStats[key].totalXP then
        addon.db.classStats[key].totalXP = 0
    end
    return addon.db.classStats[key]
end

-- Get class stats (with optional race)
function addon:GetClassStats(classKey, raceKey)
    -- Default to selectedRace if no race provided
    local actualRace = raceKey or addon.selectedRace
    return addon:InitClassStats(classKey, actualRace)
end

-- Save class stats after game
function addon:SaveClassStats()
    if not addon.selectedClass then return end
    local stats = addon:GetClassStats(addon.selectedClass)
    local state = addon.gameState
    
    if not state or not state.score then return end
    
    if state.score > stats.highScore then
        stats.highScore = state.score
    end
    
    -- Store the score earned this game
    local scoreEarned = state.score
    
    -- Add score as XP to class level
    local oldLevel = stats.level
    local oldXP = stats.totalXP or 0
    stats.totalXP = oldXP + scoreEarned
    
    -- Check for level up based on total XP (3000 per level)
    local xpRequired = addon:GetXPForLevel(stats.level)
    while stats.totalXP >= xpRequired do
        stats.totalXP = stats.totalXP - xpRequired
        stats.level = stats.level + 1
        xpRequired = addon:GetXPForLevel(stats.level)
    end
    
    if stats.level > oldLevel then
        local levelsGained = stats.level - oldLevel
        -- Base coins for leveling up
        local baseCoins = addon.CURRENCY_REWARDS.level_up * levelsGained
        
        -- Affix bonus: +125% coins per active affix (so 3 affixes = +375% = 4.75x coins)
        local affixCount = addon.activeAffixes and #addon.activeAffixes or 0
        local affixBonus = 1 + (affixCount * 1.25)
        local coinsEarned = math.floor(baseCoins * affixBonus)
        
        addon:AddCurrency("coins", coinsEarned)
        addon:PlaySound("levelUp")
        
        local bonusText = ""
        if affixCount > 0 then
            bonusText = " |cffff6600(+" .. (affixCount * 125) .. "% affix bonus)|r"
        end
        print("|cff00ff00[Tetris]|r " .. addon.CLASSES[addon.selectedClass].colorCode .. addon.CLASSES[addon.selectedClass].name .. "|r leveled up to |cffffd700Level " .. stats.level .. "|r! |cffffd700+" .. coinsEarned .. " Coins|r" .. bonusText)
    end
    
    stats.totalLines = stats.totalLines + state.totalLines
    stats.gamesPlayed = stats.gamesPlayed + 1
    
    -- Print XP gain for feedback (show actual score earned, not remaining XP)
    print("|cff00ff00[Tetris]|r +" .. scoreEarned .. " XP (" .. stats.totalXP .. "/" .. xpRequired .. " to next level)")
end

-- Check if a race is unlocked
function addon:IsRaceUnlocked(raceKey)
    local raceData = addon.RACES and addon.RACES[raceKey]
    if not raceData then return false end
    
    -- Free races are always unlocked
    if raceData.cost == 0 then return true end
    
    -- Check db.unlockedRaces
    if addon.db and addon.db.unlockedRaces and addon.db.unlockedRaces[raceKey] then
        return true
    end
    
    return false
end

-- Game constants
addon.BOARD_WIDTH = 10
addon.BOARD_HEIGHT = 20
addon.BLOCK_SIZE = 24
addon.PREVIEW_BLOCK_SIZE = 14

-- XP required per level - flat 3000 per level
local XP_PER_LEVEL = 3000

-- Get XP needed for a level (always 3000)
function addon:GetXPForLevel(level)
    return XP_PER_LEVEL
end

-- Class-themed background colors (r, g, b for board tint)
addon.CLASS_BACKGROUNDS = {
    WARRIOR = {0.15, 0.08, 0.05, "Interface\\GLUES\\Models\\UI_MainMenu\\swordgrain"},
    MAGE = {0.05, 0.08, 0.18, "Interface\\GLUES\\Models\\UI_MainMenu\\pointed"},
    ROGUE = {0.08, 0.08, 0.08, "Interface\\GLUES\\Models\\UI_MainMenu\\pointed"},
    PRIEST = {0.12, 0.12, 0.15, "Interface\\GLUES\\Models\\UI_MainMenu\\pointed"},
    HUNTER = {0.08, 0.12, 0.06, "Interface\\GLUES\\Models\\UI_MainMenu\\pointed"},
    PALADIN = {0.15, 0.12, 0.05, "Interface\\GLUES\\Models\\UI_MainMenu\\pointed"},
    SHAMAN = {0.05, 0.08, 0.15, "Interface\\GLUES\\Models\\UI_MainMenu\\pointed"},
    WARLOCK = {0.12, 0.05, 0.12, "Interface\\GLUES\\Models\\UI_MainMenu\\pointed"},
    DEATHKNIGHT = {0.12, 0.05, 0.08, "Interface\\GLUES\\Models\\UI_MainMenu\\pointed"},
    DRUID = {0.10, 0.08, 0.05, "Interface\\GLUES\\Models\\UI_MainMenu\\pointed"},
}

-- Class-specific piece textures - GUARANTEED WORKING ICONS
addon.CLASS_PIECE_TEXTURES = {
    WARRIOR = {
        I = "Interface\\Icons\\Ability_Warrior_Sunder",
        O = "Interface\\Icons\\Ability_Warrior_ShieldWall",
        T = "Interface\\Icons\\Ability_Warrior_Charge",
        L = "Interface\\Icons\\Ability_Warrior_Cleave",
        J = "Interface\\Icons\\Ability_Warrior_Revenge",
        S = "Interface\\Icons\\Ability_Warrior_Rampage",
        Z = "Interface\\Icons\\Ability_Warrior_BattleShout",
    },
    MAGE = {
        I = "Interface\\Icons\\Spell_Fire_FireBolt02",
        O = "Interface\\Icons\\Spell_Frost_FrostBolt02",
        T = "Interface\\Icons\\Spell_Arcane_PortalDalaran",
        L = "Interface\\Icons\\Spell_Fire_Fireball02",
        J = "Interface\\Icons\\Spell_Frost_FrostBlast",
        S = "Interface\\Icons\\Spell_Arcane_Blink",
        Z = "Interface\\Icons\\Spell_Fire_MeteorStorm",
    },
    ROGUE = {
        I = "Interface\\Icons\\Ability_Rogue_Eviscerate",
        O = "Interface\\Icons\\Ability_Rogue_SliceDice",
        T = "Interface\\Icons\\Ability_Rogue_KidneyShot",
        L = "Interface\\Icons\\Ability_Rogue_Ambush",
        J = "Interface\\Icons\\Ability_Backstab",
        S = "Interface\\Icons\\Ability_Stealth",
        Z = "Interface\\Icons\\Ability_Rogue_Sprint",
    },
    PRIEST = {
        I = "Interface\\Icons\\Spell_Holy_PowerWordShield",
        O = "Interface\\Icons\\Spell_Holy_Renew",
        T = "Interface\\Icons\\Spell_Holy_FlashHeal",
        L = "Interface\\Icons\\Spell_Shadow_ShadowWordPain",
        J = "Interface\\Icons\\Spell_Holy_GreaterHeal",
        S = "Interface\\Icons\\Spell_Shadow_Shadowform",
        Z = "Interface\\Icons\\Spell_Holy_WordFortitude",
    },
    HUNTER = {
        I = "Interface\\Icons\\Ability_Marksmanship",
        O = "Interface\\Icons\\Ability_Hunter_BeastTaming",
        T = "Interface\\Icons\\Ability_Whirlwind",
        L = "Interface\\Icons\\Ability_Hunter_Pathfinding",
        J = "Interface\\Icons\\Ability_Hunter_BeastWithin",
        S = "Interface\\Icons\\Ability_TrueShot",
        Z = "Interface\\Icons\\Ability_Tracking",
    },
    PALADIN = {
        I = "Interface\\Icons\\Spell_Holy_SealOfMight",
        O = "Interface\\Icons\\Spell_Holy_DevotionAura",
        T = "Interface\\Icons\\Spell_Holy_HolyBolt",
        L = "Interface\\Icons\\Spell_Holy_LayOnHands",
        J = "Interface\\Icons\\Spell_Holy_SealOfValor",
        S = "Interface\\Icons\\Spell_Holy_Restoration",
        Z = "Interface\\Icons\\Spell_Holy_AuraOfLight",
    },
    SHAMAN = {
        I = "Interface\\Icons\\Spell_Nature_Lightning",
        O = "Interface\\Icons\\Spell_Nature_EarthShock",
        T = "Interface\\Icons\\Spell_Nature_ChainLightning",
        L = "Interface\\Icons\\Spell_Fire_SealOfFire",
        J = "Interface\\Icons\\Spell_Nature_HealingWaveLesser",
        S = "Interface\\Icons\\Spell_Nature_LightningShield",
        Z = "Interface\\Icons\\Spell_Nature_Purge",
    },
    WARLOCK = {
        I = "Interface\\Icons\\Spell_Shadow_ShadowBolt",
        O = "Interface\\Icons\\Spell_Shadow_CurseOfSargeras",
        T = "Interface\\Icons\\Spell_Shadow_RainOfFire",
        L = "Interface\\Icons\\Spell_Fire_Immolation",
        J = "Interface\\Icons\\Spell_Shadow_Possession",
        S = "Interface\\Icons\\Spell_Shadow_SummonImp",
        Z = "Interface\\Icons\\Spell_Shadow_LifeDrain02",
    },
    DEATHKNIGHT = {
        I = "Interface\\Icons\\Spell_Deathknight_ClassIcon",
        O = "Interface\\Icons\\Spell_Shadow_DeathCoil",
        T = "Interface\\Icons\\Spell_Shadow_DeathAndDecay",
        L = "Interface\\Icons\\Spell_Shadow_AnimateDead",
        J = "Interface\\Icons\\Spell_Shadow_RaiseDead",
        S = "Interface\\Icons\\Spell_Shadow_PlagueCloud",
        Z = "Interface\\Icons\\Spell_Frost_FrostArmor02",
    },
    DRUID = {
        I = "Interface\\Icons\\Spell_Nature_StrangleVines",
        O = "Interface\\Icons\\Spell_Nature_Rejuvenation",
        T = "Interface\\Icons\\Spell_Nature_StarFall",
        L = "Interface\\Icons\\Ability_Racial_BearForm",
        J = "Interface\\Icons\\Ability_Druid_CatForm",
        S = "Interface\\Icons\\Spell_Nature_InsectSwarm",
        Z = "Interface\\Icons\\Spell_Nature_Thorns",
    },
    -- Premium Classes
    MONK = {
        I = "Interface\\Icons\\ability_monk_tigerpalm",
        O = "Interface\\Icons\\ability_monk_touchofkarma",
        T = "Interface\\Icons\\ability_monk_roll",
        L = "Interface\\Icons\\ability_monk_jab",
        J = "Interface\\Icons\\ability_monk_blackoutkick",
        S = "Interface\\Icons\\ability_monk_risingsunkick",
        Z = "Interface\\Icons\\ability_monk_expelharm",
    },
    DEMONHUNTER = {
        I = "Interface\\Icons\\Spell_Shadow_Metamorphosis",
        O = "Interface\\Icons\\Ability_DemonHunter_EyeBeam",
        T = "Interface\\Icons\\Spell_Fire_FelFireward",
        L = "Interface\\Icons\\Spell_Fire_Incinerate",
        J = "Interface\\Icons\\Spell_Shadow_ShadowWordDominate",
        S = "Interface\\Icons\\Spell_Fire_Immolation",
        Z = "Interface\\Icons\\Spell_Shadow_DemonBreath",
    },
    EVOKER = {
        I = "Interface\\Icons\\Spell_Arcane_Arcane01",
        O = "Interface\\Icons\\Spell_Fire_Fireball02",
        T = "Interface\\Icons\\Spell_Arcane_Arcane02",
        L = "Interface\\Icons\\Spell_Fire_Fireball",
        J = "Interface\\Icons\\Spell_Arcane_Blink",
        S = "Interface\\Icons\\Spell_Arcane_Arcane03",
        Z = "Interface\\Icons\\Spell_Arcane_Arcane04",
    },
}

-- Default fallback textures
addon.PIECE_TEXTURES = {
    I = "Interface\\Icons\\INV_Sword_04",
    O = "Interface\\Icons\\INV_Misc_Gem_Amber_02",
    T = "Interface\\Icons\\INV_Shield_04",
    L = "Interface\\Icons\\INV_Axe_01",
    J = "Interface\\Icons\\INV_Staff_01",
    S = "Interface\\Icons\\Spell_Nature_Lightning",
    Z = "Interface\\Icons\\Spell_Fire_Fire",
}

-- Get texture for a piece based on current class
function addon:GetPieceTexture(pieceType)
    if addon.selectedClass and addon.CLASS_PIECE_TEXTURES[addon.selectedClass] then
        local tex = addon.CLASS_PIECE_TEXTURES[addon.selectedClass][pieceType]
        if tex then return tex end
    end
    return addon.PIECE_TEXTURES[pieceType]
end

-- Fallback colors (still used for tinting/highlights)
addon.PIECE_COLORS = {
    I = {0.0, 0.8, 1.0, 1.0},
    O = {1.0, 0.8, 0.2, 1.0},
    T = {0.6, 0.6, 0.7, 1.0},
    L = {0.8, 0.4, 0.1, 1.0},
    J = {0.6, 0.2, 0.8, 1.0},
    S = {0.2, 0.6, 1.0, 1.0},
    Z = {0.0, 0.9, 0.2, 1.0},
}

-- Piece names (WoW themed)
addon.PIECE_NAMES = {
    I = "Sword",
    O = "Hearthstone",
    T = "Shield",
    L = "Axe",
    J = "Staff",
    S = "Lightning Bolt",
    Z = "Fel Fire",
}

-- Initialize addon
local frame = CreateFrame("Frame")
frame:RegisterEvent("ADDON_LOADED")
frame:RegisterEvent("PLAYER_LOGOUT")

frame:SetScript("OnEvent", function(self, event, arg1)
    if event == "ADDON_LOADED" and arg1 == addonName then
        -- Initialize saved variables
        if not WoWTetrisDB then
            WoWTetrisDB = CopyTable(defaults)
        else
            -- Merge with defaults for any new settings
            for k, v in pairs(defaults) do
                if WoWTetrisDB[k] == nil then
                    WoWTetrisDB[k] = v
                end
            end
            -- Merge keybinds
            for k, v in pairs(defaults.keybinds) do
                if WoWTetrisDB.keybinds[k] == nil then
                    WoWTetrisDB.keybinds[k] = v
                end
            end
        end
        
        addon.db = WoWTetrisDB
        
        -- Initialize all systems
        addon:InitializeClasses()
        addon:InitializeShop()  -- Initialize shop/currency
        addon:InitializeUI()
        addon:InitializeKeybinds()
        addon:InitializeMultiplayer()
        addon:InitializeDailyQuests()  -- Initialize quest system
        
        -- TEST MODE: Give starting currency and level for testing
        if addon.testMode then
            addon.shopData.coins = 500000
            addon.shopData.pvpTokens = 10000
            -- Set all classes to level 100 for testing
            for _, classKey in ipairs(addon.CLASS_ORDER) do
                local stats = addon:InitClassStats(classKey)
                stats.level = 100
            end
            for _, classKey in ipairs(addon.PREMIUM_CLASSES) do
                local stats = addon:InitClassStats(classKey)
                stats.level = 100
            end
            print("|cffff00ff[TEST MODE]|r 500,000 Coins, 10,000 PvP Tokens, Level 100 all classes!")
        end
        
        print("|cff00ff00WoW|r |cffff6600Tetris|r v10.27 loaded! Type |cff00ffff/tetris|r to play!")
        
        -- Show tutorial on first time after a short delay
        C_Timer.After(0.5, function()
            if addon.CheckFirstTimeTutorial then
                addon:CheckFirstTimeTutorial()
            end
        end)
        
    elseif event == "PLAYER_LOGOUT" then
        -- Save data
        WoWTetrisDB = addon.db
    end
end)

-- Slash commands
SLASH_WOWTETRIS1 = "/tetris"
SLASH_WOWTETRIS2 = "/wowtetris"
SlashCmdList["WOWTETRIS"] = function(msg)
    msg = msg:lower():trim()
    
    if msg == "reset" then
        addon.db.highScore = 0
        addon.db.totalLinesCleared = 0
        addon.db.gamesPlayed = 0
        addon.db.classStats = {}
        print("|cff00ff00WoW Tetris:|r Statistics reset!")
    elseif msg == "fullreset" or msg == "wipe" then
        -- Complete reset of ALL progression
        StaticPopupDialogs["TETRIS_FULL_RESET"] = {
            text = "|cffff0000WARNING|r\n\nThis will reset ALL progression:\n- All class levels back to 1\n- All currency (coins & PvP tokens) to 0\n- All purchased races removed\n- All purchased ultimates removed\n- All purchased sabotages removed\n- All stats and high scores\n- PvP rating reset to 1000\n\n|cffff0000This cannot be undone!|r\n\nType DELETE to confirm:",
            button1 = "Reset Everything",
            button2 = "Cancel",
            hasEditBox = true,
            OnAccept = function(self)
                local editBox = self.EditBox or self.editBox
                local text = editBox and editBox:GetText() or ""
                if text == "DELETE" then
                    -- Reset everything
                    addon.db.highScore = 0
                    addon.db.totalLinesCleared = 0
                    addon.db.gamesPlayed = 0
                    addon.db.classStats = {}
                    addon.db.coins = 0
                    addon.db.pvpTokens = 0
                    addon.db.unlockedClasses = {}
                    addon.db.unlockedUltimates = {}
                    addon.db.unlockedSabotages = {}
                    addon.db.unlockedRaces = {}
                    addon.db.pvpWins = 0
                    addon.db.pvpLosses = 0
                    addon.db.pvpRating = 1000
                    addon.db.questsCompleted = {}
                    addon.db.dailyQuestsCompleted = {}
                    addon.db.lastDailyReset = nil
                    
                    -- Reset shop data
                    addon.db.shop = {
                        coins = 0,
                        pvpTokens = 0,
                        ownedClasses = {},
                        ownedUltimates = {},
                        ownedSabotage = {},
                    }
                    addon.shopData = addon.db.shop
                    
                    -- Reset selections
                    addon.selectedClass = nil
                    addon.selectedRace = nil
                    addon.selectedUltimate = nil
                    addon.db.selectedClass = nil
                    addon.db.selectedRace = nil
                    
                    print("|cff00ff00WoW Tetris:|r |cffff0000FULL RESET COMPLETE!|r")
                    print("|cff00ff00WoW Tetris:|r All progression has been wiped. Start fresh!")
                    
                    -- Update UI
                    addon:UpdateMenuDisplay()
                else
                    print("|cffff0000WoW Tetris:|r Reset cancelled - you must type DELETE to confirm.")
                end
            end,
            timeout = 0,
            whileDead = true,
            hideOnEscape = true,
            preferredIndex = 3,
        }
        StaticPopup_Show("TETRIS_FULL_RESET")
    elseif msg == "stats" then
        print("|cff00ff00WoW Tetris|r Statistics:")
        print("  High Score: |cffffd700" .. addon.db.highScore .. "|r")
        print("  Total Lines Cleared: |cff00ffff" .. addon.db.totalLinesCleared .. "|r")
        print("  Games Played: |cffff6600" .. addon.db.gamesPlayed .. "|r")
    elseif msg == "keybinds" or msg == "keys" then
        if addon.mainFrame then
            addon:ShowKeybindOptions()
        end
    elseif msg == "leaderboard" or msg == "lb" then
        addon:ShowLeaderboard()
    elseif msg:match("^challenge ") then
        local target = msg:gsub("^challenge ", "")
        if target and target ~= "" then
            addon:SendChallenge(target)
        else
            print("|cff00ff00[Tetris]|r Usage: /tetris challenge PlayerName")
        end
    elseif msg == "help" then
        print("|cff00ff00WoW Tetris|r Commands:")
        print("  |cff00ffff/tetris|r - Open/close game")
        print("  |cff00ffff/tetris stats|r - Show statistics")
        print("  |cff00ffff/tetris leaderboard|r - Show leaderboard")
        print("  |cff00ffff/tetris challenge Name|r - Challenge a player")
        print("  |cff00ffff/tetris reset|r - Reset stats only")
        print("  |cff00ffff/tetris fullreset|r - |cffff0000WIPE ALL PROGRESSION|r")
        if addon.testMode then
            print("  |cffff0000/tetris testult|r - Test current ultimate (TEST MODE)")
        end
    elseif msg == "testult" and addon.testMode then
        if addon.selectedUltimate and addon.gameState.isPlaying then
            print("|cff00ff00[Tetris TEST]|r Forcing ultimate: " .. addon.selectedUltimate.name)
            addon.ultimateCooldown = 0
            addon:UseUltimate()
        else
            print("|cffff0000[Tetris TEST]|r No ultimate selected or not in game")
        end
    else
        -- Toggle main frame
        if addon.mainFrame then
            if addon.mainFrame:IsShown() then
                addon.mainFrame:Hide()
                addon:PauseGame()
            else
                addon.mainFrame:Show()
            end
        end
    end
end

-- Sound/Music system
addon.musicPlaying = false
addon.savedSoundSettings = nil
addon.musicHandle = nil

-- Save WoW's current sound settings and mute everything
function addon:MuteWoWSound()
    if addon.savedSoundSettings then return end  -- Already saved
    
    -- Save ALL current sound settings
    addon.savedSoundSettings = {
        masterVolume = tonumber(GetCVar("Sound_MasterVolume")) or 1,
        sfxVolume = tonumber(GetCVar("Sound_SFXVolume")) or 1,
        ambienceVolume = tonumber(GetCVar("Sound_AmbienceVolume")) or 1,
        dialogVolume = tonumber(GetCVar("Sound_DialogVolume")) or 1,
        musicVolume = tonumber(GetCVar("Sound_MusicVolume")) or 1,
        enableMusic = tonumber(GetCVar("Sound_EnableMusic")) or 1,
        enableSFX = tonumber(GetCVar("Sound_EnableSFX")) or 1,
        enableAmbience = tonumber(GetCVar("Sound_EnableAmbience")) or 1,
    }
    
    -- Mute ALL WoW sounds completely
    SetCVar("Sound_MasterVolume", 0)
    SetCVar("Sound_SFXVolume", 0)
    SetCVar("Sound_AmbienceVolume", 0)
    SetCVar("Sound_DialogVolume", 0)
    SetCVar("Sound_MusicVolume", 0)
    SetCVar("Sound_EnableMusic", 0)
    SetCVar("Sound_EnableSFX", 0)
    SetCVar("Sound_EnableAmbience", 0)
end

-- Restore WoW's sound settings
function addon:RestoreWoWSound()
    if not addon.savedSoundSettings then return end
    
    -- Restore all saved settings
    SetCVar("Sound_MasterVolume", addon.savedSoundSettings.masterVolume)
    SetCVar("Sound_SFXVolume", addon.savedSoundSettings.sfxVolume)
    SetCVar("Sound_AmbienceVolume", addon.savedSoundSettings.ambienceVolume)
    SetCVar("Sound_DialogVolume", addon.savedSoundSettings.dialogVolume)
    SetCVar("Sound_MusicVolume", addon.savedSoundSettings.musicVolume)
    SetCVar("Sound_EnableMusic", addon.savedSoundSettings.enableMusic)
    SetCVar("Sound_EnableSFX", addon.savedSoundSettings.enableSFX)
    SetCVar("Sound_EnableAmbience", addon.savedSoundSettings.enableAmbience)
    
    addon.savedSoundSettings = nil
    
    -- Force WoW to restart zone music by toggling the music setting
    -- This triggers WoW to re-evaluate what music should be playing
    if tonumber(GetCVar("Sound_EnableMusic")) == 1 then
        SetCVar("Sound_EnableMusic", 0)
        C_Timer.After(0.1, function()
            SetCVar("Sound_EnableMusic", 1)
        end)
    end
end

-- Play background music
function addon:StartMusic()
    if addon.db.musicMuted then return end
    if addon.musicPlaying then return end
    
    -- Mute WoW sounds first
    addon:MuteWoWSound()
    
    -- Only enable master volume - this allows PlaySoundFile to work
    -- But keep all individual channels disabled so no WoW sounds play
    SetCVar("Sound_MasterVolume", 1)
    -- All these stay OFF to block WoW sounds:
    -- Sound_SFXVolume = 0 (no mount/spell sounds)
    -- Sound_AmbienceVolume = 0 (no zone ambience)
    -- Sound_MusicVolume = 0 (no zone music)
    -- Sound_DialogVolume = 0 (no NPC voices)
    
    -- Path to our custom music file
    local musicFile = "Interface\\AddOns\\WoWTetris\\Falling_Lines.ogg"
    
    -- Play the sound file - try different channels
    -- "Master" channel bypasses the individual volume controls
    local willPlay, handle = PlaySoundFile(musicFile, "Master")
    
    if willPlay then
        addon.musicHandle = handle
        addon.musicPlaying = true
        
        -- Set up looping - replay when the sound ends
        -- We'll check periodically and restart if needed
        addon.musicStartTime = GetTime()
        addon.musicLoopTimer = C_Timer.NewTicker(1, function()
            if addon.musicPlaying and not addon.db.musicMuted then
                -- The OGG file length - adjust this to match your song length in seconds
                local songLength = 180  -- 3 minutes, adjust as needed
                
                if GetTime() - addon.musicStartTime >= songLength then
                    -- Song ended, restart it
                    if addon.musicHandle then
                        StopSound(addon.musicHandle)
                    end
                    local willPlay2, handle2 = PlaySoundFile(musicFile, "Master")
                    if willPlay2 then
                        addon.musicHandle = handle2
                        addon.musicStartTime = GetTime()
                    end
                end
            end
        end)
        
        print("|cff00ff00[Tetris]|r Music playing!")
    else
        -- Custom file not found, try alternate approaches
        addon.musicPlaying = true  -- Prevent retry spam
        
        -- Try with forward slashes
        local altPath = "Interface/AddOns/WoWTetris/Falling_Lines.ogg"
        willPlay, handle = PlaySoundFile(altPath, "Master")
        
        if willPlay then
            addon.musicHandle = handle
            print("|cff00ff00[Tetris]|r Music playing (alt path)!")
        else
            -- Fall back to WoW music system
            addon.usingFallbackMusic = true
            SetCVar("Sound_MusicVolume", 1)
            SetCVar("Sound_EnableMusic", 1)
            PlayMusic("Sound\\Music\\Pandaria\\MUS_50_HeartOfPandaria_02.mp3")
            print("|cffff6600[Tetris]|r Custom music not found, using WoW music.")
            print("|cff888888Ensure Falling_Lines.ogg is in: Interface/AddOns/WoWTetris/|r")
        end
    end
end

-- Stop background music (optionally restore WoW sounds)
function addon:StopMusic(restoreSounds)
    -- Stop our custom sound
    if addon.musicHandle then
        StopSound(addon.musicHandle)
        addon.musicHandle = nil
    end
    
    -- If we used fallback WoW music, stop it
    if addon.usingFallbackMusic then
        StopMusic()
        addon.usingFallbackMusic = false
    end
    
    addon.musicPlaying = false
    addon.musicStartTime = nil
    
    if addon.musicLoopTimer then
        addon.musicLoopTimer:Cancel()
        addon.musicLoopTimer = nil
    end
    
    -- Restore WoW sound settings when leaving game
    if restoreSounds then
        addon:RestoreWoWSound()
    end
end

-- Toggle music mute (during gameplay)
function addon:ToggleMusic()
    addon.db.musicMuted = not addon.db.musicMuted
    if addon.db.musicMuted then
        -- Stop our custom sound only
        if addon.musicHandle then
            StopSound(addon.musicHandle)
            addon.musicHandle = nil
        end
        addon.musicPlaying = false
        if addon.musicLoopTimer then
            addon.musicLoopTimer:Cancel()
            addon.musicLoopTimer = nil
        end
    else
        -- Restart music
        if addon.gameState and addon.gameState.isPlaying then
            addon.musicPlaying = false  -- Reset so StartMusic will work
            addon:StartMusic()
        end
    end
    return not addon.db.musicMuted
end

-- Legacy PlaySound function - now does nothing (sounds removed)
function addon:PlaySound(soundType)
    -- Sound effects removed - music only
end

-- Play spell sound (for ultimates) - disabled
function addon:PlaySpellSound(spellSoundKit)
    -- Sound effects removed - music only
end

-- Print function for debug
function addon:Debug(...)
    if addon.debugMode then
        print("|cffff00ff[Tetris Debug]|r", ...)
    end
end
