local addonName, AC = ...
AC = _G.ArenaCore
if not AC then return end

local PvPLFGStats = {}
AC.PvPLFGStats = PvPLFGStats

-- Resolve a dot-path like "ConquestFrame.RatedSoloShuffle" into the actual frame object
local function ResolveButton(path)
    local cur = _G
    for part in path:gmatch("[^.]+") do
        cur = cur and cur[part]
        if not cur then return nil end
    end
    return cur
end

-- Bracket layout: matches CONQUEST_BUTTONS / CONQUEST_BRACKET_INDEXES order
-- 1=SoloShuffle, 2=RatedBGBlitz, 3=Arena2v2, 4=Arena3v3, 5=RatedBG
local BRACKETS = {
    { path = "ConquestFrame.RatedSoloShuffle",   index = 7,  isShuffle = true },
    { path = "ConquestFrame.RatedBGBlitz",        index = 9,  isShuffle = false },
    { path = "ConquestFrame.Arena2v2",            index = 1,  isShuffle = false },
    { path = "ConquestFrame.Arena3v3",            index = 2,  isShuffle = false },
    { path = "ConquestFrame.RatedBG",             index = 4,  isShuffle = false },
}

local function GetWinRateForBracket(bracketIndex, isShuffle)
    local rating, _, _, seasonPlayed, seasonWon, _, _, _, _, _, _, roundsSeasonPlayed, roundsSeasonWon = GetPersonalRatedInfo(bracketIndex)
    local played = isShuffle and roundsSeasonPlayed or seasonPlayed
    local won    = isShuffle and roundsSeasonWon    or seasonWon

    if not rating or rating == 0 then
        return nil
    end
    if not played or played == 0 then
        return nil
    end

    return math.floor((won / played) * 100 + 0.5)
end

local function EnsureTextFrames(button)
    if not button then return nil, nil end

    -- Percentage text (moved up a touch)
    if not button._acWinRatePct then
        local pct = button:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
        pct:SetFont("Fonts\\FRIZQT__.TTF", 11, "OUTLINE")
        pct:SetShadowOffset(1, -1)
        pct:SetShadowColor(0, 0, 0, 0.8)
        button._acWinRatePct = pct
    end

    -- "winrate" label below the percentage
    if not button._acWinRateLabel then
        local lbl = button:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
        lbl:SetFont("Fonts\\FRIZQT__.TTF", 9, "OUTLINE")
        lbl:SetTextColor(0.7, 0.7, 0.7, 0.9)
        lbl:SetShadowOffset(1, -1)
        lbl:SetShadowColor(0, 0, 0, 0.8)
        lbl:SetText("winrate")
        button._acWinRateLabel = lbl
    end

    return button._acWinRatePct, button._acWinRateLabel
end

function PvPLFGStats:UpdateButton(bracketInfo)
    local button = ResolveButton(bracketInfo.path)
    local pctTxt, lblTxt = EnsureTextFrames(button)
    if not pctTxt then return end

    local enabled = AC.DB and AC.DB.profile and AC.DB.profile.moreFeatures and AC.DB.profile.moreFeatures.pvpLFGStatsEnabled
    if not enabled then
        pctTxt:Hide()
        lblTxt:Hide()
        return
    end

    local pct = GetWinRateForBracket(bracketInfo.index, bracketInfo.isShuffle)
    if not pct then
        pctTxt:Hide()
        lblTxt:Hide()
        return
    end

    pctTxt:SetText(string.format("%d%%", pct))

    if pct >= 52 then
        pctTxt:SetTextColor(0.3, 1, 0.3)     -- soft green for the winners
    elseif pct >= 45 then
        pctTxt:SetTextColor(1, 0.65, 0.2)     -- amber orange for the hopefuls
    else
        pctTxt:SetTextColor(1, 0.4, 0.4)       -- red for the rest of us
    end

    pctTxt:ClearAllPoints()
    lblTxt:ClearAllPoints()

    -- Anchor percentage slightly above center, label directly beneath it
    local anchorTo, relPoint, offsetX
    if button.Reward and button.Reward:IsShown() then
        anchorTo = button.Reward
        relPoint = "LEFT"
        offsetX = -28
    elseif button.CurrentRating and button.CurrentRating:IsShown() then
        anchorTo = button.CurrentRating
        relPoint = "RIGHT"
        offsetX = 8
    else
        anchorTo = button
        relPoint = "RIGHT"
        offsetX = -60
    end

    pctTxt:SetPoint("BOTTOM", anchorTo, relPoint, offsetX, 3)
    lblTxt:SetPoint("TOP", pctTxt, "BOTTOM", 0, -1)

    pctTxt:Show()
    lblTxt:Show()
end

function PvPLFGStats:UpdateAll()
    for _, info in ipairs(BRACKETS) do
        self:UpdateButton(info)
    end
end

function PvPLFGStats:SetEnabled(enabled)
    if AC.DB and AC.DB.profile and AC.DB.profile.moreFeatures then
        AC.DB.profile.moreFeatures.pvpLFGStatsEnabled = enabled
    end
    self:UpdateAll()
end

local hooksInstalled = false
local function InstallHooks()
    if hooksInstalled then return end
    hooksInstalled = true

    -- Hook Blizzard's update so we stay in sync whenever the panel refreshes
    if type(_G.ConquestFrame_Update) == "function" then
        hooksecurefunc("ConquestFrame_Update", function()
            C_Timer.After(0.05, function()
                PvPLFGStats:UpdateAll()
            end)
        end)
    end

    -- Refresh when the Conquest tab is shown
    local cf = _G.ConquestFrame
    if cf and type(cf.HookScript) == "function" then
        cf:HookScript("OnShow", function()
            C_Timer.After(0.1, function()
                PvPLFGStats:UpdateAll()
            end)
        end)
    end

    -- First draw in case the window is already visible
    PvPLFGStats:UpdateAll()
end

local eventFrame = CreateFrame("Frame")
eventFrame:RegisterEvent("PLAYER_LOGIN")
eventFrame:RegisterEvent("PVP_RATED_STATS_UPDATE")
eventFrame:RegisterEvent("ADDON_LOADED")
eventFrame:SetScript("OnEvent", function(_, event, arg1)
    if event == "ADDON_LOADED" and arg1 == "Blizzard_PVPUI" then
        InstallHooks()
    elseif event == "PLAYER_LOGIN" then
        C_Timer.After(0.5, function()
            if _G.ConquestFrame then
                InstallHooks()
            end
        end)
    elseif event == "PVP_RATED_STATS_UPDATE" then
        C_Timer.After(0.1, function()
            PvPLFGStats:UpdateAll()
        end)
    end
end)
