-- WoWTetris Classes & Ultimates v5.0
-- ALL ultimates are now GAME-CHANGING!
-- Premium classes: Monk, Demon Hunter, Evoker (purchasable with coins)

local addonName, addon = ...

addon.CLASSES = {
    WARRIOR = {name = "Warrior", icon = "Interface\\Icons\\ClassIcon_Warrior", colorCode = "|cffc79c6e", description = "Masters of destruction.", premium = false},
    PALADIN = {name = "Paladin", icon = "Interface\\Icons\\ClassIcon_Paladin", colorCode = "|cfff58cba", description = "Holy power transforms.", premium = false},
    HUNTER = {name = "Hunter", icon = "Interface\\Icons\\ClassIcon_Hunter", colorCode = "|cffabd473", description = "Precision strikes.", premium = false},
    ROGUE = {name = "Rogue", icon = "Interface\\Icons\\ClassIcon_Rogue", colorCode = "|cfffff569", description = "Tricks and manipulation.", premium = false},
    PRIEST = {name = "Priest", icon = "Interface\\Icons\\ClassIcon_Priest", colorCode = "|cffffffff", description = "Heal gaps, smite blocks.", premium = false},
    DEATHKNIGHT = {name = "Death Knight", icon = "Interface\\Icons\\ClassIcon_DeathKnight", colorCode = "|cffc41f3b", description = "Plague and death.", premium = false},
    SHAMAN = {name = "Shaman", icon = "Interface\\Icons\\ClassIcon_Shaman", colorCode = "|cff0070de", description = "Elemental forces.", premium = false},
    MAGE = {name = "Mage", icon = "Interface\\Icons\\ClassIcon_Mage", colorCode = "|cff69ccf0", description = "Arcane transformation.", premium = false},
    WARLOCK = {name = "Warlock", icon = "Interface\\Icons\\ClassIcon_Warlock", colorCode = "|cff9482c9", description = "Chaos and corruption.", premium = false},
    DRUID = {name = "Druid", icon = "Interface\\Icons\\ClassIcon_Druid", colorCode = "|cffff7d0a", description = "Nature's balance.", premium = false},
    -- Premium Classes
    MONK = {name = "Monk", icon = "Interface\\Icons\\ClassIcon_Monk", colorCode = "|cff00ff96", description = "Chi mastery.", premium = true, cost = 5000},
    DEMONHUNTER = {name = "Demon Hunter", icon = "Interface\\Icons\\ClassIcon_DemonHunter", colorCode = "|cffa330c9", description = "Fel-infused vengeance.", premium = true, cost = 5000},
    EVOKER = {name = "Evoker", icon = "Interface\\Icons\\ClassIcon_Evoker", colorCode = "|cff33937f", description = "Draconic power.", premium = true, cost = 7500},
}

-- Base classes available to all
addon.CLASS_ORDER = {"WARRIOR", "PALADIN", "HUNTER", "ROGUE", "PRIEST", "DEATHKNIGHT", "SHAMAN", "MAGE", "WARLOCK", "DRUID"}
-- Premium classes shown separately
addon.PREMIUM_CLASSES = {"MONK", "DEMONHUNTER", "EVOKER"}

