-- Core/Pages/ArenaFrames.lua --
-- Arena Frames configuration page extracted from UI.lua
local AC = _G.ArenaCore
if not AC then return 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")
    downText:SetFont("Interface/AddOns/ArenaCore/Media/Fonts/arenacore.ttf", 12, "")
    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
    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")
    upText:SetFont("Interface/AddOns/ArenaCore/Media/Fonts/arenacore.ttf", 12, "")
    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
            elseif path == "arenaFrames.general.showArenaLabels" then
                -- User enabled Arena 1/2/3 Names -> disable Show Names
                if AC.ProfileManager and AC.ProfileManager.SetSetting then
                    AC.ProfileManager:SetSetting("arenaFrames.general.showNames", false)
                    local otherBox = checkboxRegistry["arenaFrames.general.showNames"]
                    if otherBox then
                        otherBox:SetChecked(false)
                    end
                end
            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: 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, "Text Display Settings", 0, false)
    textDisplaySection.parent = mainContainer
    local textDisplayContent = CreateSectionContent(mainContainer, textDisplaySection, 180)
    
    CreateRowCheckbox(textDisplayContent, "Status Text", -25, "arenaFrames.general.statusText", nil, true)
    CreateRowCheckbox(textDisplayContent, "Use Percentage", -50, "arenaFrames.general.usePercentage", nil, true)
    CreateRowCheckbox(textDisplayContent, "Use Class Colors", -75, "arenaFrames.general.useClassColors", nil, true)
    CreateRowCheckbox(textDisplayContent, "Show Names", -100, "arenaFrames.general.showNames", nil, true)
    CreateRowCheckbox(textDisplayContent, "Arena Numbers Only", -125, "arenaFrames.general.showArenaNumbers", nil, true)
    CreateRowCheckbox(textDisplayContent, "  Arena 1/2/3 Names", -150, "arenaFrames.general.showArenaLabels", nil, true)
    
    -- FrameSort Integration Toggle
    local frameSortRow = CreateFrame("Frame", nil, textDisplayContent)
    frameSortRow:SetPoint("TOPLEFT", 20, -175)
    frameSortRow:SetPoint("TOPRIGHT", -20, -175)
    frameSortRow:SetHeight(26)
    
    local frameSortLabel = AC:CreateStyledText(frameSortRow, "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, "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, "Player Names Horizontal", -25, "arenaFrames.general.playerNameX", "text_positioning_horizontal")
    AC:CreateEnhancedSliderRow(namePositionContent, "Player Names Vertical", -55, "arenaFrames.general.playerNameY", "text_positioning_vertical")
    
    -- Health Text positioning sliders
    AC:CreateEnhancedSliderRow(namePositionContent, "Health Text Horizontal", -85, "arenaFrames.general.healthTextX", "text_positioning_horizontal")
    AC:CreateEnhancedSliderRow(namePositionContent, "Health Text Vertical", -115, "arenaFrames.general.healthTextY", "text_positioning_vertical")
    
    -- Resource Text positioning sliders
    AC:CreateEnhancedSliderRow(namePositionContent, "Resource Text Horizontal", -145, "arenaFrames.general.resourceTextX", "text_positioning_horizontal")
    AC:CreateEnhancedSliderRow(namePositionContent, "Resource Text Vertical", -175, "arenaFrames.general.resourceTextY", "text_positioning_vertical")
    
    -- ▼ Arena Number Positioning (Arena numbers positioning)
    local numberPositionSection = CreateCollapsibleSection(mainContainer, "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, "Arena Numbers Horizontal", -25, "arenaFrames.general.arenaNumberX", "arena_number_horizontal")
    AC:CreateEnhancedSliderRow(numberPositionContent, "Arena Numbers Vertical", -75, "arenaFrames.general.arenaNumberY", "arena_number_vertical")
    -- ▼ Text Scaling & Fonts (all the percentage sliders)
    local textScalingSection = CreateCollapsibleSection(mainContainer, "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, "Player Name Scale", -25, "arenaFrames.general.playerNameScale", "text_scaling_ultra")
    AC:CreateEnhancedSliderRow(textScalingContent, "Arena Number Scale", -55, "arenaFrames.general.arenaNumberScale", "text_scaling_ultra")
    AC:CreateEnhancedSliderRow(textScalingContent, "Health Text Scale", -85, "arenaFrames.general.healthTextScale", "text_scaling_ultra")
    AC:CreateEnhancedSliderRow(textScalingContent, "Resource Text Scale", -115, "arenaFrames.general.resourceTextScale", "text_scaling_ultra")
    AC:CreateEnhancedSliderRow(textScalingContent, "Spell Text Scale", -145, "arenaFrames.general.spellTextScale", "text_scaling_ultra")
    -- ▼ Arena Frame Themes (NEW FEATURE)
    local frameThemesSection = CreateCollapsibleSection(mainContainer, "Arena Frame Themes", 0, false)
    frameThemesSection.parent = mainContainer
    local frameThemesContent = CreateSectionContent(mainContainer, frameThemesSection, 100)
    
    -- Theme selection dropdown
    local themeLabel = AC:CreateStyledText(frameThemesContent, "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 = {"Arena Core", "The 1500 Special", "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, "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, "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, "Horizontal", -50, "arenaFrames.positioning.horizontal", "positioning_horizontal")
    AC:CreateEnhancedSliderRow(g, "Vertical", -80, "arenaFrames.positioning.vertical", "positioning_vertical")
    AC:CreateEnhancedSliderRow(g, "Spacing", -110, "arenaFrames.positioning.spacing", "spacing")
    
    -- Add Growth Direction dropdown
    local growthLabel = AC:CreateStyledText(g, "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, {"Down", "Up", "Right", "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, "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, "Scale", START_Y, "arenaFrames.sizing.scale", "sizing_scale"), nil)
    
    -- Just Blastin' only: pixel border thickness (1-5px, whole numbers)
    AddControl(AC:CreateEnhancedSliderRow(g, "Border Thickness", START_Y, "arenaFrames.sizing.borderThickness", "pixel_border_thickness"), "Just Blastin'")
    
    -- Arena Core only: frame sizing controls
    AddControl(AC:CreateEnhancedSliderRow(g, "Frame Width", START_Y, "arenaFrames.sizing.width", "sizing_width"), "Arena Core")
    AddControl(AC:CreateEnhancedSliderRow(g, "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,
        "Background Color",
        START_Y,
        "arenaFrames.sizing.arenaCoreBackgroundColor",
        {
            {text = "Dark", value = "dark"},
            {text = "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, "Target Border Thickness", START_Y, "arenaFrames.sizing.targetBorderThickness", "target_border_thickness"), nil)
    AddControl(CreateColorPickerSetting(g, "Target Border Color", START_Y, "arenaFrames.sizing.targetBorderColor", { 1, 0.6, 0, 1 }), nil)
    AddControl(CreateCheckboxSetting(g, "Disable Target Highlight", START_Y, "arenaFrames.sizing.disableTargetHighlight"), nil)
    AddControl(CreateCheckboxSetting(g, "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, "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, "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 (two lines)
    local dragAlert1 = AC:CreateStyledText(lockRow, "Ctrl+Alt+Left Click", 10, COLORS.TEXT_2, "OVERLAY", "")
    dragAlert1:SetPoint("RIGHT", -12, 6)
    dragAlert1:SetJustifyH("RIGHT")
    dragAlert1:SetTextColor(0.8, 0.9, 1.0, 0.9) -- Light blue tint
    
    local dragAlert2 = AC:CreateStyledText(lockRow, "to drag frames!", 10, COLORS.TEXT_2, "OVERLAY", "")
    dragAlert2:SetPoint("RIGHT", -12, -6)
    dragAlert2:SetJustifyH("RIGHT")
    dragAlert2: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, "General", 102, 30)
    btnGeneral._tabId = "general"
    btnGeneral:SetPoint("TOPLEFT", 18, -2)
    table.insert(tabs, btnGeneral)

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

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

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

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

    local btnAbsorbs = CreateArenaFramesTabButton(tabRow, "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, "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, "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, "Ctrl+Alt+Left Click", 10, COLORS.TEXT_2, "OVERLAY", "")
    dragAlert1:SetPoint("RIGHT", -12, 6)
    dragAlert1:SetJustifyH("RIGHT")
    dragAlert1:SetTextColor(0.8, 0.9, 1.0, 0.9)

    local dragAlert2 = AC:CreateStyledText(lockRow, "to drag frames!", 10, COLORS.TEXT_2, "OVERLAY", "")
    dragAlert2:SetPoint("RIGHT", -12, -6)
    dragAlert2:SetJustifyH("RIGHT")
    dragAlert2: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, "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, "ABSORBS", 13, COLORS.PRIMARY, "OVERLAY", "")
        title:SetPoint("TOPLEFT", 20, -18)

        local label = AC:CreateStyledText(g, "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, "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")
        if f._built then return end

        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
            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(250)
        AC:HairlineGroupBox(g)

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

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

        local enabledBox = AC:CreateFlatCheckbox(g, 20, classIconsDB.showAuras ~= false, function(value)
            local classDb = EnsureAurasDB()
            AC.DB.profile.classIcons.showAuras = value
            if not value and AC.ClassIconAuras and AC.ClassIconAuras.RestoreAll then
                AC.ClassIconAuras:RestoreAll()
            end
        end)
        enabledBox:SetPoint("TOPRIGHT", -25, -50)

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

        local spiralBox = AC:CreateFlatCheckbox(g, 20, classIconsDB.spiralGlowLine ~= false, function(value)
            EnsureAurasDB()
            AC.DB.profile.classIcons.spiralGlowLine = value

            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, -82)

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

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

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

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

        local hideBtn = AC:CreateProfileStyleButton(g, 80, 32, "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, "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, "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, "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, "Max Debuffs", -112, "moreGoodies.debuffs.maxCount", nil, {
            scaleMin = 1, scaleMax = 8, pixelMin = 1, pixelMax = 8, isPercent = false,
            tooltip = "Maximum number of debuffs to display."
        })
        AC:CreateEnhancedSliderRow(g, "Horizontal", -142, "moreGoodies.debuffs.positioning.horizontal", "positioning_horizontal_ultra")
        AC:CreateEnhancedSliderRow(g, "Vertical", -172, "moreGoodies.debuffs.positioning.vertical", "positioning_vertical_ultra")
        AC:CreateEnhancedSliderRow(g, "Scale", -202, "moreGoodies.debuffs.sizing.scale", "sizing_scale")

        local timerLabel = AC:CreateStyledText(g, "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, "Timer Font Size", -266, "moreGoodies.debuffs.timerFontSize", "cooldown_font")

        local testBtn = AC:CreateTexturedButton(g, 80, 30, "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, "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)
