local addonName, TC = ...
TC.Trivia = {}
TC.Trivia.History = TC.Trivia.History or {}

local winStreaks = {} 
local activeRound = false
local currentAnswer = ""
local currentFullAnswer = ""
local currentHintSent = false
local roundTimer = nil

function TC.Trivia:ResetStreaks()
    winStreaks = {}
    print("|cFFFFD100TownCrier:|r Active win streaks have been reset!")
    if TC.LogToLedger then TC:LogToLedger("|cFF888888System: Win Streaks Reset.|r") end
end

function TC.Trivia:StartRound()
    if activeRound then self:EndRound("No one") end
    
    if not TC.Data or not TC.Data.Trivia then
        print("|cFFFF0000TownCrier Error:|r Trivia data not found!")
        return
    end

    local triviaData = TC.Data.Trivia[math.random(1, #TC.Data.Trivia)]
    currentAnswer = triviaData.a:lower()
    currentFullAnswer = triviaData.a
    self.currentQ = triviaData.q
    currentHintSent = false
    
    local channel = TC.db.profile.channel or "GUILD"
    local rewardDisplay = (TC.db.profile.rewardAmount or 50000) / 10000
    local msg = "TownCrier Question (for " .. rewardDisplay .. "g): " .. triviaData.q
    
    SendChatMessage(msg, channel)
    
    if TC.LogToLedger then TC:LogToLedger("|cFFFFD100[Trivia Question]|r " .. triviaData.q) end
    
    activeRound = true
    
    local duration = TC.db.profile.roundDuration or 60
    if roundTimer then roundTimer:Cancel() end
    
    roundTimer = C_Timer.NewTimer(duration, function()
        if activeRound then
            SendChatMessage("TownCrier: Time's up! The answer was: " .. currentFullAnswer, channel)
            if TC.LogToLedger then TC:LogToLedger("|cFFFF4444[Trivia Time Up]|r Answer: " .. currentFullAnswer) end
            self:EndRound("No one")
        end
    end)
end

function TC.Trivia:SendHint()
    if not activeRound or currentHintSent then return end
    local hint = currentAnswer:sub(1, 3) .. "..."
    local msg = "TownCrier Hint: The answer starts with '" .. hint .. "'"
    SendChatMessage(msg, TC.db.profile.channel or "GUILD")
    if TC.LogToLedger then TC:LogToLedger("|cFF00FF00[Trivia Hint]|r " .. hint) end
    currentHintSent = true
end

function TC.Trivia:ProcessChat(text, playerName)
    if not activeRound then return end
    
    if text:lower() == currentAnswer then
        local name = strsplit("-", playerName)
        self:EndRound(name)
    end
end

function TC.Trivia:EndRound(winnerName)
    activeRound = false
    if roundTimer then roundTimer:Cancel() end
    
    if winnerName == "No one" then
        table.insert(self.History, {question = self.currentQ, winner = "None"})
    else
        winStreaks[winnerName] = (winStreaks[winnerName] or 0) + 1
        local baseReward = TC.db.profile.rewardAmount or 50000
        local finalReward = baseReward
        local isBonus = false

        if TC.db.profile.multEnabled and (winStreaks[winnerName] % 5 == 0) then
            finalReward = baseReward * (TC.db.profile.multValue or 5)
            isBonus = true
            winStreaks[winnerName] = 0
        end

        local season = TC.db.profile.currentSeason or "Season 1"
        TC.db.profile.seasons[season][winnerName] = (TC.db.profile.seasons[season][winnerName] or 0) + 1
        TC.db.profile.pendingPayouts[winnerName] = (TC.db.profile.pendingPayouts[winnerName] or 0) + finalReward

        local channel = TC.db.profile.channel or "GUILD"
        if isBonus then
            local msg = "🔥 STREAK BONUS! " .. winnerName .. " wins " .. (finalReward/10000) .. "g! 🔥"
            SendChatMessage(msg, channel)
            if TC.LogToLedger then TC:LogToLedger("|cFFFF8800[Trivia Winner]|r " .. msg) end
            PlaySound(10349)
        else
            local msg = "Winner! " .. winnerName .. " is correct! (" .. (finalReward/10000) .. "g)"
            SendChatMessage(msg, channel)
            if TC.LogToLedger then TC:LogToLedger("|cFF00FF00[Trivia Winner]|r " .. msg) end
            PlaySound(888)
        end

        table.insert(self.History, {question = self.currentQ, winner = winnerName})
    end

    -- [[ SAFE UI UPDATE LOGIC ]]
    -- We check if the player is in combat. If they are, we wait.
    if InCombatLockdown() then
        -- Add a listener to update the UI the second combat ends
        local f = CreateFrame("Frame")
        f:RegisterEvent("PLAYER_REGEN_ENABLED")
        f:SetScript("OnEvent", function(self)
            TC.Trivia:RefreshUI()
            self:UnregisterAllEvents()
        end)
    else
        self:RefreshUI()
    end
end

-- New helper function to keep things tidy
function TC.Trivia:RefreshUI()
    -- Use the explicit TC.UI namespace to avoid "self" issues
    if not TC.UI then return end
    TC.UI:UpdateHistory()
    TC.UI:UpdateLeaderboard()
    TC.UI:UpdatePurse()
end