addon.ULTIMATES = {
    WARRIOR = {
        {name = "Bladestorm", icon = "Interface\\Icons\\Ability_Whirlwind", description = "Clear 5x5 area around piece.", unlockLevel = 1, cooldown = 20, execute = function() WoWTetris:Ult_AreaClear(5) end},
        {name = "Execute", icon = "Interface\\Icons\\INV_Sword_48", description = "Clear bottom 4 rows.", unlockLevel = 15, cooldown = 35, execute = function() WoWTetris:Ult_ClearBottom(4) end},
        {name = "Cleave", icon = "Interface\\Icons\\Ability_Warrior_Cleave", description = "Clear 3 random rows.", unlockLevel = 30, cooldown = 30, execute = function() WoWTetris:Ult_ClearRandomRows(3) end},
        {name = "Rampage", icon = "Interface\\Icons\\Ability_GolemThunderClap", description = "Destroy 20 random blocks.", unlockLevel = 50, cooldown = 25, execute = function() WoWTetris:Ult_DestroyRandom(20) end},
        {name = "Avatar", icon = "Interface\\Icons\\Spell_Holy_AshesToAshes", description = "Next 3 pieces are SUPERCHARGED: Row, Column, Row clears!", unlockLevel = 100, cooldown = 60, execute = function() WoWTetris:Ult_Avatar() end},
    },
    PALADIN = {
        {name = "Consecration", icon = "Interface\\Icons\\Spell_Holy_InnerFire", description = "Clear bottom 3 rows.", unlockLevel = 1, cooldown = 20, execute = function() WoWTetris:Ult_ClearBottom(3) end},
        {name = "Hammer of Justice", icon = "Interface\\Icons\\Spell_Holy_SealOfMight", description = "Clear current column.", unlockLevel = 15, cooldown = 25, execute = function() WoWTetris:Ult_ClearCurrentColumn() end},
        {name = "Divine Storm", icon = "Interface\\Icons\\Ability_Paladin_DivineStorm", description = "Clear up to 2 incomplete rows from the bottom.", unlockLevel = 30, cooldown = 40, execute = function() WoWTetris:Ult_ClearIncompleteRows() end},
        {name = "Lay on Hands", icon = "Interface\\Icons\\Spell_Holy_LayOnHands", description = "Fill gaps in bottom 5 rows!", unlockLevel = 50, cooldown = 45, execute = function() WoWTetris:Ult_FillGaps(5) end},
        {name = "Wake of Ashes", icon = "Interface\\Icons\\INV_Sword_2h_Ashbringercorrupt", description = "Clear 6 rows + next is I-piece!", unlockLevel = 100, cooldown = 55, execute = function() WoWTetris:Ult_WakeOfAshes() end},
    },
    HUNTER = {
        {name = "Kill Shot", icon = "Interface\\Icons\\INV_Weapon_Bow_07", description = "Clear 2 most-filled rows.", unlockLevel = 1, cooldown = 20, execute = function() WoWTetris:Ult_ClearMostFilled(2) end},
        {name = "Multi-Shot", icon = "Interface\\Icons\\Ability_Marksmanship", description = "Clear 3 random columns.", unlockLevel = 15, cooldown = 30, execute = function() WoWTetris:Ult_ClearColumns(3) end},
        {name = "Explosive Trap", icon = "Interface\\Icons\\Spell_Fire_SelfDestruct", description = "Bomb: 4x4 clear when piece lands.", unlockLevel = 30, cooldown = 25, execute = function() WoWTetris:Ult_PlaceBomb(4) end},
        {name = "Aimed Shot", icon = "Interface\\Icons\\INV_Spear_07", description = "Clear current row completely.", unlockLevel = 50, cooldown = 20, execute = function() WoWTetris:Ult_ClearCurrentRow() end},
        {name = "Barrage", icon = "Interface\\Icons\\INV_Weapon_Crossbow_04", description = "Destroy 30 random blocks!", unlockLevel = 100, cooldown = 45, execute = function() WoWTetris:Ult_DestroyRandom(30) end},
    },
    ROGUE = {
        {name = "Fan of Knives", icon = "Interface\\Icons\\INV_ThrowingKnife_06", description = "Destroy 15 random blocks.", unlockLevel = 1, cooldown = 18, execute = function() WoWTetris:Ult_DestroyRandom(15) end},
        {name = "Shadowstep", icon = "Interface\\Icons\\Ability_Rogue_Shadowstep", description = "Transform piece to any type!", unlockLevel = 15, cooldown = 30, execute = function() WoWTetris:Ult_TransformPiece() end},
        {name = "Tricks", icon = "Interface\\Icons\\Ability_Rogue_Disguise", description = "Free hold swap + reset hold.", unlockLevel = 30, cooldown = 15, execute = function() WoWTetris:Ult_FreeSwap() end},
        {name = "Vendetta", icon = "Interface\\Icons\\Ability_Rogue_DeadlyBrew", description = "Clear row AND column at piece!", unlockLevel = 50, cooldown = 35, execute = function() WoWTetris:Ult_ClearCross() end},
        {name = "Shadow Dance", icon = "Interface\\Icons\\Ability_Stealth", description = "Next 3 pieces are I-pieces!", unlockLevel = 100, cooldown = 50, execute = function() WoWTetris:Ult_ChooseNextPieces(3) end},
    },
    PRIEST = {
        {name = "Holy Nova", icon = "Interface\\Icons\\Spell_Holy_HolyNova", description = "Clear 4x4 area around piece.", unlockLevel = 1, cooldown = 18, execute = function() WoWTetris:Ult_AreaClear(4) end},
        {name = "Penance", icon = "Interface\\Icons\\Spell_Holy_Penance", description = "Clear 3 random rows!", unlockLevel = 15, cooldown = 40, execute = function() WoWTetris:Ult_ClearRandomRows(3) end},
        {name = "Mass Dispel", icon = "Interface\\Icons\\Spell_Holy_DispelMagic", description = "Remove top 4 rows.", unlockLevel = 30, cooldown = 30, execute = function() WoWTetris:Ult_ClearTop(4) end},
        {name = "Divine Hymn", icon = "Interface\\Icons\\Spell_Holy_DivineHymn", description = "Fill ALL single-block gaps!", unlockLevel = 50, cooldown = 45, execute = function() WoWTetris:Ult_FillAllGaps() end},
        {name = "Salvation", icon = "Interface\\Icons\\Spell_Holy_Resurrection", description = "Clear every other row!", unlockLevel = 100, cooldown = 55, execute = function() WoWTetris:Ult_ClearAlternateRows() end},
    },
    DEATHKNIGHT = {
        {name = "Death Strike", icon = "Interface\\Icons\\Spell_Deathknight_Butcher2", description = "Clear 3x6 vertical area.", unlockLevel = 1, cooldown = 20, execute = function() WoWTetris:Ult_VerticalStrike(6) end},
        {name = "Plague Strike", icon = "Interface\\Icons\\Spell_Deathknight_Empowerruneblade2", description = "Destroy all of 1 random block type.", unlockLevel = 15, cooldown = 30, execute = function() WoWTetris:Ult_DestroyByType() end},
        {name = "Death and Decay", icon = "Interface\\Icons\\Spell_Shadow_DeathAndDecay", description = "Clear 1 row/sec for 5 seconds.", unlockLevel = 30, cooldown = 35, execute = function() WoWTetris:Ult_DeathAndDecay() end},
        {name = "Soul Reaper", icon = "Interface\\Icons\\Spell_Shadow_SoulLeech_2", description = "If >60% full, clear 3 rows!", unlockLevel = 50, cooldown = 45, execute = function() WoWTetris:Ult_SoulReaper() end},
        {name = "Army of Dead", icon = "Interface\\Icons\\Spell_Deathknight_Armyofthedead", description = "3 blocks/sec for 10 seconds!", unlockLevel = 100, cooldown = 50, execute = function() WoWTetris:Ult_ArmyOfDead() end},
    },
    SHAMAN = {
        {name = "Lightning Bolt", icon = "Interface\\Icons\\Spell_Nature_Lightning", description = "Clear current column.", unlockLevel = 1, cooldown = 18, execute = function() WoWTetris:Ult_ClearCurrentColumn() end},
        {name = "Chain Lightning", icon = "Interface\\Icons\\Spell_Nature_ChainLightning", description = "Clear 4 random columns!", unlockLevel = 15, cooldown = 40, execute = function() WoWTetris:Ult_ClearColumns(4) end},
        {name = "Earthquake", icon = "Interface\\Icons\\Spell_Nature_Earthquake", description = "All blocks fall to fill gaps!", unlockLevel = 30, cooldown = 25, execute = function() WoWTetris:Ult_Earthquake() end},
        {name = "Lava Burst", icon = "Interface\\Icons\\Spell_Fire_Fireball02", description = "Clear 3 most-filled rows!", unlockLevel = 50, cooldown = 35, execute = function() WoWTetris:Ult_ClearMostFilled(3) end},
        {name = "Ascendance", icon = "Interface\\Icons\\Spell_Fire_ElementalDevastation", description = "Clear 4 rows + 2 columns!", unlockLevel = 100, cooldown = 50, execute = function() WoWTetris:Ult_Ascendance() end},
    },
    MAGE = {
        {name = "Arcane Explosion", icon = "Interface\\Icons\\Spell_Nature_WispSplode", description = "Clear 4x4 area around piece.", unlockLevel = 1, cooldown = 18, execute = function() WoWTetris:Ult_AreaClear(4) end},
        {name = "Polymorph", icon = "Interface\\Icons\\Spell_Nature_Polymorph", description = "Transform piece to I-piece!", unlockLevel = 15, cooldown = 30, execute = function() WoWTetris:Ult_TransformToI() end},
        {name = "Frost Nova", icon = "Interface\\Icons\\Spell_Frost_FrostNova", description = "Shatter all blocks touching piece!", unlockLevel = 30, cooldown = 25, execute = function() WoWTetris:Ult_ShatterAdjacent() end},
        {name = "Combustion", icon = "Interface\\Icons\\Spell_Fire_SealOfFire", description = "Destroy 25 random blocks!", unlockLevel = 50, cooldown = 35, execute = function() WoWTetris:Ult_DestroyRandom(25) end},
        {name = "Meteor", icon = "Interface\\Icons\\Spell_Fire_Fireball", description = "MASSIVE 7x7 area clear!", unlockLevel = 100, cooldown = 50, execute = function() WoWTetris:Ult_AreaClear(7) end},
    },
    WARLOCK = {
        {name = "Shadow Bolt", icon = "Interface\\Icons\\Spell_Shadow_ShadowBolt", description = "Clear 3x3 area at piece.", unlockLevel = 1, cooldown = 15, execute = function() WoWTetris:Ult_AreaClear(3) end},
        {name = "Corruption", icon = "Interface\\Icons\\Spell_Shadow_AbominationExplosion", description = "Clear 1 row/sec for 5 sec.", unlockLevel = 15, cooldown = 35, execute = function() WoWTetris:Ult_CorruptRows(5) end},
        {name = "Rain of Fire", icon = "Interface\\Icons\\Spell_Shadow_RainOfFire", description = "Destroy 20 random blocks!", unlockLevel = 30, cooldown = 28, execute = function() WoWTetris:Ult_DestroyRandom(20) end},
        {name = "Infernal", icon = "Interface\\Icons\\Spell_Shadow_SummonInfernal", description = "Clear bottom 5 rows!", unlockLevel = 50, cooldown = 40, execute = function() WoWTetris:Ult_ClearBottom(5) end},
        {name = "Doom", icon = "Interface\\Icons\\Spell_Shadow_AuraOfDarkness", description = "After 3s, clear HALF the board!", unlockLevel = 100, cooldown = 60, execute = function() WoWTetris:Ult_Doom() end},
    },
    DRUID = {
        {name = "Swipe", icon = "Interface\\Icons\\Ability_Druid_Disembowel", description = "Clear 2 rows at piece height.", unlockLevel = 1, cooldown = 18, execute = function() WoWTetris:Ult_SwipeRows(2) end},
        {name = "Starfire", icon = "Interface\\Icons\\Spell_Arcane_StarFire", description = "Clear 3 columns around piece.", unlockLevel = 15, cooldown = 25, execute = function() WoWTetris:Ult_ClearAdjacentColumns() end},
        {name = "Wild Growth", icon = "Interface\\Icons\\Spell_Nature_ResistNature", description = "Complete all rows >70% filled!", unlockLevel = 30, cooldown = 40, execute = function() WoWTetris:Ult_WildGrowth() end},
        {name = "Starfall", icon = "Interface\\Icons\\Spell_Arcane_PortalDarnassus", description = "4 blocks/sec for 8 seconds!", unlockLevel = 50, cooldown = 45, execute = function() WoWTetris:Ult_Starfall() end},
        {name = "Incarnation", icon = "Interface\\Icons\\Ability_Druid_TreeofLife", description = "Clear ALL except bottom 2 rows!", unlockLevel = 100, cooldown = 55, execute = function() WoWTetris:Ult_Incarnation() end},
    },
    -- Premium classes (purchasable)
    MONK = {
        {name = "Tiger Palm", icon = "Interface\\Icons\\ability_monk_tigerpalm", description = "Clear 3x3 area at piece.", unlockLevel = 1, cooldown = 15, execute = function() WoWTetris:Ult_AreaClear(3) end},
        {name = "Spinning Crane Kick", icon = "Interface\\Icons\\ability_monk_cranekick_new", description = "Clear all blocks in 4-column radius.", unlockLevel = 15, cooldown = 30, execute = function() WoWTetris:Ult_ClearColumns(4) end},
        {name = "Fists of Fury", icon = "Interface\\Icons\\monk_ability_fistoffury", description = "Clear 5 random rows!", unlockLevel = 30, cooldown = 40, execute = function() WoWTetris:Ult_ClearRandomRows(5) end},
        {name = "Touch of Death", icon = "Interface\\Icons\\ability_monk_touchofdeath", description = "Instant kill: Clear most-filled row!", unlockLevel = 50, cooldown = 25, execute = function() WoWTetris:Ult_ClearMostFilled(1) end},
        {name = "Storm, Earth, Fire", icon = "Interface\\Icons\\ability_monk_stormearthandfire", description = "3 clones clear row, column, row!", unlockLevel = 100, cooldown = 55, execute = function() WoWTetris:Ult_StormEarthFire() end},
    },
    DEMONHUNTER = {
        {name = "Demon's Bite", icon = "Interface\\Icons\\ability_demonhunter_demonsbite", description = "Clear 2x4 area at piece.", unlockLevel = 1, cooldown = 15, execute = function() WoWTetris:Ult_RectClear(2, 4) end},
        {name = "Fel Rush", icon = "Interface\\Icons\\ability_demonhunter_felrush", description = "Clear entire row at piece height.", unlockLevel = 15, cooldown = 25, execute = function() WoWTetris:Ult_ClearCurrentRow() end},
        {name = "Eye Beam", icon = "Interface\\Icons\\ability_demonhunter_eyebeam", description = "Clear 3 columns in front of piece.", unlockLevel = 30, cooldown = 35, execute = function() WoWTetris:Ult_ClearColumns(3) end},
        {name = "Blade Dance", icon = "Interface\\Icons\\ability_demonhunter_bladedance", description = "Destroy 25 random blocks!", unlockLevel = 50, cooldown = 30, execute = function() WoWTetris:Ult_DestroyRandom(25) end},
        {name = "Metamorphosis", icon = "Interface\\Icons\\ability_demonhunter_metamorphasisdps", description = "Transform! 6x6 clear + speed boost!", unlockLevel = 100, cooldown = 60, execute = function() WoWTetris:Ult_Metamorphosis() end},
    },
    EVOKER = {
        {name = "Azure Strike", icon = "Interface\\Icons\\ability_evoker_azurestrike", description = "Clear current column.", unlockLevel = 1, cooldown = 18, execute = function() WoWTetris:Ult_ClearCurrentColumn() end},
        {name = "Disintegrate", icon = "Interface\\Icons\\ability_evoker_disintegrate", description = "Laser beam: Clear 2 columns!", unlockLevel = 15, cooldown = 28, execute = function() WoWTetris:Ult_ClearColumns(2) end},
        {name = "Pyre", icon = "Interface\\Icons\\ability_evoker_pyre", description = "Explosion: 5x5 area clear!", unlockLevel = 30, cooldown = 35, execute = function() WoWTetris:Ult_AreaClear(5) end},
        {name = "Eternity Surge", icon = "Interface\\Icons\\ability_evoker_eternitysurge", description = "Clear bottom 5 rows!", unlockLevel = 50, cooldown = 40, execute = function() WoWTetris:Ult_ClearBottom(5) end},
        {name = "Deep Breath", icon = "Interface\\Icons\\ability_evoker_deepbreath", description = "Fly across! Clear ALL of middle 6 rows!", unlockLevel = 100, cooldown = 55, execute = function() WoWTetris:Ult_DeepBreath() end},
    },
}

