-- ============================================================================
-- ARENA FRAME THEMES MODULE
-- ============================================================================
-- Isolated theme system for arena frames - allows users to switch between
-- different visual styles and layouts in real-time without affecting core code

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

-- ============================================================================
-- MODULE INITIALIZATION
-- ============================================================================

AC.ArenaFrameThemes = AC.ArenaFrameThemes or {}
local AFT = AC.ArenaFrameThemes

-- Theme registry
AFT.themes = {}
AFT.currentTheme = nil

-- ============================================================================
-- THEME DEFINITIONS
-- ============================================================================

-- Default "Arena Core" Theme
AFT.themes["Arena Core"] = {
    name = "Arena Core",
    description = "Default ArenaCore theme with classic styling",
    
    -- Frame dimensions
    frameWidth = 235,
    frameHeight = 68,
    
    -- Health bar settings
    healthBar = {
        texture = nil, -- Uses user's selected texture
        height = 18,
    },
    
    -- Power bar settings
    powerBar = {
        texture = nil, -- Uses user's selected texture
        height = 8,
    },
    
    -- Class icon settings
    classIcon = {
        size = 32,
        texCoord = {0.1, 0.9, 0.1, 0.9}, -- Standard crop
    },
    
    -- Spec icon settings
    specIcon = {
        size = 25,
        texCoord = {0.1, 0.9, 0.1, 0.9},
    },
    
    -- Trinket settings
    trinket = {
        size = 32,
        texCoord = {0.1, 0.9, 0.1, 0.9},
    },
    
    -- Racial settings
    racial = {
        size = 32,
        texCoord = {0.1, 0.9, 0.1, 0.9},
    },
    
    -- Name text settings (ArenaCore custom font)
    nameText = {
        font = "Interface\\AddOns\\ArenaCore\\Media\\Fonts\\arenacore.ttf",
        fontSize = 12,
        fontFlags = "OUTLINE",
        justifyH = "LEFT",
        justifyV = "MIDDLE",
        shadowOffset = {1, -1},
        shadowColor = {0, 0, 0, 1},
    },
    
    -- Health text settings (ArenaCore custom font)
    healthText = {
        font = "Interface\\AddOns\\ArenaCore\\Media\\Fonts\\arenacore.ttf",
        fontSize = 10,
        fontFlags = "OUTLINE",
        justifyH = "CENTER",
        justifyV = "MIDDLE",
        shadowOffset = {1, -1},
        shadowColor = {0, 0, 0, 1},
    },
    
    -- Background settings
    background = {
        enabled = false,
        texture = nil,
        color = {0, 0, 0, 0.8},
    },
    
    -- Border settings
    border = {
        enabled = false,
        texture = nil,
        color = {1, 1, 1, 1},
        size = 1,
    },
}

-- "The 1500 Special" Theme - Flat/Minimal Style
AFT.themes["The 1500 Special"] = {
    name = "The 1500 Special",
    description = "Clean, flat design inspired by high-rated arena gameplay",
    
    -- Frame dimensions (more compact)
    frameWidth = 200,
    frameHeight = 43,
    
    -- Health bar settings
    healthBar = {
        texture = "Interface\\AddOns\\ArenaCore\\Media\\Framethemes\\simple core\\statusbar",
        height = 25, -- Taller health bar for better visibility
    },
    
    -- Power bar settings
    powerBar = {
        texture = "Interface\\AddOns\\ArenaCore\\Media\\Framethemes\\simple core\\statusbar",
        height = 9,
    },
    
    -- Class icon settings (larger, more prominent)
    classIcon = {
        size = 43, -- Same as frame height for clean look
        texCoord = {0.07, 0.93, 0.07, 0.93}, -- Tighter crop for cleaner look
    },
    
    -- Spec icon settings
    specIcon = {
        size = 18,
        texCoord = {0.07, 0.93, 0.07, 0.93},
    },
    
    -- Trinket settings (preserve ArenaCore borders)
    trinket = {
        size = 32,
        texCoord = {0.1, 0.9, 0.1, 0.9}, -- Less aggressive cropping to preserve border compatibility
    },
    
    -- Racial settings (preserve ArenaCore borders)
    racial = {
        size = 32,
        texCoord = {0.1, 0.9, 0.1, 0.9}, -- Less aggressive cropping to preserve border compatibility
    },
    
    -- Name text settings (ArenaCore custom font)
    nameText = {
        font = "Interface\\AddOns\\ArenaCore\\Media\\Fonts\\arenacore.ttf",
        fontSize = 12,
        fontFlags = "OUTLINE",
        justifyH = "LEFT",
        justifyV = "BOTTOM",
        shadowOffset = {0, 0}, -- No shadow for cleaner look
        shadowColor = {0, 0, 0, 0},
    },
    
    -- Health text settings (ArenaCore custom font)
    healthText = {
        font = "Interface\\AddOns\\ArenaCore\\Media\\Fonts\\arenacore.ttf",
        fontSize = 11,
        fontFlags = "OUTLINE",
        justifyH = "CENTER",
        justifyV = "MIDDLE",
        shadowOffset = {0, 0}, -- No shadow
        shadowColor = {0, 0, 0, 0},
    },
    
    -- Background settings (dark background for contrast)
    background = {
        enabled = true,
        texture = "Interface\\Tooltips\\UI-Tooltip-Background",
        color = {0, 0, 0, 1}, -- Solid black background
        insets = {-2, 2, 2, -2}, -- Extend slightly beyond frame
    },
    
    -- Border settings
    border = {
        enabled = false,
        texture = nil,
        color = {1, 1, 1, 1},
        size = 1,
    },
    
    -- Special positioning for flat theme
    positioning = {
        mirrored = false,
        nameAboveHealthBar = true, -- Name goes above health bar
        compactLayout = true,
    },
}

-- ============================================================================
-- THEME APPLICATION FUNCTIONS
-- ============================================================================

function AFT:ApplyTheme(themeName, frameIndex)
    local theme = self.themes[themeName]
    if not theme then
        print("|cffFF0000ArenaCore Themes:|r Unknown theme: " .. tostring(themeName))
        return false
    end
    
    -- DEBUG DISABLED FOR PRODUCTION
    -- print("|cffFFFF00[Theme Debug]|r Checking frame systems...")
    
    -- Check ArenaCore Master Frame Manager (the correct way)
    local MFM = AC and AC.MasterFrameManager
    -- print("|cffFFFF00[Theme Debug]|r AC.MasterFrameManager exists: " .. tostring(MFM ~= nil))
    -- if MFM then
    --     print("|cffFFFF00[Theme Debug]|r MFM.frames exists: " .. tostring(MFM.frames ~= nil))
    --     if MFM.frames then
    --         for i = 1, 3 do
    --             print("|cffFFFF00[Theme Debug]|r MFM.frames[" .. i .. "] exists: " .. tostring(MFM.frames[i] ~= nil))
    --         end
    --     end
    -- end
    
    -- Check global MFM (legacy)
    local globalMFM = _G.MFM
    -- print("|cffFFFF00[Theme Debug]|r Global MFM exists: " .. tostring(globalMFM ~= nil))
    
    -- Check ArenaCore global frame system
    -- if _G.ArenaCore then
    --     print("|cffFFFF00[Theme Debug]|r ArenaCore.ArenaFrames exists: " .. tostring(_G.ArenaCore.ArenaFrames ~= nil))
    --     if _G.ArenaCore.ArenaFrames then
    --         for i = 1, 3 do
    --             print("|cffFFFF00[Theme Debug]|r ArenaCore.ArenaFrames[" .. i .. "] exists: " .. tostring(_G.ArenaCore.ArenaFrames[i] ~= nil))
    --         end
    --     end
    -- end
    
    -- Try multiple frame access methods (in correct order)
    local frames = nil
    if MFM and MFM.frames then
        frames = MFM.frames
        -- print("|cffFFFF00[Theme Debug]|r Using AC.MasterFrameManager.frames")
    elseif globalMFM and globalMFM.frames then
        frames = globalMFM.frames
        -- print("|cffFFFF00[Theme Debug]|r Using global MFM.frames")
    elseif _G.ArenaCore and _G.ArenaCore.ArenaFrames then
        frames = _G.ArenaCore.ArenaFrames
        -- print("|cffFFFF00[Theme Debug]|r Using ArenaCore.ArenaFrames")
    else
        print("|cffFF0000ArenaCore Themes:|r No frame system found! AC.MasterFrameManager.frames not available")
        return false
    end
    
    -- Get the frame to apply theme to
    local frame
    if frameIndex then
        -- Apply to specific frame
        frame = frames[frameIndex]
        if not frame then 
            print("|cffFF0000ArenaCore Themes:|r Frame " .. frameIndex .. " not found")
            return false 
        end
        self:ApplyThemeToFrame(theme, frame)
    else
        -- Apply to all frames
        local appliedCount = 0
        for i = 1, 3 do
            if frames[i] then
                self:ApplyThemeToFrame(theme, frames[i])
                appliedCount = appliedCount + 1
            end
        end
        
        if appliedCount == 0 then
            print("|cffFF0000ArenaCore Themes:|r No frames found to apply theme to")
            return false
        end
        
        -- print("|cffFFFF00[Theme Debug]|r Applied theme to " .. appliedCount .. " frames")
    end
    
    self.currentTheme = themeName
    -- DEBUG DISABLED FOR PRODUCTION
    -- print("|cff8B45FFArenaCore Themes:|r Applied theme: " .. themeName)
    return true
end

