-- DynamicTooltips: Master Spell Data
-- Merges all class data into a single lookup table

local _, DT = ...

-- Initialize global spell data table
DT.SpellData = DT.SpellData or {}

-- ============================================================================
-- MERGE CLASS DATA INTO MASTER TABLE
-- ============================================================================

-- Name-based lookup table (for when spell ID isn't found)
DT.SpellDataByName = DT.SpellDataByName or {}

-- Stores all ranks of each spell by name for rank comparison
DT.SpellRanksByName = DT.SpellRanksByName or {}

local function MergeClassData()
    if not DT.ClassData then return end
    
    for className, spells in pairs(DT.ClassData) do
        for spellID, data in pairs(spells) do
            -- Add class info to each spell
            data.class = className
            
            -- Add to master table by ID
            DT.SpellData[spellID] = data
            
            -- Also add to name-based lookup (for ranked spells)
            if data.name then
                DT.SpellDataByName[data.name:lower()] = data
                
                -- Build ranks table for this spell
                local lowerName = data.name:lower()
                if not DT.SpellRanksByName[lowerName] then
                    DT.SpellRanksByName[lowerName] = {}
                end
                -- Store by rank number for easy lookup
                if data.rank then
                    DT.SpellRanksByName[lowerName][data.rank] = {
                        spellID = spellID,
                        level = data.level or 1,
                        rank = data.rank,
                        maxRank = data.maxRank or data.rank,
                    }
                end
            end
        end
    end
end

-- ============================================================================
-- SPELL LOOKUP FUNCTIONS
-- ============================================================================

function DT.GetSpellData(spellID, spellName)
    -- Try direct ID lookup first
    local data = DT.SpellData[spellID]
    if data then return data end
    
    -- Fallback to name-based lookup (for ranked spells)
    if spellName and DT.SpellDataByName then
        return DT.SpellDataByName[spellName:lower()]
    end
    
    return nil
end

function DT.HasCoefficient(spellID)
    local data = DT.SpellData[spellID]
    if not data then return false end
    return (data.sp and data.sp > 0) or (data.wd and data.wd > 0) or (data.ap and data.ap > 0)
end

function DT.GetSpellCoefficient(spellID)
    local data = DT.SpellData[spellID]
    if not data then return 0, 0 end
    return data.sp or 0, data.wd or 0
end

function DT.GetSpellSchool(spellID)
    local data = DT.SpellData[spellID]
    if not data then return "Physical" end
    return data.school or "Physical"
end

function DT.GetSpellType(spellID)
    local data = DT.SpellData[spellID]
    if not data then return "Unknown" end
    return data.type or "Unknown"
end

function DT.IsHealingSpell(spellID)
    local data = DT.SpellData[spellID]
    if not data then return false end
    return data.isHeal == true
end

-- Get the highest rank of a spell that's trainable at a given player level
-- Returns: highestTrainableRank, highestTrainableLevel or nil if none higher
function DT.GetHighestTrainableRank(spellName, currentRank, playerLevel)
    if not spellName or not DT.SpellRanksByName then return nil, nil end
    
    local lowerName = spellName:lower()
    local ranks = DT.SpellRanksByName[lowerName]
    if not ranks then return nil, nil end
    
    local highestRank = currentRank or 0
    local highestLevel = 0
    
    for rank, info in pairs(ranks) do
        -- Check if this rank is higher than current and trainable at player level
        if rank > (currentRank or 0) and info.level and info.level <= playerLevel then
            if rank > highestRank then
                highestRank = rank
                highestLevel = info.level
            end
        end
    end
    
    -- Return nil if no higher rank is trainable
    if highestRank <= (currentRank or 0) then
        return nil, nil
    end
    
    return highestRank, highestLevel
end

-- Check if the next rank is trainable at player level
function DT.IsNextRankTrainable(spellName, currentRank, playerLevel)
    if not spellName or not currentRank or not DT.SpellRanksByName then return false end
    
    local lowerName = spellName:lower()
    local ranks = DT.SpellRanksByName[lowerName]
    if not ranks then return false end
    
    local nextRank = currentRank + 1
    local nextInfo = ranks[nextRank]
    
    if nextInfo and nextInfo.level and nextInfo.level <= playerLevel then
        return true, nextInfo.level
    end
    
    return false
end

function DT.IsDotSpell(spellID)
    local data = DT.SpellData[spellID]
    if not data then return false end
    return data.type == "DoT" or data.type == "HoT" or data.type == "Channel"
end

function DT.GetSpellDuration(spellID)
    local data = DT.SpellData[spellID]
    if not data then return 0 end
    return data.duration or 0
end

function DT.GetSpellsByClass(className)
    if not DT.ClassData or not DT.ClassData[className] then
        return {}
    end
    return DT.ClassData[className]
end

function DT.GetSpellsBySchool(school)
    local results = {}
    for spellID, data in pairs(DT.SpellData) do
        if data.school == school then
            results[spellID] = data
        end
    end
    return results
end

function DT.GetSpellsByType(spellType)
    local results = {}
    for spellID, data in pairs(DT.SpellData) do
        if data.type == spellType then
            results[spellID] = data
        end
    end
    return results
end

-- ============================================================================
-- SCHOOL COLORS
-- ============================================================================

DT.SchoolColors = {
    Physical = { r = 1.0, g = 1.0, b = 0.6 },
    Holy = { r = 1.0, g = 0.9, b = 0.5 },
    Fire = { r = 1.0, g = 0.4, b = 0.0 },
    Nature = { r = 0.3, g = 1.0, b = 0.3 },
    Frost = { r = 0.5, g = 0.8, b = 1.0 },
    Shadow = { r = 0.6, g = 0.3, b = 0.8 },
    Arcane = { r = 1.0, g = 0.5, b = 1.0 },
}

function DT.GetSchoolColor(school)
    return DT.SchoolColors[school] or DT.SchoolColors.Physical
end

-- ============================================================================
-- SPELL SUMMARIES (1-6 words for no-coefficient spells when explanatory text is off)
-- ============================================================================

DT.SpellSummaries = {
    -- WARRIOR
    ["Execute"] = "Finisher below 20% HP",
    ["Revenge"] = "Counter after block/dodge/parry",
    ["Shield Slam"] = "Block value based damage",
    ["Rend"] = "Bleed + weapon damage over time",
    ["Thunder Clap"] = "AoE slow attack speed",
    ["Demoralizing Shout"] = "AoE reduce melee AP",
    ["Battle Shout"] = "Party melee AP buff",
    ["Commanding Shout"] = "Party max HP buff",
    ["Pummel"] = "Interrupt spellcasting",
    ["Shield Bash"] = "Interrupt spellcasting",
    ["Charge"] = "Stun and generate rage",
    ["Intercept"] = "Stun at range",
    ["Intervene"] = "Absorb ally's next hit",
    ["Hamstring"] = "Snare target 60%",
    ["Sunder Armor"] = "Reduce armor, stacks 5x, +threat",
    ["Concussion Blow"] = "Stun 5 seconds",
    ["Intimidating Shout"] = "AoE fear 8 seconds",
    ["Disarm"] = "Remove target's weapons",
    ["Shield Wall"] = "Reduce damage taken 75%",
    ["Last Stand"] = "Gain 30% max HP",
    ["Shield Block"] = "Guarantee block for 5 sec",
    ["Spell Reflection"] = "Reflect next spell",
    ["Recklessness"] = "Guarantee crit, take more",
    ["Berserker Rage"] = "Immune to fear/sap/incap",
    ["Retaliation"] = "Counter melee attacks",
    ["Sweeping Strikes"] = "Next 5 hits cleave",
    ["Taunt"] = "Force target to attack you",
    ["Mocking Blow"] = "Taunt with damage",
    ["Challenging Shout"] = "AoE taunt 6 seconds",
    ["Battle Stance"] = "+stance for Arms abilities",
    ["Defensive Stance"] = "+threat, -damage taken",
    ["Berserker Stance"] = "+crit, +rage from damage",
    ["Bloodrage"] = "Generate rage from HP",
    -- PRIEST
    ["Fear Ward"] = "Prevent one fear effect",
    ["Inner Focus"] = "Next spell free, +25% crit",
    ["Levitate"] = "Slow fall over water/air",
    ["Prayer of Fortitude"] = "Group stamina buff",
    ["Power Word: Fortitude"] = "Stamina buff",
    ["Divine Spirit"] = "Spirit buff",
    ["Prayer of Spirit"] = "Group spirit buff",
    ["Shadow Protection"] = "Shadow resist buff",
    ["Prayer of Shadow Protection"] = "Group shadow resist",
    ["Vampiric Embrace"] = "Shadow dmg heals party 25%",
    ["Shadowform"] = "+15% shadow, -15% physical",
    ["Cure Disease"] = "Remove one disease",
    ["Dispel Magic"] = "Remove 2 magic effects",
    ["Mass Dispel"] = "AoE dispel, removes immunity",
    ["Abolish Disease"] = "Remove disease every 5 sec",
    ["Mana Burn"] = "Destroy target's mana",
    ["Mind Soothe"] = "Reduce aggro radius",
    ["Mind Control"] = "Control enemy temporarily",
    ["Shackle Undead"] = "CC undead 50 seconds",
    ["Psychic Scream"] = "AoE fear 8 seconds",
    -- ROGUE
    ["Rupture"] = "Bleed finisher over time",
    ["Garrote"] = "Bleed from stealth, silence",
    ["Gouge"] = "Incapacitate, breaks on dmg",
    ["Deadly Throw"] = "Ranged finisher, interrupt",
    ["Kidney Shot"] = "Stun finisher",
    ["Slice and Dice"] = "Increase attack speed",
    ["Expose Armor"] = "Reduce target armor",
    ["Cheap Shot"] = "Stealth stun 4 seconds",
    ["Sap"] = "CC humanoid from stealth",
    ["Evasion"] = "+50% dodge chance",
    ["Sprint"] = "+70% movement speed",
    ["Feint"] = "Reduce threat",
    ["Vanish"] = "Enter stealth instantly",
    ["Stealth"] = "Become invisible",
    ["Blind"] = "Disorient 10 seconds",
    ["Cloak of Shadows"] = "Remove all magic effects",
    ["Kick"] = "Interrupt spellcasting",
    ["Cold Blood"] = "Next ability guaranteed crit",
    ["Preparation"] = "Reset all cooldowns",
    ["Shadowstep"] = "Teleport behind target",
    ["Adrenaline Rush"] = "Double energy regen",
    ["Blade Flurry"] = "Attacks hit 2 targets",
    ["Distract"] = "Turn enemies away",
    ["Pick Pocket"] = "Steal from humanoids",
    ["Pick Lock"] = "Open locked chests/doors",
    ["Disarm Trap"] = "Disable trapped objects",
    ["Detect Traps"] = "See nearby traps",
    ["Safe Fall"] = "Reduce fall damage",
    -- HUNTER
    ["Wing Clip"] = "Snare target melee",
    ["Aspect of the Hawk"] = "Increase ranged AP",
    ["Aspect of the Cheetah"] = "+30% run speed, daze risk",
    ["Aspect of the Beast"] = "Untrackable",
    ["Aspect of the Pack"] = "Group speed, daze risk",
    ["Aspect of the Wild"] = "Party nature resist",
    ["Aspect of the Viper"] = "Regen mana from attacks",
    ["Revive Pet"] = "Resurrect dead pet",
    ["Feed Pet"] = "Restore pet happiness",
    ["Call Pet"] = "Summon your pet",
    ["Dismiss Pet"] = "Dismiss your pet",
    ["Tame Beast"] = "Tame a new pet",
    ["Hunter's Mark"] = "Increase ranged AP vs target",
    ["Feign Death"] = "Drop threat, play dead",
    ["Disengage"] = "Reduce threat",
    ["Distracting Shot"] = "Ranged taunt",
    ["Concussive Shot"] = "Ranged snare 4 seconds",
    -- MAGE
    ["Combustion"] = "Stack fire crit bonus",
    ["Ice Block"] = "Immune to everything",
    ["Icy Veins"] = "+20% cast speed, no pushback",
    ["Arcane Power"] = "+30% damage, +30% cost",
    ["Polymorph"] = "CC beast/humanoid 50 sec",
    ["Evocation"] = "Channel mana regen",
    ["Arcane Intellect"] = "Intellect buff",
    ["Slow Fall"] = "Reduce fall speed",
    ["Remove Curse"] = "Remove one curse",
    ["Fire Ward"] = "Absorb fire damage",
    ["Frost Ward"] = "Absorb frost damage",
    ["Mana Shield"] = "Absorb damage with mana",
    ["Spellsteal"] = "Steal a magic buff",
    ["Counterspell"] = "Interrupt + lock school",
    -- WARLOCK
    ["Drain Mana"] = "Channel steal mana",
    ["Curse of Tongues"] = "Slow casting speed 50%",
    ["Curse of Weakness"] = "Reduce melee AP",
    ["Curse of the Elements"] = "+fire/frost damage taken",
    ["Curse of Shadow"] = "+shadow/arcane damage taken",
    ["Curse of Recklessness"] = "Reduce armor, immune fear",
    ["Curse of Exhaustion"] = "Snare target 30%",
    ["Dark Pact"] = "Drain pet mana for yours",
    ["Banish"] = "CC demon/elemental 30 sec",
    ["Fear"] = "Fear target 20 seconds",
    ["Howl of Terror"] = "AoE fear 8 seconds",
    ["Enslave Demon"] = "Control demon temporarily",
    ["Demon Skin"] = "HP regen + armor buff",
    ["Demon Armor"] = "Armor + shadow resist",
    ["Fel Armor"] = "+SP from spirit, HP regen",
    ["Detect Invisibility"] = "See invisible units",
    ["Soulshatter"] = "Reduce threat by 50%",
    ["Summon Felhunter"] = "Summon anti-caster pet",
    ["Summon Voidwalker"] = "Summon tanking pet",
    ["Summon Imp"] = "Summon ranged DPS pet",
    ["Summon Succubus"] = "Summon CC/DPS pet",
    ["Summon Felguard"] = "Summon melee DPS pet",
    ["Ritual of Summoning"] = "Summon party member",
    -- WARLOCK PET ABILITIES
    ["Firebolt"] = "Imp ranged fire attack",
    ["Fire Shield"] = "Reactive fire damage shield",
    ["Blood Pact"] = "Party stamina buff",
    ["Phase Shift"] = "Imp becomes untargetable",
    ["Torment"] = "Taunt target (Voidwalker)",
    ["Consume Shadows"] = "Self-heal out of combat",
    ["Sacrifice"] = "Kill VW, absorb shield on you",
    ["Suffering"] = "AoE taunt (Voidwalker)",
    ["Lash of Pain"] = "Instant shadow damage",
    ["Soothing Kiss"] = "Reduce target threat",
    ["Seduction"] = "CC humanoid 15 sec",
    ["Lesser Invisibility"] = "Succubus goes invisible",
    ["Devour Magic"] = "Dispel + heal on success",
    ["Spell Lock"] = "Interrupt + 3 sec silence",
    ["Tainted Blood"] = "Passive: damage attackers",
    ["Paranoia"] = "Stealth detection aura",
    ["Anguish"] = "Taunt target (Felguard)",
    ["Demonic Frenzy"] = "Stacking AP on melee hit",
    ["Avoidance"] = "Reduce AoE damage taken",
    -- HUNTER PET ABILITIES
    ["Bite"] = "Physical pet attack (10s CD)",
    ["Claw"] = "Physical pet attack (next melee)",
    ["Lightning Breath"] = "Instant Nature damage (Wind Serpent)",
    ["Screech"] = "Damage + lower enemy melee AP",
    ["Scorpid Poison"] = "Nature DoT, stacks to 5",
    ["Thunderstomp"] = "Nature AoE 8yd (Gorilla)",
    ["Furious Howl"] = "Party +dmg to next attack (Wolf)",
    ["Growl"] = "Taunt target (all pets)",
    ["Cower"] = "Lower pet threat",
    ["Shell Shield"] = "50% dmg reduction 12s (Turtle)",
    -- DRUID
    ["Rip"] = "Bleed finisher over time",
    ["Shred"] = "Backstab from behind",
    ["Pounce"] = "Stealth stun + bleed",
    ["Mangle (Cat)"] = "160% WD, +30% bleed taken",
    ["Mangle (Bear)"] = "115% WD, +30% bleed taken",
    ["Ravage"] = "385% WD stealth opener",
    ["Lacerate"] = "Initial hit + stacking bleed",
    ["Maul"] = "Bear next melee + flat dmg",
    ["Ferocious Bite"] = "AP finisher, uses energy",
    ["Mark of the Wild"] = "All stats + armor buff",
    ["Force of Nature"] = "Summon 3 treants",
    ["Frenzied Regeneration"] = "Rage to HP in bear",
    ["Bear Form"] = "Tank form, +armor/HP",
    ["Cat Form"] = "Melee DPS form",
    ["Flight Form"] = "Instant cast flying",
    ["Prowl"] = "Stealth in cat form",
    ["Dash"] = "+70% speed in cat form",
    -- PALADIN
    ["Lay on Hands"] = "Full HP heal, long CD",
    ["Judgement"] = "Release seal effect",
    ["Blessing of Might"] = "Melee AP buff",
    ["Blessing of Wisdom"] = "Mana regen buff",
    ["Hammer of Justice"] = "Stun 6 seconds",
    ["Avenging Wrath"] = "+30% all damage",
    ["Blessing of Kings"] = "+10% all stats",
    ["Blessing of Sacrifice"] = "Transfer damage to you",
    ["Blessing of Freedom"] = "Immune to movement impair",
    ["Blessing of Salvation"] = "Reduce threat 30%",
    ["Blessing of Protection"] = "Immune to physical",
    ["Divine Shield"] = "Immune to everything",
    ["Divine Protection"] = "Reduce damage taken",
    ["Cleanse"] = "Remove magic/disease/poison",
    ["Purify"] = "Remove disease/poison",
    ["Turn Undead"] = "Fear undead",
    ["Retribution Aura"] = "Damage melee attackers",
    ["Devotion Aura"] = "Increase party armor",
    ["Concentration Aura"] = "Resist spell pushback",
    ["Fire Resistance Aura"] = "Party fire resist",
    ["Frost Resistance Aura"] = "Party frost resist",
    ["Shadow Resistance Aura"] = "Party shadow resist",
    ["Crusader Aura"] = "+mounted speed",
    -- SHAMAN
    ["Totem of Wrath"] = "+3% spell hit/crit",
    ["Fire Elemental Totem"] = "Summon fire elemental",
    ["Earth Elemental Totem"] = "Summon earth elemental",
    ["Stoneclaw Totem"] = "Taunt nearby enemies",
    ["Stoneskin Totem"] = "Reduce melee damage taken",
    ["Strength of Earth Totem"] = "Party strength/agility",
    ["Windfury Totem"] = "Party melee extra attacks",
    ["Grounding Totem"] = "Absorb one harmful spell",
    ["Frost Resistance Totem"] = "Party frost resist",
    ["Fire Resistance Totem"] = "Party fire resist",
    ["Nature Resistance Totem"] = "Party nature resist",
    ["Mana Spring Totem"] = "Party mana regen",
    ["Flametongue Totem"] = "Party spell damage buff",
    ["Wrath of Air Totem"] = "Party spell power/haste",
    ["Tremor Totem"] = "Remove fear/charm/sleep",
    ["Poison Cleansing Totem"] = "Remove poison effects",
    ["Disease Cleansing Totem"] = "Remove disease effects",
    ["Grace of Air Totem"] = "Party agility buff",
    ["Windfury Weapon"] = "Melee proc extra attacks",
    ["Rockbiter Weapon"] = "Increase melee damage",
    ["Water Walking"] = "Walk on water",
    ["Water Breathing"] = "Breathe underwater",
    ["Astral Recall"] = "Teleport to hearthstone",
    ["Ghost Wolf"] = "+40% speed wolf form",
    ["Cure Toxins"] = "Remove poison/disease",
    ["Purge"] = "Remove 2 magic buffs",
    ["Ancestral Spirit"] = "Resurrect dead player",
}

-- ============================================================================
-- CLASS COLORS
-- ============================================================================

DT.ClassColors = {
    Warrior = { r = 0.78, g = 0.61, b = 0.43 },
    Paladin = { r = 0.96, g = 0.55, b = 0.73 },
    Hunter = { r = 0.67, g = 0.83, b = 0.45 },
    Rogue = { r = 1.00, g = 0.96, b = 0.41 },
    Priest = { r = 1.00, g = 1.00, b = 1.00 },
    Shaman = { r = 0.00, g = 0.44, b = 0.87 },
    Mage = { r = 0.41, g = 0.80, b = 0.94 },
    Warlock = { r = 0.58, g = 0.51, b = 0.79 },
    Druid = { r = 1.00, g = 0.49, b = 0.04 },
}

function DT.GetClassColor(className)
    return DT.ClassColors[className] or { r = 1, g = 1, b = 1 }
end

-- ============================================================================
-- TYPE ICONS
-- ============================================================================

DT.TypeIcons = {
    Direct = "⚔",
    DoT = "☠",
    HoT = "✚",
    Channel = "↻",
    Shield = "🛡",
    Buff = "↑",
    Debuff = "↓",
    Melee = "⚔",
    Ranged = "🏹",
    CC = "💤",
    Ability = "★",
    Proc = "⚡",
    Totem = "▲",
    Pet = "🐾",
    Form = "◐",
    Aura = "○",
    Interrupt = "✗",
    Dispel = "✧",
    Ress = "♰",
}

function DT.GetTypeIcon(spellType)
    return DT.TypeIcons[spellType] or "•"
end

-- ============================================================================
-- STAT DISPLAY
-- ============================================================================

function DT.GetSpellStatSummary()
    local total = 0
    local withCoeff = 0
    local byClass = {}
    
    for spellID, data in pairs(DT.SpellData) do
        total = total + 1
        if (data.sp and data.sp > 0) or (data.wd and data.wd > 0) then
            withCoeff = withCoeff + 1
        end
        
        local class = data.class or "Unknown"
        byClass[class] = (byClass[class] or 0) + 1
    end
    
    return {
        total = total,
        withCoefficients = withCoeff,
        byClass = byClass,
    }
end

-- ============================================================================
-- INITIALIZATION
-- ============================================================================

-- Create event frame for initialization
local initFrame = CreateFrame("Frame")
initFrame:RegisterEvent("ADDON_LOADED")
initFrame:SetScript("OnEvent", function(self, event, addonName)
    if addonName == "DynamicTooltips" then
        -- Merge all class data
        MergeClassData()
        
        -- Add shared/generic spells not tied to a single class
        -- Wand Shoot (5019): Used by Mage, Warlock, Priest — pure weapon damage, unnormalized, no AP
        DT.SpellData[5019] = { name = "Shoot", sp = 0, wd = 1.0, school = "Physical", type = "Ranged", class = "Shared" }
        
        -- Debug output
        if DT.DB and DT.DB.debugMode then
            local stats = DT.GetSpellStatSummary()
            print(string.format("|cff66ccffDynamicTooltips|r: Loaded %d spells (%d with coefficients)", 
                stats.total, stats.withCoefficients))
        end
        
        self:UnregisterEvent("ADDON_LOADED")
    end
end)