-- Race definitions - Each race grants 1 unique ability
-- Human/Night Elf/Orc/Undead = PvP Sabotage
-- All others = Solo Ultimate
addon.RACES = {
    -- Alliance - PvP Races
    HUMAN = {
        name = "Human", 
        icon = "Interface\\Icons\\Achievement_Character_Human_Male",
        faction = "Alliance",
        abilityType = "pvp",  -- PvP Sabotage
        ability = {
            name = "Diplomatic Pressure",
            icon = "Interface\\Icons\\Achievement_Reputation_01",
            description = "Opponent loses 10% of current score!",
            type = "sabotage"
        },
        classes = {"WARRIOR", "PALADIN", "HUNTER", "ROGUE", "PRIEST", "MAGE", "WARLOCK", "MONK", "DEATHKNIGHT"},
        cost = 0,
    },
    NIGHTELF = {
        name = "Night Elf",
        icon = "Interface\\Icons\\Achievement_Character_Nightelf_Male", 
        faction = "Alliance",
        abilityType = "pvp",  -- PvP Sabotage
        ability = {
            name = "Shadowmeld Ambush",
            icon = "Interface\\Icons\\Ability_Ambush",
            description = "Hide opponent's board for 5 seconds!",
            type = "sabotage"
        },
        classes = {"WARRIOR", "HUNTER", "ROGUE", "PRIEST", "DRUID", "MAGE", "MONK", "DEMONHUNTER", "DEATHKNIGHT"},
        cost = 1500,
    },
    -- Alliance - Solo Races
    DWARF = {
        name = "Dwarf",
        icon = "Interface\\Icons\\Achievement_Character_Dwarf_Male",
        faction = "Alliance",
        abilityType = "solo",  -- Solo Ultimate
        ability = {
            name = "Stoneform",
            icon = "Interface\\Icons\\Spell_Shadow_UnholyStrength",
            description = "Remove ALL garbage blocks from board!",
            type = "ultimate",
            cooldown = 60
        },
        classes = {"WARRIOR", "PALADIN", "HUNTER", "ROGUE", "PRIEST", "SHAMAN", "MAGE", "WARLOCK", "MONK", "DEATHKNIGHT"},
        cost = 1000,
    },
    GNOME = {
        name = "Gnome",
        icon = "Interface\\Icons\\Achievement_Character_Gnome_Male",
        faction = "Alliance", 
        abilityType = "solo",
        ability = {
            name = "Engineering Genius",
            icon = "Interface\\Icons\\Trade_Engineering",
            description = "Next 5 pieces become I-pieces!",
            type = "ultimate",
            cooldown = 55
        },
        classes = {"WARRIOR", "ROGUE", "PRIEST", "MAGE", "WARLOCK", "MONK", "DEATHKNIGHT"},
        cost = 2000,
    },
    DRAENEI = {
        name = "Draenei",
        icon = "Interface\\Icons\\Achievement_Character_Draenei_Male",
        faction = "Alliance",
        abilityType = "solo",
        ability = {
            name = "Gift of the Naaru",
            icon = "Interface\\Icons\\Spell_Holy_HolyProtection",
            description = "Heal board: Fill ALL gaps in bottom 6 rows!",
            type = "ultimate",
            cooldown = 50
        },
        classes = {"WARRIOR", "PALADIN", "HUNTER", "PRIEST", "SHAMAN", "MAGE", "MONK", "DEATHKNIGHT"},
        cost = 1500,
    },
    WORGEN = {
        name = "Worgen",
        icon = "Interface\\Icons\\Achievement_Worganhead",
        faction = "Alliance",
        abilityType = "solo",
        ability = {
            name = "Darkflight Frenzy",
            icon = "Interface\\Icons\\Ability_Racial_Darkflight",
            description = "FRENZY: +50% score for 20 seconds!",
            type = "ultimate",
            cooldown = 60
        },
        classes = {"WARRIOR", "HUNTER", "ROGUE", "PRIEST", "DRUID", "MAGE", "WARLOCK", "DEATHKNIGHT"},
        cost = 0,
    },
    -- Horde - PvP Races
    ORC = {
        name = "Orc",
        icon = "Interface\\Icons\\Achievement_Character_Orc_Male",
        faction = "Horde",
        abilityType = "pvp",  -- PvP Sabotage
        ability = {
            name = "Blood Fury Assault",
            icon = "Interface\\Icons\\Racial_Orc_BerserkerStrength",
            description = "Add 1 garbage row + force instant drop!",
            type = "sabotage"
        },
        classes = {"WARRIOR", "HUNTER", "ROGUE", "SHAMAN", "MAGE", "WARLOCK", "MONK", "DEATHKNIGHT", "EVOKER"},
        cost = 0,
    },
    UNDEAD = {
        name = "Undead",
        icon = "Interface\\Icons\\Achievement_Character_Undead_Male",
        faction = "Horde",
        abilityType = "pvp",  -- PvP Sabotage
        ability = {
            name = "Will of the Forsaken",
            icon = "Interface\\Icons\\Spell_Shadow_RaiseDead",
            description = "Disable opponent's ultimate for 15 seconds!",
            type = "sabotage"
        },
        classes = {"WARRIOR", "HUNTER", "ROGUE", "PRIEST", "MAGE", "WARLOCK", "MONK", "DEATHKNIGHT"},
        cost = 1500,
    },
    -- Horde - Solo Races
    TAUREN = {
        name = "Tauren",
        icon = "Interface\\Icons\\Achievement_Character_Tauren_Male",
        faction = "Horde",
        abilityType = "solo",
        ability = {
            name = "War Stomp",
            icon = "Interface\\Icons\\Ability_WarStomp",
            description = "EARTHQUAKE: Clear bottom 5 rows instantly!",
            type = "ultimate",
            cooldown = 55
        },
        classes = {"WARRIOR", "PALADIN", "HUNTER", "PRIEST", "SHAMAN", "DRUID", "MONK", "DEATHKNIGHT"},
        cost = 1500,
    },
    TROLL = {
        name = "Troll",
        icon = "Interface\\Icons\\Achievement_Character_Troll_Male",
        faction = "Horde",
        abilityType = "solo",
        ability = {
            name = "Berserking",
            icon = "Interface\\Icons\\Racial_Troll_Berserk",
            description = "BERSERK: Ultimate charges 3x faster for 30 sec!",
            type = "ultimate",
            cooldown = 60
        },
        classes = {"WARRIOR", "HUNTER", "ROGUE", "PRIEST", "SHAMAN", "MAGE", "WARLOCK", "DRUID", "MONK", "DEATHKNIGHT"},
        cost = 0,
    },
    BLOODELF = {
        name = "Blood Elf",
        icon = "Interface\\Icons\\Achievement_Character_Bloodelf_Male",
        faction = "Horde",
        abilityType = "solo",
        ability = {
            name = "Arcane Torrent",
            icon = "Interface\\Icons\\Spell_Shadow_MindTwisting",
            description = "Instantly FULLY charge your ultimate!",
            type = "ultimate",
            cooldown = 70
        },
        classes = {"WARRIOR", "PALADIN", "HUNTER", "ROGUE", "PRIEST", "MAGE", "WARLOCK", "MONK", "DEMONHUNTER", "DEATHKNIGHT"},
        cost = 2500,
    },
    GOBLIN = {
        name = "Goblin",
        icon = "Interface\\Icons\\Achievement_GoblinHead",
        faction = "Horde",
        abilityType = "solo",
        ability = {
            name = "Rocket Barrage",
            icon = "Interface\\Icons\\INV_Gizmo_RocketLauncher",
            description = "ROCKETS: Clear 3 random rows + 15 random blocks!",
            type = "ultimate",
            cooldown = 50
        },
        classes = {"WARRIOR", "HUNTER", "ROGUE", "PRIEST", "SHAMAN", "MAGE", "WARLOCK", "DEATHKNIGHT"},
        cost = 2000,
    },
    -- Neutral
    PANDAREN = {
        name = "Pandaren",
        icon = "Interface\\Icons\\Achievement_Character_Pandaren_Female",
        faction = "Neutral",
        abilityType = "solo",
        ability = {
            name = "Inner Peace",
            icon = "Interface\\Icons\\Pandarenracial_InnerPeace",
            description = "ZEN: Slow drops 75% + double score for 15 sec!",
            type = "ultimate",
            cooldown = 55
        },
        classes = {"WARRIOR", "HUNTER", "ROGUE", "PRIEST", "SHAMAN", "MAGE", "MONK"},
        cost = 2000,
    },
    DRACTHYR = {
        name = "Dracthyr",
        icon = "Interface\\Icons\\Ability_Evoker_DragonFlight",
        faction = "Neutral",
        abilityType = "solo",
        ability = {
            name = "Soar",
            icon = "Interface\\Icons\\Ability_Evoker_Soar",
            description = "FLIGHT: Skip next 3 bad pieces, get I-pieces!",
            type = "ultimate",
            cooldown = 45
        },
        classes = {"EVOKER"},  -- Evoker only!
        cost = 5000,
    },
}

addon.RACE_ORDER = {"HUMAN", "DWARF", "NIGHTELF", "GNOME", "DRAENEI", "WORGEN", "ORC", "UNDEAD", "TAUREN", "TROLL", "BLOODELF", "GOBLIN", "PANDAREN", "DRACTHYR"}

addon.ultimateEffects = {}
addon.ultimateCooldown = 0

function addon:ShowAffectedCells(cells)
    if addon.ShowBlockGlow then addon:ShowBlockGlow(cells) end
end

function addon:Ult_ClearBottom(count)
    local state = addon.gameState
    local affected = {}
    for y = addon.BOARD_HEIGHT - count + 1, addon.BOARD_HEIGHT do
        for x = 1, addon.BOARD_WIDTH do table.insert(affected, {y, x}) end
    end
    addon:ShowAffectedCells(affected)
    for i = 1, count do
        for y = addon.BOARD_HEIGHT, 2, -1 do state.board[y] = state.board[y - 1] end
        state.board[1] = {}
        for x = 1, addon.BOARD_WIDTH do state.board[1][x] = nil end
    end
    state.totalLines = state.totalLines + count
    state.score = state.score + (100 * count)
    addon:UpdateUI()