function AFT:ApplyThemeToFrame(theme, frame)
    if not theme or not frame then 
        -- print("|cffFF0000[Theme Debug]|r ApplyThemeToFrame: Invalid theme or frame")
        return 
    end
    
    -- print("|cffFFFF00[Theme Debug]|r Applying theme " .. theme.name .. " to frame " .. tostring(frame:GetName() or "unnamed"))
    
    -- Debug: Check what elements exist on the frame
    -- print("|cffFFFF00[Theme Debug]|r Frame elements:")
    -- print("  healthBar: " .. tostring(frame.healthBar ~= nil))
    -- print("  manaBar: " .. tostring(frame.manaBar ~= nil))
    -- print("  classIcon: " .. tostring(frame.classIcon ~= nil))
    -- print("  playerName: " .. tostring(frame.playerName ~= nil))
    -- print("  specIcon: " .. tostring(frame.specIcon ~= nil))
    -- print("  trinketIndicator: " .. tostring(frame.trinketIndicator ~= nil))
    -- print("  racialIndicator: " .. tostring(frame.racialIndicator ~= nil))
    
    -- Apply frame dimensions
    if theme.frameWidth and theme.frameHeight then
        frame:SetSize(theme.frameWidth, theme.frameHeight)
        -- print("|cffFFFF00[Theme Debug]|r Set frame size to " .. theme.frameWidth .. "x" .. theme.frameHeight)
        
        -- CRITICAL: Update database dimensions so UpdateFramePositions() uses theme dimensions
        -- This prevents the layout system from overriding theme frame sizes
        if AC.DB and AC.DB.profile and AC.DB.profile.arenaFrames then
            AC.DB.profile.arenaFrames.sizing = AC.DB.profile.arenaFrames.sizing or {}
            AC.DB.profile.arenaFrames.sizing.width = theme.frameWidth
            AC.DB.profile.arenaFrames.sizing.height = theme.frameHeight
            -- print("|cffFFFF00[Theme Debug]|r Updated database dimensions to match theme")
        end
    end
    
    -- Apply health bar styling (ArenaCore uses frame.healthBar)
    if frame.healthBar and theme.healthBar then
        if theme.healthBar.texture then
            frame.healthBar:SetStatusBarTexture(theme.healthBar.texture)
        end
        if theme.healthBar.height then
            frame.healthBar:SetHeight(theme.healthBar.height)
            -- Also update container if it exists
            if frame.healthBarContainer then
                frame.healthBarContainer:SetHeight(theme.healthBar.height + 17)
            end
        end
        
        -- CRITICAL FIX: Ensure health bar is visible when theme is applied
        frame.healthBar:SetAlpha(1.0)
        frame.healthBar:Show()
        
        -- CRITICAL FIX: Set initial values so bar is visible
        frame.healthBar:SetMinMaxValues(0, 100)
        frame.healthBar:SetValue(100)
        
        -- CRITICAL FIX: Apply class colors if enabled and unit exists
        local general = AC.DB and AC.DB.profile and AC.DB.profile.arenaFrames and AC.DB.profile.arenaFrames.general
        if general and general.useClassColors and frame.unit and UnitExists(frame.unit) then
            local _, classFile = UnitClass(frame.unit)
            if classFile and RAID_CLASS_COLORS[classFile] then
                local classColor = RAID_CLASS_COLORS[classFile]
                frame.healthBar:SetStatusBarColor(classColor.r, classColor.g, classColor.b)
            end
        elseif not (general and general.useClassColors) then
            -- Default green color if class colors disabled
            frame.healthBar:SetStatusBarColor(0, 1, 0)
        end
    end
    
    -- Apply power bar styling (ArenaCore uses frame.manaBar)
    if frame.manaBar and theme.powerBar then
        if theme.powerBar.texture then
            frame.manaBar:SetStatusBarTexture(theme.powerBar.texture)
        end
        if theme.powerBar.height then
            frame.manaBar:SetHeight(theme.powerBar.height)
            -- Also update container if it exists
            if frame.manaBarContainer then
                frame.manaBarContainer:SetHeight(theme.powerBar.height + 7)
            end
        end
        
        -- CRITICAL FIX: Ensure mana bar is visible when theme is applied
        frame.manaBar:SetAlpha(1.0)
        frame.manaBar:Show()
        
        -- CRITICAL FIX: Set initial values so bar is visible
        frame.manaBar:SetMinMaxValues(0, 100)
        frame.manaBar:SetValue(100)
    end
    
    -- Apply class icon styling (ArenaCore uses frame.classIcon)
    if frame.classIcon and theme.classIcon then
        if theme.classIcon.size then
            frame.classIcon:SetSize(theme.classIcon.size, theme.classIcon.size)
            
                    end
        if theme.classIcon.texCoord then
            local tc = theme.classIcon.texCoord
            -- The actual texture is frame.classIcon.classIcon or frame.classIcon.icon
            if frame.classIcon.classIcon then
                frame.classIcon.classIcon:SetTexCoord(tc[1], tc[2], tc[3], tc[4])
            elseif frame.classIcon.icon then
                frame.classIcon.icon:SetTexCoord(tc[1], tc[2], tc[3], tc[4])
            end
        end
    end
    
    -- Apply spec icon styling (ArenaCore uses frame.specIcon)
    if frame.specIcon and theme.specIcon then
        if theme.specIcon.size then
            frame.specIcon:SetSize(theme.specIcon.size, theme.specIcon.size)
        end
        if theme.specIcon.texCoord then
            local tc = theme.specIcon.texCoord
            if frame.specIcon.icon then
                frame.specIcon.icon:SetTexCoord(tc[1], tc[2], tc[3], tc[4])
            end
        end
        
        -- CRITICAL FIX: Update black border anchors after frame resize
        if frame.specIcon.styledBorder and frame.specIcon.icon then
            local border = frame.specIcon.styledBorder
            local icon = frame.specIcon.icon
            
            -- Reanchor all 4 border edges to icon instead of frame
            if border.top then
                border.top:ClearAllPoints()
                border.top:SetPoint("TOPLEFT", icon, "TOPLEFT", 0, 0)
                border.top:SetPoint("TOPRIGHT", icon, "TOPRIGHT", 0, 0)
            end
            if border.bottom then
                border.bottom:ClearAllPoints()
                border.bottom:SetPoint("BOTTOMLEFT", icon, "BOTTOMLEFT", 0, 0)
                border.bottom:SetPoint("BOTTOMRIGHT", icon, "BOTTOMRIGHT", 0, 0)
            end
            if border.left then
                border.left:ClearAllPoints()
                border.left:SetPoint("TOPLEFT", icon, "TOPLEFT", 0, 0)
                border.left:SetPoint("BOTTOMLEFT", icon, "BOTTOMLEFT", 0, 0)
            end
            if border.right then
                border.right:ClearAllPoints()
                border.right:SetPoint("TOPRIGHT", icon, "TOPRIGHT", 0, 0)
                border.right:SetPoint("BOTTOMRIGHT", icon, "BOTTOMRIGHT", 0, 0)
            end
        end
    end
    
    -- Apply trinket styling (ArenaCore uses frame.trinket or frame.trinketIndicator)
    local trinketFrame = frame.trinket or frame.trinketIndicator
    if trinketFrame and theme.trinket then
        if theme.trinket.size then
            trinketFrame:SetSize(theme.trinket.size, theme.trinket.size)
        end
        if theme.trinket.texCoord then
            local tc = theme.trinket.texCoord
            -- CRITICAL: Only apply texCoord to the icon, NOT the border
            if trinketFrame.icon then
                trinketFrame.icon:SetTexCoord(tc[1], tc[2], tc[3], tc[4])
            elseif trinketFrame.texture then
                trinketFrame.texture:SetTexCoord(tc[1], tc[2], tc[3], tc[4])
            end
        end
        
        -- CRITICAL: Ensure ArenaCore border is preserved and visible
        self:EnsureTrinketBorder(trinketFrame)
        
        -- CRITICAL FIX: Reanchor cooldown to icon after frame resize
        if trinketFrame.cooldown and trinketFrame.icon then
            trinketFrame.cooldown:ClearAllPoints()
            trinketFrame.cooldown:SetAllPoints(trinketFrame.icon)
        end
    end
    
    -- Apply racial styling (ArenaCore uses frame.racial or frame.racialIndicator)
    local racialFrame = frame.racial or frame.racialIndicator
    if racialFrame and theme.racial then
        if theme.racial.size then
            racialFrame:SetSize(theme.racial.size, theme.racial.size)
        end
        if theme.racial.texCoord then
            local tc = theme.racial.texCoord
            -- CRITICAL: Only apply texCoord to the icon, NOT the border
            if racialFrame.icon then
                racialFrame.icon:SetTexCoord(tc[1], tc[2], tc[3], tc[4])
            elseif racialFrame.texture then
                racialFrame.texture:SetTexCoord(tc[1], tc[2], tc[3], tc[4])
            end
        end
        
        -- CRITICAL: Ensure ArenaCore border is preserved and visible
        self:EnsureTrinketBorder(racialFrame) -- Same border system for racials
        
        -- CRITICAL FIX: Reanchor cooldown to icon after frame resize
        if racialFrame.cooldown and racialFrame.icon then
            racialFrame.cooldown:ClearAllPoints()
            racialFrame.cooldown:SetAllPoints(racialFrame.icon)
        end
    end
    
    -- Apply name text styling (ArenaCore uses frame.playerName)
    if frame.playerName and theme.nameText then
        self:ApplyTextStyling(frame.playerName, theme.nameText)
        
        -- CRITICAL: Ensure player name is always visible above all other elements
        self:EnsureTextVisibility(frame.playerName, "playerName")
    end
    
    -- Apply health text styling (ArenaCore uses frame.healthBar.text)
    if frame.healthBar and frame.healthBar.text and theme.healthText then
        self:ApplyTextStyling(frame.healthBar.text, theme.healthText)
        
        -- Ensure health text is visible above health bar
        self:EnsureTextVisibility(frame.healthBar.text, "healthText")
    end
    
    -- Apply background
    if theme.background and theme.background.enabled then
        self:ApplyBackground(frame, theme.background)
    else
        self:RemoveBackground(frame)
    end
    
    -- Apply special positioning for themes like "The 1500 Special"
    if theme.positioning then
        self:ApplySpecialPositioning(frame, theme.positioning)
    else
        -- CRITICAL FIX: When switching back to "Arena Core" theme, restore normal positioning
        -- This ensures name is anchored to frame (not health bar) and uses slider settings
        if frame.playerName then
            local general = AC.DB and AC.DB.profile and AC.DB.profile.arenaFrames and AC.DB.profile.arenaFrames.general
            if general then
                -- CRITICAL FIX: Use proper nil check - 0 is a valid value!
                local nameX = (general.playerNameX ~= nil) and general.playerNameX or 52
                local nameY = (general.playerNameY ~= nil) and general.playerNameY or 0
                frame.playerName:ClearAllPoints()
                frame.playerName:SetPoint("TOPLEFT", frame, "TOPLEFT", nameX, nameY)
            end
        end
    end
    
    -- Mark frame as themed
    frame._currentTheme = theme.name
    
    -- CRITICAL: Ensure DR visibility after theme application
    -- Theme overlays might interfere with DR edit mode functionality
    C_Timer.After(0.1, function()
        AFT:EnsureDRVisibility()
    end)
    
    -- Debug message disabled for production
    -- if AC.BLACKOUT_DEBUG then
    --     print("|cff00FFFF[Theme Debug]|r Applied " .. theme.name .. " theme to frame")
    -- end
end

