-- ============================================================================
-- File: ArenaCore/modules/ClassIconAuras.lua
-- Purpose: Display CC/important auras over class portraits in Midnight
-- Hooks into Blizzard's DebuffFrame to mirror aura display to class icon
--
-- METHOD (proven Midnight approach):
--   Hook 1: debuffFrame.Icon:SetTexture  -> mirror CC texture / detect CC end
--           via QUESTION_MARK_ICON comparison
--   Hook 2: debuffFrame.Cooldown:SetCooldown -> mirror cooldown swipe
--           + OnCooldownDone safety net for natural expiry
-- ============================================================================

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

if not (AC.Midnight and AC.Midnight.isMidnight) then return end

local ClassIconAuras = {}
AC.ClassIconAuras = ClassIconAuras

local MAX_ARENA_ENEMIES = 3

ClassIconAuras.initialized = false
ClassIconAuras.hookedFrames = {}
ClassIconAuras.ccActive = {}

-- Check if auras on class icon are disabled
local function IsDisabled()
    local db = AC.DB and AC.DB.profile
    return db and db.classIcons and db.classIcons.showAuras == false
end

-- Restore class icon after CC ends
local function RestoreClassIcon(arenaIndex, classIcon, acFrame)
    classIcon.ccActive = false
    ClassIconAuras.ccActive[arenaIndex] = false
    if classIcon.auraCooldown then
        classIcon.auraCooldown:Clear()
    end
    local storedClass = acFrame.class
    if storedClass and classIcon.UpdateClassIcon then
        classIcon.UpdateClassIcon(storedClass)
    end
end

function ClassIconAuras:HookDebuffFrame(arenaIndex)
    local _, instanceType = IsInInstance()
    if instanceType ~= "arena" then return end
    if IsActiveBattlefieldArena and not IsActiveBattlefieldArena() then return end
    if self.hookedFrames[arenaIndex] then return end

    local blizzArenaFrame = _G["CompactArenaFrameMember" .. arenaIndex]
    if not blizzArenaFrame then return end

    local debuffFrame = blizzArenaFrame.DebuffFrame
    if not debuffFrame then return end

    local MFM = AC.MasterFrameManager
    local acFrame = MFM and MFM.frames and MFM.frames[arenaIndex]
    if not acFrame then return end

    local classIcon = acFrame.classIcon
    if not classIcon then return end

    -- Create cooldown overlay for swipe + countdown text
    local okCooldown, cooldownOrErr = pcall(function()
        local cd = CreateFrame("Cooldown", nil, classIcon, "CooldownFrameTemplate")
        if cd.SetHideCountdownNumbers then
            cd:SetHideCountdownNumbers(false)
        end
        local r = { cd:GetRegions() }
        for i = 1, #r do
            local region = r[i]
            if region and region.GetObjectType and region:GetObjectType() == "FontString" and region.SetFont then
                region:SetFont("Fonts\\FRIZQT__.TTF", 14, "OUTLINE")
            end
        end
        local anchor = classIcon.icon or classIcon
        cd:ClearAllPoints()
        cd:SetAllPoints(anchor)
        cd:SetDrawEdge(false)
        cd:SetDrawBling(false)
        cd:SetReverse(false)
        if cd.SetUseCircularEdge then
            cd:SetUseCircularEdge(true)
        end
        if cd.SetSwipeColor then
            cd:SetSwipeColor(0, 0, 0, 0.75)
        end
        return cd
    end)
    classIcon.auraCooldown = okCooldown and cooldownOrErr or nil

    -- HOOK 1: Mirror CC texture to class icon
    -- When CC is active, Blizzard sets Icon texture to the CC spell icon.
    -- When CC ends, Blizzard sets Icon texture to QUESTION_MARK_ICON.
    if debuffFrame.Icon then
        hooksecurefunc(debuffFrame.Icon, "SetTexture", function(_, tex)
            if IsDisabled() then
                if classIcon.ccActive then
                    RestoreClassIcon(arenaIndex, classIcon, acFrame)
                end
                return
            end
            if tex == "INTERFACE\\ICONS\\INV_MISC_QUESTIONMARK.BLP" then
                -- CC ended: restore class icon
                RestoreClassIcon(arenaIndex, classIcon, acFrame)
            else
                -- CC active: mirror texture
                classIcon.ccActive = true
                ClassIconAuras.ccActive[arenaIndex] = true
                if classIcon.icon then
                    classIcon.icon:SetTexture(tex)
                end
            end
        end)
    end

    -- HOOK 2: Mirror cooldown swipe + safety net on cooldown done
    if debuffFrame.Cooldown then
        hooksecurefunc(debuffFrame.Cooldown, "SetCooldown", function(_, start, duration)
            if IsDisabled() or not classIcon.auraCooldown then return end
            classIcon.auraCooldown:SetCooldown(start, duration)
        end)
        -- Safety net: when cooldown swipe finishes, ensure CC is cleared
        debuffFrame.Cooldown:HookScript("OnCooldownDone", function()
            if classIcon.ccActive then
                RestoreClassIcon(arenaIndex, classIcon, acFrame)
            end
        end)
    end

    self.hookedFrames[arenaIndex] = true