end

function addon:Ult_ClearTop(count)
    local state = addon.gameState
    local affected = {}
    for y = 1, count do
        for x = 1, addon.BOARD_WIDTH do
            table.insert(affected, {y, x})
            if state.board[y] then state.board[y][x] = nil end
        end
    end
    addon:ShowAffectedCells(affected)
    addon:ApplyGravity()
    addon:UpdateUI()
end

function addon:Ult_ClearRandomRows(count)
    local state = addon.gameState
    local rows = {}
    for i = 1, addon.BOARD_HEIGHT do table.insert(rows, i) end
    for i = #rows, 2, -1 do local j = math.random(1, i); rows[i], rows[j] = rows[j], rows[i] end
    local toClear, affected = {}, {}
    for i = 1, math.min(count, #rows) do
        toClear[rows[i]] = true
        for x = 1, addon.BOARD_WIDTH do table.insert(affected, {rows[i], x}) end
    end
    addon:ShowAffectedCells(affected)
    local newBoard, newY = {}, addon.BOARD_HEIGHT
    for y = addon.BOARD_HEIGHT, 1, -1 do
        if not toClear[y] then newBoard[newY] = state.board[y]; newY = newY - 1 end
    end
    while newY >= 1 do newBoard[newY] = {}; for x = 1, addon.BOARD_WIDTH do newBoard[newY][x] = nil end; newY = newY - 1 end
    state.board = newBoard
    state.totalLines = state.totalLines + count
    state.score = state.score + (100 * count)
    addon:UpdateUI()
end

function addon:Ult_DestroyRandom(count)
    local state = addon.gameState
    local filled = {}
    for y = 1, addon.BOARD_HEIGHT do
        for x = 1, addon.BOARD_WIDTH do
            if state.board[y] and state.board[y][x] then table.insert(filled, {y, x}) end
        end
    end
    for i = #filled, 2, -1 do local j = math.random(1, i); filled[i], filled[j] = filled[j], filled[i] end
    local affected = {}
    for i = 1, math.min(count, #filled) do
        local cell = filled[i]
        table.insert(affected, cell)
        state.board[cell[1]][cell[2]] = nil
    end
    addon:ShowAffectedCells(affected)
    addon:ApplyGravity()
    addon:UpdateUI()
end

function addon:Ult_ClearCurrentColumn()
    local state = addon.gameState
    if not state.currentPiece then return end
    local col = math.max(1, math.min(addon.BOARD_WIDTH, state.currentPiece.x + 2))
    local affected = {}
    for y = 1, addon.BOARD_HEIGHT do
        table.insert(affected, {y, col})
        if state.board[y] then state.board[y][col] = nil end
    end
    addon:ShowAffectedCells(affected)
    addon:ApplyGravity()
    addon:UpdateUI()
end

function addon:Ult_ClearCurrentRow()
    local state = addon.gameState
    if not state.currentPiece then return end
    local row = math.max(1, math.min(addon.BOARD_HEIGHT, state.currentPiece.y + 2))
    local affected = {}
    for x = 1, addon.BOARD_WIDTH do table.insert(affected, {row, x}) end
    for y = row, 2, -1 do state.board[y] = state.board[y - 1] end
    state.board[1] = {}
    for x = 1, addon.BOARD_WIDTH do state.board[1][x] = nil end
    addon:ShowAffectedCells(affected)
    state.totalLines = state.totalLines + 1
    state.score = state.score + 100
    addon:UpdateUI()
end

function addon:Ult_ClearColumns(count)
    local state = addon.gameState
    local cols = {}
    for i = 1, addon.BOARD_WIDTH do table.insert(cols, i) end
    for i = #cols, 2, -1 do local j = math.random(1, i); cols[i], cols[j] = cols[j], cols[i] end
    local affected = {}
    for i = 1, math.min(count, #cols) do
        local col = cols[i]
        for y = 1, addon.BOARD_HEIGHT do
            table.insert(affected, {y, col})
            if state.board[y] then state.board[y][col] = nil end
        end
    end
    addon:ShowAffectedCells(affected)
    addon:ApplyGravity()
    addon:UpdateUI()
end

function addon:Ult_AreaClear(size)
    local state = addon.gameState
    if not state.currentPiece then return end
    local cx, cy = state.currentPiece.x + 2, state.currentPiece.y + 2
    local radius = math.floor(size / 2)
    local affected = {}
    for y = cy - radius, cy + radius do
        for x = cx - radius, cx + radius do
            if y >= 1 and y <= addon.BOARD_HEIGHT and x >= 1 and x <= addon.BOARD_WIDTH then
                table.insert(affected, {y, x})
                if state.board[y] then state.board[y][x] = nil end
            end
        end
    end
    addon:ShowAffectedCells(affected)
    addon:ApplyGravity()
    addon:UpdateUI()
end

-- Apply gravity - make all floating blocks fall down
function addon:ApplyGravity()
    local state = addon.gameState
    for x = 1, addon.BOARD_WIDTH do
        local blocks = {}
        for y = addon.BOARD_HEIGHT, 1, -1 do
            if state.board[y] and state.board[y][x] then table.insert(blocks, state.board[y][x]) end
        end
        for y = 1, addon.BOARD_HEIGHT do
            if not state.board[y] then state.board[y] = {} end
            state.board[y][x] = nil
        end
        for i, block in ipairs(blocks) do state.board[addon.BOARD_HEIGHT - i + 1][x] = block end
    end
    -- Check for completed lines after gravity (skip during validation testing)
    if addon.ClearLines and not addon.skipLineClear then
        addon:ClearLines()
    end
end

function addon:Ult_Earthquake()
    addon:ApplyGravity()
    addon:UpdateUI()
end

function addon:Ult_ClearCross()
    local state = addon.gameState
    if not state.currentPiece then return end
    local cx, cy = state.currentPiece.x + 2, state.currentPiece.y + 2
    local affected = {}
    if cy >= 1 and cy <= addon.BOARD_HEIGHT then
        for x = 1, addon.BOARD_WIDTH do table.insert(affected, {cy, x}) end
    end
    if cx >= 1 and cx <= addon.BOARD_WIDTH then
        for y = 1, addon.BOARD_HEIGHT do
            table.insert(affected, {y, cx})
            if state.board[y] then state.board[y][cx] = nil end
        end
    end
    if cy >= 1 and cy <= addon.BOARD_HEIGHT then
        for y = cy, 2, -1 do state.board[y] = state.board[y - 1] end
        state.board[1] = {}
        for x = 1, addon.BOARD_WIDTH do state.board[1][x] = nil end
    end
    addon:ShowAffectedCells(affected)
    state.totalLines = state.totalLines + 1
    addon:UpdateUI()
end

function addon:Ult_ClearMostFilled(count)
    local state = addon.gameState
    local rowFill = {}
    for y = 1, addon.BOARD_HEIGHT do
        local filled = 0
        for x = 1, addon.BOARD_WIDTH do
            if state.board[y] and state.board[y][x] then filled = filled + 1 end
        end
        table.insert(rowFill, {y = y, fill = filled})
    end
    table.sort(rowFill, function(a, b) return a.fill > b.fill end)
    local toClear, affected = {}, {}
    for i = 1, math.min(count, #rowFill) do
        if rowFill[i].fill > 0 then
            toClear[rowFill[i].y] = true
            for x = 1, addon.BOARD_WIDTH do table.insert(affected, {rowFill[i].y, x}) end
        end
    end
    addon:ShowAffectedCells(affected)
    local newBoard, newY, cleared = {}, addon.BOARD_HEIGHT, 0
    for y = addon.BOARD_HEIGHT, 1, -1 do
        if not toClear[y] then newBoard[newY] = state.board[y]; newY = newY - 1
        else cleared = cleared + 1 end
    end
    while newY >= 1 do newBoard[newY] = {}; for x = 1, addon.BOARD_WIDTH do newBoard[newY][x] = nil end; newY = newY - 1 end
    state.board = newBoard
    state.totalLines = state.totalLines + cleared
    state.score = state.score + (100 * cleared)
    addon:UpdateUI()
end

function addon:Ult_ClearIncompleteRows()
    local state = addon.gameState
    local toClear = {}
    local clearCount = 0
    local maxClear = 2  -- Nerfed: Only clear up to 2 incomplete rows (was 4)
    
    -- Find incomplete rows from bottom up
    for y = addon.BOARD_HEIGHT, 1, -1 do
        if clearCount >= maxClear then break end
        local filled, hasBlock = 0, false
        for x = 1, addon.BOARD_WIDTH do
            if state.board[y] and state.board[y][x] then filled = filled + 1; hasBlock = true end
        end
        if hasBlock and filled < addon.BOARD_WIDTH then 
            toClear[y] = true 
            clearCount = clearCount + 1
        end
    end
    
    local affected = {}
    for y, _ in pairs(toClear) do
        for x = 1, addon.BOARD_WIDTH do table.insert(affected, {y, x}) end
    end
    addon:ShowAffectedCells(affected)
    local newBoard, newY, cleared = {}, addon.BOARD_HEIGHT, 0
    for y = addon.BOARD_HEIGHT, 1, -1 do
        if not toClear[y] then newBoard[newY] = state.board[y]; newY = newY - 1
        else cleared = cleared + 1 end
    end
    while newY >= 1 do newBoard[newY] = {}; for x = 1, addon.BOARD_WIDTH do newBoard[newY][x] = nil end; newY = newY - 1 end
    state.board = newBoard
    state.totalLines = state.totalLines + cleared
    addon:UpdateUI()
end

function addon:Ult_ClearAlternateRows()
    local state = addon.gameState
    local toClear = {}
    for y = 2, addon.BOARD_HEIGHT, 2 do toClear[y] = true end
    local affected = {}
    for y, _ in pairs(toClear) do
        for x = 1, addon.BOARD_WIDTH do table.insert(affected, {y, x}) end
    end
    addon:ShowAffectedCells(affected)
    local newBoard, newY, cleared = {}, addon.BOARD_HEIGHT, 0
    for y = addon.BOARD_HEIGHT, 1, -1 do
        if not toClear[y] then newBoard[newY] = state.board[y]; newY = newY - 1
        else cleared = cleared + 1 end
    end
    while newY >= 1 do newBoard[newY] = {}; for x = 1, addon.BOARD_WIDTH do newBoard[newY][x] = nil end; newY = newY - 1 end
    state.board = newBoard
    state.totalLines = state.totalLines + cleared
    addon:UpdateUI()
end

function addon:Ult_FillGaps(rowCount)
    local state = addon.gameState
    local affected = {}
    for y = addon.BOARD_HEIGHT - rowCount + 1, addon.BOARD_HEIGHT do
        if y >= 1 then
            if not state.board[y] then state.board[y] = {} end
            for x = 1, addon.BOARD_WIDTH do
                if not state.board[y][x] then
                    state.board[y][x] = {type = "O", texture = addon:GetPieceTexture("O")}
                    table.insert(affected, {y, x})
                end
            end
        end
    end
    addon:ShowAffectedCells(affected)
    addon:UpdateUI()
    if addon.ClearLines and not addon.skipLineClear then addon:ClearLines() end
end

function addon:Ult_FillAllGaps()
    local state = addon.gameState
    local affected = {}
    for y = 1, addon.BOARD_HEIGHT do
        if not state.board[y] then state.board[y] = {} end
        for x = 1, addon.BOARD_WIDTH do
            if not state.board[y][x] then
                local neighbors = 0
                if x > 1 and state.board[y][x-1] then neighbors = neighbors + 1 end
                if x < addon.BOARD_WIDTH and state.board[y][x+1] then neighbors = neighbors + 1 end
                if y > 1 and state.board[y-1] and state.board[y-1][x] then neighbors = neighbors + 1 end
                if y < addon.BOARD_HEIGHT and state.board[y+1] and state.board[y+1][x] then neighbors = neighbors + 1 end
                if neighbors >= 2 then
                    state.board[y][x] = {type = "O", texture = addon:GetPieceTexture("O")}
                    table.insert(affected, {y, x})
                end
            end
        end
    end
    addon:ShowAffectedCells(affected)
    addon:UpdateUI()
    if addon.ClearLines and not addon.skipLineClear then addon:ClearLines() end
end

function addon:Ult_WildGrowth()
    local state = addon.gameState
    local affected = {}
    for y = 1, addon.BOARD_HEIGHT do
        if not state.board[y] then state.board[y] = {} end
        local filled = 0
        for x = 1, addon.BOARD_WIDTH do if state.board[y][x] then filled = filled + 1 end end
        if filled >= addon.BOARD_WIDTH * 0.7 then
            for x = 1, addon.BOARD_WIDTH do
                if not state.board[y][x] then
                    state.board[y][x] = {type = "O", texture = addon:GetPieceTexture("O")}
                    table.insert(affected, {y, x})
                end
            end
        end
    end
    addon:ShowAffectedCells(affected)
    addon:UpdateUI()
    if addon.ClearLines and not addon.skipLineClear then addon:ClearLines() end
end

function addon:Ult_TransformToI()
    local state = addon.gameState
    if state.currentPiece then state.currentPiece.type = "I"; state.currentPiece.rotation = 0 end
    addon:UpdateUI()
end

function addon:Ult_TransformPiece()
    addon:ShowPieceSelector()
end

function addon:ShowPieceSelector()
    if not addon.pieceSelectorFrame then
        local f = CreateFrame("Frame", "WoWTetrisPieceSelect", addon.mainFrame, "BackdropTemplate")
        f:SetSize(280, 80)
        f:SetPoint("CENTER", 0, 100)
        f:SetBackdrop({bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background-Dark", edgeFile = "Interface\\DialogFrame\\UI-DialogBox-Gold-Border", tile = true, tileSize = 32, edgeSize = 24, insets = {left=6, right=6, top=6, bottom=6}})
        f:SetFrameStrata("DIALOG")
        f:SetFrameLevel(200)
        local title = f:CreateFontString(nil, "OVERLAY", "GameFontNormal")
        title:SetPoint("TOP", 0, -10)
        title:SetText("|cff00ff00Choose your piece:|r")
        local pieces = {"I", "O", "T", "L", "J", "S", "Z"}
        f.buttons = {}
        for i, pType in ipairs(pieces) do
            local btn = CreateFrame("Button", nil, f)
            btn:SetSize(30, 30)
            btn:SetPoint("TOPLEFT", 15 + (i-1)*37, -30)
            local tex = btn:CreateTexture(nil, "ARTWORK")
            tex:SetAllPoints()
            tex:SetTexture(addon:GetPieceTexture(pType))
            tex:SetTexCoord(0.08, 0.92, 0.08, 0.92)
            local hl = btn:CreateTexture(nil, "HIGHLIGHT")
            hl:SetAllPoints()
            hl:SetColorTexture(1, 1, 1, 0.3)
            btn:SetScript("OnClick", function()
                if addon.gameState.currentPiece then
                    addon.gameState.currentPiece.type = pType
                    addon.gameState.currentPiece.rotation = 0
                end
                f:Hide()
                addon:UpdateUI()
            end)
            f.buttons[i] = btn
        end
        addon.pieceSelectorFrame = f
    end
    addon.pieceSelectorFrame:Show()
end

function addon:Ult_FreeSwap()
    local state = addon.gameState
    if not state.currentPiece then return end
    local current, held = state.currentPiece.type, state.heldPiece
    if held then state.currentPiece.type = held; state.currentPiece.rotation = 0 end
    state.heldPiece = current
    state.canHold = true
    addon:UpdateUI()
end

function addon:Ult_ChooseNextPieces(count)
    local state = addon.gameState
    -- Set the next pieces directly
    for i = 1, math.min(count, #state.nextPieces) do state.nextPieces[i] = "I" end
    -- Also set forced pieces for any additional pieces beyond the preview
    addon.forcedPieceCount = count
    addon.forcedPieceType = "I"
    addon:UpdateUI()
    print("|cff00ff00[Tetris]|r Next " .. count .. " pieces are I-pieces!")
end

function addon:Ult_VerticalStrike(height)
    local state = addon.gameState
    if not state.currentPiece then return end
    local cx, cy = state.currentPiece.x + 2, state.currentPiece.y + 2
    local affected = {}
    for y = cy - math.floor(height/2), cy + math.floor(height/2) do
        for x = cx - 1, cx + 1 do
            if y >= 1 and y <= addon.BOARD_HEIGHT and x >= 1 and x <= addon.BOARD_WIDTH then
                table.insert(affected, {y, x})
                if state.board[y] then state.board[y][x] = nil end
            end
        end
    end
    addon:ShowAffectedCells(affected)
    addon:ApplyGravity()
    addon:UpdateUI()
end

function addon:Ult_DestroyByType()
    local state = addon.gameState
    local types = {"I", "O", "T", "L", "J", "S", "Z"}
    local targetType = types[math.random(#types)]
    local affected = {}
    for y = 1, addon.BOARD_HEIGHT do
        for x = 1, addon.BOARD_WIDTH do
            if state.board[y] and state.board[y][x] and state.board[y][x].type == targetType then
                table.insert(affected, {y, x})
                state.board[y][x] = nil
            end
        end
    end
    addon:ShowAffectedCells(affected)
    print("|cff00ff00[Tetris]|r Destroyed all " .. targetType .. " blocks!")
    addon:ApplyGravity()
    addon:UpdateUI()
end

function addon:Ult_DeathAndDecay()
    for i = 1, 5 do
        C_Timer.After(i, function() if addon.gameState.isPlaying then addon:Ult_ClearBottom(1) end end)
    end
end

function addon:Ult_SoulReaper()
    local state = addon.gameState
    local total = addon.BOARD_WIDTH * addon.BOARD_HEIGHT
    local filled = 0
    for y = 1, addon.BOARD_HEIGHT do
        for x = 1, addon.BOARD_WIDTH do
            if state.board[y] and state.board[y][x] then filled = filled + 1 end
        end
    end
    -- Nerfed: Need 60% full, only clear 3 rows (was 5)
    if filled >= total * 0.6 then
        addon:Ult_ClearBottom(3)
        print("|cff00ff00[Tetris]|r SOUL REAPER EXECUTED!")
    else
        addon:Ult_ClearBottom(1)
        print("|cffff6600[Tetris]|r Board not full enough.")
    end
end

function addon:Ult_ArmyOfDead()
    for i = 1, 10 do
        C_Timer.After(i, function() if addon.gameState.isPlaying then addon:Ult_DestroyRandom(3) end end)
    end
    print("|cff00ff00[Tetris]|r Army rises for 10 seconds!")
end

function addon:Ult_Ascendance()
    addon:Ult_ClearBottom(4)
    C_Timer.After(0.3, function() addon:Ult_ClearColumns(2) end)
end

function addon:Ult_ShatterAdjacent()
    local state = addon.gameState
    if not state.currentPiece then return end
    local blocks = addon:GetPieceBlocks(state.currentPiece.type, state.currentPiece.rotation)
    local toDestroy = {}
    for _, block in ipairs(blocks) do
        local px, py = state.currentPiece.x + block[1] + 1, state.currentPiece.y + block[2] + 1
        for dy = -1, 1 do
            for dx = -1, 1 do
                if dy ~= 0 or dx ~= 0 then
                    local nx, ny = px + dx, py + dy
                    if ny >= 1 and ny <= addon.BOARD_HEIGHT and nx >= 1 and nx <= addon.BOARD_WIDTH then
                        if state.board[ny] and state.board[ny][nx] then toDestroy[ny .. "," .. nx] = {ny, nx} end
                    end
                end
            end
        end
    end
    local affected = {}
    for _, cell in pairs(toDestroy) do table.insert(affected, cell); state.board[cell[1]][cell[2]] = nil end
    addon:ShowAffectedCells(affected)
    addon:ApplyGravity()
    addon:UpdateUI()
end

function addon:Ult_CorruptRows(count)
    for i = 1, count do
        C_Timer.After(i, function() if addon.gameState.isPlaying then addon:Ult_ClearBottom(1) end end)
    end
    print("|cff00ff00[Tetris]|r Corruption spreading...")
end

function addon:Ult_Doom()
    print("|cffff0000[Tetris]|r DOOM in 3 seconds!")
    C_Timer.After(3, function()
        if addon.gameState.isPlaying then
            addon:Ult_DestroyRandom(math.floor(addon.BOARD_WIDTH * addon.BOARD_HEIGHT / 2))
            print("|cff00ff00[Tetris]|r DOOM executed!")
        end
    end)
end

function addon:Ult_SwipeRows(count)
    local state = addon.gameState
    if not state.currentPiece then return end
    local cy = state.currentPiece.y + 2
    local toClear = {}
    for i = 0, count - 1 do
        local y = cy + i
        if y >= 1 and y <= addon.BOARD_HEIGHT then toClear[y] = true end
    end
    local affected = {}
    for y, _ in pairs(toClear) do for x = 1, addon.BOARD_WIDTH do table.insert(affected, {y, x}) end end
    addon:ShowAffectedCells(affected)
    local newBoard, newY, cleared = {}, addon.BOARD_HEIGHT, 0
    for y = addon.BOARD_HEIGHT, 1, -1 do
        if not toClear[y] then newBoard[newY] = state.board[y]; newY = newY - 1
        else cleared = cleared + 1 end
    end
    while newY >= 1 do newBoard[newY] = {}; for x = 1, addon.BOARD_WIDTH do newBoard[newY][x] = nil end; newY = newY - 1 end
    state.board = newBoard
    state.totalLines = state.totalLines + cleared
    addon:UpdateUI()
end

function addon:Ult_ClearAdjacentColumns()
    local state = addon.gameState
    if not state.currentPiece then return end
    local cx = state.currentPiece.x + 2
    local cols = {cx - 1, cx, cx + 1}
    local affected = {}
    for _, col in ipairs(cols) do
        if col >= 1 and col <= addon.BOARD_WIDTH then
            for y = 1, addon.BOARD_HEIGHT do
                table.insert(affected, {y, col})
                if state.board[y] then state.board[y][col] = nil end
            end
        end
    end
    addon:ShowAffectedCells(affected)
    addon:ApplyGravity()
    addon:UpdateUI()
end

function addon:Ult_Starfall()
    for i = 1, 8 do
        C_Timer.After(i, function() if addon.gameState.isPlaying then addon:Ult_DestroyRandom(4) end end)
    end
    print("|cff00ff00[Tetris]|r Starfall for 8 seconds!")
end

function addon:Ult_Incarnation()
    local state = addon.gameState
    local affected = {}
    for y = 1, addon.BOARD_HEIGHT - 2 do
        for x = 1, addon.BOARD_WIDTH do
            if state.board[y] and state.board[y][x] then table.insert(affected, {y, x}) end
            if state.board[y] then state.board[y][x] = nil end
        end
    end
    addon:ShowAffectedCells(affected)
    addon:ApplyGravity()
    addon:UpdateUI()
end

function addon:Ult_WakeOfAshes()
    addon:Ult_ClearBottom(6)
    local state = addon.gameState
    if state.nextPieces and #state.nextPieces > 0 then state.nextPieces[1] = "I" end
    -- Also set forced piece for validation detection
    addon.forcedPieceCount = 1
    addon.forcedPieceType = "I"
    print("|cff00ff00[Tetris]|r Next piece is I-piece!")
    addon:UpdateUI()
end

function addon:Ult_PlaceBomb(size)
    addon.bombPending = size
    print("|cffff6600[Tetris]|r Bomb planted!")
end

function addon:CheckBomb()
    if addon.bombPending then
        local size = addon.bombPending
        addon.bombPending = nil
        C_Timer.After(0.1, function() addon:Ult_AreaClear(size); print("|cff00ff00[Tetris]|r BOOM!") end)
    end
end

function addon:UseUltimate()
    if not addon.selectedUltimate then print("|cffff0000[Tetris]|r No ultimate!"); return false end
    
    -- Validate ultimate belongs to selected class (check both base and shop ultimates)
    local available = addon:GetAvailableUltimates()
    local validUltimate = false
    for _, ult in ipairs(available) do
        if ult.name == addon.selectedUltimate.name then
            validUltimate = true
            -- Update execute function in case it's a shop ultimate
            if ult.execute then
                addon.selectedUltimate.execute = ult.execute
            end
            break
        end
    end
    if not validUltimate then
        print("|cffff0000[Tetris]|r Invalid ultimate for this class!")
        addon.selectedUltimate = nil
        -- Auto-select first available for current class
        for _, ult in ipairs(available) do
            if not ult.locked then
                addon.selectedUltimate = ult
                break
            end
        end
        return false
    end
    
    if addon.ultimateCooldown > 0 then 
        print("|cffff6600[Tetris]|r Ultimate on cooldown: " .. math.ceil(addon.ultimateCooldown) .. "s")
        return false 
    end
    if not addon:IsUltimateCharged() then
        local current, needed = addon:GetUltimateCharge()
        print("|cffff6600[Tetris]|r Ultimate not charged! " .. current .. "/" .. needed .. " points")
        return false
    end
    if not addon.gameState.isPlaying or addon.gameState.isPaused then return false end
    
    print("|cff00ff00[Tetris]|r " .. addon.selectedUltimate.name .. "!")
    
    -- Execute the ultimate
    if addon.selectedUltimate.execute then
        local success, err = pcall(addon.selectedUltimate.execute)
        if not success then print("|cffff0000[Tetris]|r Error: " .. tostring(err)) end
    elseif addon.selectedUltimate.isShopItem and addon.selectedUltimate.shopId then
        addon:ExecuteShopUltimate(addon.selectedUltimate.shopId)
    else
        print("|cffff0000[Tetris]|r Ultimate has no execute function!")
        return false
    end
    
    -- Start cooldown and reset charge
    addon.ultimateCooldown = addon.selectedUltimate.cooldown or 30
    addon.ultimateChargeUsed = addon.gameState.score  -- Mark score at which we used it
    
    addon:ShowUltimateFlash()
    addon:PlaySound("ultimate")
    addon:UpdateUI()
    
    -- Track ultimate use for quests
    if addon.TrackUltimateUse then addon:TrackUltimateUse() end
    
    -- Broadcast to opponent in PvP
    if addon.mpState and addon.mpState.inMatch then
        addon:SendUltimateCooldown()
    end
    
    return true
end

-- Get ultimate charge requirement based on unlock level
function addon:GetUltimateChargeRequired()
    if not addon.selectedUltimate then return 50 end
    local unlockLevel = addon.selectedUltimate.unlockLevel or 1
    -- Balanced charge based on unlock level:
    -- Level 1: 50, Level 15: 100, Level 30: 200, Level 50: 350, Level 100: 500
    if unlockLevel >= 100 then return 500
    elseif unlockLevel >= 50 then return 350
    elseif unlockLevel >= 30 then return 200
    elseif unlockLevel >= 15 then return 100
    else return 50 end
end

-- Get current charge progress
function addon:GetUltimateCharge()
    local baseScore = addon.ultimateChargeUsed or 0
    local currentScore = addon.gameState.score or 0
    local chargeNeeded = addon:GetUltimateChargeRequired()
    local chargeProgress = currentScore - baseScore
    
    -- Apply charge multiplier from timed effects
    local chargeMultiplier = 1
    if addon.HasTimedEffect and addon:HasTimedEffect("fastCharge") then
        chargeMultiplier = 2
    end
    if addon.HasTimedEffect and addon:HasTimedEffect("fastCharge3x") then
        chargeMultiplier = 3
    end
    chargeProgress = chargeProgress * chargeMultiplier
    
    -- Clamp to 0 minimum (in case of reset issues)
    chargeProgress = math.max(0, chargeProgress)
    return math.min(chargeProgress, chargeNeeded), chargeNeeded
end

-- Check if ultimate is fully charged
function addon:IsUltimateCharged()
    local current, needed = addon:GetUltimateCharge()
    return current >= needed
end

function addon:UpdateUltimateCooldown(elapsed)
    if addon.ultimateCooldown > 0 then
        addon.ultimateCooldown = addon.ultimateCooldown - elapsed
        if addon.ultimateCooldown <= 0 then 
            addon.ultimateCooldown = 0
            if addon:IsUltimateCharged() then
                addon:PlaySound("ultimateReady") 
            end
        end
    end
end

-- Send ultimate cooldown to opponent
function addon:GetAvailableUltimates()
    if not addon.selectedClass then return {} end
    local baseUlts = addon.ULTIMATES[addon.selectedClass] or {}
    local stats = addon:GetClassStats(addon.selectedClass)
    local available = {}
    
    -- Add base class ultimates (5 per class)
    for _, ult in ipairs(baseUlts) do
        local locked = not addon.testMode and stats.level < ult.unlockLevel
        local ultCopy = {}
        for k, v in pairs(ult) do ultCopy[k] = v end
        ultCopy.locked = locked
        ultCopy.isShopItem = false
        table.insert(available, ultCopy)
    end
    
    -- Add purchased shop ultimates for this class
    if addon.SHOP_ITEMS and addon.SHOP_ITEMS.ultimates then
        for _, shopUlt in ipairs(addon.SHOP_ITEMS.ultimates) do
            if shopUlt.forClass == addon.selectedClass then
                -- Check if purchased
                local owned = addon:OwnsItem(shopUlt.id, "ultimate")
                if owned or addon.testMode then
                    local ultCopy = {
                        name = shopUlt.name,
                        icon = shopUlt.icon,
                        description = shopUlt.description,
                        cooldown = 45,  -- Default shop ultimate cooldown
                        unlockLevel = 0,
                        locked = false,
                        isShopItem = true,
                        shopId = shopUlt.id,
                        execute = function() addon:ExecuteShopUltimate(shopUlt.id) end
                    }
                    table.insert(available, ultCopy)
                end
            end
        end
    end
    
    return available
end

-- Get available PvP sabotages (base + shop)
function addon:GetAvailableSabotages()
    if not addon.selectedClass then return {} end
    local baseSabs = addon.PVP_ABILITIES[addon.selectedClass] or {}
    local stats = addon:GetClassStats(addon.selectedClass)
    local available = {}
    
    -- Add base class sabotages (5 per class)
    for i, sab in ipairs(baseSabs) do
        local locked = not addon.testMode and stats.level < (sab.unlockLevel or 1)
        local sabCopy = {}
        for k, v in pairs(sab) do sabCopy[k] = v end
        sabCopy.locked = locked
        sabCopy.isShopItem = false
        sabCopy.index = i
        table.insert(available, sabCopy)
    end
    
    -- Add purchased shop sabotages for this class or ALL
    if addon.SHOP_ITEMS and addon.SHOP_ITEMS.sabotage then
        for _, shopSab in ipairs(addon.SHOP_ITEMS.sabotage) do
            if shopSab.forClass == addon.selectedClass or shopSab.forClass == "ALL" then
                -- Check if purchased
                local owned = addon:OwnsItem(shopSab.id, "sabotage")
                if owned or addon.testMode then
                    local sabCopy = {
                        name = shopSab.name,
                        icon = shopSab.icon,
                        description = shopSab.description,
                        unlockLevel = 0,
                        locked = false,
                        isShopItem = true,
                        shopId = shopSab.id,
                    }
                    table.insert(available, sabCopy)
                end
            end
        end
    end
    
    return available
end

-- Execute shop ultimate effect
function addon:ExecuteShopUltimate(shopId)
    -- Find the shop item
    for _, item in ipairs(addon.SHOP_ITEMS.ultimates or {}) do
        if item.id == shopId then
            print("|cffffd700[Tetris]|r Used shop ultimate: " .. item.name .. "!")
            
            -- WARRIOR shop ultimates
            if shopId == "ult_war_1" then addon:Ult_ClearRandomRows(4)  -- Colossus Smash
            elseif shopId == "ult_war_2" then addon:Ult_DestroyRandom(30)  -- Bladestorm+
            elseif shopId == "ult_war_3" then addon:Ult_ClearBottom(6)  -- Thunderous Roar
            elseif shopId == "ult_war_4" then addon:Ult_AreaClear(8)  -- Odyn's Fury
            
            -- PALADIN shop ultimates
            elseif shopId == "ult_pal_1" then addon:Ult_FillGaps(10)  -- Light of Dawn
            elseif shopId == "ult_pal_2" then addon:Ult_ClearBottom(4); addon:Ult_FillGaps(3)  -- Guardian
            elseif shopId == "ult_pal_3" then addon:Ult_ClearAlternateRows()  -- Final Reckoning
            elseif shopId == "ult_pal_4" then addon:Ult_SetForcedPieces(5, "I")  -- Blessing of Kings
            
            -- HUNTER shop ultimates
            elseif shopId == "ult_hun_1" then addon:Ult_ClearCurrentRow(); addon:Ult_ClearCurrentColumn()  -- Death Chakram
            elseif shopId == "ult_hun_2" then addon:Ult_ClearColumns(5)  -- Volley
            elseif shopId == "ult_hun_3" then addon:Ult_ClearMostFilled(4)  -- Stampede
            elseif shopId == "ult_hun_4" then addon:Ult_SetForcedPieces(8, "I")  -- Coordinated Assault
            
            -- ROGUE shop ultimates
            elseif shopId == "ult_rog_1" then addon:Ult_ClearCross()  -- Killing Spree
            elseif shopId == "ult_rog_2" then addon:Ult_DestroyRandom(35)  -- Kingsbane
            elseif shopId == "ult_rog_3" then addon:Ult_ClearRandomRows(4); addon:Ult_FreeSwap()  -- Flagellation
            elseif shopId == "ult_rog_4" then addon:Ult_SetForcedPieces(6, "I")  -- Deathmark
            
            -- PRIEST shop ultimates
            elseif shopId == "ult_pri_1" then addon:Ult_ClearTop(5)  -- Halo
            elseif shopId == "ult_pri_2" then addon:Ult_FillAllGaps()  -- Power Word: Barrier
            elseif shopId == "ult_pri_3" then addon:Ult_ClearRandomRows(5)  -- Shadowfiend
            elseif shopId == "ult_pri_4" then addon:Ult_SetTimedEffect("doubleScore", 20); addon:Ult_FillGaps(5)  -- Spirit Shell
            
            -- DEATHKNIGHT shop ultimates
            elseif shopId == "ult_dk_1" then addon:Ult_ClearBottom(4); addon:Ult_DestroyRandom(10)  -- Frostwyrm's Fury
            elseif shopId == "ult_dk_2" then addon:Ult_AreaClear(6); addon:Ult_ClearRandomRows(2)  -- Abomination Limb
            elseif shopId == "ult_dk_3" then addon:Ult_StartDoT(3, 8)  -- Unholy Blight (3 blocks/sec for 8 sec)
            elseif shopId == "ult_dk_4" then addon:Ult_ClearAllButBottom(3)  -- Summon Gargoyle
            
            -- SHAMAN shop ultimates
            elseif shopId == "ult_sha_1" then addon:Ult_ClearColumns(4); addon:Ult_ClearRandomRows(2)  -- Stormkeeper
            elseif shopId == "ult_sha_2" then addon:Ult_Earthquake()  -- Earth Elemental
            elseif shopId == "ult_sha_3" then addon:Ult_FillGaps(8)  -- Healing Tide
            elseif shopId == "ult_sha_4" then addon:Ult_ClearAlternateRows()  -- Primordial Wave
            
            -- MAGE shop ultimates
            elseif shopId == "ult_mag_1" then addon:Ult_SetTimedEffect("slowDrop", 15)  -- Icy Veins
            elseif shopId == "ult_mag_2" then addon:Ult_AreaClear(4); addon:Ult_DestroyRandom(10)  -- Combustion
            elseif shopId == "ult_mag_3" then addon:Ult_SetTimedEffect("tripleScore", 20)  -- Arcane Power
            elseif shopId == "ult_mag_4" then addon:Ult_TargetedAreaClear(6)  -- Meteor (targeted)
            
            -- WARLOCK shop ultimates
            elseif shopId == "ult_wlk_1" then addon:Ult_ClearBottom(3); addon:Ult_DestroyRandom(10)  -- Summon Infernal
            elseif shopId == "ult_wlk_2" then addon:Ult_SetTimedEffect("doubleScore", 12); addon:Ult_SetTimedEffect("fastCharge", 12)  -- Dark Soul
            elseif shopId == "ult_wlk_3" then addon:Ult_DestroyRandom(15); addon:Ult_ClearRandomRows(4)  -- Summon Doomguard
            elseif shopId == "ult_wlk_4" then addon:Ult_ClearAllButTop(4)  -- Ritual of Doom
            
            -- DRUID shop ultimates
            elseif shopId == "ult_dru_1" then addon:Ult_ClearRandomRows(3)  -- Incarnation
            elseif shopId == "ult_dru_2" then addon:Ult_ConvokeSpirits()  -- Convoke (8 random effects)
            elseif shopId == "ult_dru_3" then addon:Ult_ClearColumns(2); addon:Ult_ClearColumns(2)  -- Celestial Alignment
            elseif shopId == "ult_dru_4" then addon:Ult_FillGaps(8)  -- Heart of the Wild
            
            -- MONK shop ultimates
            elseif shopId == "ult_mon_1" then addon:Ult_StartDoT(3, 8)  -- Invoke Xuen (3 blocks/sec for 8 sec)
            elseif shopId == "ult_mon_2" then addon.ultimateCooldown = 0; addon.ultimateChargeUsed = addon.gameState.score - 9999  -- Thunder Focus Tea (instant charge)
            elseif shopId == "ult_mon_3" then addon:Ult_ClearSequentialRows(5)  -- Weapons of Order
            elseif shopId == "ult_mon_4" then addon:Ult_FillGaps(6); addon:Ult_ClearRandomRows(4)  -- Invoke Yu'lon
            
            -- DEMON HUNTER shop ultimates
            elseif shopId == "ult_dh_1" then addon:Ult_ClearRow(1); addon:Ult_ClearRow(20)  -- The Hunt
            elseif shopId == "ult_dh_2" then addon:Ult_ClearCenterColumns(3)  -- Fel Devastation
            elseif shopId == "ult_dh_3" then addon:Ult_SetTimedEffect("immune", 5)  -- Darkness (no blocks land)
            elseif shopId == "ult_dh_4" then addon:Ult_AreaClear(6); addon:Ult_SetTimedEffect("fastDrop", 15)  -- Demonic
            
            -- EVOKER shop ultimates
            elseif shopId == "ult_evo_1" then addon:Ult_ClearBottom(5)  -- Fire Breath
            elseif shopId == "ult_evo_2" then addon:Ult_FillGaps(10)  -- Dream Breath
            elseif shopId == "ult_evo_3" then addon:Ult_SetTimedEffect("fastCharge", 20)  -- Dragonrage
            elseif shopId == "ult_evo_4" then addon:Ult_SetTimedEffect("pause", 3); addon:Ult_FillAllGaps()  -- Emerald Communion
            
            else
                -- Default: clear 5 random rows
                print("|cffff0000[Tetris]|r Unknown shop ultimate: " .. shopId)
                addon:Ult_ClearRandomRows(5)
            end
            return
        end
    end
end

-- Set forced pieces (for Gnome, Paladin Blessing, etc.)
function addon:Ult_SetForcedPieces(count, pieceType)
    addon.forcedPieceCount = count
    addon.forcedPieceType = pieceType
    print("|cff00ff00[Tetris]|r Next " .. count .. " pieces will be " .. pieceType .. "-pieces!")
end

-- Set timed effect
function addon:Ult_SetTimedEffect(effectName, duration)
    addon.timedEffects = addon.timedEffects or {}
    addon.timedEffects[effectName] = GetTime() + duration
    print("|cff00ff00[Tetris]|r " .. effectName .. " active for " .. duration .. " seconds!")
end

-- Check if timed effect is active
function addon:HasTimedEffect(effectName)
    if not addon.timedEffects then return false end
    local endTime = addon.timedEffects[effectName]
    if endTime and GetTime() < endTime then
        return true
    end
    return false
end

-- Start damage over time effect (clear X blocks per second for Y seconds)
function addon:Ult_StartDoT(blocksPerSec, duration)
    local ticks = 0
    local maxTicks = duration
    local ticker
    ticker = C_Timer.NewTicker(1, function()
        ticks = ticks + 1
        addon:Ult_DestroyRandom(blocksPerSec)
        print("|cffffd700[DoT]|r Destroyed " .. blocksPerSec .. " blocks! (" .. ticks .. "/" .. maxTicks .. ")")
        if ticks >= maxTicks then
            ticker:Cancel()
        end
    end)
end

-- Clear rows sequentially with delay
function addon:Ult_ClearSequentialRows(count)
    for i = 1, count do
        C_Timer.After(i * 0.3, function()
            addon:Ult_ClearMostFilled(1)
        end)
    end
end

-- Clear center columns
function addon:Ult_ClearCenterColumns(count)
    local state = addon.gameState
    local centerCol = math.floor(state.cols / 2)
    local startCol = centerCol - math.floor(count / 2)
    for c = startCol, startCol + count - 1 do
        for r = 1, state.rows do
            state.board[r][c] = nil
        end
    end
    addon:ApplyGravity()
    addon:RenderBoard()
end

-- Clear all but top X rows
function addon:Ult_ClearAllButTop(keepRows)
    local state = addon.gameState
    for r = keepRows + 1, state.rows do
        for c = 1, state.cols do
            state.board[r][c] = nil
        end
    end
    addon:ApplyGravity()
    addon:RenderBoard()
end

-- Clear all but bottom X rows
function addon:Ult_ClearAllButBottom(keepRows)
    local state = addon.gameState
    for r = 1, state.rows - keepRows do
        for c = 1, state.cols do
            state.board[r][c] = nil
        end
    end
    addon:ApplyGravity()
    addon:RenderBoard()
end

-- Convoke Spirits - 8 random effects
function addon:Ult_ConvokeSpirits()
    local effects = {"clearRow", "clearCol", "fillGaps", "destroyRandom", "clearBottom", "clearTop"}
    for i = 1, 8 do
        C_Timer.After(i * 0.25, function()
            local effect = effects[math.random(#effects)]
            if effect == "clearRow" then addon:Ult_ClearRandomRows(1)
            elseif effect == "clearCol" then addon:Ult_ClearColumns(1)
            elseif effect == "fillGaps" then addon:Ult_FillGaps(2)
            elseif effect == "destroyRandom" then addon:Ult_DestroyRandom(5)
            elseif effect == "clearBottom" then addon:Ult_ClearBottom(1)
            elseif effect == "clearTop" then addon:Ult_ClearTop(1)
            end
        end)
    end
end

-- Targeted area clear (player chooses location) - simplified: clears around current piece
function addon:Ult_TargetedAreaClear(size)
    local state = addon.gameState
    local piece = state.currentPiece
    if piece then
        local centerX = piece.x + 1
        local centerY = piece.y + 1
        local halfSize = math.floor(size / 2)
        for r = centerY - halfSize, centerY + halfSize do
            for c = centerX - halfSize, centerX + halfSize do
                if r >= 1 and r <= state.rows and c >= 1 and c <= state.cols then
                    state.board[r][c] = nil
                end
            end
        end
        addon:ApplyGravity()
        addon:RenderBoard()
        print("|cffffd700[Tetris]|r METEOR strikes for " .. size .. "x" .. size .. " clear!")
    else
        -- Fallback: clear center area
        addon:Ult_AreaClear(size)
    end
end

function addon:InitializeClasses()
    -- Restore saved selections
    addon.selectedClass = addon.db.selectedClass or nil
    addon.selectedRace = addon.db.selectedRace or nil
    
    -- Restore ultimate if class is selected
    if addon.selectedClass and addon.db.selectedUltimateName then
        local ultimates = addon:GetAvailableUltimates()
        for _, ult in ipairs(ultimates) do
            if ult.name == addon.db.selectedUltimateName then
                addon.selectedUltimate = ult
                break
            end
        end
    else
        addon.selectedUltimate = nil
    end
    
    addon.ultimateCooldown = 0
    addon.ultimateChargeUsed = 0
    addon.ultimateEffects = {}
    addon.superchargedPieces = 0  -- For Avatar
    addon.superchargePattern = {} -- {row, column, row}
end

-- Stub for old effect system (no longer used)
function addon:HasEffect(effectName)
    return false
end

function addon:AddTimedEffect(name, duration)
    -- No longer used
end

-- New Avatar ultimate - supercharge next 3 pieces
function addon:Ult_Avatar()
    addon.superchargedPieces = 3
    addon.superchargePattern = {"row", "column", "row"}
    print("|cffffd700[Tetris]|r AVATAR ACTIVATED! Next 3 pieces will clear: ROW → COLUMN → ROW!")
end

-- Process supercharged piece on landing
function addon:ProcessSuperchargedPiece()
    if addon.superchargedPieces <= 0 then return false end
    
    local patternIndex = 4 - addon.superchargedPieces
    local pattern = addon.superchargePattern[patternIndex]
    
    addon.superchargedPieces = addon.superchargedPieces - 1
    
    if pattern == "row" then
        -- Clear the row where the piece landed
        local state = addon.gameState
        local pieceY = state.currentPiece and state.currentPiece.y or 10
        addon:Ult_ClearRow(pieceY)
        print("|cffffd700[Avatar]|r ROW CLEARED! (" .. (3 - addon.superchargedPieces) .. "/3)")
    elseif pattern == "column" then
        -- Clear the column where the piece landed
        local state = addon.gameState
        local pieceX = state.currentPiece and state.currentPiece.x or 5
        addon:Ult_ClearColumn(pieceX)
        print("|cffffd700[Avatar]|r COLUMN CLEARED! (" .. (3 - addon.superchargedPieces) .. "/3)")
    end
    
    return true
end

-- Clear specific row
function addon:Ult_ClearRow(row)
    local state = addon.gameState
    if row < 1 or row > addon.BOARD_HEIGHT then return end
    
    for y = row, 2, -1 do
        state.board[y] = state.board[y - 1]
    end
    state.board[1] = {}
    for x = 1, addon.BOARD_WIDTH do state.board[1][x] = nil end
end

-- Clear specific column
function addon:Ult_ClearColumn(col)
    local state = addon.gameState
    if col < 1 or col > addon.BOARD_WIDTH then return end
    
    for y = 1, addon.BOARD_HEIGHT do
        state.board[y][col] = nil
    end
end

-- Monk: Storm, Earth, and Fire - same as Avatar pattern
function addon:Ult_StormEarthFire()
    addon.superchargedPieces = 3
    addon.superchargePattern = {"row", "column", "row"}
    print("|cff00ff96[Tetris]|r STORM, EARTH, AND FIRE! 3 clones incoming!")
end

-- DH: Metamorphosis - big clear + speed boost
function addon:Ult_Metamorphosis()
    addon:Ult_AreaClear(6)
    -- Add temporary speed slow (beneficial)
    addon.metamorphosisActive = true
    addon.metamorphosisDuration = 10
    print("|cffa330c9[Tetris]|r METAMORPHOSIS! 6x6 clear + 10 sec speed boost!")
end

-- Evoker: Deep Breath - clear middle rows
function addon:Ult_DeepBreath()
    local state = addon.gameState
    -- Clear rows 7-12 (middle 6 rows)
    local affected = {}
    for y = 7, 12 do
        for x = 1, addon.BOARD_WIDTH do
            table.insert(affected, {y, x})
        end
    end
    addon:ShowAffectedCells(affected)
    
    -- Actually clear by shifting
    for i = 1, 6 do
        for y = 12, 2, -1 do
            state.board[y] = state.board[y - 1]
        end
        state.board[1] = {}
        for x = 1, addon.BOARD_WIDTH do state.board[1][x] = nil end
    end
    print("|cff33937f[Tetris]|r DEEP BREATH! Middle 6 rows cleared!")
end

-- DH: Rectangular clear
function addon:Ult_RectClear(width, height)
    local state = addon.gameState
    local piece = state.currentPiece
    if not piece then return end
    
    local cx, cy = piece.x, piece.y
    local affected = {}
    
    for dy = 0, height - 1 do
        for dx = 0, width - 1 do
            local x = cx + dx - math.floor(width/2)
            local y = cy + dy - math.floor(height/2)
            if x >= 1 and x <= addon.BOARD_WIDTH and y >= 1 and y <= addon.BOARD_HEIGHT then
                table.insert(affected, {y, x})
                state.board[y][x] = nil
            end
        end
    end
    addon:ShowAffectedCells(affected)
end

-- Remove all garbage blocks (Dwarf racial: Stoneform)
function addon:Ult_RemoveGarbageBlocks()
    local state = addon.gameState
    local removed = 0
    
    for r = 1, state.rows do
        for c = 1, state.cols do
            if state.board[r][c] and state.board[r][c].isGarbage then
                state.board[r][c] = nil
                removed = removed + 1
            end
        end
    end
    
    addon:ApplyGravity()
    addon:RenderBoard()
    
    if removed > 0 then
        print("|cff00ff00[Tetris]|r Removed " .. removed .. " garbage blocks!")
    else
        print("|cff888888[Tetris]|r No garbage blocks to remove.")
    end
end

-- Clear a specific row
function addon:Ult_ClearRow(row)
    local state = addon.gameState
    if row < 1 or row > state.rows then return end
    
    for c = 1, state.cols do
        state.board[row][c] = nil
    end
    addon:ApplyGravity()
    addon:RenderBoard()
end

-- Clear columns adjacent to current piece (Druid: Starfire)
function addon:Ult_ClearAdjacentColumns()
    local state = addon.gameState
    local piece = state.currentPiece
    if not piece then 
        addon:Ult_ClearColumns(3)
        return 
    end
    
    local cx = piece.x + 2  -- Center column of piece
    for col = cx - 1, cx + 1 do
        if col >= 1 and col <= state.cols then
            for row = 1, state.rows do
                state.board[row][col] = nil
            end
        end
    end
    addon:ApplyGravity()
    addon:RenderBoard()
end
