-- WoWTetris Quest System
-- Daily quests for class XP

local addonName, addon = ...

-- Quest definitions (20 total quests that rotate)
addon.QUEST_POOL = {
    -- Score quests
    {id = 1, name = "Score Hunter", description = "Score 1,000 points in a single game", type = "score", target = 1000, xpReward = 150},
    {id = 2, name = "High Scorer", description = "Score 2,500 points in a single game", type = "score", target = 2500, xpReward = 300},
    {id = 3, name = "Score Master", description = "Score 5,000 points in a single game", type = "score", target = 5000, xpReward = 500},
    
    -- Line clear quests
    {id = 4, name = "Line Clearer", description = "Clear 10 lines in a single game", type = "lines", target = 10, xpReward = 100},
    {id = 5, name = "Row Destroyer", description = "Clear 25 lines in a single game", type = "lines", target = 25, xpReward = 250},
    {id = 6, name = "Tetris Pro", description = "Clear 50 lines in a single game", type = "lines", target = 50, xpReward = 400},
    
    -- Tetris quests (4-line clears)
    {id = 7, name = "First Tetris", description = "Clear a Tetris (4 lines at once)", type = "tetris", target = 1, xpReward = 200},
    {id = 8, name = "Double Tetris", description = "Clear 2 Tetrises in a single game", type = "tetris", target = 2, xpReward = 350},
    {id = 9, name = "Tetris King", description = "Clear 5 Tetrises in a single game", type = "tetris", target = 5, xpReward = 600},
    
    -- Combo quests
    {id = 10, name = "Combo Starter", description = "Get a 3-combo", type = "combo", target = 3, xpReward = 150},
    {id = 11, name = "Combo Master", description = "Get a 5-combo", type = "combo", target = 5, xpReward = 300},
    {id = 12, name = "Combo Legend", description = "Get an 8-combo", type = "combo", target = 8, xpReward = 500},
    
    -- Time survival quests
    {id = 13, name = "Survivor", description = "Survive for 2 minutes", type = "time", target = 120, xpReward = 150},
    {id = 14, name = "Endurance", description = "Survive for 5 minutes", type = "time", target = 300, xpReward = 350},
    {id = 15, name = "Marathon", description = "Survive for 10 minutes", type = "time", target = 600, xpReward = 600},
    
    -- Ultimate quests
    {id = 16, name = "Ultimate User", description = "Use your ultimate 1 time", type = "ultimate", target = 1, xpReward = 100},
    {id = 17, name = "Ultimate Spammer", description = "Use your ultimate 3 times in one game", type = "ultimate", target = 3, xpReward = 250},
    
    -- Level quests
    {id = 18, name = "Level Up", description = "Reach level 3 in a game", type = "level", target = 3, xpReward = 150},
    {id = 19, name = "High Level", description = "Reach level 5 in a game", type = "level", target = 5, xpReward = 300},
    {id = 20, name = "Level Master", description = "Reach level 10 in a game", type = "level", target = 10, xpReward = 500},
}

-- PvP specific quests
addon.PVP_QUEST_POOL = {
    {id = 101, name = "First Blood", description = "Win a PvP match", type = "pvp_win", target = 1, xpReward = 300},
    {id = 102, name = "PvP Victor", description = "Win 3 PvP matches", type = "pvp_win", target = 3, xpReward = 600},
    {id = 103, name = "Saboteur", description = "Use 3 sabotage abilities in PvP", type = "pvp_sabotage", target = 3, xpReward = 200},
    {id = 104, name = "Aggressive", description = "Use 5 sabotage abilities in PvP", type = "pvp_sabotage", target = 5, xpReward = 350},
    {id = 105, name = "PvP Warrior", description = "Play 5 PvP matches", type = "pvp_play", target = 5, xpReward = 250},
}

-- Quest state
addon.questState = {
    dailyQuests = {},      -- {questId, classId, progress, completed}
    bonusQuests = {},      -- 2 random other class quests
    pvpQuests = {},        -- 5 PvP quests
    lastResetDay = 0,      -- Day number for reset tracking
    selectedQuestClass = nil, -- Which class quests are currently shown
}

-- Affix rotation state
addon.affixRotation = {
    lastRotationTime = 0,
    currentAffixes = {},
}

-- Get the current day number (for reset tracking)
function addon:GetDayNumber()
    return math.floor(time() / 86400)
end