end

function ClassIconAuras:Initialize()
    if self.initialized then return end
    local _, instanceType = IsInInstance()
    if instanceType ~= "arena" then return end
    if IsActiveBattlefieldArena and not IsActiveBattlefieldArena() then return end

    for i = 1, MAX_ARENA_ENEMIES do
        self:HookDebuffFrame(i)
    end
    self.initialized = true
end

function ClassIconAuras:RefreshHooks()
    for i = 1, MAX_ARENA_ENEMIES do
        self:HookDebuffFrame(i)
    end
end

function ClassIconAuras:RestoreAll()
    local MFM = AC.MasterFrameManager
    if not MFM or not MFM.frames then return end

    for i = 1, MAX_ARENA_ENEMIES do
        local acFrame = MFM.frames[i]
        if acFrame and acFrame.classIcon then
            local classIcon = acFrame.classIcon
            if classIcon.auraCooldown then
                classIcon.auraCooldown:Clear()
            end
            classIcon.ccActive = false
            self.ccActive[i] = false
            local storedClass = acFrame.class
            if storedClass and classIcon.UpdateClassIcon then
                classIcon.UpdateClassIcon(storedClass)
            end
        end
    end
end

-- ============================================================================
-- EVENT HANDLING
-- ============================================================================

local eventFrame = CreateFrame("Frame")
eventFrame:RegisterEvent("PLAYER_ENTERING_WORLD")
eventFrame:RegisterEvent("ARENA_PREP_OPPONENT_SPECIALIZATIONS")
eventFrame:RegisterEvent("ARENA_OPPONENT_UPDATE")
eventFrame:RegisterEvent("GROUP_ROSTER_UPDATE")

eventFrame:SetScript("OnEvent", function(self, event, ...)
    local _, instanceType = IsInInstance()

    if event == "PLAYER_ENTERING_WORLD" then
        if instanceType == "arena" then
            C_Timer.After(0.5, function()
                if IsActiveBattlefieldArena and IsActiveBattlefieldArena() then
                    ClassIconAuras:RefreshHooks()
                end
            end)
        else
            ClassIconAuras:RestoreAll()
        end
    elseif event == "ARENA_PREP_OPPONENT_SPECIALIZATIONS" then
        ClassIconAuras:RestoreAll()
        C_Timer.After(0.1, function()
            if IsActiveBattlefieldArena and IsActiveBattlefieldArena() then
                ClassIconAuras:RefreshHooks()
            end
        end)
    elseif event == "GROUP_ROSTER_UPDATE" then
        if instanceType == "arena" then
            ClassIconAuras:RestoreAll()
        end
    elseif event == "ARENA_OPPONENT_UPDATE" then
        C_Timer.After(0.1, function()
            if IsActiveBattlefieldArena and IsActiveBattlefieldArena() then
                ClassIconAuras:RefreshHooks()
            end
        end)
    end
end)

C_Timer.After(0.5, function()
    if AC.Midnight and AC.Midnight.isMidnight then
        local _, instanceType = IsInInstance()
        if instanceType == "arena" and (not IsActiveBattlefieldArena or IsActiveBattlefieldArena()) then
            ClassIconAuras:Initialize()
        end
    end
end)