function AFT:ApplyTextStyling(fontString, textSettings)
    if not fontString or not textSettings then return end
    
    -- CRITICAL: Ensure text appears above health bars by setting proper strata/level
    local parentFrame = fontString:GetParent()
    if parentFrame then
        -- Check if this is a player name (needs to be above health bars)
        local isPlayerName = (fontString == parentFrame.playerName)
        
        if isPlayerName then
            -- Create or get text overlay frame for proper layering
            if not parentFrame.nameTextOverlay then
                parentFrame.nameTextOverlay = CreateFrame("Frame", nil, parentFrame)
                parentFrame.nameTextOverlay:SetAllPoints(parentFrame)
                parentFrame.nameTextOverlay:SetFrameStrata("MEDIUM")
                parentFrame.nameTextOverlay:SetFrameLevel(200) -- Very high level to appear above health bars
            end
            
            -- Move the font string to the overlay frame
            fontString:SetParent(parentFrame.nameTextOverlay)
            -- print("|cffFFFF00[Theme Debug]|r Moved player name to high strata overlay")
        end
    end
    
    -- Apply font using ArenaCore's SafeSetFont if available
    if textSettings.font and textSettings.fontSize and textSettings.fontFlags then
        if AC.SafeSetFont then
            -- Use ArenaCore's safe font setting method
            AC.SafeSetFont(fontString, textSettings.font, textSettings.fontSize, textSettings.fontFlags)
            -- print("|cffFFFF00[Theme Debug]|r Applied ArenaCore font: " .. textSettings.font .. " (" .. textSettings.fontSize .. "px)")
        else
            -- Fallback to direct font setting
            fontString:SetFont(textSettings.font, textSettings.fontSize, textSettings.fontFlags)
            -- print("|cffFFFF00[Theme Debug]|r Applied font (fallback): " .. textSettings.font .. " (" .. textSettings.fontSize .. "px)")
        end
    end
    
    -- Apply justification
    if textSettings.justifyH then
        fontString:SetJustifyH(textSettings.justifyH)
    end
    if textSettings.justifyV then
        fontString:SetJustifyV(textSettings.justifyV)
    end
    
    -- Apply shadow
    if textSettings.shadowOffset and textSettings.shadowColor then
        local offset = textSettings.shadowOffset
        local color = textSettings.shadowColor
        fontString:SetShadowOffset(offset[1], offset[2])
        fontString:SetShadowColor(color[1], color[2], color[3], color[4])
    end
end

function AFT:EnsureTextVisibility(fontString, textType)
    if not fontString then return end
    
    local parentFrame = fontString:GetParent()
    if not parentFrame then return end
    
    -- Get the main arena frame (might be nested)
    local mainFrame = parentFrame
    while mainFrame and not mainFrame.playerName do
        mainFrame = mainFrame:GetParent()
        if not mainFrame or mainFrame == UIParent then break end
    end
    
    if not mainFrame then return end
    
    -- Create high-level overlay for text elements if it doesn't exist
    if not mainFrame._themeTextOverlay then
        mainFrame._themeTextOverlay = CreateFrame("Frame", nil, mainFrame)
        mainFrame._themeTextOverlay:SetAllPoints(mainFrame)
        mainFrame._themeTextOverlay:SetFrameStrata("MEDIUM")
        mainFrame._themeTextOverlay:SetFrameLevel(250) -- Very high level above all other elements
        -- print("|cffFFFF00[Theme Debug]|r Created high-level text overlay frame")
    end
    
    -- Move text to overlay if it's not already there
    if fontString:GetParent() ~= mainFrame._themeTextOverlay then
        fontString:SetParent(mainFrame._themeTextOverlay)
        -- print("|cffFFFF00[Theme Debug]|r Moved " .. textType .. " to high-level overlay for visibility")
    end
end

function AFT:EnsureTrinketBorder(iconFrame)
    if not iconFrame then return end
    
    -- Get the actual icon texture (not the frame)
    local icon = iconFrame.icon or iconFrame.texture
    if not icon then return end
    
    -- Check if ArenaCore border exists
    if iconFrame.border then
        -- Ensure border is visible and properly configured
        iconFrame.border:Show()
        iconFrame.border:SetTexture("Interface\\AddOns\\ArenaCore\\Media\\Classicons\\Overlays\\orangeoverlay.tga")
        iconFrame.border:SetTexCoord(0, 1, 0, 1) -- Full texture for rounded overlay
        
        -- CRITICAL FIX: Border should extend beyond icon for proper visibility
        iconFrame.border:ClearAllPoints()
        iconFrame.border:SetPoint("TOPLEFT", icon, "TOPLEFT", -2, 2)
        iconFrame.border:SetPoint("BOTTOMRIGHT", icon, "BOTTOMRIGHT", 2, -2)
        
        -- Ensure border is on OVERLAY layer (above the icon)
        iconFrame.border:SetDrawLayer("OVERLAY", 0)
        
        -- print("|cffFFFF00[Theme Debug]|r Restored ArenaCore border for trinket/racial icon")
    else
        -- Create border if it doesn't exist (shouldn't happen, but safety check)
        local border = iconFrame:CreateTexture(nil, "OVERLAY")
        border:SetPoint("TOPLEFT", icon, "TOPLEFT", -2, 2)
        border:SetPoint("BOTTOMRIGHT", icon, "BOTTOMRIGHT", 2, -2)
        border:SetTexture("Interface\\AddOns\\ArenaCore\\Media\\Classicons\\Overlays\\orangeoverlay.tga")
        border:SetTexCoord(0, 1, 0, 1)
        iconFrame.border = border
        
        -- print("|cffFFFF00[Theme Debug]|r Created missing ArenaCore border for trinket/racial icon")
    end
end

function AFT:EnsureDRVisibility()
    -- Ensure DR containers maintain proper strata and aren't affected by theme overlays
    local MFM = AC and AC.MasterFrameManager
    if not MFM or not MFM.frames then return end
    
    for i = 1, 3 do
        local frame = MFM.frames[i]
        if frame and frame.drContainer then
            -- Ensure DR container has proper strata for edit mode interaction
            frame.drContainer:SetFrameStrata("MEDIUM")
            frame.drContainer:SetFrameLevel(100) -- High enough to be interactive but below text overlays
            
            -- Ensure all DR icons within the container are visible and properly layered
            if frame.drIcons then
                for category, drIcon in pairs(frame.drIcons) do
                    if drIcon then
                        drIcon:SetFrameStrata("MEDIUM")
                        drIcon:SetFrameLevel(101) -- Slightly above container
                    end
                end
            end
            
            -- print("|cffFFFF00[DR Debug]|r Ensured DR visibility for frame " .. i)
        end
    end
end

function AFT:ApplyBackground(frame, bgSettings)
    if not frame or not bgSettings then return end
    
    -- Create or get background texture
    if not frame._themeBackground then
        frame._themeBackground = frame:CreateTexture(nil, "BACKGROUND", nil, 1)
    end
    
    local bg = frame._themeBackground
    
    -- Set texture
    if bgSettings.texture then
        bg:SetTexture(bgSettings.texture)
    end
    
    -- Set color
    if bgSettings.color then
        local c = bgSettings.color
        bg:SetVertexColor(c[1], c[2], c[3], c[4])
    end
    
    -- Set position
    if bgSettings.insets then
        local insets = bgSettings.insets
        bg:SetPoint("TOPLEFT", frame, "TOPLEFT", insets[1], insets[2])
        bg:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", insets[3], insets[4])
    else
        bg:SetAllPoints(frame)
    end
    
    bg:Show()
end

function AFT:RemoveBackground(frame)
    if frame and frame._themeBackground then
        frame._themeBackground:Hide()
    end
end

function AFT:ApplySpecialPositioning(frame, positioning)
    if not frame or not positioning then return end
    
    -- DEBUG: Track if this is being called during slider drag
    if AC and AC._sliderDragActive then
        print("|cffFF0000[SLIDER DEBUG]|r ApplySpecialPositioning called during DRAG MODE - this causes glitching!")
    end
    
    -- Handle "The 1500 Special" positioning
    if positioning.nameAboveHealthBar and frame.playerName and frame.healthBar then
        -- CRITICAL FIX: Read from THEME-SPECIFIC settings, not global settings
        -- This allows each theme to have its own independent slider values
        local currentTheme = self:GetCurrentTheme()
        local themeData = AC.DB and AC.DB.profile and AC.DB.profile.themeData and AC.DB.profile.themeData[currentTheme]
        local general = themeData and themeData.arenaFrames and themeData.arenaFrames.general
        
        -- Fallback to global settings if theme-specific settings don't exist yet
        if not general then
            general = AC.DB and AC.DB.profile and AC.DB.profile.arenaFrames and AC.DB.profile.arenaFrames.general
        end
        
        -- CRITICAL FIX: Use proper nil check - 0 is a valid value!
        local nameX = (general and general.playerNameX ~= nil) and general.playerNameX or 0
        local nameY = (general and general.playerNameY ~= nil) and general.playerNameY or 2
        
        frame.playerName:ClearAllPoints()
        -- Use user's X offset but position above health bar (Y relative to health bar top)
        frame.playerName:SetPoint("BOTTOMLEFT", frame.healthBar, "TOPLEFT", nameX, nameY)
        frame.playerName:SetPoint("BOTTOMRIGHT", frame.healthBar, "TOPRIGHT", nameX, nameY)
        frame.playerName:SetHeight(12)
    end
    
    -- Handle compact layout for "The 1500 Special"
    if positioning.compactLayout then
        -- Adjust class icon positioning for compact layout
        if frame.classIcon then
            -- CRITICAL: Respect user positioning offsets from database
            local pos = AC.DB and AC.DB.profile and AC.DB.profile.classIcons and AC.DB.profile.classIcons.positioning or {}
            local xOffset = -2 + (pos.horizontal or 0)  -- Base compact position + user offset
            local yOffset = 0 + (pos.vertical or 0)     -- User vertical offset
            
            frame.classIcon:ClearAllPoints()
            frame.classIcon:SetPoint("RIGHT", frame, "LEFT", xOffset, yOffset)
            -- DEBUG DISABLED FOR PRODUCTION
            -- print("|cffFFFF00[Theme Debug]|r Applied compact class icon positioning with user offsets")
        end
        
        -- Adjust health bar positioning for compact layout
        if frame.healthBar and frame.classIcon then
            frame.healthBar:ClearAllPoints()
            frame.healthBar:SetPoint("LEFT", frame.classIcon, "RIGHT", 2, 0)
            -- DEBUG DISABLED FOR PRODUCTION
            -- print("|cffFFFF00[Theme Debug]|r Applied compact health bar positioning")
        end
    end
end

-- ============================================================================
-- DATABASE INTEGRATION
-- ============================================================================

function AFT:InitializeDatabase()
    -- Ensure theme setting exists in database
    if not AC.DB or not AC.DB.profile then
        C_Timer.After(0.1, function() self:InitializeDatabase() end)
        return
    end
    
    -- Initialize theme setting
    if not AC.DB.profile.arenaFrameTheme then
        AC.DB.profile.arenaFrameTheme = "Arena Core" -- Default theme
    end
    
    -- Initialize theme-specific settings storage
    if not AC.DB.profile.themeSettings then
        AC.DB.profile.themeSettings = {}
    end
    
    -- Apply saved theme
    self:ApplyTheme(AC.DB.profile.arenaFrameTheme)
end

function AFT:SaveTheme(themeName)
    if AC.DB and AC.DB.profile then
        AC.DB.profile.arenaFrameTheme = themeName
    end
end

-- ============================================================================
-- COMPLETE THEME-SPECIFIC SETTINGS SYSTEM
-- ============================================================================
-- Every setting category is stored per-theme for complete isolation
-- Settings categories: arenaFrames, trinkets, racials, specIcons, diminishingReturns, castBars, textures, classPacks

-- Deep copy helper function
local function DeepCopy(original)
    if type(original) ~= 'table' then return original end
    local copy = {}
    for k, v in pairs(original) do
        copy[k] = DeepCopy(v)
    end
    return copy
end

