-- Core/Pages/ArenaFrames.lua --
-- Arena Frames configuration page extracted from UI.lua
local AC = _G.ArenaCore
if not AC then return end

-- Localization helper
local function L(section, key, fallback)
    if AC.UILocalization then
        return AC.UILocalization:Get(section, key, fallback)
    end
    return fallback or key
end

local function ArenaFramesGroupBox(group)
    if not group then return end

    group.__acSkipThemeRefresh = true

    if group.__acFill and group.__acFill.Hide then
        group.__acFill:Hide()
    end
    if group.__acBorderFrame and group.__acBorderFrame.Hide then
        group.__acBorderFrame:Hide()
    end

    local fill = group:CreateTexture(nil, "BACKGROUND", nil, 2)
    fill:SetColorTexture(0.10, 0.10, 0.10, 1)
    fill:SetPoint("TOPLEFT", 1, -1)
    fill:SetPoint("BOTTOMRIGHT", -1, 1)
    fill.__acSkipThemeRefresh = true
    group.__acFill = fill
    group.__acFillIsGroupBox = true

    group.__acBorderFrame = nil
end

local V = AC.Vanity
local COLORS = AC.COLORS
local S = AC.Settings  -- Settings system for compatibility

-- Helper function to create a dropdown setting using the themed dropdown
local function CreateLinkedDropdown(parent, label, y, subPath, options, defaultVal, callback)
  local row = CreateFrame("Frame", nil, parent)
  row:SetPoint("TOPLEFT", 20, y); row:SetPoint("TOPRIGHT", -20, y); row:SetHeight(26)

  local l = AC:CreateStyledText(row, label, 11, AC.COLORS.TEXT_2, "OVERLAY", "")
  l:SetPoint("LEFT", 0, 0); l:SetWidth(120); l:SetJustifyH("LEFT")

  -- Convert options to simple string array for CreateFlatDropdown
  local optionTexts = {}
  local valueToText = {}
  local textToValue = {}
  
  for i, option in ipairs(options) do
    table.insert(optionTexts, option.text)
    valueToText[option.value] = option.text
    textToValue[option.text] = option.value
  end
  
  -- Get initial text for the selected value
  local initialText = valueToText[defaultVal] or optionTexts[1] or ""

  -- Create themed dropdown
  local dropdown = AC:CreateFlatDropdown(row, 150, 24, optionTexts, initialText, function(selectedText)
    local value = textToValue[selectedText]
    
    -- Save to database using proper path
    local keys = {}
    for k in string.gmatch(subPath, "([^%.]+)") do 
      table.insert(keys, k) 
    end
    
    local target = AC.DB.profile
    for i = 1, #keys - 1 do
      target[keys[i]] = target[keys[i]] or {}
      target = target[keys[i]]
    end
    target[keys[#keys]] = value
    
    -- Call callback if provided
    if callback then callback(value) end
  end)
  
  dropdown:SetPoint("LEFT", l, "RIGHT", 10, 0)

  return row
end

local function CreateColorPickerSetting(parent, label, y, path, defaultValue)
    local row = CreateFrame("Frame", nil, parent)
    row:SetPoint("TOPLEFT", 20, y)
    row:SetPoint("TOPRIGHT", -20, y)
    row:SetHeight(26)

    local l = AC:CreateStyledText(row, label, 11, COLORS.TEXT_2, "OVERLAY", "")
    l:SetPoint("LEFT", 0, 0)
    l:SetWidth(120)
    l:SetJustifyH("LEFT")

    local function ReadValue()
        local v
        if AC.ArenaFrameThemes and AC.DB and AC.DB.profile and type(path) == "string" and path:find("^arenaFrames%.") then
            local currentTheme = AC.ArenaFrameThemes:GetCurrentTheme()
            if currentTheme and AC.DB.profile.themeData and AC.DB.profile.themeData[currentTheme] then
                local themeValue = AC.ProfileManager and AC.ProfileManager.GetSetting and AC.ProfileManager:GetSetting("themeData." .. currentTheme .. "." .. path)
                if themeValue ~= nil then
                    v = themeValue
                end
            end
        end

        if v == nil and AC.ProfileManager and AC.ProfileManager.GetSetting then
            v = AC.ProfileManager:GetSetting(path)
        end

        if v == nil and S and S.Get then
            v = S:Get(path)
        end

        if v == nil then
            v = defaultValue
        end
        return v
    end

    local function NormalizeRGBA(v)
        if type(v) == "table" then
            local r = v.r or v[1] or 1
            local g = v.g or v[2] or 0.6
            local b = v.b or v[3] or 0
            local a = v.a or v[4] or 1
            return r, g, b, a
        end
        return 1, 0.6, 0, 1
    end

    local function SaveValue(r, g, b, a)
        local value = { r, g, b, a }
        if AC.ProfileManager and AC.ProfileManager.SetSetting then
            AC.ProfileManager:SetSetting(path, value)
        end

        if S and S.Set then
            S:Set(path, value)
        end

        if AC and AC.EnsureDB and AC.SetPath then
            AC:EnsureDB()
            if type(path) == "string" and path:match("^arenaFrames%.") then
                AC:SetPath(AC.DB.profile, path, value)
                _G.ArenaCoreDB = AC.DB

                if AC.ArenaFrameThemes then
                    local currentTheme = AC.ArenaFrameThemes:GetCurrentTheme()
                    if currentTheme then
                        AC.DB.profile.themeData = AC.DB.profile.themeData or {}
                        AC.DB.profile.themeData[currentTheme] = AC.DB.profile.themeData[currentTheme] or {}
                        AC:SetPath(AC.DB.profile.themeData[currentTheme], path, value)
                    end
                end
            end
        end
    end

    local btn = CreateFrame("Button", nil, row)
    btn:SetSize(150, 24)
    btn:SetPoint("LEFT", l, "RIGHT", 10, 0)

    local border = AC:CreateFlatTexture(btn, "BACKGROUND", 1, {0.196, 0.196, 0.196, 1}, 1)
    border:SetAllPoints()

    local bg = AC:CreateFlatTexture(btn, "BACKGROUND", 2, {0.102, 0.102, 0.102, 1}, 1)
    bg:SetPoint("TOPLEFT", 1, -1)
    bg:SetPoint("BOTTOMRIGHT", -1, 1)

    local swatch = btn:CreateTexture(nil, "OVERLAY")
    swatch:SetPoint("LEFT", 6, 0)
    swatch:SetSize(18, 18)
    swatch:SetTexture("Interface\\Buttons\\WHITE8X8")

    local txt = AC:CreateStyledText(btn, "Pick", 11, {0.706, 0.706, 0.706, 1}, "OVERLAY", "")
    txt:SetPoint("LEFT", swatch, "RIGHT", 8, 0)
    txt:SetJustifyH("LEFT")

    local function RefreshDisplay()
        local r, g, b, a = NormalizeRGBA(ReadValue())
        swatch:SetVertexColor(r, g, b, a)
    end
    RefreshDisplay()

    local function OpenPicker()
        if not ColorPickerFrame then return end

        local r, g, b, a = NormalizeRGBA(ReadValue())

        local function GetOpacity()
            if OpacitySliderFrame and OpacitySliderFrame.GetValue then
                return OpacitySliderFrame:GetValue()
            end
            return ColorPickerFrame.opacity or 0
        end

        local function ApplyNow()
            if AC.UpdateAllTargetBorders then
                AC:UpdateAllTargetBorders()
            end
        end

        local function OnColorChanged()
            local nr, ng, nb = ColorPickerFrame:GetColorRGB()
            local na = 1 - (GetOpacity() or 0)
            SaveValue(nr, ng, nb, na)
            RefreshDisplay()
            ApplyNow()
        end

        local function OnCancel(prev)
            local pr, pg, pb, pa
            if type(prev) == "table" then
                pr, pg, pb, pa = prev[1], prev[2], prev[3], prev[4]
            elseif type(ColorPickerFrame.previousValues) == "table" then
                pr, pg, pb, pa = ColorPickerFrame.previousValues[1], ColorPickerFrame.previousValues[2], ColorPickerFrame.previousValues[3], ColorPickerFrame.previousValues[4]
            end
            if pr then
                SaveValue(pr, pg, pb, pa)
            end
            RefreshDisplay()
            ApplyNow()
        end

        local opacity = 1 - (a or 1)
        ColorPickerFrame.previousValues = { r, g, b, a or 1 }

        if ColorPickerFrame.SetupColorPickerAndShow then
            ColorPickerFrame:SetupColorPickerAndShow({
                r = r,
                g = g,
                b = b,
                opacity = opacity,
                hasOpacity = true,
                swatchFunc = OnColorChanged,
                opacityFunc = OnColorChanged,
                cancelFunc = OnCancel,
            })
        else
            ColorPickerFrame.hasOpacity = true
            ColorPickerFrame.opacity = opacity
            ColorPickerFrame.func = OnColorChanged
            ColorPickerFrame.opacityFunc = OnColorChanged
            ColorPickerFrame.cancelFunc = OnCancel
            if ColorPickerFrame.SetColorRGB then
                ColorPickerFrame:SetColorRGB(r, g, b)
            end
            ColorPickerFrame:Show()
        end
    end

    btn:SetScript("OnClick", OpenPicker)
    btn:SetScript("OnShow", RefreshDisplay)

    row.button = btn
    row.RefreshDisplay = RefreshDisplay

    return row
end

-- Reset function limited to Arena Frames settings only (must be after AC is defined)
function AC:ResetArenaFramesSettings()
    self.DB.profile = self.DB.profile or {}
    
    -- Always use your curated defaults from addon.DEFAULTS
    if self.DEFAULTS and self.DEFAULTS.arenaFrames then
        -- Deep copy to avoid reference issues
        local function DeepCopy(tbl)
            if type(tbl) ~= "table" then return tbl end
            local out = {}
            for k, v in pairs(tbl) do out[k] = DeepCopy(v) end
            return out
        end
        self.DB.profile.arenaFrames = DeepCopy(self.DEFAULTS.arenaFrames)
    end
    
    -- Reset layout system to defaults (includes your dragged position)
    if self.DEFAULTS and self.DEFAULTS.layout then
        local function DeepCopy(tbl)
            if type(tbl) ~= "table" then return tbl end
            local out = {}
            for k, v in pairs(tbl) do out[k] = DeepCopy(v) end
            return out
        end
        self.DB.profile.layout = DeepCopy(self.DEFAULTS.layout)
    end
    
    -- Apply layout using new Layout system (but skip cast bars to avoid conflict)
    if self.Layout then
        -- Only restore Arena Frame position, not cast bars
        if self.Layout.RestoreBaseAnchor and self.ArenaFrames and self.ArenaFrames[1] then
            self.Layout:RestoreBaseAnchor(self.ArenaFrames[1])
        end
        
        -- Position other elements but NOT cast bars (they have their own page)
        if self.Layout.PositionHealthResourceBars then
            self.Layout:PositionHealthResourceBars()
        end
        if self.Layout.PositionTrinkets then
            self.Layout:PositionTrinkets()
        end
        if self.Layout.PositionRacials then
            self.Layout:PositionRacials()
        end
        if self.Layout.PositionSpecIcons then
            self.Layout:PositionSpecIcons()
        end
        if self.Layout.PositionClassIcons then
            self.Layout:PositionClassIcons()
        end
        if self.Layout.PositionDiminishingReturns then
            self.Layout:PositionDiminishingReturns()
        end
    end
    
    if self.ApplyAllArenaFrameSettings then self:ApplyAllArenaFrameSettings() end
    
    -- CRITICAL FIX: Refresh cast bars with the correct defaults after reset
    if self.RefreshCastBarsLayout then
        self:RefreshCastBarsLayout()
        print("|cff22AA44Arena Core:|r Cast bars refreshed with correct defaults")
    end
    
    -- CRITICAL FIX: Refresh ALL UI sliders to show the reset values
    print("|cff22AA44Arena Core:|r Refreshing UI sliders to match reset values...")
    
    -- Force refresh the current page to update all sliders
    if self.ShowPage then 
        self:ShowPage("ArenaFrames") 
        
        -- Additional refresh after a short delay to ensure sliders update
        C_Timer.After(0.1, function()
            if self.RefreshCurrentPage then
                self:RefreshCurrentPage()
            elseif self.ShowPage then
                self:ShowPage("ArenaFrames")
            end
            print("|cff22AA44Arena Core:|r UI sliders refreshed - Default Settings complete!")
        end)
    end
end

-- Helper function to create slider settings - PROFILE MANAGER INTEGRATION
local function CreateSliderSetting(parent, label, y, path, min, max, value, pct, compactDisplay)
    local row = CreateFrame("Frame", nil, parent)
    row:SetPoint("TOPLEFT", 20, y)
    row:SetPoint("TOPRIGHT", -20, y)
    row:SetHeight(26)

    local labelText = AC:CreateStyledText(row, label, 11, COLORS.TEXT_2, "OVERLAY", "")
    labelText:SetPoint("LEFT", row, "LEFT", 0, 0)
    labelText:SetWidth(120)
    labelText:SetJustifyH("LEFT")

    -- CRITICAL FIX: Read from THEME-SPECIFIC location (same place drag saves to)
    local currentValue = value
    
    -- For positioning sliders, read from theme-specific database
    if path:find("arenaFrames%.positioning") and AC.ArenaFrameThemes and AC.DB and AC.DB.profile then
        local currentTheme = AC.ArenaFrameThemes:GetCurrentTheme()
        if currentTheme and AC.DB.profile.themeData and AC.DB.profile.themeData[currentTheme] then
            local themeData = AC.DB.profile.themeData[currentTheme]
            if themeData.arenaFrames and themeData.arenaFrames.positioning then
                -- Extract the setting name from path (e.g., "horizontal" from "arenaFrames.positioning.horizontal")
                local settingName = path:match("%.([^%.]+)$")
                if settingName and themeData.arenaFrames.positioning[settingName] ~= nil then
                    currentValue = themeData.arenaFrames.positioning[settingName]
                end
            end
        end
    end
    
    -- For sizing sliders, also read from theme-specific database
    if path:find("arenaFrames%.sizing") and AC.ArenaFrameThemes and AC.DB and AC.DB.profile then
        local currentTheme = AC.ArenaFrameThemes:GetCurrentTheme()
        if currentTheme and AC.DB.profile.themeData and AC.DB.profile.themeData[currentTheme] then
            local themeData = AC.DB.profile.themeData[currentTheme]
            if themeData.arenaFrames and themeData.arenaFrames.sizing then
                -- Extract the setting name from path (e.g., "scale" from "arenaFrames.sizing.scale")
                local settingName = path:match("%.([^%.]+)$")
                if settingName and themeData.arenaFrames.sizing[settingName] ~= nil then
                    currentValue = themeData.arenaFrames.sizing[settingName]
                end
            end
        end
    end
    
    -- Fallback to old system if theme-specific value not found
    if currentValue == value then
        if AC.ProfileManager and AC.ProfileManager.GetSetting then
            currentValue = AC.ProfileManager:GetSetting(path)
            if currentValue == nil then
                -- Fallback to FrameSystem or Settings system if ProfileManager doesn't have it
                if AC.FrameSystem and AC.FrameSystem.GetSetting then
                    currentValue = AC.FrameSystem:GetSetting(path) or value
                elseif S and S.Get then
                    currentValue = S:Get(path) or value or 0
                end
            end
        elseif AC.FrameSystem and AC.FrameSystem.GetSetting then
            currentValue = AC.FrameSystem:GetSetting(path) or value
        elseif S and S.Get then
            currentValue = S:Get(path) or value or 0
        end
    end

    -- Create DOWN arrow button for fine adjustment
    local downBtn = CreateFrame("Button", nil, row)
    downBtn:SetSize(16, 16)
    downBtn:SetPoint("LEFT", labelText, "RIGHT", 6, 0)
    
    -- Down arrow styling
    local downBg = downBtn:CreateTexture(nil, "BACKGROUND")
    downBg:SetAllPoints()
    downBg:SetColorTexture(0.2, 0.2, 0.2, 0.8)
    
    local downBorder = downBtn:CreateTexture(nil, "BORDER") 
    downBorder:SetAllPoints()
    downBorder:SetColorTexture(0.4, 0.4, 0.4, 1)
    downBorder:SetPoint("TOPLEFT", 1, -1)
    downBorder:SetPoint("BOTTOMRIGHT", -1, 1)
    
    local downText = downBtn:CreateFontString(nil, "OVERLAY")
    -- CRITICAL FIX: Use locale-appropriate font for Chinese/Korean/Russian support
    local currentLocale = GetLocale()
    local usesCJK = (currentLocale == "zhCN" or currentLocale == "zhTW" or 
                    currentLocale == "koKR" or currentLocale == "ruRU")
    if usesCJK then
        downText:SetFontObject(GameFontNormal)
        local fontPath, fontHeight, fontFlags = downText:GetFont()
        downText:SetFont(fontPath, 12, "")
    else
        downText:SetFont("Interface/AddOns/ArenaCore/Media/Fonts/arenacore.ttf", 12, "")
    end
    downText:SetText("-")
    downText:SetTextColor(0.8, 0.8, 0.8, 1)
    downText:SetPoint("CENTER")

    local slider = AC:CreateFlatSlider(row, 150, 20, min, max, currentValue, pct or false, compactDisplay or false, function(newValue)
        -- Save to theme-specific database for positioning and sizing
        if (path:find("arenaFrames%.positioning") or path:find("arenaFrames%.sizing")) and AC.ArenaFrameThemes and AC.DB and AC.DB.profile then
            local currentTheme = AC.ArenaFrameThemes:GetCurrentTheme()
            if currentTheme then
                AC.DB.profile.themeData = AC.DB.profile.themeData or {}
                AC.DB.profile.themeData[currentTheme] = AC.DB.profile.themeData[currentTheme] or {}
                AC.DB.profile.themeData[currentTheme].arenaFrames = AC.DB.profile.themeData[currentTheme].arenaFrames or {}

                -- Extract setting type and name from path
                local settingType = path:match("arenaFrames%.([^%.]+)")
                local settingName = path:match("%.([^%.]+)$")

                if settingType and settingName then
                    AC.DB.profile.themeData[currentTheme].arenaFrames[settingType] = AC.DB.profile.themeData[currentTheme].arenaFrames[settingType] or {}
                    AC.DB.profile.themeData[currentTheme].arenaFrames[settingType][settingName] = newValue
                end
            end
        end

        -- Update via Profile Manager for proper sync (primary)
        if AC.ProfileManager and AC.ProfileManager.SetSetting then
            AC.ProfileManager:SetSetting(path, newValue)
        end
        -- Also update Frame System and legacy system for compatibility
        if AC.FrameSystem and AC.FrameSystem.SetSetting then
            AC.FrameSystem:SetSetting(path, newValue)
        end
        if S and S.Set then
            S:Set(path, newValue)
        end

        -- Update font sizes in real-time for fontSize setting
        if path == "classIcons.fontSize" then
            if AC.ClassIconAuras and AC.ClassIconAuras.UpdateFontSize then
                AC.ClassIconAuras:UpdateFontSize()
            end
            if AC.SimpleCCTest and AC.SimpleCCTest.UpdateFontSize then
                AC.SimpleCCTest:UpdateFontSize()
            end
        end
    end)
    slider:SetPoint("LEFT", downBtn, "RIGHT", 4, 0)

    -- Store slider reference for direct updates during reset
    if not AC.sliderWidgets then AC.sliderWidgets = {} end
    AC.sliderWidgets[path] = slider.slider

    -- Create UP arrow button for fine adjustment  
    local upBtn = CreateFrame("Button", nil, row)
    upBtn:SetSize(16, 16)
    upBtn:SetPoint("LEFT", slider, "RIGHT", 4, 0)
    
    -- Up arrow styling
    local upBg = upBtn:CreateTexture(nil, "BACKGROUND")
    upBg:SetAllPoints()
    upBg:SetColorTexture(0.2, 0.2, 0.2, 0.8)
    
    local upBorder = upBtn:CreateTexture(nil, "BORDER")
    upBorder:SetAllPoints() 
    upBorder:SetColorTexture(0.4, 0.4, 0.4, 1)
    upBorder:SetPoint("TOPLEFT", 1, -1)
    upBorder:SetPoint("BOTTOMRIGHT", -1, 1)
    
    local upText = upBtn:CreateFontString(nil, "OVERLAY")
    -- CRITICAL FIX: Use locale-appropriate font for Chinese/Korean/Russian support
    local currentLocale = GetLocale()
    local usesCJK = (currentLocale == "zhCN" or currentLocale == "zhTW" or 
                    currentLocale == "koKR" or currentLocale == "ruRU")
    if usesCJK then
        upText:SetFontObject(GameFontNormal)
        local fontPath, fontHeight, fontFlags = upText:GetFont()
        upText:SetFont(fontPath, 12, "")
    else
        upText:SetFont("Interface/AddOns/ArenaCore/Media/Fonts/arenacore.ttf", 12, "")
    end
    upText:SetText("+")
    upText:SetTextColor(0.8, 0.8, 0.8, 1)
    upText:SetPoint("CENTER")

    local maxT = AC:CreateStyledText(row, pct and (max .. "%") or tostring(max), 9, COLORS.TEXT_MUTED, "OVERLAY", "")
    maxT:SetPoint("LEFT", upBtn, "RIGHT", 6, 0)
    maxT:SetWidth(25)
    maxT:SetJustifyH("LEFT")

    local valT = AC:CreateStyledText(row, "", 11, COLORS.TEXT_2, "OVERLAY", "")
    valT:SetPoint("RIGHT", row, "RIGHT", -10, 0)
    valT:SetPoint("LEFT", maxT, "RIGHT", 10, 0)
    valT:SetWidth(35)
    valT:SetJustifyH("CENTER")

    -- PRESERVE ORIGINAL update function
    local function upd()
        local v = slider.slider:GetValue()
        if pct then 
            valT:SetText(string.format("%.0f%%", v))
        elseif compactDisplay then
            valT:SetText(string.format("%.0f", math.floor(v / 100)))
        else 
            valT:SetText(string.format("%.0f", v)) 
        end
    end

    -- PRESERVE ORIGINAL slider event handler - DON'T MODIFY
    slider.slider:SetScript("OnValueChanged", function(_, v)
        upd()
        AC:OnArenaFramesSliderChanged(slider, path, v)
    end)
    
    -- Down arrow click handler
    downBtn:SetScript("OnClick", function()
        local currentVal = slider.slider:GetValue()
        local increment = compactDisplay and 100 or 1
        local newVal = math.max(min, currentVal - increment)
        slider.slider:SetValue(newVal)
    end)
    
    -- Up arrow click handler  
    upBtn:SetScript("OnClick", function()
        local currentVal = slider.slider:GetValue()
        local increment = compactDisplay and 100 or 1
        local newVal = math.min(max, currentVal + increment)
        slider.slider:SetValue(newVal)
    end)
    
    -- Down arrow hover effects
    downBtn:SetScript("OnEnter", function()
        downBg:SetColorTexture(0.3, 0.3, 0.3, 0.9)
        downText:SetTextColor(1, 1, 1, 1)
    end)
    
    downBtn:SetScript("OnLeave", function()
        downBg:SetColorTexture(0.2, 0.2, 0.2, 0.8)
        downText:SetTextColor(0.8, 0.8, 0.8, 1)
    end)
    
    -- Up arrow hover effects
    upBtn:SetScript("OnEnter", function()
        upBg:SetColorTexture(0.3, 0.3, 0.3, 0.9)
        upText:SetTextColor(1, 1, 1, 1)
    end)
    
    upBtn:SetScript("OnLeave", function()
        upBg:SetColorTexture(0.2, 0.2, 0.2, 0.8)
        upText:SetTextColor(0.8, 0.8, 0.8, 1)
    end)

    upd()
    return row
end
local checkboxRegistry = {}

-- Helper function to create checkbox settings with proper database binding
local function CreateRowCheckbox(parent, label, y, path, checked, disableInnerLines)
    local row = CreateFrame("Frame", nil, parent)
    row:SetPoint("TOPLEFT", 20, y)
    row:SetPoint("TOPRIGHT", -20, y)
    row:SetHeight(26)

    local cardFill = row:CreateTexture(nil, "BACKGROUND", nil, 1)
    cardFill:SetColorTexture(0.10, 0.10, 0.10, 1)
    cardFill:SetPoint("TOPLEFT", 1, -1)
    cardFill:SetPoint("BOTTOMRIGHT", -1, 1)
    cardFill.__acSkipThemeRefresh = true

    if not disableInnerLines then
        local cardTopLine = row:CreateTexture(nil, "BORDER", nil, 2)
        cardTopLine:SetColorTexture(0.4, 0.4, 0.4, 0.5)
        cardTopLine:SetPoint("TOPLEFT", 0, 0)
        cardTopLine:SetPoint("TOPRIGHT", 0, 0)
        cardTopLine:SetHeight(1)
        cardTopLine.__acSkipThemeRefresh = true

        local cardBottomLine = row:CreateTexture(nil, "BORDER", nil, 2)
        cardBottomLine:SetColorTexture(0.4, 0.4, 0.4, 0.5)
        cardBottomLine:SetPoint("BOTTOMLEFT", 0, 0)
        cardBottomLine:SetPoint("BOTTOMRIGHT", 0, 0)
        cardBottomLine:SetHeight(1)
        cardBottomLine.__acSkipThemeRefresh = true
    end

    local l = AC:CreateStyledText(row, label, 12, COLORS.TEXT_2, "OVERLAY", "")
    l:SetPoint("LEFT", 0, 0)
    l:SetWidth(180)

    -- Get current value from Profile Manager FIRST, then Settings system
    local currentChecked = checked
    if AC.ProfileManager and AC.ProfileManager.GetSetting then
        currentChecked = AC.ProfileManager:GetSetting(path)
        if currentChecked == nil then
            -- Fallback to Settings system if ProfileManager doesn't have it
            currentChecked = checked
        end
    end
    
    local box = AC:CreateFlatCheckbox(row, 20, currentChecked)
    box:SetPoint("RIGHT", -25, 0)
    
    -- CRITICAL: Register checkbox for mutual exclusivity updates
    checkboxRegistry[path] = box

    -- Force update the checkbox visual state (ensures it matches the database value)
    box:SetChecked(currentChecked)
    
    -- Register checkbox with CheckboxTracker for Edit Mode support
    if AC.CheckboxTracker then
        AC.CheckboxTracker:Register(box, path)
    end

    -- Store reference for updates
    row.updateIndicator = function()
        cardFill:SetColorTexture(0.10, 0.10, 0.10, 1)
    end
    
    -- Add hover effect to lighten the background
    row:SetScript("OnEnter", function()
        cardFill:SetColorTexture(0.14, 0.14, 0.14, 1)
    end)
    
    row:SetScript("OnLeave", function()
        cardFill:SetColorTexture(0.10, 0.10, 0.10, 1)
    end)

    -- Update indicator when checkbox changes
    box:SetScript("OnClick", function(selfBtn)
        local isChecked = selfBtn:GetChecked()
        
        -- Mutual exclusivity for Show Names and Arena 1/2/3 Names
        if isChecked then
            if path == "arenaFrames.general.showNames" then
                -- User enabled Show Names -> disable Arena 1/2/3 Names
                if AC.ProfileManager and AC.ProfileManager.SetSetting then
                    AC.ProfileManager:SetSetting("arenaFrames.general.showArenaLabels", false)
                    local otherBox = checkboxRegistry["arenaFrames.general.showArenaLabels"]
                    if otherBox then
                        otherBox:SetChecked(false)
                    end
                end
            end
        else
            -- When unchecking, also uncheck dependent options
            if path == "arenaFrames.general.showNames" then
                -- User disabled Show Names -> also disable Use Spec Names
                if AC.ProfileManager and AC.ProfileManager.SetSetting then
                    AC.ProfileManager:SetSetting("arenaFrames.general.useSpecNames", false)
                    local useSpecNamesBox = checkboxRegistry["arenaFrames.general.useSpecNames"]
                    if useSpecNamesBox then
                        useSpecNamesBox:SetChecked(false)
                    end
                end
            elseif path == "arenaFrames.general.showArenaLabels" then
                -- User enabled Arena 1/2/3 Names -> disable Show Names and Use Spec Names
                if AC.ProfileManager and AC.ProfileManager.SetSetting then
                    AC.ProfileManager:SetSetting("arenaFrames.general.showNames", false)
                    AC.ProfileManager:SetSetting("arenaFrames.general.useSpecNames", false)
                    local showNamesBox = checkboxRegistry["arenaFrames.general.showNames"]
                    if showNamesBox then
                        showNamesBox:SetChecked(false)
                    end
                    local useSpecNamesBox = checkboxRegistry["arenaFrames.general.useSpecNames"]
                    if useSpecNamesBox then
                        useSpecNamesBox:SetChecked(false)
                    end
                end
            elseif path == "arenaFrames.general.useSpecNames" then
                -- Use Spec Names requires Show Names to be enabled - no mutual exclusivity needed
                -- This is a sub-option of Show Names, not a competing option
            elseif path == "arenaFrames.sizing.disableTargetHighlight" then
                if AC.ProfileManager and AC.ProfileManager.SetSetting then
                    AC.ProfileManager:SetSetting("arenaFrames.sizing.targetHighlightOnClassIcon", false)
                    local otherBox = checkboxRegistry["arenaFrames.sizing.targetHighlightOnClassIcon"]
                    if otherBox then
                        otherBox:SetChecked(false)
                    end
                end
            elseif path == "arenaFrames.sizing.targetHighlightOnClassIcon" then
                if AC.ProfileManager and AC.ProfileManager.SetSetting then
                    AC.ProfileManager:SetSetting("arenaFrames.sizing.disableTargetHighlight", false)
                    local otherBox = checkboxRegistry["arenaFrames.sizing.disableTargetHighlight"]
                    if otherBox then
                        otherBox:SetChecked(false)
                    end
                end
            end
        end
        
        -- SIMPLIFIED: Let ProfileManager handle everything (Edit Mode, database, refresh)
        -- ProfileManager.SetSetting() already handles:
        -- - Buffering to tempProfileBuffer if in Edit Mode
        -- - Writing to database for visual updates
        -- - Triggering appropriate refresh functions
        if AC.ProfileManager and AC.ProfileManager.SetSetting then
            AC.ProfileManager:SetSetting(path, isChecked)
        end
        
        -- CRITICAL: Real-time refresh for Use Spec Names setting
        if path == "arenaFrames.general.useSpecNames" then
            -- Refresh all arena frame text immediately
            if AC.RefreshArenaFrameText then
                AC:RefreshArenaFrameText()
            elseif AC.SetArenaFrameText then
                -- Manual refresh for all frames (both test and live)
                for i = 1, 3 do
                    local frame = AC.ArenaFrames and AC.ArenaFrames[i]
                    if frame then
                        -- Determine mode and refresh accordingly
                        local mode = "live_arena"
                        if AC.DB and AC.DB.profile and AC.DB.profile.testMode then
                            mode = "test_mode"
                        end
                        
                        local unit = frame.unit or ("arena" .. i)
                        AC:SetArenaFrameText(frame, i, mode, unit)
                    end
                end
            end
        end
        
        -- CRITICAL: Target highlight toggles need immediate refresh (checkbox path bypasses Helpers.lua)
        if path == "arenaFrames.sizing.disableTargetHighlight" or path == "arenaFrames.sizing.targetHighlightOnClassIcon" then
            if AC.UpdateAllTargetBorders then
                AC:UpdateAllTargetBorders()
            end
            if AC.TargetHighlight and AC.TargetHighlight.RefreshAll then
                AC.TargetHighlight:RefreshAll()
            end
        end
        
        -- Update visual indicator
        row.updateIndicator()
    end)

    -- Force synchronization of visual state with database value
    C_Timer.After(0.01, function()
        if box then
            local dbValue = AC.ProfileManager and AC.ProfileManager.GetSetting and AC.ProfileManager:GetSetting(path)
            if dbValue ~= nil then
                box:SetChecked(dbValue)
                row.updateIndicator()
            end
        end
    end)
    
    return row
end

local CreateCheckboxSetting = CreateRowCheckbox

-- Helper function to create collapsible section headers
local function CreateCollapsibleSection(parent, title, y, isExpanded)
    local section = CreateFrame("Frame", nil, parent)
    section:SetPoint("TOPLEFT", 18, y)
    section:SetPoint("TOPRIGHT", -18, y)
    section:SetHeight(35)
    section:SetFrameLevel((parent:GetFrameLevel() or 0) + 10)
    section:SetClipsChildren(false)

    local header = CreateFrame("Frame", nil, section)
    header:SetPoint("TOPLEFT", 0, 0)
    header:SetPoint("TOPRIGHT", 0, 0)
    header:SetHeight(35)
    header:SetFrameLevel(section:GetFrameLevel() + 5)

    ArenaFramesGroupBox(header)
    
    -- Removed borders to avoid conflicts with hover effects
    
    -- Create clickable button for the entire header
    local button = CreateFrame("Button", nil, header)
    button:SetAllPoints()
    button:SetFrameLevel(header:GetFrameLevel() + 1)
    
    -- Expand/collapse arrow (match Shade cooldown manager)
    local arrow = button:CreateTexture(nil, "OVERLAY")
    arrow:SetSize(16, 16)
    arrow:SetPoint("RIGHT", -25, 0)
    arrow:SetAtlas("auctionhouse-ui-dropdown-arrow-up", true)
    
    -- Section title with light grey color matching "Horizontal" text
    local titleText = AC:CreateStyledText(button, title, 13, COLORS.TEXT_2, "OVERLAY", "")
    titleText:SetPoint("LEFT", 15, 0)
    
    -- State management
    section.isExpanded = isExpanded or false
    section.contentFrame = nil
    section.arrow = arrow
    section.button = button
    section.bg = header.__acFill
    section.header = header
    
    -- Update arrow display
    local function updateArrow()
        if section.isExpanded then
            arrow:SetAtlas("auctionhouse-ui-dropdown-arrow-down", true)
        else
            arrow:SetAtlas("auctionhouse-ui-dropdown-arrow-up", true)
        end
    end
    updateArrow()
    
    local glow = header:CreateTexture(nil, "BORDER")
    glow:SetColorTexture(0.85, 0.85, 0.85, 1)
    glow:SetAllPoints(header)
    glow:SetBlendMode("BLEND")
    glow:SetAlpha(0)
    section.glow = glow
    button.glow = glow
    
    -- Hover effects - keep grey color but add subtle overlay
    button:SetScript("OnEnter", function()
        -- Keep original grey background color (don't change it)
        if button.glow then
            button.glow:SetAlpha(0.12)
        end

        -- Match Shade behavior: hint the dropdown by showing the "down" arrow on hover
        if not section.isExpanded then
            arrow:SetAtlas("auctionhouse-ui-dropdown-arrow-down", true)
        end
    end)
    
    button:SetScript("OnLeave", function()
        -- Keep original grey background color (don't change it)
        if button.glow then
            button.glow:SetAlpha(0)
        end

        -- Restore normal arrow state
        updateArrow()
    end)
    
    -- Click handler with dynamic layout update
    button:SetScript("OnClick", function()
        section.isExpanded = not section.isExpanded
        updateArrow()
        
        if section.contentFrame then
            if section.isExpanded then
                section.contentFrame:Show()
            else
                section.contentFrame:Hide()
            end
        end
        
        -- Trigger dynamic layout refresh
        if section.onToggle then
            section.onToggle(section.isExpanded)
        end
        
        -- Update layout of all sections
        if section.parent and section.parent.updateLayout then
            section.parent:updateLayout()
            -- CRITICAL FIX: Always push other groups down when ANY section toggles
            if section.parent.pushOtherGroupsDown then
                -- Add a tiny delay to ensure the layout update completes first
                C_Timer.After(0.01, function()
                    section.parent:pushOtherGroupsDown()
                end)
            end
        end
    end)
    
    return section
end

-- Helper function to create content frame for collapsible sections with dynamic sizing and styling
local function CreateSectionContent(parent, section, initialHeight)
    local content = CreateFrame("Frame", nil, section)
    content:SetPoint("TOPLEFT", section.header, "BOTTOMLEFT", 0, -1)
    content:SetPoint("TOPRIGHT", section.header, "BOTTOMRIGHT", 0, -1)
    content:SetHeight(initialHeight or 100) -- Default height
    content:SetFrameLevel(section:GetFrameLevel() + 1)

    if content.__acContentBg and content.__acContentBg.Hide then
        content.__acContentBg:Hide()
    end
    if content.__acContentBorderTop and content.__acContentBorderTop.Hide then
        content.__acContentBorderTop:Hide()
    end
    if content.__acContentBorderBottom and content.__acContentBorderBottom.Hide then
        content.__acContentBorderBottom:Hide()
    end
    if content.__acContentBorderLeft and content.__acContentBorderLeft.Hide then
        content.__acContentBorderLeft:Hide()
    end
    if content.__acContentBorderRight and content.__acContentBorderRight.Hide then
        content.__acContentBorderRight:Hide()
    end

    local bg = content:CreateTexture(nil, "BACKGROUND", nil, 0)
    bg:SetColorTexture(0.10, 0.10, 0.10, 1)
    bg:SetPoint("TOPLEFT", 1, -1)
    bg:SetPoint("BOTTOMRIGHT", -1, 1)
    bg.__acSkipThemeRefresh = true
    content.__acContentBg = bg

    local borderTop = content:CreateTexture(nil, "BORDER", nil, 1)
    borderTop:SetColorTexture(0.4, 0.4, 0.4, 0.45)
    borderTop:SetPoint("TOPLEFT", 0, 0)
    borderTop:SetPoint("TOPRIGHT", 0, 0)
    borderTop:SetHeight(1)
    borderTop.__acSkipThemeRefresh = true
    content.__acContentBorderTop = borderTop

    local borderBottom = content:CreateTexture(nil, "BORDER", nil, 1)
    borderBottom:SetColorTexture(0.4, 0.4, 0.4, 0.45)
    borderBottom:SetPoint("BOTTOMLEFT", 0, 0)
    borderBottom:SetPoint("BOTTOMRIGHT", 0, 0)
    borderBottom:SetHeight(1)
    borderBottom.__acSkipThemeRefresh = true
    content.__acContentBorderBottom = borderBottom

    local borderLeft = content:CreateTexture(nil, "BORDER", nil, 1)
    borderLeft:SetColorTexture(0.4, 0.4, 0.4, 0.45)
    borderLeft:SetPoint("TOPLEFT", 0, 0)
    borderLeft:SetPoint("BOTTOMLEFT", 0, 0)
    borderLeft:SetWidth(1)
    borderLeft.__acSkipThemeRefresh = true
    content.__acContentBorderLeft = borderLeft

    local borderRight = content:CreateTexture(nil, "BORDER", nil, 1)
    borderRight:SetColorTexture(0.4, 0.4, 0.4, 0.45)
    borderRight:SetPoint("TOPRIGHT", 0, 0)
    borderRight:SetPoint("BOTTOMRIGHT", 0, 0)
    borderRight:SetWidth(1)
    borderRight.__acSkipThemeRefresh = true
    content.__acContentBorderRight = borderRight
    
    section.contentFrame = content
    
    -- Function to auto-size content based on children
    function content:AutoSize()
        local totalHeight = 0
        local maxChildY = 0
        
        for i = 1, self:GetNumChildren() do
            local child = select(i, self:GetChildren())
            if child and child:IsVisible() then
                local childBottom = math.abs(select(5, child:GetPoint(1)) or 0) + child:GetHeight()
                maxChildY = math.max(maxChildY, childBottom)
            end
        end
        
        -- Add padding and set height
        totalHeight = maxChildY + 20 -- 20px bottom padding
        local minHeight = math.max(totalHeight, 50) -- Minimum 50px height
        local scale = self.GetEffectiveScale and self:GetEffectiveScale() or 1
        self:SetHeight(math.floor(minHeight * scale + 0.5) / scale)
        
        return self:GetHeight()
    end
    
    -- Initially hide if section is collapsed
    if not section.isExpanded then
        content:Hide()
    end
    
    return content
end

-- Layout constants for professional spacing
local ROW_GAP = 6
local PAD_X = 10
local PAD_Y = 8
local H_GUTTER = 12
local HEADER_HEIGHT = 35

-- Measurement helper function
local function MeasureSection(section)
    if not section.body then return HEADER_HEIGHT end
    
    local sectionWidth = section:GetWidth()
    local bodyWidth = sectionWidth - PAD_X * 2
    local totalRowHeight = 0
    
    -- Measure each row in the body
    for i = 1, section.body:GetNumChildren() do
        local row = select(i, section.body:GetChildren())
        if row and row:IsVisible() then
            -- Set row width and measure
            row:SetWidth(bodyWidth)
            
            -- Get actual row height (accounting for text wrapping)
            local rowHeight = math.max(row:GetHeight(), 25) -- Minimum row height
            totalRowHeight = totalRowHeight + rowHeight + ROW_GAP
        end
    end
    
    -- Set body height
    if totalRowHeight > 0 then
        section.body:SetHeight(totalRowHeight + PAD_Y * 2)
    end
    
    -- Return total section height
    local effectiveHeight = HEADER_HEIGHT
    if section.isExpanded and section.body then
        effectiveHeight = effectiveHeight + section.body:GetHeight()
    end
    
    return effectiveHeight
end

-- Master layout function
local function Layout(scrollChild)
    if not scrollChild or not scrollChild.sections then return end
    
    local scrollWidth = scrollChild:GetParent():GetWidth()
    local contentWidth = scrollWidth - H_GUTTER * 2
    local currentY = 0
    
    -- Layout each section in order
    for i, section in ipairs(scrollChild.sections) do
        -- Set section width
        section:SetWidth(contentWidth)
        
        -- Measure section height
        local sectionHeight = MeasureSection(section)
        
        -- Position section
        section:ClearAllPoints()
        section:SetPoint("TOPLEFT", H_GUTTER, -currentY)
        section:SetHeight(sectionHeight)
        
        -- Move cursor down
        currentY = currentY + sectionHeight + ROW_GAP
    end
    
    -- Update scroll child height
    local totalHeight = currentY + PAD_Y
    scrollChild:SetHeight(math.max(totalHeight, scrollChild:GetParent():GetHeight()))
end

-- Throttled layout function to prevent excessive calls
local layoutTimer = nil
local function ThrottledLayout(scrollChild)
    if layoutTimer then return end
    layoutTimer = C_Timer.After(0, function()
        Layout(scrollChild)
        layoutTimer = nil
    end)
end

-- Create robust collapsible section with proper measurement
local function CreateRobustSection(parent, title, isExpanded)
    local section = CreateFrame("Frame", nil, parent)
    section.isExpanded = isExpanded or false
    
    -- Create header
    local header = CreateFrame("Button", nil, section)
    header:SetHeight(HEADER_HEIGHT)
    header:SetPoint("TOPLEFT", 0, 0)
    header:SetPoint("TOPRIGHT", 0, 0)
    
    -- Header background
    local bg = header:CreateTexture(nil, "BACKGROUND")
    bg:SetAllPoints()
    bg:SetColorTexture(0.109, 0.109, 0.109, 1) -- #1c1c1c
    
    local border = header:CreateTexture(nil, "BORDER")
    border:SetAllPoints()
    border:SetColorTexture(0.4, 0.4, 0.4, 0.6)
    border:SetPoint("TOPLEFT", 1, -1)
    border:SetPoint("BOTTOMRIGHT", -1, 1)
    
    -- Arrow
    local arrow = header:CreateTexture(nil, "OVERLAY")
    arrow:SetTexture("Interface\\AddOns\\ArenaCore\\Media\\UI\\dropdown-arrow-purple.tga")
    arrow:SetSize(16, 16)
    arrow:SetPoint("LEFT", 15, 0)
    
    -- Title
    local titleText = AC:CreateStyledText(header, title, 13, {1,1,1,1}, "OVERLAY", "")
    titleText:SetPoint("LEFT", arrow, "RIGHT", 8, 0)
    titleText:SetWordWrap(true)
    
    -- Create body
    local body = CreateFrame("Frame", nil, section)
    body:SetPoint("TOPLEFT", 0, -HEADER_HEIGHT)
    body:SetPoint("TOPRIGHT", 0, -HEADER_HEIGHT)
    body:SetHeight(1) -- Will be measured dynamically
    
    section.header = header
    section.body = body
    section.arrow = arrow
    section.bg = bg
    
    -- Update arrow display
    local function updateArrow()
        if section.isExpanded then
            arrow:SetRotation(math.rad(0))
        else
            arrow:SetRotation(math.rad(-90))
        end
    end
    updateArrow()
    
    -- Hover effects
    header:SetScript("OnEnter", function()
        bg:SetColorTexture(0.2, 0.2, 0.2, 1)
    end)
    
    header:SetScript("OnLeave", function()
        bg:SetColorTexture(0.109, 0.109, 0.109, 1)
    end)
    
    -- Click handler
    header:SetScript("OnClick", function()
        section.isExpanded = not section.isExpanded
        updateArrow()
        
        -- Trigger layout update
        if parent.Layout then
            ThrottledLayout(parent)
        end
    end)
    
    return section
end

-- Create GENERAL settings group with collapsible sections and dynamic layout
local function CreateGroup_GENERAL(parent, y)
    local mainContainer = CreateFrame("Frame", nil, parent)
    mainContainer:SetPoint("TOPLEFT", 0, y)
    mainContainer:SetPoint("TOPRIGHT", 0, y)
    mainContainer:SetHeight(800) -- Increased to accommodate all sections when expanded

    local function SnapToPixels(frame, value)
        local scale = frame and frame.GetEffectiveScale and frame:GetEffectiveScale() or 1
        return math.floor(value * scale + 0.5) / scale
    end
    
    -- Store all sections for dynamic layout
    mainContainer.sections = {}
    mainContainer.sectionOrder = {}
    
    -- Simple dynamic layout function - prevents overlap and pushes content down
    function mainContainer:updateLayout()
        local currentY = 0
        local gap = SnapToPixels(self, 15)
        local separation = SnapToPixels(self, 1)
        
        -- Position each section sequentially to prevent overlap
        for i, section in ipairs(self.sectionOrder) do
            local snappedY = SnapToPixels(self, currentY)

            local sectionHeight = 35
            if section.isExpanded and section.contentFrame then
                section.contentFrame:AutoSize()
                sectionHeight = sectionHeight + SnapToPixels(self, section.contentFrame:GetHeight()) + separation
            end
            sectionHeight = SnapToPixels(self, sectionHeight)

            -- Clear existing points and reposition
            section:ClearAllPoints()
            section:SetPoint("TOPLEFT", 18, snappedY)
            section:SetPoint("TOPRIGHT", -18, snappedY)
            section:SetHeight(sectionHeight)
            
            -- Add spacing between sections to keep layout clean
            currentY = currentY - sectionHeight - gap
        end
        
        -- Update container height and push other groups down
        local totalHeight = math.abs(currentY) + 20
        self:SetHeight(totalHeight)
        self:pushOtherGroupsDown()
    end
    
    -- SIMPLIFIED: Store direct references to the groups we need to move
    mainContainer.positioningGroup = nil -- Will be set after groups are created
    mainContainer.sizingGroup = nil -- Will be set after groups are created
    
    -- Simple function to push POSITIONING and SIZING groups down when sections expand
    function mainContainer:pushOtherGroupsDown()
        -- Calculate the actual height based on expanded sections
        local totalHeight = 0
        for i, section in ipairs(self.sectionOrder) do
            totalHeight = totalHeight + (section:GetHeight() or 35) + 15
        end
        
        local positioningY = -totalHeight - 20 -- Gap after collapsible sections
        local sizingY = positioningY - 170 - 15 -- POSITIONING height + gap
        
            -- Use direct references to the groups (much simpler!)
        if self.positioningGroup then
            self.positioningGroup:ClearAllPoints()
            self.positioningGroup:SetPoint("TOPLEFT", 18, positioningY)
            self.positioningGroup:SetPoint("TOPRIGHT", -18, positioningY)
        end
        
        if self.sizingGroup then
            self.sizingGroup:ClearAllPoints()
            self.sizingGroup:SetPoint("TOPLEFT", 18, sizingY)
            self.sizingGroup:SetPoint("TOPRIGHT", -18, sizingY)
        end
    end
    
    -- ▼ Text Display Settings (first 5 checkboxes)
    local textDisplaySection = CreateCollapsibleSection(mainContainer, L("ARENA_FRAMES", "text_display_settings", "Text Display Settings"), 0, false)
    textDisplaySection.parent = mainContainer
    local textDisplayContent = CreateSectionContent(mainContainer, textDisplaySection, 205)
    
    CreateRowCheckbox(textDisplayContent, L("ARENA_FRAMES", "status_text", "Status Text"), -25, "arenaFrames.general.statusText", nil, true)
    CreateRowCheckbox(textDisplayContent, L("ARENA_FRAMES", "use_percentage", "Use Percentage"), -50, "arenaFrames.general.usePercentage", nil, true)
    CreateRowCheckbox(textDisplayContent, L("ARENA_FRAMES", "use_class_colors", "Use Class Colors"), -75, "arenaFrames.general.useClassColors", nil, true)
    CreateRowCheckbox(textDisplayContent, L("ARENA_FRAMES", "show_names", "Show Names"), -100, "arenaFrames.general.showNames", nil, true)
    CreateRowCheckbox(textDisplayContent, L("ARENA_FRAMES", "use_spec_names", "Use Spec Names"), -125, "arenaFrames.general.useSpecNames", nil, true)
    CreateRowCheckbox(textDisplayContent, L("ARENA_FRAMES", "arena_numbers_only", "Arena Numbers Only"), -150, "arenaFrames.general.showArenaNumbers", nil, true)
    CreateRowCheckbox(textDisplayContent, "  " .. L("ARENA_FRAMES", "arena_123_names", "Arena 1/2/3 Names"), -175, "arenaFrames.general.showArenaLabels", nil, true)
    
    -- FrameSort Integration Toggle
    local frameSortRow = CreateFrame("Frame", nil, textDisplayContent)
    frameSortRow:SetPoint("TOPLEFT", 20, -200)
    frameSortRow:SetPoint("TOPRIGHT", -20, -200)
    frameSortRow:SetHeight(26)
    
    local frameSortLabel = AC:CreateStyledText(frameSortRow, L("ARENA_FRAMES", "framesort_integration", "FrameSort Integration"), 12, COLORS.TEXT_2, "OVERLAY", "")
    frameSortLabel:SetPoint("LEFT", 0, 0)
    frameSortLabel:SetWidth(180)
    
    -- Get current value
    local frameSortEnabled = AC.DB and AC.DB.profile 
        and AC.DB.profile.arenaFrames 
        and AC.DB.profile.arenaFrames.general 
        and AC.DB.profile.arenaFrames.general.enableFrameSortIntegration or false
    
    local frameSortBox = AC:CreateFlatCheckbox(frameSortRow, 20, frameSortEnabled)
    frameSortBox:SetPoint("RIGHT", -25, 0)

    local frameSortCard = frameSortRow:CreateTexture(nil, "BACKGROUND", nil, 1)
    frameSortCard:SetColorTexture(0.10, 0.10, 0.10, 1)
    frameSortCard:SetPoint("TOPLEFT", 1, -1)
    frameSortCard:SetPoint("BOTTOMRIGHT", -1, 1)
    frameSortCard.__acSkipThemeRefresh = true

    -- Add hover effect
    frameSortRow:SetScript("OnEnter", function()
        frameSortCard:SetColorTexture(0.14, 0.14, 0.14, 1)
    end)
    frameSortRow:SetScript("OnLeave", function()
        frameSortCard:SetColorTexture(0.10, 0.10, 0.10, 1)
    end)
    
    -- Status icon (shows alert or checkmark)
    local frameSortStatusIcon = textDisplayContent:CreateTexture(nil, "OVERLAY")
    frameSortStatusIcon:SetSize(20, 20)  -- Slightly larger for better visibility
    frameSortStatusIcon:SetPoint("TOPLEFT", frameSortRow, "BOTTOMLEFT", 0, -4)
    frameSortStatusIcon:Hide()  -- Hidden by default
    
    -- Status/Warning Text
    local frameSortStatusText = textDisplayContent:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
    frameSortStatusText:SetPoint("LEFT", frameSortStatusIcon, "RIGHT", 4, 0)  -- Position after icon
    frameSortStatusText:SetJustifyH("LEFT")
    frameSortStatusText:SetWidth(380)
    
    -- Update status text function
    local function UpdateFrameSortStatus()
        local isEnabled = AC.DB and AC.DB.profile 
            and AC.DB.profile.arenaFrames 
            and AC.DB.profile.arenaFrames.general 
            and AC.DB.profile.arenaFrames.general.enableFrameSortIntegration or false
        local isDetected = FrameSortApi and FrameSortApi.v3
        
        if isEnabled and not isDetected then
            -- WARNING: Enabled but not detected - show alert icon
            frameSortStatusIcon:SetAtlas("Crosshair_Important_128")
            frameSortStatusIcon:SetVertexColor(1, 1, 1, 1)  -- Reset to white
            frameSortStatusIcon:Show()
            frameSortStatusText:SetText("|cffFF0000Warning:|r FrameSort addon not detected. Install FrameSort or disable integration.")
            frameSortStatusText:SetTextColor(1, 0.2, 0.2)
        elseif isEnabled and isDetected then
            -- SUCCESS: Enabled and detected - show green checkmark icon (same as unlock message)
            frameSortStatusIcon:SetAtlas("VAS-icon-checkmark-glw")
            frameSortStatusIcon:SetVertexColor(1, 1, 1, 1)  -- Reset to white (atlas has green built-in)
            frameSortStatusIcon:Show()
            frameSortStatusText:SetText("FrameSort detected and active")
            frameSortStatusText:SetTextColor(0.2, 1, 0.2)
        else
            -- DISABLED: No status needed - hide icon
            frameSortStatusIcon:Hide()
            frameSortStatusText:SetText("")
        end
    end
    
    -- Checkbox click handler
    frameSortBox:SetScript("OnClick", function(selfBtn)
        local isChecked = selfBtn:GetChecked()
        
        if AC.ProfileManager and AC.ProfileManager.SetSetting then
            AC.ProfileManager:SetSetting("arenaFrames.general.enableFrameSortIntegration", isChecked)
        else
            if AC.DB and AC.DB.profile and AC.DB.profile.arenaFrames and AC.DB.profile.arenaFrames.general then
                AC.DB.profile.arenaFrames.general.enableFrameSortIntegration = isChecked
            end
        end
        
        -- Update status text
        UpdateFrameSortStatus()
        
        -- Refresh frames immediately
        if AC.MasterFrameManager and AC.MasterFrameManager.UpdateFramePositions then
            AC.MasterFrameManager:UpdateFramePositions()
        end
        
        -- Refresh arena numbers
        if AC.RefreshArenaNumbers then
            AC:RefreshArenaNumbers()
        end
        
        -- Show warning if enabled but FrameSort not detected
        if isChecked and not (FrameSortApi and FrameSortApi.v3) then
            print("|cffFF0000[ArenaCore]|r FrameSort addon not detected! Please install FrameSort or disable integration.")
        end
    end)
    
    -- Initial status update
    UpdateFrameSortStatus()
    
    -- ▼ Name/Status Positioning (X/Y sliders for names/player names and status text)
    local namePositionSection = CreateCollapsibleSection(mainContainer, L("ARENA_FRAMES", "name_status_positioning", "Name/Status Positioning"), 0, false)
    namePositionSection.parent = mainContainer
    local namePositionContent = CreateSectionContent(mainContainer, namePositionSection, 205)
    
    -- Enhanced sliders with ultra-fine precision for text positioning
    AC:CreateEnhancedSliderRow(namePositionContent, L("ARENA_FRAMES", "player_names_horizontal", "Player Names Horizontal"), -25, "arenaFrames.general.playerNameX", "text_positioning_horizontal")
    AC:CreateEnhancedSliderRow(namePositionContent, L("ARENA_FRAMES", "player_names_vertical", "Player Names Vertical"), -55, "arenaFrames.general.playerNameY", "text_positioning_vertical")
    
    -- Health Text positioning sliders
    AC:CreateEnhancedSliderRow(namePositionContent, L("ARENA_FRAMES", "health_text_horizontal", "Health Text Horizontal"), -85, "arenaFrames.general.healthTextX", "text_positioning_horizontal")
    AC:CreateEnhancedSliderRow(namePositionContent, L("ARENA_FRAMES", "health_text_vertical", "Health Text Vertical"), -115, "arenaFrames.general.healthTextY", "text_positioning_vertical")
    
    -- Resource Text positioning sliders
    AC:CreateEnhancedSliderRow(namePositionContent, L("ARENA_FRAMES", "resource_text_horizontal", "Resource Text Horizontal"), -145, "arenaFrames.general.resourceTextX", "text_positioning_horizontal")
    AC:CreateEnhancedSliderRow(namePositionContent, L("ARENA_FRAMES", "resource_text_vertical", "Resource Text Vertical"), -175, "arenaFrames.general.resourceTextY", "text_positioning_vertical")
    
    -- ▼ Arena Number Positioning (Arena numbers positioning)
    local numberPositionSection = CreateCollapsibleSection(mainContainer, L("ARENA_FRAMES", "arena_number_positioning", "Arena Number Positioning"), 0, false)
    numberPositionSection.parent = mainContainer
    local numberPositionContent = CreateSectionContent(mainContainer, numberPositionSection, 85)
    
    -- Enhanced sliders with ultra-fine precision for arena number positioning
    AC:CreateEnhancedSliderRow(numberPositionContent, L("ARENA_FRAMES", "arena_numbers_horizontal", "Arena Numbers Horizontal"), -25, "arenaFrames.general.arenaNumberX", "arena_number_horizontal")
    AC:CreateEnhancedSliderRow(numberPositionContent, L("ARENA_FRAMES", "arena_numbers_vertical", "Arena Numbers Vertical"), -75, "arenaFrames.general.arenaNumberY", "arena_number_vertical")
    -- ▼ Text Scaling & Fonts (all the percentage sliders)
    local textScalingSection = CreateCollapsibleSection(mainContainer, L("ARENA_FRAMES", "text_scaling_fonts", "Text Scaling & Fonts"), 0, false)
    textScalingSection.parent = mainContainer
    local textScalingContent = CreateSectionContent(mainContainer, textScalingSection, 175)
    
    -- Enhanced sliders with ultra-fine precision for text scaling
    AC:CreateEnhancedSliderRow(textScalingContent, L("ARENA_FRAMES", "player_name_scale", "Player Name Scale"), -25, "arenaFrames.general.playerNameScale", "text_scaling_ultra")
    AC:CreateEnhancedSliderRow(textScalingContent, L("ARENA_FRAMES", "arena_number_scale", "Arena Number Scale"), -55, "arenaFrames.general.arenaNumberScale", "text_scaling_ultra")
    AC:CreateEnhancedSliderRow(textScalingContent, L("ARENA_FRAMES", "health_text_scale", "Health Text Scale"), -85, "arenaFrames.general.healthTextScale", "text_scaling_ultra")
    AC:CreateEnhancedSliderRow(textScalingContent, L("ARENA_FRAMES", "resource_text_scale", "Resource Text Scale"), -115, "arenaFrames.general.resourceTextScale", "text_scaling_ultra")
    AC:CreateEnhancedSliderRow(textScalingContent, L("ARENA_FRAMES", "spell_text_scale", "Spell Text Scale"), -145, "arenaFrames.general.spellTextScale", "text_scaling_ultra")
    -- ▼ Arena Frame Themes (NEW FEATURE)
    local frameThemesSection = CreateCollapsibleSection(mainContainer, L("ARENA_FRAMES", "arena_frame_themes", "Arena Frame Themes"), 0, false)
    frameThemesSection.parent = mainContainer
    local frameThemesContent = CreateSectionContent(mainContainer, frameThemesSection, 100)
    
    -- Theme selection dropdown
    local themeLabel = AC:CreateStyledText(frameThemesContent, L("ARENA_FRAMES", "frame_theme", "Frame Theme"), 11, AC.COLORS.TEXT_2, "OVERLAY", "")
    themeLabel:SetPoint("TOPLEFT", 20, -25)
    themeLabel:SetWidth(120)
    themeLabel:SetJustifyH("LEFT")
    
    -- Get current theme and available themes
    local currentTheme = "Arena Core" -- Default
    if AC.ArenaFrameThemes then
        currentTheme = AC.ArenaFrameThemes:GetCurrentTheme()
    end
    
    local themeOptions = {L("ARENA_FRAMES", "arena_core_theme", "Arena Core"), L("ARENA_FRAMES", "the_1500_special", "The 1500 Special"), L("ARENA_FRAMES", "just_blastin", "Just Blastin'")}
    
    local themeDropdown = AC:CreateFlatDropdown(frameThemesContent, 150, 24, themeOptions, currentTheme, function(selectedTheme)
        -- Apply theme in real-time
        -- SwitchTheme now shows a reload popup and returns false immediately
        -- The popup handles user feedback, so no need for success/fail messages here
        if AC.ArenaFrameThemes then
            AC.ArenaFrameThemes:SwitchTheme(selectedTheme)
        else
            print("|cffFF6B6B ArenaCore:|r Theme system not loaded yet")
        end
        
        -- CRITICAL: Update Width/Height slider visibility based on theme
        if AC.ArenaFramesPage_UpdateSizingSliders then
            AC:ArenaFramesPage_UpdateSizingSliders(selectedTheme)
        end
    end)
    themeDropdown:SetPoint("LEFT", themeLabel, "RIGHT", 10, 0)
    
    -- Theme description text
    local themeDesc = AC:CreateStyledText(frameThemesContent, L("ARENA_FRAMES", "theme_description", "Choose your preferred arena frame visual style"), 10, AC.COLORS.TEXT_3, "OVERLAY", "")
    themeDesc:SetPoint("TOPLEFT", 20, -8)
    themeDesc:SetPoint("TOPRIGHT", -20, -8)
    themeDesc:SetJustifyH("LEFT")
    themeDesc:SetWordWrap(true)
    
    -- Store sections in order for layout management
    mainContainer.sections = {
        textDisplay = textDisplaySection,
        namePosition = namePositionSection,
        numberPosition = numberPositionSection,
        textScaling = textScalingSection,
        frameThemes = frameThemesSection
    }
    
    mainContainer.sectionOrder = {
        textDisplaySection,
        namePositionSection,
        numberPositionSection,
        textScalingSection,
        frameThemesSection
    }
    
    -- Set up toggle callbacks for dynamic layout with throttling
    for _, section in ipairs(mainContainer.sectionOrder) do
        section.onToggle = function()
            C_Timer.After(0, function() 
                mainContainer:updateLayout()
                -- CRITICAL: Also push other groups down when ANY dropdown expands/collapses
                if mainContainer.pushOtherGroupsDown then
                    mainContainer:pushOtherGroupsDown()
                end
            end)
        end
    end
    
    -- Initial layout with scroll bar setup
    C_Timer.After(0.1, function() 
        mainContainer:updateLayout()
        if mainContainer.pushOtherGroupsDown then
            mainContainer:pushOtherGroupsDown()
        end
        -- ENHANCED: Initialize scroll bar range after layout is complete
        C_Timer.After(0.05, function()
            if mainContainer.pushOtherGroupsDown then
                mainContainer:pushOtherGroupsDown() -- This will set proper scroll range
            end
        end)
    end)
    
    return mainContainer
end

-- Create POSITIONING settings group
local function CreateGroup_POSITIONING(parent, y)
    local g = CreateFrame("Frame", nil, parent)
    g:SetPoint("TOPLEFT", 18, y)
    g:SetPoint("TOPRIGHT", -18, y)
    g:SetHeight(170)

    AC:HairlineGroupBox(g)

    local title = AC:CreateStyledText(g, L("ARENA_FRAMES", "section_positioning", "ARENA FRAME POSITIONING"), 13, COLORS.PRIMARY, "OVERLAY", "")
    title:SetPoint("TOPLEFT", 20, -18)

    -- POSITIONING SLIDERS: Save directly to horizontal/vertical (source of truth)
    -- These control the absolute position of the arena frames anchor
    AC:CreateEnhancedSliderRow(g, L("ARENA_FRAMES", "horizontal", "Horizontal"), -50, "arenaFrames.positioning.horizontal", "positioning_horizontal")
    AC:CreateEnhancedSliderRow(g, L("ARENA_FRAMES", "vertical", "Vertical"), -80, "arenaFrames.positioning.vertical", "positioning_vertical")
    AC:CreateEnhancedSliderRow(g, L("ARENA_FRAMES", "spacing", "Spacing"), -110, "arenaFrames.positioning.spacing", "spacing")
    
    -- Add Growth Direction dropdown
    local growthLabel = AC:CreateStyledText(g, L("ARENA_FRAMES", "growth_direction", "Growth Direction"), 11, COLORS.TEXT_2, "OVERLAY", "")
    growthLabel:SetPoint("TOPLEFT", 20, -140)
    growthLabel:SetWidth(100)
    growthLabel:SetJustifyH("LEFT")
    
        local growthDir = S:Get("arenaFrames.positioning.growthDirection", "Down")
    local growthDropdown = AC:CreateFlatDropdown(g, 120, 24, {L("ARENA_FRAMES", "down", "Down"), L("ARENA_FRAMES", "up", "Up"), L("ARENA_FRAMES", "right", "Right"), L("ARENA_FRAMES", "left", "Left")}, growthDir, function(value)
        AC:OnArenaFramesGrowthDirectionChanged(value)
    end)
    growthDropdown:SetPoint("LEFT", growthLabel, "RIGHT", 10, 0)
    
    AC.growthDirectionDropdown = growthDropdown
    
    return g
end

local function CreateArenaFramesTabButton(parent, text, width, height)
    local COLORS = AC.COLORS or {}

    local btn = CreateFrame("Button", nil, parent)
    btn:SetSize(width or 102, height or 30)

    local bg = AC:CreateFlatTexture(btn, "BACKGROUND", 0, {0.06, 0.06, 0.06, 1}, 1)
    bg:SetAllPoints()
    btn.bg = bg

    local hover = AC:CreateFlatTexture(btn, "ARTWORK", 1, COLORS.BORDER_LIGHT or {0.278, 0.278, 0.278, 1}, 0.15)
    hover:SetAllPoints()
    hover:Hide()
    btn.hover = hover

    local glow = btn:CreateTexture(nil, "OVERLAY")
    glow:SetTexture("Interface\\AddOns\\ArenaCore\\Media\\UI\\tab-purple-matte.tga")
    glow:SetAllPoints()
    glow:SetBlendMode("ADD")
    glow:SetAlpha(0)
    btn.glow = glow

    local function CreateGlowLine()
        local t = btn:CreateTexture(nil, "OVERLAY")
        local c = COLORS.PRIMARY or {0.545, 0.271, 1.000, 1}
        t:SetColorTexture(c[1], c[2], c[3], 1)
        if t.SetSnapToPixelGrid then t:SetSnapToPixelGrid(true) end
        if t.SetTexelSnappingBias then t:SetTexelSnappingBias(0) end
        t:Hide()
        return t
    end

    local outlineTop = CreateGlowLine()
    outlineTop:SetPoint("TOPLEFT", btn, "TOPLEFT", 1, 0)
    outlineTop:SetPoint("TOPRIGHT", btn, "TOPRIGHT", -1, 0)
    outlineTop:SetHeight(1)

    local outlineBottom = CreateGlowLine()
    outlineBottom:SetPoint("BOTTOMLEFT", btn, "BOTTOMLEFT", 1, 1)
    outlineBottom:SetPoint("BOTTOMRIGHT", btn, "BOTTOMRIGHT", -1, 1)
    outlineBottom:SetHeight(1)

    local outlineLeft = CreateGlowLine()
    outlineLeft:SetPoint("TOPLEFT", btn, "TOPLEFT", 0, -1)
    outlineLeft:SetPoint("BOTTOMLEFT", btn, "BOTTOMLEFT", 0, 1)
    outlineLeft:SetWidth(1)

    local outlineRight = CreateGlowLine()
    outlineRight:SetPoint("TOPRIGHT", btn, "TOPRIGHT", 0, -1)
    outlineRight:SetPoint("BOTTOMRIGHT", btn, "BOTTOMRIGHT", 0, 1)
    outlineRight:SetWidth(1)

    btn.outlineTop = outlineTop
    btn.outlineBottom = outlineBottom
    btn.outlineLeft = outlineLeft
    btn.outlineRight = outlineRight

    local label = AC:CreateStyledText(btn, text or "", 11, (COLORS.TEXT_2 or {0.706, 0.706, 0.706, 1}), "OVERLAY", "")
    label:SetPoint("CENTER", 0, 0)
    btn.label = label

    btn.isSelected = false

    function btn:SetSelected(selected)
        self.isSelected = selected and true or false

        if self.isSelected then
            self.bg:SetColorTexture(0.11, 0.11, 0.11, 1)
            self.hover:Hide()
            self.outlineTop:Show()
            self.outlineBottom:Show()
            self.outlineLeft:Show()
            self.outlineRight:Show()
            if self.glow then
                self.glow:SetAlpha(0.22)
            end
            self.label:SetTextColor((COLORS.TEXT and COLORS.TEXT[1]) or 1, (COLORS.TEXT and COLORS.TEXT[2]) or 1, (COLORS.TEXT and COLORS.TEXT[3]) or 1, 1)
        else
            self.bg:SetColorTexture(0.06, 0.06, 0.06, 1)
            self.outlineTop:Hide()
            self.outlineBottom:Hide()
            self.outlineLeft:Hide()
            self.outlineRight:Hide()
            if self.glow then
                self.glow:SetAlpha(0)
            end
            self.label:SetTextColor((COLORS.TEXT_2 and COLORS.TEXT_2[1]) or 0.706, (COLORS.TEXT_2 and COLORS.TEXT_2[2]) or 0.706, (COLORS.TEXT_2 and COLORS.TEXT_2[3]) or 0.706, 1)
        end
    end

    btn:SetScript("OnEnter", function(selfBtn)
        if not selfBtn.isSelected then
            selfBtn.hover:Show()
            selfBtn.outlineTop:Show()
            selfBtn.outlineBottom:Show()
            selfBtn.outlineLeft:Show()
            selfBtn.outlineRight:Show()
            if selfBtn.glow then
                selfBtn.glow:SetAlpha(0.22)
            end
            selfBtn.label:SetTextColor((COLORS.TEXT and COLORS.TEXT[1]) or 1, (COLORS.TEXT and COLORS.TEXT[2]) or 1, (COLORS.TEXT and COLORS.TEXT[3]) or 1, 1)
        end
    end)

    btn:SetScript("OnLeave", function(selfBtn)
        if not selfBtn.isSelected then
            selfBtn.hover:Hide()
            selfBtn.outlineTop:Hide()
            selfBtn.outlineBottom:Hide()
            selfBtn.outlineLeft:Hide()
            selfBtn.outlineRight:Hide()
            if selfBtn.glow then
                selfBtn.glow:SetAlpha(0)
            end
            selfBtn.label:SetTextColor((COLORS.TEXT_2 and COLORS.TEXT_2[1]) or 0.706, (COLORS.TEXT_2 and COLORS.TEXT_2[2]) or 0.706, (COLORS.TEXT_2 and COLORS.TEXT_2[3]) or 0.706, 1)
        end
    end)

    return btn
end

-- Create SIZING settings group
local function CreateGroup_SIZING(parent, y)
    local g = CreateFrame("Frame", nil, parent)
    g:SetPoint("TOPLEFT", 18, y)
    g:SetPoint("TOPRIGHT", -18, y)
    g:SetHeight(310)

    AC:HairlineGroupBox(g)

    local title = AC:CreateStyledText(g, L("ARENA_FRAMES", "section_sizing", "ARENA FRAME SIZING"), 13, COLORS.PRIMARY, "OVERLAY", "")
    title:SetPoint("TOPLEFT", 20, -18)

    -- All controls stored in order with optional theme requirement
    -- theme = nil means always visible, otherwise only shown for that theme
    local SPACING = 30
    local START_Y = -50
    g.sizingControls = {}
    
    local function AddControl(frame, theme)
        table.insert(g.sizingControls, { frame = frame, theme = theme })
    end
    
    -- Scale (always visible)
    AddControl(AC:CreateEnhancedSliderRow(g, L("COMMON", "scale", "Scale"), START_Y, "arenaFrames.sizing.scale", "sizing_scale"), nil)
    
    -- Just Blastin' only: pixel border thickness (1-5px, whole numbers)
    AddControl(AC:CreateEnhancedSliderRow(g, L("ARENA_FRAMES", "border_thickness", "Border Thickness"), START_Y, "arenaFrames.sizing.borderThickness", "pixel_border_thickness"), "Just Blastin'")
    
    -- Arena Core only: frame sizing controls
    AddControl(AC:CreateEnhancedSliderRow(g, L("COMMON", "width", "Frame Width"), START_Y, "arenaFrames.sizing.width", "sizing_width"), "Arena Core")
    AddControl(AC:CreateEnhancedSliderRow(g, L("COMMON", "height", "Frame Height"), START_Y, "arenaFrames.sizing.height", "sizing_height"), "Arena Core")
    
    -- Arena Core only: background color dropdown
    local currentBgColor = AC.DB and AC.DB.profile and AC.DB.profile.arenaFrames and 
                           AC.DB.profile.arenaFrames.sizing and 
                           AC.DB.profile.arenaFrames.sizing.arenaCoreBackgroundColor or "dark"
    
    AddControl(CreateLinkedDropdown(
        g,
        L("ARENA_FRAMES", "background_color", "Background Color"),
        START_Y,
        "arenaFrames.sizing.arenaCoreBackgroundColor",
        {
            {text = L("ARENA_FRAMES", "dark", "Dark"), value = "dark"},
            {text = L("ARENA_FRAMES", "original", "Original"), value = "original"}
        },
        currentBgColor,
        function(value)
            -- Apply background color change immediately
            if AC.ArenaFrameThemes and AC.ArenaFrameThemes.ApplyArenaCoreBackgroundColor then
                AC.ArenaFrameThemes:ApplyArenaCoreBackgroundColor(value)
            end

            -- Persist across reload: theme loader restores profile from themeData
            if AC.DB and AC.DB.profile and AC.ArenaFrameThemes and AC.ArenaFrameThemes.GetCurrentTheme then
                local themeName = AC.ArenaFrameThemes:GetCurrentTheme()
                if themeName == "Arena Core" then
                    AC.DB.profile.themeData = AC.DB.profile.themeData or {}
                    AC.DB.profile.themeData[themeName] = AC.DB.profile.themeData[themeName] or {}
                    AC.DB.profile.themeData[themeName].arenaFrames = AC.DB.profile.themeData[themeName].arenaFrames or {}
                    AC.DB.profile.themeData[themeName].arenaFrames.sizing = AC.DB.profile.themeData[themeName].arenaFrames.sizing or {}
                    AC.DB.profile.themeData[themeName].arenaFrames.sizing.arenaCoreBackgroundColor = value
                end
            end
        end
    ), "Arena Core")
    
    -- Always visible: target highlight settings
    AddControl(AC:CreateEnhancedSliderRow(g, L("ARENA_FRAMES", "target_border_thickness", "Target Border Thickness"), START_Y, "arenaFrames.sizing.targetBorderThickness", "target_border_thickness"), nil)
    AddControl(CreateColorPickerSetting(g, L("ARENA_FRAMES", "target_border_color", "Target Border Color"), START_Y, "arenaFrames.sizing.targetBorderColor", { 1, 0.6, 0, 1 }), nil)
    AddControl(CreateCheckboxSetting(g, L("ARENA_FRAMES", "disable_target_highlight", "Disable Target Highlight"), START_Y, "arenaFrames.sizing.disableTargetHighlight"), nil)
    AddControl(CreateCheckboxSetting(g, L("ARENA_FRAMES", "target_highlight_on_class_icon", "Target Highlight On Class Icon Instead"), START_Y, "arenaFrames.sizing.targetHighlightOnClassIcon"), nil)
    
    -- Dynamic relayout: repositions visible controls so there are no gaps
    function g:RelayoutControls(themeName)
        local yPos = START_Y
        for _, entry in ipairs(self.sizingControls) do
            local visible = (entry.theme == nil) or (entry.theme == themeName)
            entry.frame:SetShown(visible)
            if visible then
                entry.frame:ClearAllPoints()
                entry.frame:SetPoint("TOPLEFT", 20, yPos)
                entry.frame:SetPoint("TOPRIGHT", -20, yPos)
                yPos = yPos - SPACING
            end
        end
    end
    
    return g
end

function AC:SaveSettingsToDisk()
        -- CRITICAL FIX: Save ALL settings to disk, not just position!
        -- The button is called "Save Settings" so it should save EVERYTHING
        
        if not AC or not AC.DB then
            print("|cffFF0000ArenaCore:|r Database not available!")
            return
        end
        
        -- Force WoW to write the saved variables to disk
        -- This ensures all current settings (including scale, width, height, etc.) are persisted
        if AC.DB.profile then
            -- Mark the database as changed so WoW will save it
            AC.DB.profile.lastSaved = time()
            
            print("|cff8B45FFArena Core:|r All settings saved to disk!")
            print("|cff8B45FFArena Core:|r Scale: " .. tostring(AC.DB.profile.arenaFrames.sizing.scale) .. "%, Width: " .. tostring(AC.DB.profile.arenaFrames.sizing.width) .. "px, Height: " .. tostring(AC.DB.profile.arenaFrames.sizing.height) .. "px")
            
            -- Play custom ArenaCore save sound for feedback
            PlaySoundFile("Interface/AddOns/ArenaCore/Media/Sounds/InfoSaved.mp3", "Master")
        else
            print("|cffFF0000ArenaCore:|r Could not access database profile!")
        end
end

-- Create the tab row with action buttons
local function CreateTabRow(parent)
  local prev = { parent:GetChildren() }
  for _, ch in ipairs(prev) do ch:Hide(); ch:SetParent(nil) end

  local row = CreateFrame("Frame", nil, parent)
  row:SetAllPoints()

    -- ============================================================================
    -- EDIT MODE BUTTON - DISABLED
    -- ============================================================================
    -- Edit Mode removed to eliminate positioning drift
    -- 
    -- WHY REMOVED:
    -- - GetPoint() capture accumulated floating-point errors
    -- - Result: 1-3 pixel drift after multiple theme switches
    --
    -- SOLUTION:
    -- - Use sliders for positioning (single source of truth)
    -- - No position capture = no feedback loop = ZERO DRIFT
    --
    -- LEGACY CODE:
    -- - Edit Mode files moved to legacy/ folder
    -- - Can be restored if needed in future
    -- - See POSITIONING_RESEARCH.md for details
    -- ============================================================================
    
    -- Edit Mode button code INTENTIONALLY REMOVED
    -- Users now use sliders on Trinkets/Other page for positioning
    -- Sliders provide precise 1-pixel control without drift

    -- Create a second row for lock/unlock buttons below the first row
    local lockRow = CreateFrame("Frame", nil, parent)
    lockRow:SetSize(parent:GetWidth() - 24, 32)
    lockRow:SetPoint("TOP", row, "BOTTOM", 0, -4)
    
    -- Create ProfileStyle buttons for Unlock/Lock
    local unlockBtn = AC:CreateProfileStyleButton(lockRow, 100, 28, L("ARENA_FRAMES", "unlock", "Unlock"), "primary", 11)
    unlockBtn:SetPoint("LEFT", 12, 0)
    
    unlockBtn:SetScript("OnClick", function()
        -- CRITICAL FIX: Call EnableFrameDragging() to properly set up drag system
        if AC.EnableFrameDragging then
            AC:EnableFrameDragging()
        else
            AC.framesLocked = false
            print("|cffFF0000ArenaCore:|r EnableFrameDragging function not available!")
        end
        if AC.IsUIVisible and AC.currentPage == "ArenaFrames" and AC.ShowPage then
            AC:ShowPage("ArenaFrames")
        end
    end)
    
    local lockBtn = AC:CreateProfileStyleButton(lockRow, 100, 28, L("ARENA_FRAMES", "lock", "Lock"), "primary", 11)
    lockBtn:SetPoint("LEFT", unlockBtn, "RIGHT", 8, 0)
    
    lockBtn:SetScript("OnClick", function()
        -- CRITICAL FIX: Call DisableFrameDragging() to properly disable drag system
        if AC.DisableFrameDragging then
            AC:DisableFrameDragging()
        else
            AC.framesLocked = true
            print("|cffFF0000ArenaCore:|r DisableFrameDragging function not available!")
        end
        if AC.IsUIVisible and AC.currentPage == "ArenaFrames" and AC.ShowPage then
            AC:ShowPage("ArenaFrames")
        end
    end)

    -- Add drag instruction alert message across from the buttons (five lines)
    local dragAlert1 = AC:CreateStyledText(lockRow, L("ARENA_FRAMES", "ctrl_alt_left_click", "Ctrl+Alt+Left Click"), 10, COLORS.TEXT_2, "OVERLAY", "")
    dragAlert1:SetPoint("RIGHT", -12, 28)
    dragAlert1:SetJustifyH("RIGHT")
    dragAlert1:SetTextColor(0.8, 0.9, 1.0, 0.9) -- Light blue tint
    
    local dragAlert2 = AC:CreateStyledText(lockRow, L("ARENA_FRAMES", "to_drag_frames", "to drag frames!"), 10, COLORS.TEXT_2, "OVERLAY", "")
    dragAlert2:SetPoint("RIGHT", -12, 18)
    dragAlert2:SetJustifyH("RIGHT")
    dragAlert2:SetTextColor(0.8, 0.9, 1.0, 0.9) -- Light blue tint
    
    local dragAlert3 = AC:CreateStyledText(lockRow, L("ARENA_FRAMES", "shift_left_click", "Shift+Left Click"), 10, COLORS.TEXT_2, "OVERLAY", "")
    dragAlert3:SetPoint("RIGHT", -12, 8)
    dragAlert3:SetJustifyH("RIGHT")
    dragAlert3:SetTextColor(0.8, 0.9, 1.0, 0.9) -- Light blue tint
    
    local dragAlert4 = AC:CreateStyledText(lockRow, L("ARENA_FRAMES", "to_drag_elements", "to drag Cast Bars, Trinkets,"), 10, COLORS.TEXT_2, "OVERLAY", "")
    dragAlert4:SetPoint("RIGHT", -12, -2)
    dragAlert4:SetJustifyH("RIGHT")
    dragAlert4:SetTextColor(0.8, 0.9, 1.0, 0.9) -- Light blue tint
    
    local dragAlert5 = AC:CreateStyledText(lockRow, L("ARENA_FRAMES", "racials_spec_class_icons", "Racials, Spec Icons, or Class Icons!"), 10, COLORS.TEXT_2, "OVERLAY", "")
    dragAlert5:SetPoint("RIGHT", -12, -12)
    dragAlert5:SetJustifyH("RIGHT")
    dragAlert5:SetTextColor(0.8, 0.9, 1.0, 0.9) -- Light blue tint

    AC:PurgeFakeHideTest(row)
    row:SetScript("OnShow", function() AC:PurgeFakeHideTest(row) end)

    AC.tabContainer = parent
end

function AC:OnArenaFramesSliderChanged(slider, path, value)
    -- CRITICAL: Don't save if drag just finished (prevents overwriting drag position)
    if AC.justFinishedDragging then
        return
    end
    
    -- Use both settings systems to ensure consistency
    if S and S.Set then
        S:Set(path, value)
    end

    -- ALSO save to the DB directly for immediate access
    if AC and AC.EnsureDB and AC.SetPath then
        AC:EnsureDB()
        -- Only accept paths under arenaFrames.*
        if type(path) == "string" and path:match("^arenaFrames%.") then
            AC:SetPath(AC.DB.profile, path, value)
            _G.ArenaCoreDB = AC.DB
            
            -- CRITICAL: ALSO save to theme-specific settings for theme isolation
            if AC.ArenaFrameThemes then
                local currentTheme = AC.ArenaFrameThemes:GetCurrentTheme()
                if currentTheme then
                    -- Initialize theme data structure if needed
                    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 to theme-specific location
                    AC:SetPath(AC.DB.profile.themeData[currentTheme], path, value)
                end
            end
        end
    end

    -- Apply changes to Master Frame Manager system immediately
    if path:find("arenaFrames.positioning") then
        -- Handle positioning changes (horizontal, vertical, spacing)
        -- CRITICAL FIX: Only call UpdateFramePositions ONCE (not twice)
        -- MasterFrameManager.UpdateFramePositions is the authoritative function
        if AC.MasterFrameManager and AC.MasterFrameManager.UpdateFramePositions then
            AC.MasterFrameManager:UpdateFramePositions()
        elseif AC.UpdateFramePositions then
            AC:UpdateFramePositions()
        end
    elseif path:find("arenaFrames.sizing.scale") then
        -- Handle scale changes
        if AC.UpdateFrameScale then
            AC:UpdateFrameScale()
        end
        -- CRITICAL: Trigger position refresh to show scale changes immediately
        if AC.MasterFrameManager and AC.MasterFrameManager.UpdateFramePositions then
            AC.MasterFrameManager:UpdateFramePositions()
        elseif AC.UpdateFramePositions then
            AC:UpdateFramePositions()
        end
        print("|cff8B45FFArena Core:|r Scale updated!")
    elseif path:find("arenaFrames.sizing") then
        -- Handle size changes (width, height)
        if AC.UpdateFrameSize then
            AC:UpdateFrameSize()
        end
        -- CRITICAL: Trigger position refresh to show size changes immediately
        if AC.MasterFrameManager and AC.MasterFrameManager.UpdateFramePositions then
            AC.MasterFrameManager:UpdateFramePositions()
        elseif AC.UpdateFramePositions then
            AC:UpdateFramePositions()
        end
        
        print("|cff8B45FFArena Core:|r Size updated!")
    elseif path:find("arenaFrames.general") then
        -- Handle general settings
        if AC.RefreshAllFrames then
            AC:RefreshAllFrames()
        end
        print("|cff8B45FFArena Core:|r Settings updated!")
    end
end

function AC:OnArenaFramesCheckboxToggle(checkbox, path, checked)
    S:Set(path, checked)

    -- Apply changes to Master Frame Manager system immediately
    if path:find("arenaFrames.general") then
        if AC.RefreshAllFrames then
            AC:RefreshAllFrames()
        end
        print("|cff8B45FFArena Core:|r " .. (path:gsub(".*%.", "")) .. " " .. (checked and "enabled" or "disabled") .. "!")
    end
end

function AC:OnArenaFramesGrowthDirectionChanged(direction)
    -- Set flag to indicate this is a UI control change (for smart positioning refresh)
    AC._isSliderChange = true
    
    S:Set("arenaFrames.positioning.growthDirection", direction)
    
    -- Apply changes to Master Frame Manager system immediately
    if AC.UpdateFramePositions then
        AC:UpdateFramePositions()
    end
    if AC.MasterFrameManager and AC.MasterFrameManager.UpdateFramePositions then
        AC.MasterFrameManager:UpdateFramePositions()
    end
    print("|cff8B45FFArena Core:|r Growth direction: " .. direction)
    
    -- Clear the flag after processing
    AC._isSliderChange = false
end

-- ============================================================================
-- DUPLICATE CreateTabRow REMOVED - Using the proper textured version above (line 856)
-- ============================================================================

-- RESTRUCTURED: Work exactly like other pages using the main content area
local function CreateArenaFramesPage(root)
    if V and V.EnsureMottoStrip then V:EnsureMottoStrip(root) end
    
    local strip = CreateFrame("Frame", nil, root)
    strip:SetHeight(136)
    if strip.SetClipsChildren then
        strip:SetClipsChildren(false)
    end

    if root._mottoStrip then
        strip:SetPoint("TOPLEFT", root._mottoStrip, "BOTTOMLEFT", 0, -8)
        strip:SetPoint("TOPRIGHT", root._mottoStrip, "BOTTOMRIGHT", 0, -8)
    else
        strip:SetPoint("TOPLEFT", 6, -52)
        strip:SetPoint("TOPRIGHT", -6, -52)
    end

    local sBorder = AC:CreateFlatTexture(strip, "BACKGROUND", 1, COLORS.BORDER_LIGHT, 0.6)
    sBorder:SetAllPoints()

    local sFill = AC:CreateFlatTexture(strip, "BACKGROUND", 2, {0.12, 0.12, 0.12, 1}, 1)
    sFill:SetPoint("TOPLEFT", 1, -1)
    sFill:SetPoint("BOTTOMRIGHT", -1, 1)

    local tabRow = CreateFrame("Frame", nil, strip)
    tabRow:SetHeight(88)
    tabRow:SetFrameLevel((strip:GetFrameLevel() or 1) + 2)
    if tabRow.SetClipsChildren then
        tabRow:SetClipsChildren(false)
    end
    tabRow:SetPoint("TOPLEFT", 0, -6)
    tabRow:SetPoint("TOPRIGHT", 0, -6)

    local tabs = {}
    local contentFrames = {}
    local activeTab = "general"

    local function SetArenaFramesScrollEnabled(enabled)
        if AC and AC.contentArea and AC.contentArea.EnableMouseWheel then
            AC.contentArea:EnableMouseWheel(enabled and true or false)
        end
    end

    local function SetActiveTab(id)
        activeTab = id
        for _, b in ipairs(tabs) do
            b:SetSelected(b._tabId == id)
        end
        for pid, f in pairs(contentFrames) do
            if pid == id then
                f:Show()
            else
                f:Hide()
            end
        end
        if AC.UpdateContentHeight then
            C_Timer.After(0.05, function()
                AC:UpdateContentHeight()
            end)
        end

        -- Enable scrolling for all tabs
        SetArenaFramesScrollEnabled(true)
    end

    local btnGeneral = CreateArenaFramesTabButton(tabRow, L("ARENA_FRAMES", "tab_general", "General"), 102, 30)
    btnGeneral._tabId = "general"
    btnGeneral:SetPoint("TOPLEFT", 18, -2)
    table.insert(tabs, btnGeneral)

    local btnPositioning = CreateArenaFramesTabButton(tabRow, L("ARENA_FRAMES", "tab_positioning", "Positioning"), 110, 30)
    btnPositioning._tabId = "positioning"
    btnPositioning:SetPoint("LEFT", btnGeneral, "RIGHT", 8, 0)
    table.insert(tabs, btnPositioning)

    local btnSizing = CreateArenaFramesTabButton(tabRow, L("ARENA_FRAMES", "tab_sizing", "Sizing"), 90, 30)
    btnSizing._tabId = "sizing"
    btnSizing:SetPoint("LEFT", btnPositioning, "RIGHT", 8, 0)
    table.insert(tabs, btnSizing)

    local btnAuras = CreateArenaFramesTabButton(tabRow, L("ARENA_FRAMES", "tab_auras", "Auras"), 102, 30)
    btnAuras._tabId = "auras"
    btnAuras:SetPoint("TOPLEFT", btnGeneral, "BOTTOMLEFT", 0, -10)
    table.insert(tabs, btnAuras)

    local btnDebuffs = CreateArenaFramesTabButton(tabRow, L("ARENA_FRAMES", "tab_debuffs", "Debuffs"), 110, 30)
    btnDebuffs._tabId = "debuffs"
    btnDebuffs:SetPoint("TOPLEFT", btnPositioning, "BOTTOMLEFT", 0, -10)
    table.insert(tabs, btnDebuffs)

    local btnAbsorbs = CreateArenaFramesTabButton(tabRow, L("ARENA_FRAMES", "tab_absorbs", "Absorbs"), 90, 30)
    btnAbsorbs._tabId = "absorbs"
    btnAbsorbs:SetPoint("LEFT", btnDebuffs, "RIGHT", 8, 0)
    table.insert(tabs, btnAbsorbs)

    local lockRow = CreateFrame("Frame", nil, strip)
    lockRow:SetHeight(28)
    do
        local lockRowLevel = (tabRow:GetFrameLevel() or 2) - 1
        if lockRowLevel < 1 then lockRowLevel = 1 end
        lockRow:SetFrameLevel(lockRowLevel)
    end
    lockRow:SetPoint("TOPLEFT", tabRow, "BOTTOMLEFT", 0, -10)
    lockRow:SetPoint("TOPRIGHT", tabRow, "BOTTOMRIGHT", 0, -10)

    local unlockBtn = AC:CreateProfileStyleButton(lockRow, 100, 28, L("ARENA_FRAMES", "unlock", "Unlock"), "primary", 11)
    unlockBtn:SetPoint("LEFT", 18, 0)
    unlockBtn:SetScript("OnClick", function()
        if AC.EnableFrameDragging then
            AC:EnableFrameDragging()
        else
            AC.framesLocked = false
            print("|cffFF0000ArenaCore:|r EnableFrameDragging function not available!")
        end
        if AC.IsUIVisible and AC.currentPage == "ArenaFrames" and AC.ShowPage then
            AC:ShowPage("ArenaFrames")
        end
    end)

    local lockBtn = AC:CreateProfileStyleButton(lockRow, 100, 28, L("ARENA_FRAMES", "lock", "Lock"), "primary", 11)
    lockBtn:SetPoint("LEFT", unlockBtn, "RIGHT", 8, 0)
    lockBtn:SetScript("OnClick", function()
        if AC.DisableFrameDragging then
            AC:DisableFrameDragging()
        else
            AC.framesLocked = true
            print("|cffFF0000ArenaCore:|r DisableFrameDragging function not available!")
        end
        if AC.IsUIVisible and AC.currentPage == "ArenaFrames" and AC.ShowPage then
            AC:ShowPage("ArenaFrames")
        end
    end)

    local dragAlert1 = AC:CreateStyledText(lockRow, L("ARENA_FRAMES", "ctrl_alt_left_click", "Ctrl+Alt+Left Click"), 10, COLORS.TEXT_2, "OVERLAY", "")
    dragAlert1:SetPoint("RIGHT", -12, 28)
    dragAlert1:SetJustifyH("RIGHT")
    dragAlert1:SetTextColor(0.8, 0.9, 1.0, 0.9)

    local dragAlert2 = AC:CreateStyledText(lockRow, L("ARENA_FRAMES", "to_drag_frames", "to drag frames!"), 10, COLORS.TEXT_2, "OVERLAY", "")
    dragAlert2:SetPoint("RIGHT", -12, 18)
    dragAlert2:SetJustifyH("RIGHT")
    dragAlert2:SetTextColor(0.8, 0.9, 1.0, 0.9)

    local dragAlert3 = AC:CreateStyledText(lockRow, L("ARENA_FRAMES", "shift_left_click", "Shift+Left Click"), 10, COLORS.TEXT_2, "OVERLAY", "")
    dragAlert3:SetPoint("RIGHT", -12, 8)
    dragAlert3:SetJustifyH("RIGHT")
    dragAlert3:SetTextColor(0.8, 0.9, 1.0, 0.9)

    local dragAlert4 = AC:CreateStyledText(lockRow, L("ARENA_FRAMES", "to_drag_elements", "to drag Cast Bars, Trinkets,"), 10, COLORS.TEXT_2, "OVERLAY", "")
    dragAlert4:SetPoint("RIGHT", -12, -2)
    dragAlert4:SetJustifyH("RIGHT")
    dragAlert4:SetTextColor(0.8, 0.9, 1.0, 0.9)
    
    local dragAlert5 = AC:CreateStyledText(lockRow, L("ARENA_FRAMES", "racials_spec_class_icons", "Racials, Spec Icons, or Class Icons!"), 10, COLORS.TEXT_2, "OVERLAY", "")
    dragAlert5:SetPoint("RIGHT", -12, -12)
    dragAlert5:SetJustifyH("RIGHT")
    dragAlert5:SetTextColor(0.8, 0.9, 1.0, 0.9)

    local contentRoot = CreateFrame("Frame", nil, root)
    contentRoot:SetPoint("TOPLEFT", strip, "BOTTOMLEFT", 0, -10)
    contentRoot:SetPoint("TOPRIGHT", strip, "BOTTOMRIGHT", 0, -10)
    contentRoot:SetPoint("BOTTOMLEFT", 0, 0)
    contentRoot:SetPoint("BOTTOMRIGHT", 0, 0)

    local function EnsureContentFrame(id)
        if contentFrames[id] then return contentFrames[id] end
        local f = CreateFrame("Frame", nil, contentRoot)
        f:SetAllPoints()
        f:Hide()
        contentFrames[id] = f
        return f
    end

    local function BuildGeneral()
        local f = EnsureContentFrame("general")
        if f._built then return end

        local expandHint = CreateFrame("Frame", nil, f)
        expandHint:SetHeight(18)
        expandHint:SetPoint("TOPLEFT", 18, -6)
        expandHint:SetPoint("TOPRIGHT", -18, -6)

        local hintIcon = expandHint:CreateTexture(nil, "OVERLAY")
        hintIcon:SetSize(14, 14)
        hintIcon:SetPoint("LEFT", 0, 0)
        if hintIcon.SetAtlas then
            hintIcon:SetAtlas("UI-Dialog-Icon-AlertNew", true)
        else
            hintIcon:SetTexture("Interface\\DialogFrame\\UI-Dialog-Icon-AlertNew")
        end

        local hintText = AC:CreateStyledText(expandHint, L("ARENA_FRAMES", "expand_hint", "Click a section below to expand detailed options"), 11, {1.0, 0.55, 0.0, 1}, "OVERLAY", "")
        hintText:SetPoint("LEFT", hintIcon, "RIGHT", 6, 0)
        hintText:SetJustifyH("LEFT")

        local generalGroup = CreateGroup_GENERAL(f, -34)
        if generalGroup and generalGroup.pushOtherGroupsDown then
            generalGroup.pushOtherGroupsDown = function()
                if AC.UpdateContentHeight then
                    C_Timer.After(0.05, function()
                        AC:UpdateContentHeight()
                    end)
                end
            end
        end
        f._built = true
    end

    local function BuildAbsorbs()
        local f = EnsureContentFrame("absorbs")
        if f._built then return end

        local function EnsureAbsorbsDB()
            AC.DB = AC.DB or {}
            AC.DB.profile = AC.DB.profile or {}
            AC.DB.profile.moreGoodies = AC.DB.profile.moreGoodies or {}
            AC.DB.profile.moreGoodies.absorbs = AC.DB.profile.moreGoodies.absorbs or {}
            if AC.DB.profile.moreGoodies.absorbs.enabled == nil then
                AC.DB.profile.moreGoodies.absorbs.enabled = true
            end
            return AC.DB.profile.moreGoodies.absorbs
        end

        local absorbsDB = EnsureAbsorbsDB()

        local g = CreateFrame("Frame", nil, f)
        g:SetPoint("TOPLEFT", 18, -12)
        g:SetPoint("TOPRIGHT", -18, -12)
        g:SetHeight(210)
        AC:HairlineGroupBox(g)

        local title = AC:CreateStyledText(g, L("ARENA_FRAMES", "section_absorbs", "ABSORBS"), 13, COLORS.PRIMARY, "OVERLAY", "")
        title:SetPoint("TOPLEFT", 20, -18)

        local label = AC:CreateStyledText(g, L("ARENA_FRAMES", "tab_absorbs", "Absorbs"), 12, COLORS.TEXT_2, "OVERLAY", "")
        label:SetPoint("TOPLEFT", 20, -50)

        local checkbox = AC:CreateFlatCheckbox(g, 20, absorbsDB.enabled ~= false, function(value)
            local db = EnsureAbsorbsDB()
            db.enabled = value

            if AC.Absorbs and AC.Absorbs.UpdateAllAbsorbs then
                AC.Absorbs:UpdateAllAbsorbs()
            end

            if not value and AC.Absorbs and AC.Absorbs.HideLines then
                AC.Absorbs:HideLines()
            end
        end)
        checkbox:SetPoint("TOPRIGHT", -25, -50)

        local descText = AC:CreateStyledText(g, L("ARENA_FRAMES", "absorbs_description", "Shows absorb shields on enemy health bars (green for magic, white for physical). Absorbs will also pulse/glow when target has an immunity on (I.E. Cloak of Shadows, Blessing of Protection etc.)"), 10, COLORS.TEXT_MUTED, "OVERLAY", "")
        descText:SetPoint("TOPLEFT", 20, -78)
        descText:SetPoint("TOPRIGHT", -20, -78)
        descText:SetJustifyH("LEFT")
        descText:SetWordWrap(true)

        f._built = true
    end

    local function BuildAuras()
        local f = EnsureContentFrame("auras")
        -- Removed _built check to ensure slider refreshes with current database value each time

        local function EnsureAurasDB()
            AC.DB = AC.DB or {}
            AC.DB.profile = AC.DB.profile or {}
            AC.DB.profile.classIcons = AC.DB.profile.classIcons or {}
            AC.DB.profile.moreGoodies = AC.DB.profile.moreGoodies or {}
            AC.DB.profile.moreGoodies.auras = AC.DB.profile.moreGoodies.auras or {}
            if AC.DB.profile.classIcons.spiralGlowLine == nil then
                AC.DB.profile.classIcons.spiralGlowLine = true
            end
            if AC.DB.profile.classIcons.showImportantAuras == nil then
                AC.DB.profile.classIcons.showImportantAuras = true
            end
            if AC.DB.profile.classIcons.importantSpiralGlowLine == nil then
                AC.DB.profile.classIcons.importantSpiralGlowLine = true
            end
            if AC.DB.profile.classIcons.fontSize == nil then
                AC.DB.profile.classIcons.fontSize = 14
            end
            return AC.DB.profile.classIcons, AC.DB.profile.moreGoodies.auras
        end

        local classIconsDB, aurasDB = EnsureAurasDB()

        local g = CreateFrame("Frame", nil, f)
        g:SetPoint("TOPLEFT", 18, -12)
        g:SetPoint("TOPRIGHT", -18, -12)
        g:SetHeight(410)
        AC:HairlineGroupBox(g)

        local title = AC:CreateStyledText(g, L("ARENA_FRAMES", "section_auras", "AURAS"), 13, COLORS.PRIMARY, "OVERLAY", "")
        title:SetPoint("TOPLEFT", 20, -18)

        -- Font Size Slider (custom compact version)
        local fontSizeLabel = AC:CreateStyledText(g, L("ARENA_FRAMES", "font_size", "Font Size"), 11, COLORS.TEXT_2, "OVERLAY", "")
        fontSizeLabel:SetPoint("TOPLEFT", 20, -42)
        fontSizeLabel:SetWidth(60)
        fontSizeLabel:SetJustifyH("LEFT")

        local fontSizeSlider = AC:CreateFlatSlider(g, 100, 20, 10, 24, classIconsDB.fontSize or 14, false, function(newValue)
            if AC.ProfileManager and AC.ProfileManager.SetSetting then
                AC.ProfileManager:SetSetting("classIcons.fontSize", newValue)
            else
                EnsureAurasDB()
                AC.DB.profile.classIcons.fontSize = newValue
            end
            if AC.ClassIconAuras and AC.ClassIconAuras.UpdateFontSize then
                AC.ClassIconAuras:UpdateFontSize()
            end
            if AC.SimpleCCTest and AC.SimpleCCTest.UpdateFontSize then
                AC.SimpleCCTest:UpdateFontSize()
            end
        end)
        fontSizeSlider:SetPoint("LEFT", fontSizeLabel, "RIGHT", 8, 0)

        local enabledLabel = AC:CreateStyledText(g, L("ARENA_FRAMES", "enable_cc_auras", "Enable Crowd Control Auras"), 12, COLORS.TEXT_2, "OVERLAY", "")
        enabledLabel:SetPoint("TOPLEFT", 20, -74)

        local enabledBox = AC:CreateFlatCheckbox(g, 20, classIconsDB.showAuras ~= false, function(value)
            EnsureAurasDB()
            if AC.ProfileManager and AC.ProfileManager.SetSetting then
                AC.ProfileManager:SetSetting("classIcons.showAuras", value)
            else
                AC.DB.profile.classIcons.showAuras = value
            end
            
            -- Show/hide test CC auras based on toggle state
            if AC.SimpleCCTest then
                if value and AC.SimpleCCTest.IsActive and not AC.SimpleCCTest:IsActive() then
                    AC.SimpleCCTest:Show()
                elseif not value and AC.SimpleCCTest.IsActive and AC.SimpleCCTest:IsActive() then
                    AC.SimpleCCTest:Hide()
                end
            end
        end)
        enabledBox:SetPoint("TOPRIGHT", -25, -74)

        local spiralLabel = AC:CreateStyledText(g, L("ARENA_FRAMES", "spiral_glow_line", "Spiral Glow Line"), 12, COLORS.TEXT_2, "OVERLAY", "")
        spiralLabel:SetPoint("TOPLEFT", 20, -112)

        local spiralBox = AC:CreateFlatCheckbox(g, 20, classIconsDB.spiralGlowLine ~= false, function(value)
            EnsureAurasDB()
            if AC.ProfileManager and AC.ProfileManager.SetSetting then
                AC.ProfileManager:SetSetting("classIcons.spiralGlowLine", value)
            else
                AC.DB.profile.classIcons.spiralGlowLine = value
            end

            if AC.ClassIconAuras and AC.ClassIconAuras.UpdateSpiralGlowLine then
                AC.ClassIconAuras:UpdateSpiralGlowLine()
            end
            if AC.SimpleCCTest and AC.SimpleCCTest.UpdateSpiralGlowLine then
                AC.SimpleCCTest:UpdateSpiralGlowLine()
            end
        end)
        spiralBox:SetPoint("TOPRIGHT", -25, -112)

        local enabledDesc = AC:CreateStyledText(g, L("ARENA_FRAMES", "cc_auras_description", "Shows crowd control effects on the class icon with cooldown spiral."), 10, COLORS.TEXT_MUTED, "OVERLAY", "")
        enabledDesc:SetPoint("TOPLEFT", 20, -136)
        enabledDesc:SetPoint("TOPRIGHT", -20, -136)
        enabledDesc:SetJustifyH("LEFT")
        enabledDesc:SetWordWrap(true)

        -- Important Auras Section
        local sectionDivider = g:CreateTexture(nil, "BORDER")
        sectionDivider:SetColorTexture(0.3, 0.3, 0.3, 0.5)
        sectionDivider:SetPoint("TOPLEFT", 20, -160)
        sectionDivider:SetPoint("TOPRIGHT", -20, -160)
        sectionDivider:SetHeight(1)

        local importantTitle = AC:CreateStyledText(g, L("ARENA_FRAMES", "important_auras", "IMPORTANT AURAS"), 12, COLORS.PRIMARY, "OVERLAY", "")
        importantTitle:SetPoint("TOPLEFT", 20, -180)

        local importantLabel = AC:CreateStyledText(g, L("ARENA_FRAMES", "enable_important_auras", "Enable Important Auras"), 12, COLORS.TEXT_2, "OVERLAY", "")
        importantLabel:SetPoint("TOPLEFT", 20, -205)

        local importantBox = AC:CreateFlatCheckbox(g, 20, classIconsDB.showImportantAuras ~= false, function(value)
            EnsureAurasDB()
            if AC.ProfileManager and AC.ProfileManager.SetSetting then
                AC.ProfileManager:SetSetting("classIcons.showImportantAuras", value)
            else
                AC.DB.profile.classIcons.showImportantAuras = value
            end
            
            -- Refresh important auras system
            if AC.ClassIconAuras and AC.ClassIconAuras.RefreshImportantAuras then
                AC.ClassIconAuras:RefreshImportantAuras()
            end
        end)
        importantBox:SetPoint("TOPRIGHT", -25, -205)

        local importantSpiralLabel = AC:CreateStyledText(g, L("ARENA_FRAMES", "spiral_glow_line", "Spiral Glow Line"), 12, COLORS.TEXT_2, "OVERLAY", "")
        importantSpiralLabel:SetPoint("TOPLEFT", 20, -237)

        local importantSpiralBox = AC:CreateFlatCheckbox(g, 20, classIconsDB.importantSpiralGlowLine ~= false, function(value)
            EnsureAurasDB()
            if AC.ProfileManager and AC.ProfileManager.SetSetting then
                AC.ProfileManager:SetSetting("classIcons.importantSpiralGlowLine", value)
            else
                AC.DB.profile.classIcons.importantSpiralGlowLine = value
            end

            if AC.ClassIconAuras and AC.ClassIconAuras.UpdateImportantSpiralGlowLine then
                AC.ClassIconAuras:UpdateImportantSpiralGlowLine()
            end
        end)
        importantSpiralBox:SetPoint("TOPRIGHT", -25, -237)

        local importantDesc = AC:CreateStyledText(g, L("ARENA_FRAMES", "important_auras_description", "Shows important buff spells on the class icon with cooldown spiral. Blizzard determines which spells are important."), 10, COLORS.TEXT_MUTED, "OVERLAY", "")
        importantDesc:SetPoint("TOPLEFT", 20, -261)
        importantDesc:SetPoint("TOPRIGHT", -20, -261)
        importantDesc:SetJustifyH("LEFT")
        importantDesc:SetWordWrap(true)

        local tooltipLabel = AC:CreateStyledText(g, L("ARENA_FRAMES", "hide_tooltips", "Hide Tooltips"), 12, COLORS.TEXT_2, "OVERLAY", "")
        tooltipLabel:SetPoint("TOPLEFT", 20, -301)

        local tooltipBox = AC:CreateFlatCheckbox(g, 20, aurasDB.hideTooltips == true, function(value)
            EnsureAurasDB()
            AC.DB.profile.moreGoodies.auras.hideTooltips = value
        end)
        tooltipBox:SetPoint("TOPRIGHT", -25, -301)

        local testBtn = AC:CreateProfileStyleButton(g, 80, 32, L("ARENA_FRAMES", "test", "TEST"), "success", 12)
        testBtn:SetPoint("TOPLEFT", 20, -337)
        testBtn:SetScript("OnClick", function()
            if AC.SimpleCCTest then
                AC.SimpleCCTest:Show()
            end
        end)

        local hideBtn = AC:CreateProfileStyleButton(g, 80, 32, L("ARENA_FRAMES", "hide", "HIDE"), "danger", 12)
        hideBtn:SetPoint("LEFT", testBtn, "RIGHT", 10, 0)
        hideBtn:SetScript("OnClick", function()
            if AC.SimpleCCTest then
                AC.SimpleCCTest:Hide()
            end
        end)

        f._built = true
    end

    local function BuildDebuffs()
        local f = EnsureContentFrame("debuffs")
        if f._built then return end

        local function EnsureDebuffsDB()
            AC.DB = AC.DB or {}
            AC.DB.profile = AC.DB.profile or {}
            AC.DB.profile.moreGoodies = AC.DB.profile.moreGoodies or {}
            AC.DB.profile.moreGoodies.debuffs = AC.DB.profile.moreGoodies.debuffs or {}
            local db = AC.DB.profile.moreGoodies.debuffs
            if db.enabled == nil then db.enabled = true end
            if db.playerDebuffsOnly == nil then db.playerDebuffsOnly = false end
            if db.showTimer == nil then db.showTimer = true end
            if db.timerFontSize == nil then db.timerFontSize = 10 end
            return db
        end

        local db = EnsureDebuffsDB()

        local g = CreateFrame("Frame", nil, f)
        g:SetPoint("TOPLEFT", 18, -12)
        g:SetPoint("TOPRIGHT", -18, -12)
        g:SetHeight(470)
        AC:HairlineGroupBox(g)

        local title = AC:CreateStyledText(g, L("ARENA_FRAMES", "section_debuffs", "DEBUFFS"), 13, COLORS.PRIMARY, "OVERLAY", "")
        title:SetPoint("TOPLEFT", 20, -18)

        local function RefreshDebuffs()
            if AC.FrameManager and AC.FrameManager.RefreshDebuffSettings then
                AC.FrameManager:RefreshDebuffSettings()
            end
        end

        local enableLabel = AC:CreateStyledText(g, L("ARENA_FRAMES", "enable_enemy_debuff_tracking", "Enable Enemy Debuff Tracking"), 12, COLORS.TEXT_2, "OVERLAY", "")
        enableLabel:SetPoint("TOPLEFT", 20, -50)
        local enableBox = AC:CreateFlatCheckbox(g, 20, db.enabled ~= false, function(value)
            local db2 = EnsureDebuffsDB()
            db2.enabled = value
            RefreshDebuffs()
        end)
        enableBox:SetPoint("TOPRIGHT", -25, -50)

        local playerOnlyLabel = AC:CreateStyledText(g, L("ARENA_FRAMES", "player_debuffs_only", "Player Debuffs Only"), 12, COLORS.TEXT_2, "OVERLAY", "")
        playerOnlyLabel:SetPoint("TOPLEFT", 20, -80)
        local playerOnlyBox = AC:CreateFlatCheckbox(g, 20, db.playerDebuffsOnly == true, function(value)
            local db2 = EnsureDebuffsDB()
            db2.playerDebuffsOnly = value
            RefreshDebuffs()
        end)
        playerOnlyBox:SetPoint("TOPRIGHT", -25, -80)

        AC:CreateEnhancedSliderRow(g, L("ARENA_FRAMES", "max_debuffs", "Max Debuffs"), -112, "moreGoodies.debuffs.maxCount", nil, {
            scaleMin = 1, scaleMax = 8, pixelMin = 1, pixelMax = 8, isPercent = false,
            tooltip = L("ARENA_FRAMES", "max_debuffs_tooltip", "Maximum number of debuffs to display.")
        })
        AC:CreateEnhancedSliderRow(g, L("COMMON", "horizontal", "Horizontal"), -142, "moreGoodies.debuffs.positioning.horizontal", "positioning_horizontal_ultra")
        AC:CreateEnhancedSliderRow(g, L("COMMON", "vertical", "Vertical"), -172, "moreGoodies.debuffs.positioning.vertical", "positioning_vertical_ultra")
        AC:CreateEnhancedSliderRow(g, L("COMMON", "scale", "Scale"), -202, "moreGoodies.debuffs.sizing.scale", "sizing_scale")

        local timerLabel = AC:CreateStyledText(g, L("ARENA_FRAMES", "show_countdown_timers", "Show Countdown Timers"), 12, COLORS.TEXT_2, "OVERLAY", "")
        timerLabel:SetPoint("TOPLEFT", 20, -234)
        local timerBox = AC:CreateFlatCheckbox(g, 20, db.showTimer ~= false, function(value)
            local db2 = EnsureDebuffsDB()
            db2.showTimer = value
            RefreshDebuffs()
        end)
        timerBox:SetPoint("TOPRIGHT", -25, -234)

        AC:CreateEnhancedSliderRow(g, L("ARENA_FRAMES", "timer_font_size", "Timer Font Size"), -266, "moreGoodies.debuffs.timerFontSize", "cooldown_font")

        local testBtn = AC:CreateTexturedButton(g, 80, 30, L("ARENA_FRAMES", "test", "TEST"), "button-test")
        testBtn:SetPoint("TOPLEFT", 20, -312)
        testBtn:SetScript("OnClick", function()
            if AC.FrameManager and AC.FrameManager.TestDebuffMode then
                AC.FrameManager:TestDebuffMode()
            end
        end)

        local hideBtn = AC:CreateTexturedButton(g, 80, 30, L("ARENA_FRAMES", "hide", "HIDE"), "button-hide")
        hideBtn:SetPoint("LEFT", testBtn, "RIGHT", 10, 0)
        hideBtn:SetScript("OnClick", function()
            if AC.FrameManager and AC.FrameManager.HideDebuffTest then
                AC.FrameManager:HideDebuffTest()
            end
        end)

        C_Timer.After(0.1, function()
            if AC.sliderWidgets then
                local function hookSlider(path)
                    local slider = AC.sliderWidgets[path]
                    if slider and slider.HookScript then
                        slider:HookScript("OnValueChanged", function()
                            RefreshDebuffs()
                        end)
                    end
                end
                hookSlider("moreGoodies.debuffs.maxCount")
                hookSlider("moreGoodies.debuffs.positioning.horizontal")
                hookSlider("moreGoodies.debuffs.positioning.vertical")
                hookSlider("moreGoodies.debuffs.sizing.scale")
                hookSlider("moreGoodies.debuffs.timerFontSize")
            end
        end)

        f._built = true
    end

    local function BuildPositioning()
        local f = EnsureContentFrame("positioning")
        if f._built then return end
        CreateGroup_POSITIONING(f, -12)
        f._built = true
    end

    local function BuildSizing()
        local f = EnsureContentFrame("sizing")
        if f._built then return end
        local sizingGroup = CreateGroup_SIZING(f, -12)
        function AC:ArenaFramesPage_UpdateSizingSliders(themeName)
            if not sizingGroup then return end
            sizingGroup:RelayoutControls(themeName)
        end
        C_Timer.After(0.1, function()
            if AC.ArenaFrameThemes then
                local currentTheme = AC.ArenaFrameThemes:GetCurrentTheme()
                AC:ArenaFramesPage_UpdateSizingSliders(currentTheme)
            end
        end)
        f._built = true
    end

    btnGeneral:SetScript("OnClick", function()
        BuildGeneral()
        SetActiveTab("general")
    end)
    btnPositioning:SetScript("OnClick", function()
        BuildPositioning()
        SetActiveTab("positioning")
    end)
    btnSizing:SetScript("OnClick", function()
        BuildSizing()
        SetActiveTab("sizing")
    end)
    btnAuras:SetScript("OnClick", function()
        BuildAuras()
        SetActiveTab("auras")
    end)
    btnDebuffs:SetScript("OnClick", function()
        BuildDebuffs()
        SetActiveTab("debuffs")
    end)

    btnAbsorbs:SetScript("OnClick", function()
        BuildAbsorbs()
        SetActiveTab("absorbs")
    end)

    BuildGeneral()
    SetActiveTab("general")

    root:HookScript("OnHide", function()
        SetArenaFramesScrollEnabled(true)
    end)

    AC:HideLegacyJunk(strip)
end

-- CreateArenaFramesPage function defined

-- ============================================================================
-- Apply All Settings
-- ============================================================================
-- New function to apply all saved settings to the frames at once.
-- This is called after the addon loads to synchronize the visual state.
function AC:ApplyAllArenaFrameSettings()
    -- OLD ApplyAllArenaFrameSettings disabled - using new unified system
    return -- Exit early, new system handles everything
    
    -- OLD CODE DISABLED:
    -- Commented out old refresh logic - now handled by other systems
    -- if AC.UpdateFramePosition then AC:UpdateFramePosition() end
    -- if AC.UpdateFrameSpacing then AC:UpdateFrameSpacing() end
    -- if AC.UpdateFrameScale then AC:UpdateFrameScale() end
    -- if AC.UpdateFrameSize then AC:UpdateFrameSize() end
    -- if AC.RefreshGeneralSettings then AC:RefreshGeneralSettings() end
end

-- ============================================================================
-- Event Handling
-- ============================================================================
-- Use an event handler to apply settings after the addon and frames are fully loaded.
local initFrame = CreateFrame("Frame")
initFrame:RegisterEvent("PLAYER_LOGIN")
initFrame:SetScript("OnEvent", function(self, event)
    if event == "PLAYER_LOGIN" then
        C_Timer.After(0.5, function() -- Short delay to ensure frames are created
            AC:ApplyAllArenaFrameSettings()
        end)
        self:UnregisterEvent("PLAYER_LOGIN")
    end
end)

-- Register the page with the AC system
AC:RegisterPage("ArenaFrames", CreateArenaFramesPage)
