local addonName, TC = ...
TC.Leaderboard = {}

function TC.Leaderboard:GetTopPlayers(limit)
    local season = TC.db.profile.currentSeason or "Season 1"
    local data = TC.db.profile.seasons[season] or {}
    
    local sorted = {}
    for name, score in pairs(data) do
        table.insert(sorted, {name = name, score = score})
    end
    
    table.sort(sorted, function(a, b) return a.score > b.score end)
    
    local result = {}
    for i = 1, math.min(limit, #sorted) do
        table.insert(result, sorted[i])
    end
    return result
end

-- [[ THE FIXED ANNOUNCE FUNCTION ]]
function TC.Leaderboard:AnnounceTopScholars()
    local players = self:GetTopPlayers(5)
    
    if #players == 0 then
        print("|cFFFFD100TownCrier:|r No leaderboard data to announce yet.")
        return
    end

    -- Check if we are in combat. If so, don't fire the chat yet!
    if InCombatLockdown() then
        print("|cFFFFD100TownCrier:|r Cannot post standings during combat. Queuing for end of fight...")
        local f = CreateFrame("Frame")
        f:RegisterEvent("PLAYER_REGEN_ENABLED")
        f:SetScript("OnEvent", function(self)
            TC.Leaderboard:ExecuteAnnouncement(players)
            self:UnregisterAllEvents()
        end)
    else
        self:ExecuteAnnouncement(players)
    end
end

-- Helper function to handle the actual chat sending
function TC.Leaderboard:ExecuteAnnouncement(players)
    local channel = TC.db.profile.channel or "GUILD"
    local seasonName = TC.db.profile.currentSeason or "Season 1"
    
    SendChatMessage("TownCrier: Top Scholars for " .. seasonName .. "!", channel)
    
    for i, p in ipairs(players) do
        -- We add a slight staggered delay so Blizzard doesn't kick us for spamming
        C_Timer.After(i * 1.2, function()
            SendChatMessage(i .. ". " .. p.name .. " (" .. p.score .. " wins)", channel)
        end)
    end

    if TC.LogToLedger then
        TC:LogToLedger("|cFF00FFFF[Leaderboard]|r Posted standings to " .. channel)
    end
end