-- Save ALL current settings to current theme
function AFT:SaveCurrentThemeSettings()
    local currentTheme = self:GetCurrentTheme()
    if not currentTheme or not AC.DB or not AC.DB.profile then return end
    
    -- Initialize theme settings storage
    if not AC.DB.profile.themeData then
        AC.DB.profile.themeData = {}
    end
    if not AC.DB.profile.themeData[currentTheme] then
        AC.DB.profile.themeData[currentTheme] = {}
    end
    
    -- Save ALL settings categories to this theme (deep copy to prevent reference issues)
    local themeData = AC.DB.profile.themeData[currentTheme]
    
    -- Arena Frames (positioning, general settings, etc.)
    if AC.DB.profile.arenaFrames then
        themeData.arenaFrames = DeepCopy(AC.DB.profile.arenaFrames)
    end
    
    -- Trinkets
    if AC.DB.profile.trinkets then
        themeData.trinkets = DeepCopy(AC.DB.profile.trinkets)
    end
    
    -- Racials
    if AC.DB.profile.racials then
        themeData.racials = DeepCopy(AC.DB.profile.racials)
    end
    
    -- Spec Icons
    if AC.DB.profile.specIcons then
        themeData.specIcons = DeepCopy(AC.DB.profile.specIcons)
    end
    
    -- Diminishing Returns
    if AC.DB.profile.diminishingReturns then
        themeData.diminishingReturns = DeepCopy(AC.DB.profile.diminishingReturns)
    end
    
    -- Cast Bars
    if AC.DB.profile.castBars then
        themeData.castBars = DeepCopy(AC.DB.profile.castBars)
    end
    
    -- Textures
    if AC.DB.profile.textures then
        themeData.textures = DeepCopy(AC.DB.profile.textures)
    end
    
    -- Class Packs
    if AC.DB.profile.classPacks then
        themeData.classPacks = DeepCopy(AC.DB.profile.classPacks)
    end
    
    -- Class Icons (CRITICAL FIX: Was missing, causing settings to bleed across themes)
    if AC.DB.profile.classIcons then
        themeData.classIcons = DeepCopy(AC.DB.profile.classIcons)
    end
    
    -- print("|cff00FF00[Theme Settings]|r Saved all settings to theme: " .. currentTheme)
end

