-- MoonWell client game-mode integration.
-- WarcraftXL retains the selected character's server-provided charFlags while
-- WoW replaces the GlueXML Lua state with the in-world FrameXML state.

MoonWell_IsTraitor = false

local function RefreshFactionIcons()
    if PlayerFrame_UpdatePvPStatus then
        PlayerFrame_UpdatePvPStatus()
    end

    if PVPFrame and PVPFrame:IsShown() and PVPFrame_Update then
        PVPFrame_Update()
    end
    if BattlefieldFrame and BattlefieldFrame:IsShown() and BattlefieldFrame_Update then
        BattlefieldFrame_Update()
    end

    if PVPMicroButton and PVPMicroButton.DragonUIPVPIcon then
        local factionGroup = UnitFactionGroup("player")
        if factionGroup then
            local displayFaction = MoonWell_IsTraitor
                and (factionGroup == "Alliance" and "Horde" or "Alliance")
                or factionGroup
            local texture = "Interface\\AddOns\\DragonUI\\Textures\\Micromenu\\micropvp"
            local icon = PVPMicroButton.DragonUIPVPIcon
            local highlight = PVPMicroButton:GetHighlightTexture()

            if displayFaction == "Alliance" then
                icon:SetTexture(texture)
                icon:SetTexCoord(0, 118/256, 0, 151/256)
                if highlight then
                    highlight:SetTexture(texture)
                    highlight:SetTexCoord(0, 118/256, 0, 151/256)
                end
            elseif displayFaction == "Horde" then
                icon:SetTexture(texture)
                icon:SetTexCoord(118/256, 236/256, 0, 151/256)
                if highlight then
                    highlight:SetTexture(texture)
                    highlight:SetTexCoord(118/256, 236/256, 0, 151/256)
                end
            end
        end
    end
end

local function ReadNativeGameMode()
    if type(MoonWellIsTraitor) ~= "function" then
        return false
    end

    MoonWell_IsTraitor = MoonWellIsTraitor() and true or false
    RefreshFactionIcons()
    return true
end

local events = CreateFrame("Frame")
events:RegisterEvent("PLAYER_LOGIN")
events:RegisterEvent("PLAYER_ENTERING_WORLD")
events:RegisterEvent("UNIT_FACTION")
events:SetScript("OnEvent", function(self, event, unit)
    if event ~= "UNIT_FACTION" or unit == "player" then
        ReadNativeGameMode()
    end
end)

-- WarcraftXL may publish its Lua globals shortly after addons are loaded.
-- Lua 5.1/WotLK has no C_Timer, so retry cheaply until the native API appears.
local elapsedTotal = 0
events:SetScript("OnUpdate", function(self, elapsed)
    elapsedTotal = elapsedTotal + elapsed
    if elapsedTotal < 0.25 then
        return
    end
    elapsedTotal = 0

    if ReadNativeGameMode() then
        self:SetScript("OnUpdate", nil)
    end
end)
