local DRTracker = {}

local AC = _G.ArenaCore

-- Use DRList library for proper DR spell categorization
local DRList = LibStub and LibStub("DRList-1.0", true)
local spellList = DRList and DRList.spellList or {}

-- Ensure DR spell list is available
local DR_SPELL_CATEGORIES = {}
if DRList and DRList.spellList then
    -- Use DRList's categorization
    for spellID, effectType in pairs(DRList.spellList) do
        DR_SPELL_CATEGORIES[spellID] = effectType
    end
else
    -- Fallback hardcoded categories (comprehensive arena coverage)
    DR_SPELL_CATEGORIES = {
        -- Stuns - ADDED: 210141(Zombie Explosion), 377048(Absolute Zero), 221562(Asphyxiate Blood), 91797(Monstrous Blow), 287254(Dead of Winter), 205630(Illidan's Grasp Primary), 208618(Illidan's Grasp Secondary), 211881(Fel Eruption), 200166(Metamorphosis), 203123(Maim), 163505(Rake Prowl), 325321(Wild Hunt's Charge), 372245(Terror of the Skies), 408544(Seismic Slam), 357021(Consecutive Concussion), 389831(Snowdrift), 458605(Leg Sweep 2), 202346(Double Barrel), 255941(Wake of Ashes), 118905(Static Charge), 118345(Pulverize), 305485(Lightning Lasso), 89766(Axe Toss), 171017(Meteor Strike Infernal), 171018(Meteor Strike Abyssal), 385954(Shield Charge), 132168(Shockwave Protection), 145047(Shockwave PvE), 199085(Warpath), 255723(Bull Rush), 332423(Sparkling Driftglobe)
        [108194] = "stun", [91800] = "stun", [853] = "stun", [408] = "stun", [1833] = "stun",
        [179057] = "stun", [20549] = "stun", [119381] = "stun", [202244] = "stun",
        [30283] = "stun", [89766] = "stun", [22703] = "stun", [20549] = "stun",
        [199804] = "stun", [200200] = "stun", [287712] = "stun", [5211] = "stun",
        [210141] = "stun", [377048] = "stun", [221562] = "stun", [91797] = "stun", [287254] = "stun", [205630] = "stun", [208618] = "stun", [211881] = "stun", [200166] = "stun", [203123] = "stun", [163505] = "stun", [325321] = "stun", [372245] = "stun", [408544] = "stun", [357021] = "stun", [389831] = "stun", [458605] = "stun", [202346] = "stun", [255941] = "stun", [118905] = "stun", [118345] = "stun", [305485] = "stun", [171017] = "stun", [171018] = "stun", [385954] = "stun", [132168] = "stun", [145047] = "stun", [199085] = "stun", [255723] = "stun", [332423] = "stun",

        -- Disorients (Cyclone, etc.) - ADDED: 207167(Blinding Sleet), 207685(Sigil of Misery), 360806(Sleep Walk), 353084(Ring of Fire), 198909(Song of Chi-ji), 202274(Hot Trub), 105421(Blinding Light), 10326(Turn Evil), 205364(Dominate Mind), 118699(Fear Horrify), 130616(Fear Horrify), 261589(Seduction Grimoire), 6358(Seduction Succubus), 316593(Intimidating Shout Menace), 316595(Intimidating Shout Menace), 331866(Agent of Chaos), 324263(Sulfuric Emission)
        [33786] = "disorient", [8122] = "disorient", [2094] = "disorient", [31661] = "disorient",
        [82691] = "disorient", [118] = "disorient", [161355] = "disorient", [161353] = "disorient",
        [161354] = "disorient", [161372] = "disorient", [277784] = "disorient", [277778] = "disorient",
        [207167] = "disorient", [207685] = "disorient", [360806] = "disorient", [353084] = "disorient", [198909] = "disorient", [202274] = "disorient", [105421] = "disorient", [10326] = "disorient", [205364] = "disorient", [118699] = "disorient", [130616] = "disorient", [261589] = "disorient", [6358] = "disorient", [316593] = "disorient", [316595] = "disorient", [331866] = "disorient", [324263] = "disorient",

        -- Incapacitates - ADDED: 217832(Blinding Light PvE), 221527(Succulent Feast), 378441(Deterrence), 203337(Psychic Scream PvE), 213691(Scatter Shot), 383121(Mass Polymorph), 28271(Polymorph Turtle), 28272(Polymorph Pig), 61025(Polymorph Serpent), 61305(Polymorph Black Cat), 61780(Polymorph Turkey), 61721(Polymorph Rabbit), 126819(Monstrous Blow), 161353(Polymorph Porcupine), 161354(Polymorph Penguin), 161355(Polymorph Peacock), 161372(Polymorph Penguin), 277787(Polymorph Bumblebee), 277792(Polymorph Direhorn), 321395(Polymorph Mawrat), 391622(Polymorph Duck), 460396(Polymorph Mosswool), 461489(Polymorph Vulpine), 115078(Paralysis), 357768(Paralysis 2), 200196(Holy Word: Chastise PvE), 51514(Hex PvE), 196942(Voodoo Totem), 210873(Hex PvE), 211004(Hex PvE), 211010(Hex PvE), 211015(Hex PvE), 211016(Hex PvE), 269352(Mend Pet), 309328(Clobbering Seal), 277778(Paralysis PvE), 277784(Paralysis PvE), 197214(Sundering), 107079(Quaking Palm)
        [118] = "incapacitate", [51514] = "incapacitate", [6770] = "incapacitate", [20066] = "incapacitate",
        [9484] = "incapacitate", [605] = "incapacitate", [710] = "incapacitate", [5782] = "incapacitate",
        [3355] = "incapacitate", [19386] = "incapacitate", [19387] = "incapacitate",
        [217832] = "incapacitate", [221527] = "incapacitate", [378441] = "incapacitate", [203337] = "incapacitate", [213691] = "incapacitate", [383121] = "incapacitate", [28271] = "incapacitate", [28272] = "incapacitate", [61025] = "incapacitate", [61305] = "incapacitate", [61780] = "incapacitate", [61721] = "incapacitate", [126819] = "incapacitate", [161353] = "incapacitate", [161354] = "incapacitate", [161355] = "incapacitate", [161372] = "incapacitate", [277787] = "incapacitate", [277792] = "incapacitate", [321395] = "incapacitate", [391622] = "incapacitate", [460396] = "incapacitate", [461489] = "incapacitate", [115078] = "incapacitate", [357768] = "incapacitate", [200196] = "incapacitate", [51514] = "incapacitate", [196942] = "incapacitate", [210873] = "incapacitate", [211004] = "incapacitate", [211010] = "incapacitate", [211015] = "incapacitate", [211016] = "incapacitate", [269352] = "incapacitate", [309328] = "incapacitate", [277778] = "incapacitate", [277784] = "incapacitate", [197214] = "incapacitate", [107079] = "incapacitate",

        -- Silences - ADDED: 374776(Tightening Grasp), 204490(Sigil of Silence), 410065(Reactive Resin), 202933(Spider Sting), 356727(Spider Venom), 354831(Piercing Howl), 355596(Piercing Howl PvE), 217824(Shield of Virtue), 15487(Silence PvE), 196364(Unstable Affliction Silence)
        [15487] = "silence", [1330] = "silence", [19647] = "silence", [34490] = "silence",
        [18498] = "silence", [31117] = "silence", [132409] = "silence", [47476] = "silence",
        [78675] = "silence", [97547] = "silence",
        [374776] = "silence", [204490] = "silence", [410065] = "silence", [202933] = "silence", [356727] = "silence", [354831] = "silence", [355596] = "silence", [217824] = "silence", [15487] = "silence", [196364] = "silence",

        -- Roots - ADDED: 204085(Deathchill), 233395(Deathchill Frost), 454787(Living Flame), 235963(Entangling Roots Earthen), 170855(Entangling Roots Nature), 102359(Mass Entanglement), 355689(Landslide), 393456(Trap Launcher), 162480(Steel Trap), 201158(Super Sticky Tar), 114404(Void Tendrils), 342375(Tormenting Backlash), 116706(Disable), 324382(Clash), 285515(Surge of Power), 199042(Thunderstruck), 75148(Embersilk Net), 55536(Frostweave Net), 268966(Hooked Deep Sea Net)
        [339] = "root", [122] = "root", [53148] = "root", [64695] = "root", [63685] = "root",
        [45334] = "root", [33395] = "root", [19306] = "root", [55080] = "root", [87194] = "root",
        [102359] = "root", [50245] = "root",
        [204085] = "root", [233395] = "root", [454787] = "root", [235963] = "root", [170855] = "root", [102359] = "root", [355689] = "root", [393456] = "root", [162480] = "root", [201158] = "root", [114404] = "root", [342375] = "root", [116706] = "root", [324382] = "root", [285515] = "root", [199042] = "root", [75148] = "root", [55536] = "root", [268966] = "root",

        -- Fear - ADDED: 130616(Horrify), 261589(Seduction Grimoire)
        [5782] = "fear", [5484] = "fear", [6789] = "fear", [8122] = "fear", [87204] = "fear",
        [2094] = "fear", [5246] = "fear", [64044] = "fear", [111397] = "fear",
        [130616] = "fear", [261589] = "fear",

        -- Knockbacks - ADDED: 202249(Overrun), 431620(Upheaval), 186387(Burst), 236776(Hi-Explosive Trap), 236777(Hi-Explosive Trap 2), 462031(Implosive Trap), 157981(Blast Wave PvE), 51490(Thunderstorm), 368970(Tail Swipe), 357214(Wing Buffet)
        [186387] = "knockback", [157981] = "knockback", [200806] = "knockback", [204263] = "knockback",
        [61391] = "knockback", [102793] = "knockback", [108199] = "knockback",
        [202249] = "knockback", [431620] = "knockback", [186387] = "knockback", [236776] = "knockback", [236777] = "knockback", [462031] = "knockback", [157981] = "knockback", [51490] = "knockback", [368970] = "knockback", [357214] = "knockback",
    }
end

local MAX_ARENA_ENEMIES = MAX_ARENA_ENEMIES or 3

-- Unit Aura compatibility for modern WoW API
local UnitAura = UnitAura
if UnitAura == nil then
  --- Deprecated in 10.2.5, replaced with C_UnitAuras.GetAuraDataByIndex
  UnitAura = function(unitToken, index, filter)
		local auraData = C_UnitAuras.GetAuraDataByIndex(unitToken, index, filter)
		if not auraData then
			return nil;
		end
		return AuraUtil.UnpackAuraData(auraData)
	end
end

-- Unit Aura functions that return info about the first Aura matching the spellName or spellID given on the unit.
local WA_GetUnitAura = function(unit, spell, filter)
  if filter and not filter:upper():find("FUL") then
      filter = filter.."|HELPFUL"
  end
  for i = 1, 255 do
    local name, _, _, _, _, _, _, _, _, spellId = UnitAura(unit, i, filter)
    if not name then return end
    if spell == spellId or spell == name then
      return UnitAura(unit, i, filter)
    end
  end
end

local WA_GetUnitDebuff = function(unit, spell, filter)
  filter = filter and filter.."|HARMFUL" or "HARMFUL"
  return WA_GetUnitAura(unit, spell, filter)
end

function DRTracker:IsSourceFriendly(sourceGUID, sourceFlags)
    -- DO NOT call AC:IsDRSourceFriendly - causes infinite recursion
    
    if sourceFlags and bit then
        local mine = bit.band(sourceFlags, COMBATLOG_OBJECT_AFFILIATION_MINE) > 0
        local party = bit.band(sourceFlags, COMBATLOG_OBJECT_AFFILIATION_PARTY) > 0
        local raid = bit.band(sourceFlags, COMBATLOG_OBJECT_AFFILIATION_RAID) > 0
        if mine or party or raid then
            return true
        end
    end

    if not sourceGUID then return false end

    if UnitGUID("player") == sourceGUID then return true end
    if UnitGUID("pet") == sourceGUID then return true end

    for i = 1, 4 do
        if UnitGUID("party" .. i) == sourceGUID then return true end
        if UnitGUID("partypet" .. i) == sourceGUID then return true end
    end

    return false
end

function DRTracker:GetUnitIDFromGUID(guid)
    if not guid then return nil end

    for i = 1, MAX_ARENA_ENEMIES do
        local unit = "arena" .. i
        if UnitGUID(unit) == guid then
            return unit
        end
    end

    return nil
end

function DRTracker:GetFrameForUnit(unitID)
    local manager = AC and AC.FrameManager
    if manager and manager.GetFrames then
        local frames = manager:GetFrames()
        if frames then
            local index = tonumber(unitID:match("arena(%d+)"))
            if index and frames[index] then
                return frames[index]
            end
        end
    end

    if AC and AC.arenaFrames then
        local index = tonumber(unitID:match("arena(%d+)"))
        if index and AC.arenaFrames[index] then
            return AC.arenaFrames[index]
        end
    end

    return nil
end

function DRTracker:EnsureDRModule()
    local manager = AC and AC.FrameManager
    if manager and manager.DR then
        return manager.DR
    end

    manager = AC and AC.MasterFrameManager
    if manager and manager.DR then
        return manager.DR
    end

    return nil
end

function DRTracker:UpdateDisplay(unitID, category, actualSpellID)
    local drModule = self:EnsureDRModule()
    if not drModule then return end

    drModule:UpdateLiveDisplay(unitID, category, actualSpellID)
end

function DRTracker:TrackApplication(unitGUID, spellID, category, auraDuration)
    local drModule = self:EnsureDRModule()
    if not drModule then return end

    drModule:TrackApplication(unitGUID, spellID, category, auraDuration)
end

function DRTracker:StartRealArenaTicker()
    local drModule = self:EnsureDRModule()
    if not drModule then return end

    drModule:StartRealArenaTicker()
end

function DRTracker:HandleCombatLog()
    if not AC then return end

    local timestamp, subevent, _, sourceGUID, sourceName, sourceFlags, _,
          destGUID, destName, destFlags, _, spellID, spellName, _, auraType = CombatLogGetCurrentEventInfo()

    if subevent == "SPELL_AURA_APPLIED" or subevent == "SPELL_AURA_REFRESH" then
        local friendly = self:IsSourceFriendly(sourceGUID, sourceFlags)
        if not friendly then
            return
        end

        local unitID = self:GetUnitIDFromGUID(destGUID)
        if not unitID then
            return
        end

        local drCategory = DR_SPELL_CATEGORIES[spellID]
        if not drCategory then
            return
        end

        if auraType ~= "DEBUFF" then
            return
        end

        -- Get aura duration using WA_GetUnitDebuff
        local _, _, _, _, auraDuration, _ = WA_GetUnitDebuff(unitID, spellID)

        self:TrackApplication(destGUID, spellID, drCategory, auraDuration)
        self:UpdateDisplay(unitID, drCategory, spellID)

    elseif subevent == "SPELL_AURA_REMOVED" then
        -- Handle aura removal for DR tracking
        if auraType == "DEBUFF" then
            local drCategory = DR_SPELL_CATEGORIES[spellID]
            if drCategory then
                local unitID = self:GetUnitIDFromGUID(destGUID)
                if unitID then
                    self:TrackApplication(destGUID, spellID, drCategory)
                end
            end
        end
    end
end

function DRTracker:Initialize()
    if not AC then return end

    -- DO NOT register COMBAT_LOG here - it's called from main ArenaCore handler
    -- Registering here causes duplicate event processing and infinite loops
    
    self:StartRealArenaTicker()
end

AC.modules = AC.modules or {}
AC.modules.diminishingReturns = AC.modules.diminishingReturns or {}
AC.modules.diminishingReturns.tracker = DRTracker

return DRTracker