-- Get hardcoded default settings for "The 1500 Special" theme
-- Generated: 2025-11-17 14:19:06
-- Paste this into GetThe1500SpecialDefaults() function
-- Generated: 2025-11-17 15:59:46
function AFT:GetThe1500SpecialDefaults()
    return {
  ["classPacks"] = {
    ["HUNTER"] = {
      [1] = {
        [1] = {
          [1] = {
            [1] = 19574,
            [2] = 1,
          },
          [2] = {
            [1] = 359844,
            [2] = 2,
          },
        },
        [2] = {
          [1] = {
            [1] = 186265,
            [2] = 1,
          },
          [2] = {
            [1] = 264735,
            [2] = 2,
          },
        },
        [3] = {
          [1] = {
            [1] = 3355,
            [2] = 1,
          },
          [2] = {
            [1] = 109248,
            [2] = 2,
          },
          [3] = {
            [1] = 213691,
            [2] = 3,
          },
        },
      },
      [2] = {
        [1] = {
          [1] = {
            [1] = 288613,
            [2] = 1,
          },
          [2] = {
            [1] = 257044,
            [2] = 2,
          },
        },
        [2] = {
          [1] = {
            [1] = 186265,
            [2] = 1,
          },
          [2] = {
            [1] = 264735,
            [2] = 2,
          },
        },
        [3] = {
          [1] = {
            [1] = 3355,
            [2] = 1,
          },
          [2] = {
            [1] = 109248,
            [2] = 2,
          },
          [3] = {
            [1] = 213691,
            [2] = 3,
          },
        },
      },
      [3] = {
        [1] = {
          [1] = {
            [1] = 360952,
            [2] = 1,
          },
          [2] = {
            [1] = 360966,
            [2] = 2,
          },
          [3] = {
            [1] = 203415,
            [2] = 3,
          },
        },
        [2] = {
          [1] = {
            [1] = 186265,
            [2] = 1,
          },
          [2] = {
            [1] = 264735,
            [2] = 2,
          },
        },
        [3] = {
          [1] = {
            [1] = 3355,
            [2] = 1,
          },
          [2] = {
            [1] = 19577,
            [2] = 2,
          },
          [3] = {
            [1] = 190925,
            [2] = 3,
          },
        },
      },
    },
    ["WARRIOR"] = {
      [1] = {
        [1] = {
          [1] = {
            [1] = 107574,
            [2] = 1,
          },
          [2] = {
            [1] = 167105,
            [2] = 2,
          },
          [3] = {
            [1] = 198817,
            [2] = 2,
          },
        },
        [2] = {
          [1] = {
            [1] = 118038,
            [2] = 1,
          },
          [2] = {
            [1] = 23920,
            [2] = 2,
          },
          [3] = {
            [1] = 97462,
            [2] = 3,
          },
        },
        [3] = {
          [1] = {
            [1] = 107570,
            [2] = 2,
          },
          [2] = {
            [1] = 5246,
            [2] = 2,
          },
        },
      },
      [2] = {
        [1] = {
          [1] = {
            [1] = 1719,
            [2] = 1,
          },
          [2] = {
            [1] = 107574,
            [2] = 2,
          },
          [3] = {
            [1] = 385059,
            [2] = 3,
          },
        },
        [2] = {
          [1] = {
            [1] = 23920,
            [2] = 2,
          },
          [2] = {
            [1] = 97462,
            [2] = 3,
          },
          [3] = {
            [1] = 184364,
            [2] = 2,
          },
        },
        [3] = {
          [1] = {
            [1] = 5246,
            [2] = 1,
          },
          [2] = {
            [1] = 107570,
            [2] = 2,
          },
          [3] = {
            [1] = 12323,
            [2] = 3,
          },
        },
      },
      [3] = {
        [1] = {
          [1] = {
            [1] = 107574,
            [2] = 1,
          },
          [2] = {
            [1] = 385952,
            [2] = 2,
          },
          [3] = {
            [1] = 376079,
            [2] = 3,
          },
        },
        [2] = {
          [1] = {
            [1] = 23920,
            [2] = 1,
          },
          [2] = {
            [1] = 12975,
            [2] = 2,
          },
          [3] = {
            [1] = 871,
            [2] = 3,
          },
        },
        [3] = {
          [1] = {
            [1] = 46968,
            [2] = 2,
          },
          [2] = {
            [1] = 107570,
            [2] = 2,
          },
        },
      },
    },
    ["ROGUE"] = {
      [1] = {
        [1] = {
          [1] = {
            [1] = 360194,
            [2] = 1,
          },
          [2] = {
            [1] = 385627,
            [2] = 2,
          },
          [3] = {
            [1] = 212182,
            [2] = 2,
          },
        },
        [2] = {
          [1] = {
            [1] = 31224,
            [2] = 1,
          },
          [2] = {
            [1] = 5277,
            [2] = 2,
          },
          [3] = {
            [1] = 1856,
            [2] = 3,
          },
        },
        [3] = {
          [1] = {
            [1] = 408,
            [2] = 1,
          },
          [2] = {
            [1] = 1833,
            [2] = 2,
          },
          [3] = {
            [1] = 6770,
            [2] = 3,
          },
        },
      },
      [2] = {
        [1] = {
          [1] = {
            [1] = 13750,
            [2] = 1,
          },
          [2] = {
            [1] = 51690,
            [2] = 3,
          },
          [3] = {
            [1] = 13877,
            [2] = 2,
          },
        },
        [2] = {
          [1] = {
            [1] = 31224,
            [2] = 1,
          },
          [2] = {
            [1] = 5277,
            [2] = 2,
          },
          [3] = {
            [1] = 1856,
            [2] = 3,
          },
        },
        [3] = {
          [1] = {
            [1] = 1776,
            [2] = 2,
          },
          [2] = {
            [1] = 408,
            [2] = 1,
          },
          [3] = {
            [1] = 1833,
            [2] = 3,
          },
        },
      },
      [3] = {
        [1] = {
          [1] = {
            [1] = 185313,
            [2] = 1,
          },
          [2] = {
            [1] = 212283,
            [2] = 2,
          },
          [3] = {
            [1] = 280719,
            [2] = 2,
          },
        },
        [2] = {
          [1] = {
            [1] = 31224,
            [2] = 1,
          },
          [2] = {
            [1] = 5277,
            [2] = 2,
          },
          [3] = {
            [1] = 1856,
            [2] = 3,
          },
        },
        [3] = {
          [1] = {
            [1] = 1833,
            [2] = 2,
          },
          [2] = {
            [1] = 408,
            [2] = 1,
          },
          [3] = {
            [1] = 6770,
            [2] = 3,
          },
        },
      },
    },
    ["MAGE"] = {
      [1] = {
        [1] = {
          [1] = {
            [1] = 365350,
            [2] = 1,
          },
          [2] = {
            [1] = 321507,
            [2] = 2,
          },
          [3] = {
            [1] = 376103,
            [2] = 3,
          },
        },
        [2] = {
          [1] = {
            [1] = 45438,
            [2] = 1,
          },
          [2] = {
            [1] = 235450,
            [2] = 2,
          },
          [3] = {
            [1] = 110959,
            [2] = 3,
          },
        },
        [3] = {
          [1] = {
            [1] = 118,
            [2] = 1,
          },
          [2] = {
            [1] = 31661,
            [2] = 2,
          },
          [3] = {
            [1] = 82691,
            [2] = 2,
          },
        },
      },
      [2] = {
        [1] = {
          [1] = {
            [1] = 190319,
            [2] = 1,
          },
          [2] = {
            [1] = 153561,
            [2] = 2,
          },
          [3] = {
            [1] = 257541,
            [2] = 3,
          },
        },
        [2] = {
          [1] = {
            [1] = 45438,
            [2] = 1,
          },
          [2] = {
            [1] = 235313,
            [2] = 2,
          },
          [3] = {
            [1] = 86949,
            [2] = 3,
          },
        },
        [3] = {
          [1] = {
            [1] = 118,
            [2] = 1,
          },
          [2] = {
            [1] = 82691,
            [2] = 2,
          },
          [3] = {
            [1] = 31661,
            [2] = 3,
          },
        },
      },
      [3] = {
        [1] = {
          [1] = {
            [1] = 12472,
            [2] = 1,
          },
          [2] = {
            [1] = 153595,
            [2] = 2,
          },
          [3] = {
            [1] = 205021,
            [2] = 3,
          },
        },
        [2] = {
          [1] = {
            [1] = 45438,
            [2] = 1,
          },
          [2] = {
            [1] = 11426,
            [2] = 2,
          },
          [3] = {
            [1] = 235219,
            [2] = 3,
          },
        },
        [3] = {
          [1] = {
            [1] = 118,
            [2] = 1,
          },
          [2] = {
            [1] = 82691,
            [2] = 2,
          },
          [3] = {
            [1] = 31661,
            [2] = 3,
          },
        },
      },
    },
    ["growthDirection"] = "Horizontal",
    ["offsetX"] = 61,
    ["spacing"] = 1,
    ["anchor"] = "TOPLEFT",
    ["DRUID"] = {
      [1] = {
        [1] = {
          [1] = {
            [1] = 102560,
            [2] = 1,
          },
          [2] = {
            [1] = 391528,
            [2] = 2,
          },
        },
        [2] = {
          [1] = {
            [1] = 22812,
            [2] = 1,
          },
          [2] = {
            [1] = 22842,
            [2] = 2,
          },
        },
        [3] = {
          [1] = {
            [1] = 33786,
            [2] = 1,
          },
          [2] = {
            [1] = 78675,
            [2] = 2,
          },
          [3] = {
            [1] = 102793,
            [2] = 3,
          },
        },
      },
      [2] = {
        [1] = {
          [1] = {
            [1] = 102543,
            [2] = 1,
          },
          [2] = {
            [1] = 391528,
            [2] = 3,
          },
          [3] = {
            [1] = 106951,
            [2] = 2,
          },
        },
        [2] = {
          [1] = {
            [1] = 61336,
            [2] = 1,
          },
          [2] = {
            [1] = 22812,
            [2] = 2,
          },
        },
        [3] = {
          [1] = {
            [1] = 22570,
            [2] = 1,
          },
          [2] = {
            [1] = 5211,
            [2] = 2,
          },
          [3] = {
            [1] = 33786,
            [2] = 1,
          },
        },
      },
      [3] = {
        [1] = {
          [1] = {
            [1] = 102558,
            [2] = 1,
          },
          [2] = {
            [1] = 391528,
            [2] = 2,
          },
          [3] = {
            [1] = 50334,
            [2] = 3,
          },
        },
        [2] = {
          [1] = {
            [1] = 61336,
            [2] = 1,
          },
          [2] = {
            [1] = 22812,
            [2] = 2,
          },
          [3] = {
            [1] = 22842,
            [2] = 3,
          },
        },
        [3] = {
          [1] = {
            [1] = 99,
            [2] = 1,
          },
          [2] = {
            [1] = 102793,
            [2] = 2,
          },
          [3] = {
            [1] = 106839,
            [2] = 3,
          },
        },
      },
    },
    ["MONK"] = {
      [1] = {
        [1] = {
          [1] = {
            [1] = 132578,
            [2] = 1,
          },
          [2] = {
            [1] = 387184,
            [2] = 2,
          },
          [3] = {
            [1] = 386276,
            [2] = 3,
          },
        },
        [2] = {
          [1] = {
            [1] = 115203,
            [2] = 1,
          },
          [2] = {
            [1] = 115176,
            [2] = 2,
          },
          [3] = {
            [1] = 122278,
            [2] = 3,
          },
        },
        [3] = {
          [1] = {
            [1] = 119381,
            [2] = 1,
          },
          [2] = {
            [1] = 115078,
            [2] = 2,
          },
          [3] = {
            [1] = 116844,
            [2] = 3,
          },
        },
      },
      [2] = {
        [1] = {
          [1] = {
            [1] = 115310,
            [2] = 1,
          },
          [2] = {
            [1] = 116680,
            [2] = 3,
          },
          [3] = {
            [1] = 116849,
            [2] = 2,
          },
        },
        [2] = {
          [1] = {
            [1] = 115203,
            [2] = 1,
          },
          [2] = {
            [1] = 122783,
            [2] = 2,
          },
          [3] = {
            [1] = 122278,
            [2] = 3,
          },
        },
        [3] = {
          [1] = {
            [1] = 119381,
            [2] = 2,
          },
          [2] = {
            [1] = 115078,
            [2] = 1,
          },
          [3] = {
            [1] = 116844,
            [2] = 3,
          },
        },
      },
      [3] = {
        [1] = {
          [1] = {
            [1] = 137639,
            [2] = 1,
          },
          [2] = {
            [1] = 123904,
            [2] = 2,
          },
          [3] = {
            [1] = 285272,
            [2] = 2,
          },
        },
        [2] = {
          [1] = {
            [1] = 122783,
            [2] = 1,
          },
          [2] = {
            [1] = 122278,
            [2] = 2,
          },
          [3] = {
            [1] = 115203,
            [2] = 2,
          },
        },
        [3] = {
          [1] = {
            [1] = 116844,
            [2] = 3,
          },
          [2] = {
            [1] = 115078,
            [2] = 1,
          },
          [3] = {
            [1] = 119381,
            [2] = 2,
          },
        },
      },
    },
    ["size"] = 25,
    ["DEATHKNIGHT"] = {
      [1] = {
        [1] = {
          [1] = {
            [1] = 47568,
            [2] = 2,
          },
          [2] = {
            [1] = 49028,
            [2] = 3,
          },
          [3] = {
            [1] = 383269,
            [2] = 2,
          },
        },
        [2] = {
          [1] = {
            [1] = 48792,
            [2] = 2,
          },
          [2] = {
            [1] = 48707,
            [2] = 1,
          },
          [3] = {
            [1] = 55233,
            [2] = 3,
          },
        },
        [3] = {
          [1] = {
            [1] = 221562,
            [2] = 1,
          },
          [2] = {
            [1] = 108199,
            [2] = 2,
          },
          [3] = {
            [1] = 49576,
            [2] = 3,
          },
        },
      },
      [2] = {
        [1] = {
          [1] = {
            [1] = 47568,
            [2] = 3,
          },
          [2] = {
            [1] = 51271,
            [2] = 2,
          },
          [3] = {
            [1] = 196770,
            [2] = 1,
          },
        },
        [2] = {
          [1] = {
            [1] = 48707,
            [2] = 1,
          },
          [2] = {
            [1] = 48792,
            [2] = 2,
          },
          [3] = {
            [1] = 51052,
            [2] = 3,
          },
        },
        [3] = {
          [1] = {
            [1] = 108194,
            [2] = 2,
          },
          [2] = {
            [1] = 207167,
            [2] = 1,
          },
          [3] = {
            [1] = 49576,
            [2] = 3,
          },
        },
      },
      [3] = {
        [1] = {
          [1] = {
            [1] = 207289,
            [2] = 1,
          },
          [2] = {
            [1] = 42650,
            [2] = 2,
          },
        },
        [2] = {
          [1] = {
            [1] = 48792,
            [2] = 2,
          },
          [2] = {
            [1] = 48707,
            [2] = 1,
          },
          [3] = {
            [1] = 51052,
            [2] = 3,
          },
        },
        [3] = {
          [1] = {
            [1] = 108194,
            [2] = 1,
          },
          [2] = {
            [1] = 49576,
            [2] = 2,
          },
        },
      },
    },
    ["PRIEST"] = {
      [1] = {
        [1] = {
          [1] = {
            [1] = 10060,
            [2] = 1,
          },
          [2] = {
            [1] = 421543,
            [2] = 2,
          },
        },
        [2] = {
          [1] = {
            [1] = 33206,
            [2] = 1,
          },
          [2] = {
            [1] = 62618,
            [2] = 2,
          },
        },
        [3] = {
          [1] = {
            [1] = 8122,
            [2] = 2,
          },
          [2] = {
            [1] = 605,
            [2] = 1,
          },
        },
      },
      [2] = {
        [1] = {
          [1] = {
            [1] = 200183,
            [2] = 1,
          },
          [2] = {
            [1] = 372616,
            [2] = 4,
          },
          [3] = {
            [1] = 64843,
            [2] = 2,
          },
        },
        [2] = {
          [1] = {
            [1] = 47788,
            [2] = 1,
          },
          [2] = {
            [1] = 64901,
            [2] = 3,
          },
        },
        [3] = {
          [1] = {
            [1] = 8122,
            [2] = 2,
          },
          [2] = {
            [1] = 88625,
            [2] = 1,
          },
          [3] = {
            [1] = 605,
            [2] = 2,
          },
        },
      },
      [3] = {
        [1] = {
          [1] = {
            [1] = 228260,
            [2] = 1,
          },
          [2] = {
            [1] = 10060,
            [2] = 2,
          },
          [3] = {
            [1] = 391109,
            [2] = 3,
          },
        },
        [2] = {
          [1] = {
            [1] = 47585,
            [2] = 1,
          },
          [2] = {
            [1] = 108968,
            [2] = 2,
          },
        },
        [3] = {
          [1] = {
            [1] = 15487,
            [2] = 2,
          },
          [2] = {
            [1] = 64044,
            [2] = 2,
          },
          [3] = {
            [1] = 8122,
            [2] = 1,
          },
        },
      },
    },
    ["PALADIN"] = {
      [1] = {
        [1] = {
          [1] = {
            [1] = 31884,
            [2] = 1,
          },
          [2] = {
            [1] = 414170,
            [2] = 2,
          },
          [3] = {
            [1] = 210294,
            [2] = 3,
          },
        },
        [2] = {
          [1] = {
            [1] = 642,
            [2] = 1,
          },
          [2] = {
            [1] = 1022,
            [2] = 2,
          },
          [3] = {
            [1] = 31821,
            [2] = 3,
          },
        },
        [3] = {
          [1] = {
            [1] = 853,
            [2] = 2,
          },
          [2] = {
            [1] = 20066,
            [2] = 1,
          },
          [3] = {
            [1] = 6940,
            [2] = 3,
          },
        },
      },
      [2] = {
        [1] = {
          [1] = {
            [1] = 31884,
            [2] = 1,
          },
        },
        [2] = {
          [1] = {
            [1] = 31850,
            [2] = 1,
          },
          [2] = {
            [1] = 86659,
            [2] = 2,
          },
          [3] = {
            [1] = 642,
            [2] = 1,
          },
        },
        [3] = {
          [1] = {
            [1] = 853,
            [2] = 2,
          },
          [2] = {
            [1] = 115750,
            [2] = 2,
          },
          [3] = {
            [1] = 1044,
            [2] = 1,
          },
        },
      },
      [3] = {
        [1] = {
          [1] = {
            [1] = 31884,
            [2] = 1,
          },
          [2] = {
            [1] = 231895,
            [2] = 2,
          },
          [3] = {
            [1] = 343721,
            [2] = 2,
          },
        },
        [2] = {
          [1] = {
            [1] = 642,
            [2] = 1,
          },
          [2] = {
            [1] = 184662,
            [2] = 2,
          },
          [3] = {
            [1] = 1022,
            [2] = 3,
          },
        },
        [3] = {
          [1] = {
            [1] = 115750,
            [2] = 2,
          },
          [2] = {
            [1] = 20066,
            [2] = 1,
          },
          [3] = {
            [1] = 853,
            [2] = 3,
          },
        },
      },
    },
    ["fontSize"] = 16,
    ["WARLOCK"] = {
      [1] = {
        [1] = {
          [1] = {
            [1] = 386997,
            [2] = 2,
          },
          [2] = {
            [1] = 205180,
            [2] = 1,
          },
          [3] = {
            [1] = 113860,
            [2] = 3,
          },
        },
        [2] = {
          [1] = {
            [1] = 104773,
            [2] = 1,
          },
          [2] = {
            [1] = 48020,
            [2] = 3,
          },
          [3] = {
            [1] = 108416,
            [2] = 2,
          },
        },
        [3] = {
          [1] = {
            [1] = 5782,
            [2] = 1,
          },
          [2] = {
            [1] = 6789,
            [2] = 2,
          },
          [3] = {
            [1] = 30283,
            [2] = 2,
          },
        },
      },
      [2] = {
        [1] = {
          [1] = {
            [1] = 265187,
            [2] = 1,
          },
          [2] = {
            [1] = 111898,
            [2] = 2,
          },
          [3] = {
            [1] = 267217,
            [2] = 3,
          },
        },
        [2] = {
          [1] = {
            [1] = 104773,
            [2] = 1,
          },
          [2] = {
            [1] = 48020,
            [2] = 3,
          },
          [3] = {
            [1] = 108416,
            [2] = 2,
          },
        },
        [3] = {
          [1] = {
            [1] = 5782,
            [2] = 1,
          },
          [2] = {
            [1] = 6789,
            [2] = 2,
          },
          [3] = {
            [1] = 89766,
            [2] = 2,
          },
        },
      },
      [3] = {
        [1] = {
          [1] = {
            [1] = 1122,
            [2] = 2,
          },
          [2] = {
            [1] = 80240,
            [2] = 3,
          },
          [3] = {
            [1] = 196670,
            [2] = 1,
          },
        },
        [2] = {
          [1] = {
            [1] = 104773,
            [2] = 1,
          },
          [2] = {
            [1] = 48020,
            [2] = 3,
          },
          [3] = {
            [1] = 108416,
            [2] = 2,
          },
        },
        [3] = {
          [1] = {
            [1] = 5782,
            [2] = 1,
          },
          [2] = {
            [1] = 6789,
            [2] = 2,
          },
          [3] = {
            [1] = 30283,
            [2] = 2,
          },
        },
      },
    },
    ["DEMONHUNTER"] = {
      [1] = {
        [1] = {
          [1] = {
            [1] = 191427,
            [2] = 1,
          },
          [2] = {
            [1] = 370965,
            [2] = 2,
          },
          [3] = {
            [1] = 258860,
            [2] = 3,
          },
        },
        [2] = {
          [1] = {
            [1] = 198589,
            [2] = 1,
          },
          [2] = {
            [1] = 196555,
            [2] = 2,
          },
          [3] = {
            [1] = 196718,
            [2] = 3,
          },
        },
        [3] = {
          [1] = {
            [1] = 217832,
            [2] = 1,
          },
          [2] = {
            [1] = 179057,
            [2] = 3,
          },
          [3] = {
            [1] = 207684,
            [2] = 2,
          },
        },
      },
      [2] = {
        [1] = {
          [1] = {
            [1] = 187827,
            [2] = 1,
          },
          [2] = {
            [1] = 207407,
            [2] = 2,
          },
        },
        [2] = {
          [1] = {
            [1] = 196718,
            [2] = 1,
          },
          [2] = {
            [1] = 204021,
            [2] = 2,
          },
        },
        [3] = {
          [1] = {
            [1] = 202137,
            [2] = 1,
          },
          [2] = {
            [1] = 217832,
            [2] = 3,
          },
          [3] = {
            [1] = 207684,
            [2] = 2,
          },
        },
      },
    },
    ["enabled"] = true,
    ["offsetY"] = 29,
    ["EVOKER"] = {
      [1] = {
        [1] = {
          [1] = {
            [1] = 375087,
            [2] = 1,
          },
          [2] = {
            [1] = 370553,
            [2] = 2,
          },
          [3] = {
            [1] = 357210,
            [2] = 3,
          },
        },
        [2] = {
          [1] = {
            [1] = 363916,
            [2] = 1,
          },
          [2] = {
            [1] = 374348,
            [2] = 2,
          },
          [3] = {
            [1] = 374227,
            [2] = 3,
          },
        },
        [3] = {
          [1] = {
            [1] = 360806,
            [2] = 1,
          },
          [2] = {
            [1] = 358385,
            [2] = 2,
          },
          [3] = {
            [1] = 372048,
            [2] = 3,
          },
        },
      },
      [2] = {
        [1] = {
          [1] = {
            [1] = 370960,
            [2] = 1,
          },
          [2] = {
            [1] = 359816,
            [2] = 2,
          },
          [3] = {
            [1] = 370537,
            [2] = 3,
          },
        },
        [2] = {
          [1] = {
            [1] = 363916,
            [2] = 1,
          },
          [2] = {
            [1] = 363534,
            [2] = 2,
          },
          [3] = {
            [1] = 357170,
            [2] = 3,
          },
        },
        [3] = {
          [1] = {
            [1] = 360806,
            [2] = 1,
          },
          [2] = {
            [1] = 370665,
            [2] = 2,
          },
          [3] = {
            [1] = 374968,
            [2] = 3,
          },
        },
      },
      [3] = {
        [1] = {
          [1] = {
            [1] = 403631,
            [2] = 1,
          },
          [2] = {
            [1] = 409311,
            [2] = 2,
          },
          [3] = {
            [1] = 370553,
            [2] = 3,
          },
        },
        [2] = {
          [1] = {
            [1] = 363916,
            [2] = 1,
          },
          [2] = {
            [1] = 374348,
            [2] = 2,
          },
          [3] = {
            [1] = 357170,
            [2] = 3,
          },
        },
        [3] = {
          [1] = {
            [1] = 360806,
            [2] = 1,
          },
          [2] = {
            [1] = 358385,
            [2] = 2,
          },
          [3] = {
            [1] = 395152,
            [2] = 3,
          },
        },
      },
    },
    ["SHAMAN"] = {
      [1] = {
        [1] = {
          [1] = {
            [1] = 191634,
            [2] = 2,
          },
          [2] = {
            [1] = 375982,
            [2] = 1,
          },
          [3] = {
            [1] = 114050,
            [2] = 2,
          },
        },
        [2] = {
          [1] = {
            [1] = 108271,
            [2] = 1,
          },
          [2] = {
            [1] = 108270,
            [2] = 2,
          },
          [3] = {
            [1] = 198103,
            [2] = 4,
          },
        },
        [3] = {
          [1] = {
            [1] = 192058,
            [2] = 2,
          },
          [2] = {
            [1] = 51514,
            [2] = 1,
          },
          [3] = {
            [1] = 204336,
            [2] = 2,
          },
        },
      },
      [2] = {
        [1] = {
          [1] = {
            [1] = 114051,
            [2] = 1,
          },
          [2] = {
            [1] = 51533,
            [2] = 2,
          },
          [3] = {
            [1] = 384352,
            [2] = 2,
          },
        },
        [2] = {
          [1] = {
            [1] = 108271,
            [2] = 1,
          },
          [2] = {
            [1] = 108270,
            [2] = 2,
          },
        },
        [3] = {
          [1] = {
            [1] = 51514,
            [2] = 1,
          },
          [2] = {
            [1] = 192058,
            [2] = 2,
          },
          [3] = {
            [1] = 204336,
            [2] = 2,
          },
        },
      },
      [3] = {
        [1] = {
          [1] = {
            [1] = 114052,
            [2] = 1,
          },
          [2] = {
            [1] = 108280,
            [2] = 2,
          },
        },
        [2] = {
          [1] = {
            [1] = 108271,
            [2] = 1,
          },
          [2] = {
            [1] = 108270,
            [2] = 2,
          },
          [3] = {
            [1] = 98008,
            [2] = 1,
          },
        },
        [3] = {
          [1] = {
            [1] = 204336,
            [2] = 1,
          },
          [2] = {
            [1] = 192058,
            [2] = 2,
          },
          [3] = {
            [1] = 51514,
            [2] = 1,
          },
        },
      },
    },
  },
  ["specIcons"] = {
    ["enabled"] = true,
    ["positioning"] = {
      ["vertical"] = -15,
      ["overrides"] = {
      },
      ["draggedBaseX"] = 47,
      ["sliderOffsetY"] = -12,
      ["horizontal"] = 94,
      ["sliderOffsetX"] = 47,
      ["draggedBaseY"] = -3,
    },
    ["sizing"] = {
      ["scale"] = 100,
    },
  },
  ["textures"] = {
    ["powerBarTexture"] = "Interface\\AddOns\\ArenaCore\\Media\\Frametextures\\texture12.tga",
    ["sizing"] = {
      ["resourceHeight"] = 13,
      ["healthWidth"] = 156,
      ["healthHeight"] = 27,
      ["resourceWidth"] = 156,
    },
    ["barPosition"] = {
      ["horizontal"] = 56,
      ["vertical"] = 15,
      ["spacing"] = 2,
    },
    ["castBarTexture"] = "Interface\\AddOns\\ArenaCore\\Media\\Frametextures\\texture21.tga",
    ["barSizing"] = {
      ["resourceHeight"] = 8,
      ["healthWidth"] = 128,
      ["healthHeight"] = 18,
      ["resourceWidth"] = 136,
    },
    ["positioning"] = {
      ["vertical"] = 1,
      ["spacing"] = 1,
      ["sliderOffsetY"] = 1,
      ["horizontal"] = 1,
      ["sliderOffsetX"] = 1,
    },
    ["useDifferentPowerBarTexture"] = true,
    ["healthBarTexture"] = "Interface\\AddOns\\ArenaCore\\Media\\Frametextures\\texture27.tga",
    ["useDifferentCastBarTexture"] = true,
  },
  ["diminishingReturns"] = {
    ["initialized"] = true,
    ["customSpellsList"] = {
    },
    ["sizing"] = {
      ["fontSize"] = 13,
      ["scale"] = 100,
      ["size"] = 33,
      ["borderSize"] = 0,
      ["stageFontSize"] = 11,
    },
    ["rows"] = {
      ["dynamicPositioning"] = true,
      ["mode"] = "Straight",
    },
    ["categories"] = {
      ["knockback"] = false,
      ["disarm"] = true,
      ["banish"] = true,
      ["fear"] = true,
      ["disorient"] = true,
      ["mc"] = true,
      ["stun"] = true,
      ["silence"] = true,
      ["incapacitate"] = true,
      ["root"] = true,
      ["cyclone"] = true,
    },
    ["classSpecEnabled"] = false,
    ["lastSelectedCategory"] = "knockback",
    ["positioning"] = {
      ["stageFontX"] = -2,
      ["timerFontX"] = 0,
      ["timerFontY"] = 1,
      ["growthDirection"] = "Left",
      ["draggedBaseX"] = -143,
      ["vertical"] = 0,
      ["sliderOffsetX"] = 23,
      ["stageFontY"] = 2,
      ["sliderOffsetY"] = -69,
      ["horizontal"] = -120,
      ["spacing"] = 3,
      ["draggedBaseY"] = 69,
    },
    ["colorCodedBorders"] = false,
    ["iconSettings"] = {
      ["knockback"] = "61391",
      ["stun"] = "1833",
      ["root"] = "122",
      ["disarm"] = "236077",
      ["disorient"] = "8122",
      ["silence"] = "15487",
      ["incapacitate"] = "118",
    },
    ["classSpecSelection"] = "",
    ["customSpells"] = {
    },
    ["enabled"] = true,
  },
  ["trinkets"] = {
    ["enabled"] = true,
    ["iconDesign"] = "alliance",
    ["positioning"] = {
      ["vertical"] = 0,
      ["overrides"] = {
      },
      ["draggedBaseX"] = 66,
      ["sliderOffsetX"] = 0,
      ["horizontal"] = 66,
      ["sliderOffsetY"] = -4,
      ["draggedBaseY"] = 4,
    },
    ["sizing"] = {
      ["scale"] = 185,
      ["fontSize"] = 9,
    },
  },
  ["racials"] = {
    ["enabled"] = true,
    ["positioning"] = {
      ["vertical"] = 0,
      ["overrides"] = {
      },
      ["draggedBaseX"] = 120,
      ["sliderOffsetY"] = 0,
      ["horizontal"] = 120,
      ["sliderOffsetX"] = 0,
      ["draggedBaseY"] = 0,
    },
    ["sizing"] = {
      ["scale"] = 129,
      ["fontSize"] = 10,
    },
  },
  ["arenaFrames"] = {
    ["general"] = {
      ["showArenaLabels"] = true,
      ["resourceTextScale"] = 83,
      ["usePercentage"] = true,
      ["arenaNumberScale"] = 119,
      ["healthTextScale"] = 100,
      ["arenaNumberX"] = 346,
      ["showNames"] = false,
      ["playerNameScale"] = 105,
      ["showArenaNumbers"] = false,
      ["useClassColors"] = true,
      ["spellTextScale"] = 113,
      ["arenaNumberY"] = -3,
      ["statusText"] = false,
      ["showArenaServerNames"] = false,
      ["playerNameY"] = 3,
      ["playerNameX"] = 131,
    },
    ["positioning"] = {
      ["draggedBaseY"] = 484,
      ["vertical"] = 681,
      ["sliderOffsetY"] = 0,
      ["spacing"] = 32,
      ["sliderOffsetX"] = 0,
      ["horizontal"] = 1309,
      ["draggedBaseX"] = 931,
      ["growthDirection"] = "Down",
    },
    ["testModeActive"] = true,
    ["sizing"] = {
      ["height"] = 43,
      ["scale"] = 106,
      ["width"] = 200,
    },
  },
  ["classIcons"] = {
    ["enabled"] = true,
    ["positioning"] = {
      ["vertical"] = 1,
      ["overrides"] = {
      },
      ["draggedBaseX"] = 139,
      ["sliderOffsetY"] = 2,
      ["horizontal"] = 203,
      ["sliderOffsetX"] = 64,
      ["draggedBaseY"] = -1,
    },
    ["theme"] = "coldclasses",
    ["sizing"] = {
      ["scale"] = 100,
      ["borderThickness"] = 100,
    },
  },
  ["castBars"] = {
    ["sizing"] = {
      ["height"] = 25,
      ["scale"] = 90,
      ["width"] = 200,
    },
    ["positioning"] = {
      ["vertical"] = -52,
      ["draggedBaseX"] = -155,
      ["sliderOffsetY"] = 0,
      ["horizontal"] = -155,
      ["sliderOffsetX"] = 0,
      ["draggedBaseY"] = -52,
    },
    ["spellSchoolColors"] = false,
    ["spellIcons"] = {
      ["enabled"] = true,
      ["positioning"] = {
        ["vertical"] = 0,
        ["horizontal"] = -1,
      },
      ["sizing"] = {
        ["scale"] = 106,
      },
    },
  },
}
end