-- Get current affix rotation period (72 hours from Wed 03:00)
function addon:GetAffixRotationPeriod()
    -- Get server time
    local serverTime = GetServerTime()
    local dateInfo = date("*t", serverTime)
    
    -- Find last Wednesday 03:00
    local daysSinceWed = (dateInfo.wday - 4) % 7  -- wday: 1=Sun, 4=Wed
    local lastWed = serverTime - (daysSinceWed * 86400)
    
    -- Adjust to 03:00
    local wedDateInfo = date("*t", lastWed)
    lastWed = lastWed - (wedDateInfo.hour * 3600) - (wedDateInfo.min * 60) - wedDateInfo.sec + (3 * 3600)
    
    -- If we're before this week's Wed 03:00, go back a week
    if lastWed > serverTime then
        lastWed = lastWed - (7 * 86400)
    end
    
    -- Calculate which 72-hour period we're in
    local secondsSinceWed = serverTime - lastWed
    local periodNumber = math.floor(secondsSinceWed / (72 * 3600))
    
    return lastWed + (periodNumber * 72 * 3600), periodNumber
end

-- Initialize/update affix rotation
function addon:InitializeAffixRotation()
    local rotationStart, periodNum = addon:GetAffixRotationPeriod()
    
    -- Check if we need new affixes
    if addon.affixRotation.lastRotationTime ~= rotationStart then
        addon.affixRotation.lastRotationTime = rotationStart
        
        -- Deterministic selection based on period (no randomseed in WoW)
        local function seededRandom(seed, max)
            seed = (seed * 1103515245 + 12345) % 2147483648
            return (seed % max) + 1, seed
        end
        
        -- Randomly select 3-4 affixes for this period
        local numAffixes = 3 + (periodNum % 2)  -- Alternates between 3 and 4
        local available = {}
        for i, affix in ipairs(addon.AFFIXES) do
            available[i] = affix.id
        end
        
        addon.affixRotation.currentAffixes = {}
        local seed = (periodNum + 1000) * 7919
        for i = 1, numAffixes do
            if #available > 0 then
                local idx
                idx, seed = seededRandom(seed, #available)
                table.insert(addon.affixRotation.currentAffixes, available[idx])
                table.remove(available, idx)
            end
        end
        
        -- Auto-enable rotated affixes
        addon.activeAffixes = {}
        for _, affixId in ipairs(addon.affixRotation.currentAffixes) do
            table.insert(addon.activeAffixes, affixId)
        end
        
        print("|cffff6600[Tetris]|r Affix rotation updated! " .. #addon.activeAffixes .. " affixes active.")
    end
end

-- Initialize/reset daily quests
function addon:InitializeDailyQuests()
    local currentDay = addon:GetDayNumber()
    
    -- Load saved state if exists
    if addon.db and addon.db.questState and addon.db.questState.lastResetDay then
        addon.questState = addon.db.questState
    end
    
    -- Check if we need to reset (new day)
    if not addon.questState.lastResetDay or addon.questState.lastResetDay ~= currentDay then
        addon:ResetDailyQuests()
    end
    
    -- Initialize affix rotation
    addon:InitializeAffixRotation()
end

-- Reset daily quests for a new day
function addon:ResetDailyQuests()
    local currentDay = addon:GetDayNumber()
    addon.questState.lastResetDay = currentDay
    
    -- Deterministic shuffle based on day (no randomseed in WoW)
    local function seededRandom(seed, max)
        -- Simple LCG for deterministic random
        seed = (seed * 1103515245 + 12345) % 2147483648
        return (seed % max) + 1, seed
    end
    
    -- Shuffle quest pool deterministically
    local shuffled = {}
    for i, quest in ipairs(addon.QUEST_POOL) do
        shuffled[i] = quest
    end
    local seed = currentDay * 31337
    for i = #shuffled, 2, -1 do
        local j
        j, seed = seededRandom(seed, i)
        shuffled[i], shuffled[j] = shuffled[j], shuffled[i]
    end
    
    -- Pick 10 quests for class quests (player chooses which class)
    addon.questState.dailyQuests = {}
    for i = 1, 10 do
        local quest = shuffled[i]
        if quest then
            table.insert(addon.questState.dailyQuests, {
                questId = quest.id,
                progress = 0,
                completed = false,
                claimed = false,
            })
        end
    end
    
    -- Pick 2 more as bonus quests (random class)
    addon.questState.bonusQuests = {}
    local allClasses = addon.CLASS_ORDER
    for i = 1, 2 do
        local quest = shuffled[10 + i]
        if quest then
            local classIdx
            classIdx, seed = seededRandom(seed, #allClasses)
            local randomClass = allClasses[classIdx]
            table.insert(addon.questState.bonusQuests, {
                questId = quest.id,
                classId = randomClass,
                progress = 0,
                completed = false,
                claimed = false,
            })
        end
    end
    
    -- Shuffle PvP quests deterministically
    local pvpShuffled = {}
    for i, quest in ipairs(addon.PVP_QUEST_POOL) do
        pvpShuffled[i] = quest
    end
    for i = #pvpShuffled, 2, -1 do
        local j
        j, seed = seededRandom(seed, i)
        pvpShuffled[i], pvpShuffled[j] = pvpShuffled[j], pvpShuffled[i]
    end
    
    -- Pick 5 PvP quests
    addon.questState.pvpQuests = {}
    for i = 1, 5 do
        local quest = pvpShuffled[i]
        if quest then
            table.insert(addon.questState.pvpQuests, {
                questId = quest.id,
                progress = 0,
                completed = false,
                claimed = false,
            })
        end
    end
    
    -- Save state
    addon:SaveQuestState()
    
    print("|cff00ff00[Tetris]|r Daily quests have been reset!")
end

-- Save quest state
function addon:SaveQuestState()
    addon.db.questState = addon.questState
end

-- Get quest definition by ID
function addon:GetQuestById(questId)
    for _, quest in ipairs(addon.QUEST_POOL) do
        if quest.id == questId then return quest end
    end
    for _, quest in ipairs(addon.PVP_QUEST_POOL) do
        if quest.id == questId then return quest end
    end
    return nil
end

-- Update quest progress
function addon:UpdateQuestProgress(questType, value, classPlayed)
    -- Allow tracking during gameplay OR at game over
    if not addon.gameState.isPlaying and not addon.gameState.isGameOver then
        if questType ~= "pvp_win" and questType ~= "pvp_play" then 
            return 
        end
    end
    
    -- Round time values to integers
    if questType == "time" then
        value = math.floor(value)
    end
    
    -- Update daily quests (only if playing that class)
    for _, questState in ipairs(addon.questState.dailyQuests) do
        if not questState.completed then
            local quest = addon:GetQuestById(questState.questId)
            if quest and quest.type == questType then
                -- Daily quests apply to whatever class you're currently playing
                if classPlayed == addon.selectedClass or classPlayed == nil then
                    questState.progress = math.max(questState.progress, value)
                    if questState.progress >= quest.target then
                        questState.completed = true
                        print("|cffffff00[Tetris]|r Quest Complete: " .. quest.name .. "!")
                    end
                end
            end
        end
    end
    
    -- Update bonus quests (only for specific class)
    for _, questState in ipairs(addon.questState.bonusQuests) do
        if not questState.completed then
            local quest = addon:GetQuestById(questState.questId)
            if quest and quest.type == questType then
                if questState.classId == addon.selectedClass then
                    questState.progress = math.max(questState.progress, value)
                    if questState.progress >= quest.target then
                        questState.completed = true
                        print("|cffffff00[Tetris]|r Bonus Quest Complete: " .. quest.name .. "!")
                    end
                end
            end
        end
    end
    
    -- Update PvP quests
    for _, questState in ipairs(addon.questState.pvpQuests) do
        if not questState.completed then
            local quest = addon:GetQuestById(questState.questId)
            if quest and quest.type == questType then
                if questType == "pvp_win" or questType == "pvp_play" or questType == "pvp_sabotage" then
                    questState.progress = questState.progress + value
                else
                    questState.progress = math.max(questState.progress, value)
                end
                if questState.progress >= quest.target then
                    questState.completed = true
                    print("|cffffff00[Tetris]|r PvP Quest Complete: " .. quest.name .. "!")
                end
            end
        end
    end
    
    addon:SaveQuestState()
end

-- Claim quest reward
function addon:ClaimQuestReward(questState, targetClass)
    if not questState then return false end
    if not questState.completed or questState.claimed then return false end
    
    local quest = addon:GetQuestById(questState.questId)
    if not quest then return false end
    
    -- Add XP to the target class (with fallback)
    local classToReward = targetClass or addon.selectedClass or "WARRIOR"
    
    -- Verify class exists
    if not addon.CLASSES or not addon.CLASSES[classToReward] then
        classToReward = "WARRIOR"
    end
    
    addon:AddClassXP(classToReward, quest.xpReward)
    
    -- Add coins using shop system
    if addon.AddCurrency then
        local coinReward = math.floor(quest.xpReward / 5)  -- 20% of XP as coins
        addon:AddCurrency("coins", coinReward)
        
        -- PvP quests also give PvP tokens
        if quest.type and quest.type:find("pvp") then
            local pvpTokenReward = math.floor(quest.xpReward / 20)
            addon:AddCurrency("pvpTokens", pvpTokenReward)
        end
    end
    
    questState.claimed = true
    addon:SaveQuestState()
    
    local className = addon.CLASSES[classToReward] and addon.CLASSES[classToReward].name or classToReward
    print("|cff00ff00[Tetris]|r Quest rewards claimed for " .. className .. "!")
    return true
end

-- Add XP to a class
function addon:AddClassXP(className, xp)
    local stats = addon:GetClassStats(className)
    local oldLevel = stats.level
    
    -- Add XP (using score as XP equivalent)
    stats.totalXP = (stats.totalXP or 0) + xp
    
    -- Check for level up
    local newLevel = oldLevel
    while stats.totalXP >= addon:GetXPForLevel(newLevel) do
        newLevel = newLevel + 1
    end
    
    if newLevel > oldLevel then
        stats.level = newLevel
        print("|cff00ff00[Tetris]|r " .. addon.CLASSES[className].name .. " leveled up to " .. newLevel .. "!")
    end
    
    addon:SaveClassStats(className, stats)
end

-- Hook into game events to track quest progress
function addon:TrackQuestProgress()
    local state = addon.gameState
    
    -- Update score quest
    addon:UpdateQuestProgress("score", state.score)
    
    -- Update lines quest
    addon:UpdateQuestProgress("lines", state.totalLines)
    
    -- Update time quest
    addon:UpdateQuestProgress("time", state.gameTime)
    
    -- Update level quest (use class level, not in-game level)
    local stats = addon:GetClassStats(addon.selectedClass)
    addon:UpdateQuestProgress("level", stats.level)
    
    -- Update combo quest (tracked in real-time)
    addon:UpdateQuestProgress("combo", state.combo or 0)
end

-- Track tetris (called when 4 lines cleared)
function addon:TrackTetris()
    addon.questState.tetrisCount = (addon.questState.tetrisCount or 0) + 1
    addon:UpdateQuestProgress("tetris", addon.questState.tetrisCount)
end

-- Track ultimate use
function addon:TrackUltimateUse()
    addon.questState.ultimateCount = (addon.questState.ultimateCount or 0) + 1
    addon:UpdateQuestProgress("ultimate", addon.questState.ultimateCount)
end

-- Track PvP win
function addon:TrackPvPWin()
    addon:UpdateQuestProgress("pvp_win", 1)
end

-- Track PvP match played
function addon:TrackPvPMatch()
    addon:UpdateQuestProgress("pvp_play", 1)
end

-- Track sabotage use
function addon:TrackSabotageUse()
    addon:UpdateQuestProgress("pvp_sabotage", 1)
end

-- Reset per-game counters at game start
function addon:ResetGameQuestCounters()
    addon.questState.tetrisCount = 0
    addon.questState.ultimateCount = 0
    
    -- Reset time-based quest progress (they track current game time, not cumulative)
    for _, questState in ipairs(addon.questState.dailyQuests or {}) do
        if not questState.claimed then
            local quest = addon:GetQuestById(questState.questId)
            if quest and quest.type == "time" then
                questState.progress = 0
            end
        end
    end
    
    for _, questState in ipairs(addon.questState.bonusQuests or {}) do
        if not questState.claimed then
            local quest = addon:GetQuestById(questState.questId)
            if quest and quest.type == "time" then
                questState.progress = 0
            end
        end
    end
end

-- Count unclaimed completed quests
function addon:GetUnclaimedQuestCount()
    local count = 0
    for _, q in ipairs(addon.questState.dailyQuests) do
        if q.completed and not q.claimed then count = count + 1 end
    end
    for _, q in ipairs(addon.questState.bonusQuests) do
        if q.completed and not q.claimed then count = count + 1 end
    end
    for _, q in ipairs(addon.questState.pvpQuests) do
        if q.completed and not q.claimed then count = count + 1 end
    end
    return count
end