-- Load ALL theme-specific settings when switching themes
function AFT:LoadThemeSettings(themeName)
    if not themeName or not AC.DB or not AC.DB.profile then return end
    
    -- Initialize theme settings storage
    if not AC.DB.profile.themeData then
        AC.DB.profile.themeData = {}
    end
    
    -- Get saved settings for this theme
    local themeData = AC.DB.profile.themeData[themeName]
    
    -- CRITICAL: For "The 1500 Special", use hardcoded defaults for first-time users
    if not themeData and themeName == "The 1500 Special" then
        themeData = self:GetThe1500SpecialDefaults()
        if themeData then
            -- Save the defaults to user's database
            AC.DB.profile.themeData[themeName] = DeepCopy(themeData)
        end
    end
    
    if themeData then
        -- Restore ALL settings categories from this theme (deep copy to prevent reference issues)
        
        if themeData.arenaFrames then
            AC.DB.profile.arenaFrames = DeepCopy(themeData.arenaFrames)
        end
        
        if themeData.trinkets then
            AC.DB.profile.trinkets = DeepCopy(themeData.trinkets)
        end
        
        if themeData.racials then
            AC.DB.profile.racials = DeepCopy(themeData.racials)
        end
        
        if themeData.specIcons then
            AC.DB.profile.specIcons = DeepCopy(themeData.specIcons)
        end
        
        if themeData.diminishingReturns then
            AC.DB.profile.diminishingReturns = DeepCopy(themeData.diminishingReturns)
        end
        
        if themeData.castBars then
            AC.DB.profile.castBars = DeepCopy(themeData.castBars)
        end
        
        if themeData.textures then
            AC.DB.profile.textures = DeepCopy(themeData.textures)
        end
        
        if themeData.classPacks then
            AC.DB.profile.classPacks = DeepCopy(themeData.classPacks)
        end
        
        -- Class Icons (CRITICAL FIX: Was missing, causing settings to bleed across themes)
        if themeData.classIcons then
            AC.DB.profile.classIcons = DeepCopy(themeData.classIcons)
        end
        
        -- print("|cff00FF00[Theme Settings]|r Loaded all settings from theme: " .. themeName)
    else
        -- First time using this theme - save current settings as defaults for this theme
        self:SaveCurrentThemeSettings()
        -- print("|cffFFAA00[Theme Settings]|r First time using theme '" .. themeName .. "' - saved current settings as defaults")
    end
end

function AFT:GetCurrentTheme()
    if AC.DB and AC.DB.profile and AC.DB.profile.arenaFrameTheme then
        return AC.DB.profile.arenaFrameTheme
    end
    return "Arena Core" -- Default
end

function AFT:GetAvailableThemes()
    local themeList = {}
    for themeName, _ in pairs(self.themes) do
        table.insert(themeList, themeName)
    end
    table.sort(themeList)
    return themeList
end

-- ============================================================================
-- PUBLIC API
-- ============================================================================

function AFT:SwitchTheme(themeName)
    if not self.themes[themeName] then
        print("|cffFF0000ArenaCore Themes:|r Theme not found: " .. tostring(themeName))
        return false
    end
    
    -- CRITICAL: Save current theme's ALL settings before switching
    self:SaveCurrentThemeSettings()
    
    -- Load new theme's ALL settings
    self:LoadThemeSettings(themeName)
    
    -- Apply theme visuals
    if self:ApplyTheme(themeName) then
        -- Save theme choice to database
        self:SaveTheme(themeName)
        
        -- CRITICAL: Refresh ALL layout systems with new theme-specific settings
        
        -- Arena Frames general settings (names, numbers, scales)
        if AC.ApplyGeneralSettings then
            AC:ApplyGeneralSettings()
        end
        
        -- CRITICAL FIX: Reparent health text to absorb frames if in test mode with absorbs enabled
        -- This ensures text stays visible above shields after theme switching
        if AC.testModeEnabled and AC.Absorbs and AC.Absorbs.ForceShowLines then
            C_Timer.After(0.05, function()
                AC.Absorbs:ForceShowLines()
            end)
        end
        
        -- CRITICAL: Reapply theme special positioning after general settings
        -- This ensures "The 1500 Special" name positioning isn't overridden
        local theme = self.themes[themeName]
        if theme and theme.positioning then
            local MFM = AC and AC.MasterFrameManager
            if MFM and MFM.frames then
                for i = 1, 3 do
                    if MFM.frames[i] then
                        self:ApplySpecialPositioning(MFM.frames[i], theme.positioning)
                    end
                end
            end
        end
        
        -- Frame positioning and spacing
        if AC.UpdateFramePositions then
            AC:UpdateFramePositions()
        end
        
        -- Trinkets & Racials & Spec Icons
        if AC.RefreshTrinketsOtherLayout then
            AC:RefreshTrinketsOtherLayout()
        end
        
        -- Diminishing Returns
        if AC.RefreshDRLayout and not AC._skipDRRepositionOnSave then
            AC:RefreshDRLayout()
        elseif AC.RefreshDRLayout and AC._skipDRRepositionOnSave then
            print("|cff00FF00[THEME SAVE]|r DR refresh SKIPPED - protection active")
        end
        
        -- Cast Bars
        if AC.RefreshCastBarsLayout then
            AC:RefreshCastBarsLayout()
        end
        
        -- Textures (health/mana bars)
        if AC.RefreshTexturesLayout then
            AC:RefreshTexturesLayout()
        end
        
        -- Class Packs (TriBadges)
        if AC.RefreshClassPacksLayout then
            AC:RefreshClassPacksLayout()
        end
        
        -- CRITICAL: Reapply theme dimensions after all layout updates
        C_Timer.After(0.1, function()
            local theme = self.themes[themeName]
            if theme and theme.frameWidth and theme.frameHeight then
                local MFM = AC and AC.MasterFrameManager
                if MFM and MFM.frames then
                    for i = 1, 3 do
                        if MFM.frames[i] then
                            MFM.frames[i]:SetSize(theme.frameWidth, theme.frameHeight)
                        end
                    end
                end
            end
            
            -- DEBUG DISABLED FOR PRODUCTION
            -- print("|cff8B45FFArenaCore Themes:|r Switched to '" .. themeName .. "' with all theme-specific settings")
        end)
        
        return true
    end
    
    return false
end

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

-- Initialize when addon loads
local function Initialize()
    AFT:InitializeDatabase()
    
    -- Hook into UpdateFramePositions to preserve theme dimensions
    local MFM = AC and AC.MasterFrameManager
    if MFM and MFM.UpdateFramePositions then
        local originalUpdateFramePositions = MFM.UpdateFramePositions
        MFM.UpdateFramePositions = function(self, ...)
            -- Call original function
            originalUpdateFramePositions(self, ...)
            
            -- Reapply theme dimensions if a theme is active
            local currentTheme = AFT:GetCurrentTheme()
            if currentTheme and currentTheme ~= "Arena Core" then
                local theme = AFT.themes[currentTheme]
                if theme and theme.frameWidth and theme.frameHeight then
                    C_Timer.After(0.05, function()
                        if MFM.frames then
                            for i = 1, 3 do
                                if MFM.frames[i] then
                                    MFM.frames[i]:SetSize(theme.frameWidth, theme.frameHeight)
                                end
                            end
                            -- DEBUG DISABLED FOR PRODUCTION
                            -- print("|cffFFFF00[Theme Debug]|r Preserved theme dimensions after UpdateFramePositions")
                        end
                    end)
                end
            end
        end
        -- DEBUG DISABLED FOR PRODUCTION
        -- print("|cff8B45FFArenaCore Themes:|r Hooked UpdateFramePositions to preserve theme dimensions")
    end
    
    -- CRITICAL FIX: Create missing RefreshDRLayout function for real-time DR positioning
    if not AC.RefreshDRLayout then
        AC.RefreshDRLayout = function()
            -- Update DR positions for all arena frames in real-time
            local MFM = AC and AC.MasterFrameManager
            if MFM and MFM.frames then
                for i = 1, 3 do
                    local frame = MFM.frames[i]
                    if frame and AC.UpdateDRPositions then
                        AC:UpdateDRPositions(frame)
                    end
                    
                    -- DR container positioning now handled exclusively by DR.lua UpdatePositions/UpdatePositionsWithOffset
                end
                print("|cffFFFF00[DR Debug]|r RefreshDRLayout: Updated DR positions for all frames")
            end
            
            -- ADDITIONAL FIX: Ensure DR containers maintain proper strata after theme changes
            AFT:EnsureDRVisibility()
        end
        -- DEBUG DISABLED FOR PRODUCTION
        -- print("|cff8B45FFArenaCore Themes:|r Created missing RefreshDRLayout function for real-time DR updates")
    end
    
    -- Wait for frame system to be ready
    local attempts = 0
    local function CheckFrameSystem()
        attempts = attempts + 1
        
        local MFM = AC and AC.MasterFrameManager
        if (MFM and MFM.frames) or (_G.ArenaCore and _G.ArenaCore.ArenaFrames) then
            -- DEBUG DISABLED FOR PRODUCTION
            -- print("|cff8B45FFArenaCore Themes:|r Frame system detected, themes ready!")
            -- Apply saved theme if any
            local savedTheme = AFT:GetCurrentTheme()
            if savedTheme then
                C_Timer.After(0.1, function()
                    -- CRITICAL: Load theme-specific settings first (database settings)
                    -- This ensures user's saved settings for this theme are loaded
                    AFT:LoadThemeSettings(savedTheme)
                    
                    -- Then apply visual theme settings
                    AFT:ApplyTheme(savedTheme)
                    
                    -- CRITICAL: Refresh textures after theme application
                    -- This ensures health/mana bar textures are applied when reloading in arena
                    C_Timer.After(0.2, function()
                        if AC.RefreshTexturesLayout then
                            AC:RefreshTexturesLayout()
                        end
                    end)
                end)
            end
        elseif attempts < 20 then -- Try for 10 seconds
            C_Timer.After(0.5, CheckFrameSystem)
        else
            print("|cffFF6B6B ArenaCore Themes:|r Warning: Frame system not detected after 10 seconds")
        end
    end
    
    CheckFrameSystem()
end

-- Hook into addon initialization
if AC and AC.DB then
    Initialize()
else
    local frame = CreateFrame("Frame")
    frame:RegisterEvent("ADDON_LOADED")
    frame:SetScript("OnEvent", function(self, event, addonName)
        if addonName == "ArenaCore" then
            C_Timer.After(1, Initialize) -- Give more time for systems to load
            self:UnregisterEvent("ADDON_LOADED")
        end
    end)
end

-- ============================================================================
-- THEME SETTINGS EXPORT/IMPORT
-- ============================================================================

-- Helper function to serialize table to Lua code
local function SerializeValue(val, indent)
    indent = indent or ""
    local t = type(val)
    
    if t == "string" then
        return string.format("%q", val)
    elseif t == "number" or t == "boolean" then
        return tostring(val)
    elseif t == "table" then
        local lines = {"{"}
        for k, v in pairs(val) do
            local key
            if type(k) == "string" then
                key = string.format("[%q]", k)
            else
                key = "[" .. k .. "]"
            end
            table.insert(lines, indent .. "  " .. key .. " = " .. SerializeValue(v, indent .. "  ") .. ",")
        end
        table.insert(lines, indent .. "}")
        return table.concat(lines, "\n")
    else
        return "nil"
    end
end

-- Create export popup window with copy/paste functionality
local function CreateExportWindow(title, content)
    -- Create main frame
    local frame = CreateFrame("Frame", "ACThemeExportFrame", UIParent, "BackdropTemplate")
    frame:SetSize(700, 500)
    frame:SetPoint("CENTER")
    frame:SetFrameStrata("DIALOG")
    frame:SetMovable(true)
    frame:EnableMouse(true)
    frame:SetClampedToScreen(true)
    
    -- Backdrop
    frame:SetBackdrop({
        bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background",
        edgeFile = "Interface\\DialogFrame\\UI-DialogBox-Border",
        tile = true,
        tileSize = 32,
        edgeSize = 32,
        insets = { left = 8, right = 8, top = 8, bottom = 8 }
    })
    frame:SetBackdropColor(0, 0, 0, 1)
    
    -- Title bar
    local titleBar = CreateFrame("Frame", nil, frame)
    titleBar:SetSize(700, 30)
    titleBar:SetPoint("TOP", 0, 12)
    titleBar:EnableMouse(true)
    titleBar:RegisterForDrag("LeftButton")
    titleBar:SetScript("OnDragStart", function() frame:StartMoving() end)
    titleBar:SetScript("OnDragStop", function() frame:StopMovingOrSizing() end)
    
    local titleText = titleBar:CreateFontString(nil, "OVERLAY")
    titleText:SetFont("Fonts\\FRIZQT__.TTF", 14, "OUTLINE")
    titleText:SetText(title)
    titleText:SetPoint("CENTER", titleBar, "CENTER", 0, 0)
    titleText:SetTextColor(1, 0.82, 0, 1)
    
    -- Close button
    local closeBtn = CreateFrame("Button", nil, frame, "UIPanelCloseButton")
    closeBtn:SetPoint("TOPRIGHT", frame, "TOPRIGHT", -5, -5)
    closeBtn:SetScript("OnClick", function() frame:Hide() end)
    
    -- Scroll frame for text
    local scrollFrame = CreateFrame("ScrollFrame", "ACThemeExportScrollFrame", frame, "UIPanelScrollFrameTemplate")
    scrollFrame:SetPoint("TOPLEFT", frame, "TOPLEFT", 20, -40)
    scrollFrame:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", -40, 50)
    
    -- Edit box for text content
    local editBox = CreateFrame("EditBox", nil, scrollFrame)
    editBox:SetMultiLine(true)
    editBox:SetAutoFocus(false)
    editBox:SetFontObject(ChatFontNormal)
    editBox:SetWidth(scrollFrame:GetWidth() - 20)
    editBox:SetText(content)
    editBox:SetCursorPosition(0)
    editBox:SetScript("OnEscapePressed", function() frame:Hide() end)
    
    scrollFrame:SetScrollChild(editBox)
    
    -- Select All button
    local selectAllBtn = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate")
    selectAllBtn:SetSize(100, 25)
    selectAllBtn:SetPoint("BOTTOMLEFT", frame, "BOTTOMLEFT", 20, 15)
    selectAllBtn:SetText("Select All")
    selectAllBtn:SetScript("OnClick", function()
        editBox:SetFocus()
        editBox:HighlightText()
    end)
    
    -- Copy instruction text
    local instructionText = frame:CreateFontString(nil, "OVERLAY")
    instructionText:SetFont("Fonts\\FRIZQT__.TTF", 11, "OUTLINE")
    instructionText:SetText("Press Ctrl+C to copy, then paste into GetThe1500SpecialDefaults() function")
    instructionText:SetPoint("BOTTOM", frame, "BOTTOM", 0, 20)
    instructionText:SetTextColor(0.8, 0.8, 0.8, 1)
    
    -- Auto-select all text when window opens
    C_Timer.After(0.1, function()
        editBox:SetFocus()
        editBox:HighlightText()
    end)
    
    frame:Show()
    return frame
end

-- Export current theme settings to popup window for baking into defaults
SLASH_ACTHEME_EXPORT1 = "/actheme_export"
SlashCmdList["ACTHEME_EXPORT"] = function()
    local currentTheme = AFT:GetCurrentTheme()
    if not currentTheme then
        print("|cffFF0000[Theme Export]|r No active theme")
        return
    end
    
    if currentTheme ~= "The 1500 Special" then
        print("|cffFF0000[Theme Export]|r Please switch to 'The 1500 Special' theme first!")
        print("|cffFFAA00[Theme Export]|r Use: /actheme The 1500 Special")
        return
    end
    
    -- Save current settings first
    AFT:SaveCurrentThemeSettings()
    
    -- Get the saved data
    local themeData = AC.DB.profile.themeData and AC.DB.profile.themeData[currentTheme]
    if not themeData then
        print("|cffFF0000[Theme Export]|r No saved data for this theme")
        return
    end
    
    -- Generate Lua code
    local luaCode = "-- Paste this into GetThe1500SpecialDefaults() function\n"
    luaCode = luaCode .. "-- Generated: " .. date("%Y-%m-%d %H:%M:%S") .. "\n"
    luaCode = luaCode .. "return " .. SerializeValue(themeData, "")
    
    -- Create popup window with the code
    CreateExportWindow("The 1500 Special - Theme Settings Export", luaCode)
    
    print("|cff00FF00[Theme Export]|r Export window opened! Select all (Ctrl+A) and copy (Ctrl+C)")
end

-- ============================================================================
-- DEBUG COMMANDS
-- ============================================================================

-- Slash command for testing themes
SLASH_ARENACORE_THEME1 = "/actheme"
SlashCmdList["ARENACORE_THEME"] = function(msg)
    local themeName = msg:trim()
    
    if themeName == "" then
        print("|cff00FFFF[ArenaCore Themes]|r Available themes:")
        for name, theme in pairs(AFT.themes) do
            local current = (name == AFT:GetCurrentTheme()) and " |cff00FF00(CURRENT)|r" or ""
            print("  - " .. name .. current)
        end
        print("|cff00FFFF[ArenaCore Themes]|r Usage: /actheme <theme name>")
        print("|cff00FFFF[ArenaCore Themes]|r Debug: /actheme debug")
        return
    end
    
    if themeName:lower() == "debug" then
        print("|cff00FFFF[ArenaCore Themes Debug]|r System Status:")
        print("  ArenaCore: " .. tostring(_G.ArenaCore ~= nil))
        local MFM = AC and AC.MasterFrameManager
        print("  AC.MasterFrameManager: " .. tostring(MFM ~= nil))
        print("  Global MFM: " .. tostring(_G.MFM ~= nil))
        print("  AFT: " .. tostring(AFT ~= nil))
        if MFM and MFM.frames then
            local frameCount = 0
            for i = 1, 3 do
                if MFM.frames[i] then frameCount = frameCount + 1 end
            end
            print("  MFM frames: " .. frameCount .. "/3")
        end
        if _G.ArenaCore and _G.ArenaCore.ArenaFrames then
            print("  AC frames: " .. tostring(#_G.ArenaCore.ArenaFrames or 0))
        end
        return
    end
    
    if AFT:SwitchTheme(themeName) then
        print("|cff00FF00[ArenaCore Themes]|r Switched to: " .. themeName)
    else
        print("|cffFF0000[ArenaCore Themes]|r Failed to switch to: " .. themeName)
    end
end
