-- COMPLETE AND CORRECTED DiminishingReturns.lua
-- ============================================================================
-- File: ArenaCore/Core/Pages/DiminishingReturns.lua (v1.1 - LUA COMMENT FIX)
-- ============================================================================
local AC = _G.ArenaCore
if not AC then return end

local V = AC.Vanity
local DB_PATH = "diminishingReturns"

-- Initialize DR categories when the page loads
local function InitializeDRDatabase()
    local db = AC.DB.profile.diminishingReturns
    db.categories = db.categories or {}
    db.iconSettings = db.iconSettings or {}
    db.customSpells = db.customSpells or {}
    db.classSpecEnabled = db.classSpecEnabled or false
    db.classSpecSelection = db.classSpecSelection or ""
    db.spiralAnimation = db.spiralAnimation or {}
    if db.spiralGlowLine == nil then
        db.spiralGlowLine = true
    end
end

-- Helper to link UI controls to the database
local function CreateLinkedControl(parent, y, controlType, config)
    local row = CreateFrame("Frame", nil, parent)
    row:SetPoint("TOPLEFT", 20, y); row:SetPoint("TOPRIGHT", -20, y); row:SetHeight(26)

    local fullPath = DB_PATH .. "." .. config.path
    local keys = {}; for k in string.gmatch(fullPath, "([^%.]+)") do table.insert(keys, k) end
    
    -- CRITICAL FIX: Ensure config.val is never nil
    if config.val == nil then
        config.val = config.default or 0
        -- DEBUG DISABLED FOR PRODUCTION
        -- print("|cffFFAA00ArenaCore DR:|r Using default value for", config.path, "=", config.val)
    end

    local function OnChange(value)
        -- CRITICAL FIX: Handle nil values properly
        if value == nil then
            print("|cffFF0000ArenaCore DR Error:|r OnChange received nil value for", config.path)
            value = config.default or 0
        end

        if AC.ProfileManager and AC.ProfileManager.SetSetting then
            AC.ProfileManager:SetSetting(fullPath, value)
        else
            local target = AC.DB.profile; for i = 1, #keys - 1 do target = target[keys[i]] end
            target[keys[#keys]] = value
        end
        if config.valT then
            if config.isPct then 
                config.valT:SetText(string.format("%.0f%%", value))
            elseif config.compactDisplay then
                config.valT:SetText(string.format("%.0f", math.floor(value / 100)))
            else 
                config.valT:SetText(string.format("%.0f", value)) 
            end
        end
        
        -- CRITICAL FIX: Refresh DR icons to apply checkbox settings
        -- For checkboxes, we need to update the actual icon visuals or visibility
        if config.path == "enabled" then
            -- Master enable/disable - use RefreshDRLayout which handles Midnight vs regular DR
            if AC.RefreshDRLayout then
                AC:RefreshDRLayout()
            end
        elseif config.path == "showStageIndicators" or config.path == "colorCodedBorders" then
            -- Update visuals only (no repositioning). Calling UpdateDRPositions here causes a visible "jump".
            -- CRITICAL FIX: Update ALL DR icons (visible AND hidden) to ensure borders refresh properly
            if AC.DR_PvP and AC.DR_PvP.UpdateAllDRStages then
                -- Use the new PvP DR system's UpdateAllDRStages function
                AC.DR_PvP:UpdateAllDRStages()
            elseif AC.MasterFrameManager and AC.MasterFrameManager.frames then
                -- Fallback to old system
                for i = 1, 3 do
                    local frame = AC.MasterFrameManager.frames[i]
                    if frame and frame.drIcons then
                        for category, drIcon in pairs(frame.drIcons) do
                            -- CRITICAL: Remove IsShown() check - update ALL icons, not just visible ones
                            if drIcon and drIcon.UpdateStage then
                                local stage
                                if AC.testModeEnabled then
                                    -- In test mode, use frame index for stage
                                    local isMidnight = AC.Midnight and AC.Midnight.isMidnight
                                    if isMidnight then
                                        -- Midnight: Arena 1 = stage 1 (green), Arena 2/3 = stage 2 (red)
                                        stage = (i == 1) and 1 or 2
                                    else
                                        -- Pre-Midnight: 3 stages cycling
                                        stage = ((i - 1) % 3) + 1
                                    end
                                else
                                    -- In live arena, calculate stage from diminished value
                                    -- CRITICAL FIX: Check from LARGEST to SMALLEST (>= not <=)
                                    local diminished = drIcon.diminished or 1.0
                                    if diminished >= 1.0 then
                                        stage = 1
                                    elseif diminished >= 0.5 then
                                        stage = 2
                                    elseif diminished > 0 then
                                        stage = 3
                                    else
                                        stage = 3  -- Immune
                                    end
                                end
                                drIcon:UpdateStage(stage)
                            end
                        end
                    end
                end
            end
        elseif config.path == "spiralAnimation.enabled" or config.path == "spiralAnimation.opacity" then
            -- Spiral Animation settings changed - refresh all DR icons
            if AC.DRSpiralAnimation and AC.DRSpiralAnimation.RefreshAllIcons then
                AC.DRSpiralAnimation:RefreshAllIcons()
            end
            -- Also update PvP DR spiral animations
            if AC.DR_PvP and AC.DR_PvP.UpdateSpiralAnimations then
                AC.DR_PvP:UpdateSpiralAnimations()
            end
        elseif config.path == "spiralGlowLine" then
            if AC.DR_PvP and AC.DR_PvP.UpdateSpiralGlowLine then
                AC.DR_PvP:UpdateSpiralGlowLine()
            end
        else
            -- For sliders, use direct UpdatePositions for smooth real-time updates
            -- RefreshDRLayout causes a full refresh which creates a visual "jump"
            -- Direct UpdatePositions smoothly moves icons to new position
            if AC.MasterFrameManager and AC.MasterFrameManager.frames then
                for i = 1, 3 do
                    local frame = AC.MasterFrameManager.frames[i]
                    if frame and AC.UpdateDRPositions then
                        AC:UpdateDRPositions(frame)
                    end
                end
            end
        end
    end

    if controlType == "Slider" then
        local displayMin = config.min
        local displayMax = config.max
        if config.compactDisplay then
            displayMin = math.floor(config.min / 100)
            displayMax = math.floor(config.max / 100)
        end

        local l = AC:CreateStyledText(row, config.label, 11, AC.COLORS.TEXT_2, "OVERLAY", ""); l:SetPoint("LEFT", 0, 0); l:SetWidth(70); l:SetJustifyH("LEFT")
        local minT = AC:CreateStyledText(row, config.isPct and (displayMin .. "%") or tostring(displayMin), 9, AC.COLORS.TEXT_MUTED, "OVERLAY", ""); minT:SetPoint("LEFT", l, "RIGHT", 6, 0); minT:SetWidth(25); minT:SetJustifyH("RIGHT")
        
        -- Create DOWN arrow button for fine adjustment
        local downBtn = CreateFrame("Button", nil, row)
        downBtn:SetSize(16, 16)
        downBtn:SetPoint("LEFT", minT, "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 valT = AC:CreateStyledText(row, "", 11, AC.COLORS.TEXT_2, "OVERLAY", ""); valT:SetWidth(35); valT:SetJustifyH("CENTER")
        config.valT = valT
        local slider = AC:CreateFlatSlider(row, 120, 18, config.min, config.max, config.val, config.isPct, OnChange)
        slider:SetPoint("LEFT", downBtn, "RIGHT", 4, 0)
        
        -- CRITICAL: Wire up OnValueChanged handler (CreateFlatSlider doesn't do this)
        slider.slider:SetScript("OnValueChanged", function(self, value)
            OnChange(value)
        end)

        -- 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, config.isPct and (displayMax .. "%") or tostring(displayMax), 9, AC.COLORS.TEXT_MUTED, "OVERLAY", ""); maxT:SetPoint("LEFT", upBtn, "RIGHT", 6, 0); maxT:SetWidth(25); maxT:SetJustifyH("LEFT")
        valT:SetPoint("RIGHT", row, "RIGHT", -10, 0)
        valT:SetPoint("LEFT", maxT, "RIGHT", 10, 0)
        
        -- Initialize the value display
        OnChange(config.val)

        -- Down arrow click handler
        downBtn:SetScript("OnClick", function()
            local currentVal = slider.slider:GetValue()
            local increment = config.compactDisplay and 100 or 1
            local newVal = math.max(config.min, currentVal - increment)
            slider.slider:SetValue(newVal)
        end)

        -- Up arrow click handler
        upBtn:SetScript("OnClick", function()
            local currentVal = slider.slider:GetValue()
            local increment = config.compactDisplay and 100 or 1
            local newVal = math.min(config.max, currentVal + increment)
            slider.slider:SetValue(newVal)
        end)
        
        -- 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)
        
        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)
    elseif controlType == "Checkbox" then
        local l = AC:CreateStyledText(row, config.label, 11, AC.COLORS.TEXT_2, "OVERLAY", ""); l:SetPoint("LEFT", 0, 0); l:SetWidth(100); l:SetJustifyH("LEFT")
        local box = AC:CreateFlatCheckbox(row, 20, config.val, OnChange)
        box:SetPoint("RIGHT", -25, 0)
        row.label = l
        row.checkbox = box
    elseif controlType == "Dropdown" then
        local l = AC:CreateStyledText(row, config.label, 11, AC.COLORS.TEXT_2, "OVERLAY", ""); l:SetPoint("LEFT", 0, 0); l:SetWidth(100); l:SetJustifyH("LEFT")
        local dropdown = AC:CreateFlatDropdown(row, 120, 24, config.options, config.val, OnChange)
        dropdown:SetPoint("LEFT", l, "RIGHT", 10, 0)
    end
    return row
end

local function CreateDiminishingReturnsPage(parent)
    local db = (AC.DB and AC.DB.profile and AC.DB.profile[DB_PATH])
    if not db then 
        return 
    end

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

        local fill = group:CreateTexture(nil, "BACKGROUND", nil, 2)
        local bgColor = AC.COLORS and AC.COLORS.HEADER_BG or {0.102, 0.102, 0.102, 1}
        fill:SetColorTexture(bgColor[1], bgColor[2], bgColor[3], bgColor[4] or 1)
        fill:SetPoint("TOPLEFT", 1, -1)
        fill:SetPoint("BOTTOMRIGHT", -1, 1)
        group.__acFill = fill
        group.__acFillIsGroupBox = true

        local borderFrame = CreateFrame("Frame", nil, group)
        borderFrame:SetAllPoints(group)

        local uniqueLevel = group:GetFrameLevel() + 1
        if group:GetParent() then
            uniqueLevel = uniqueLevel + (group:GetFrameLevel() % 3)
        end
        borderFrame:SetFrameLevel(uniqueLevel)

        local purpleTop = borderFrame:CreateTexture(nil, "BORDER", nil, 1)
        purpleTop:SetColorTexture(0.545, 0.271, 1.000, 1)
        purpleTop:SetPoint("TOPLEFT", group, "TOPLEFT", 0, 0)
        purpleTop:SetPoint("TOPRIGHT", group, "TOPRIGHT", 0, 0)
        purpleTop:SetHeight(1)
        if purpleTop.SetSnapToPixelGrid then purpleTop:SetSnapToPixelGrid(true) end
        if purpleTop.SetTexelSnappingBias then purpleTop:SetTexelSnappingBias(0) end

        local grayTop = borderFrame:CreateTexture(nil, "BORDER", nil, 0)
        grayTop:SetColorTexture(0.278, 0.278, 0.278, 0.9)
        grayTop:SetPoint("TOPLEFT", group, "TOPLEFT", 0, -1)
        grayTop:SetPoint("TOPRIGHT", group, "TOPRIGHT", 0, -1)
        grayTop:SetHeight(1)

        local grayBottom = borderFrame:CreateTexture(nil, "BORDER", nil, 0)
        grayBottom:SetColorTexture(0.278, 0.278, 0.278, 0.9)
        grayBottom:SetPoint("BOTTOMLEFT", group, "BOTTOMLEFT", 0, 0)
        grayBottom:SetPoint("BOTTOMRIGHT", group, "BOTTOMRIGHT", 0, 0)
        grayBottom:SetHeight(1)

        local grayLeft = borderFrame:CreateTexture(nil, "BORDER", nil, 0)
        grayLeft:SetColorTexture(0.278, 0.278, 0.278, 0.9)
        grayLeft:SetPoint("TOPLEFT", group, "TOPLEFT", 0, 0)
        grayLeft:SetPoint("BOTTOMLEFT", group, "BOTTOMLEFT", 0, 0)
        grayLeft:SetWidth(1)

        local grayRight = borderFrame:CreateTexture(nil, "BORDER", nil, 0)
        grayRight:SetColorTexture(0.278, 0.278, 0.278, 0.9)
        grayRight:SetPoint("TOPRIGHT", group, "TOPRIGHT", 0, 0)
        grayRight:SetPoint("BOTTOMRIGHT", group, "BOTTOMRIGHT", 0, 0)
        grayRight:SetWidth(1)

        group.__acBorderFrame = borderFrame
    end
    
    -- Initialize DR database
    InitializeDRDatabase()

    if V and V.EnsureMottoStrip then V:EnsureMottoStrip(parent) end

    	-- Create the top button bar first
	local buttonBar = CreateFrame("Frame", nil, parent)
	if parent._mottoStrip then
		buttonBar:SetPoint("TOPLEFT", parent._mottoStrip, "BOTTOMLEFT", 2, -8)
		buttonBar:SetPoint("TOPRIGHT", parent._mottoStrip, "BOTTOMRIGHT", -2, -8)
	else
		buttonBar:SetPoint("TOPLEFT", 10, -52)
		buttonBar:SetPoint("TOPRIGHT", -10, -52)
	end
	buttonBar:SetHeight(40)

    	local sBorder = AC:CreateFlatTexture(buttonBar, "BACKGROUND", 1, AC.COLORS.BORDER_LIGHT, 0.6)
	sBorder:SetAllPoints()
	local sFill = AC:CreateFlatTexture(buttonBar, "BACKGROUND", 2, AC.COLORS.INPUT_DARK, 1)
	sFill:SetPoint("TOPLEFT", 1, -1); sFill:SetPoint("BOTTOMRIGHT", -1, 1)

	local function CreateDRSubTabButton(parentFrame, text, width, height)
		local btn = CreateFrame("Button", nil, parentFrame)
		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, AC.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 = AC.COLORS.PRIMARY or {0.545, 0.271, 1.000, 1}
			t:SetColorTexture(c[1], c[2], c[3], 1)
			t:SetDrawLayer("OVERLAY")
			if t.SetSnapToPixelGrid then
				t:SetTexelSnappingBias(0)
				t:SetSnapToPixelGrid(false)
			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, (AC.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((AC.COLORS.TEXT and AC.COLORS.TEXT[1]) or 1, (AC.COLORS.TEXT and AC.COLORS.TEXT[2]) or 1, (AC.COLORS.TEXT and AC.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((AC.COLORS.TEXT_2 and AC.COLORS.TEXT_2[1]) or 0.706, (AC.COLORS.TEXT_2 and AC.COLORS.TEXT_2[2]) or 0.706, (AC.COLORS.TEXT_2 and AC.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((AC.COLORS.TEXT and AC.COLORS.TEXT[1]) or 1, (AC.COLORS.TEXT and AC.COLORS.TEXT[2]) or 1, (AC.COLORS.TEXT and AC.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((AC.COLORS.TEXT_2 and AC.COLORS.TEXT_2[1]) or 0.706, (AC.COLORS.TEXT_2 and AC.COLORS.TEXT_2[2]) or 0.706, (AC.COLORS.TEXT_2 and AC.COLORS.TEXT_2[3]) or 0.706, 1)
			end
		end)

		return btn
	end

	local contentRoot = CreateFrame("Frame", nil, parent)
	contentRoot:SetPoint("TOPLEFT", buttonBar, "BOTTOMLEFT", 0, -10)
	contentRoot:SetPoint("BOTTOMRIGHT", parent, "BOTTOMRIGHT", 0, 0)

	local function EnsureContentFrame(key)
		parent.__drContentFrames = parent.__drContentFrames or {}
		if parent.__drContentFrames[key] then
			return parent.__drContentFrames[key]
		end
		local f = CreateFrame("Frame", nil, contentRoot)
		f:SetAllPoints(contentRoot)
		f:Hide()
		parent.__drContentFrames[key] = f
		return f
	end

	local tabs = {}
	local selectedTab
	local function SetTab(key)
		if selectedTab == key then return end
		selectedTab = key
		for k, frame in pairs(parent.__drContentFrames or {}) do
			if k == key then frame:Show() else frame:Hide() end
		end
		for k, btn in pairs(tabs) do
			btn:SetSelected(k == key)
		end
	end

	local tabGeneral = CreateDRSubTabButton(buttonBar, "General", 120, 30)
	tabGeneral:SetPoint("LEFT", buttonBar, "LEFT", 12, 0)
	tabs.general = tabGeneral

	local tabRows = CreateDRSubTabButton(buttonBar, "Rows", 120, 30)
	tabRows:SetPoint("LEFT", tabGeneral, "RIGHT", 8, 0)
	tabs.rows = tabRows

	local tabPosSize = CreateDRSubTabButton(buttonBar, "Positioning & Sizing", 150, 30)
	tabPosSize:SetPoint("LEFT", tabRows, "RIGHT", 8, 0)
	tabs.possize = tabPosSize

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

		local groupGeneral = CreateFrame("Frame", nil, f)
		groupGeneral:SetPoint("TOPLEFT", f, "TOPLEFT", 18, -12)
		groupGeneral:SetPoint("TOPRIGHT", f, "TOPRIGHT", -18, -12)
		groupGeneral:SetHeight(430)
		DRHairlineGroupBox(groupGeneral)

		AC:CreateStyledText(groupGeneral, "GENERAL", 13, AC.COLORS.PRIMARY, "OVERLAY", ""):SetPoint("TOPLEFT", 20, -18)

		CreateLinkedControl(groupGeneral, -50, "Checkbox", { label = "Enable DR Tracking", path = "enabled", val = db.enabled, default = true })
		CreateLinkedControl(groupGeneral, -80, "Checkbox", { label = "Spiral Glow Line", path = "spiralGlowLine", val = db.spiralGlowLine, default = true })
		CreateLinkedControl(groupGeneral, -110, "Checkbox", { label = "Show Stage Indicators", path = "showStageIndicators", val = db.showStageIndicators, default = true })
		local colorCodedBordersRow = CreateLinkedControl(groupGeneral, -140, "Checkbox", { label = "Color Coded Borders", path = "colorCodedBorders", val = db.colorCodedBorders, default = false })

		local function GetBorderStyleDisplay()
			local v = db.borderStyle
			if v == "pixel_black" then
				return "Skill Issue Outline"
			end
			return "Arena Core"
		end

		local UpdateBorderColorEnabledState

		local function SaveBorderStyle(displayText)
			local internalValue = (displayText == "Skill Issue Outline") and "pixel_black" or "arenacore"
			if AC.ProfileManager and AC.ProfileManager.SetSetting then
				AC.ProfileManager:SetSetting("diminishingReturns.borderStyle", internalValue)
			else
				db.borderStyle = internalValue
			end
			UpdateBorderColorEnabledState()
			if AC.DR_PvP and AC.DR_PvP.UpdateAllDRStages then
				AC.DR_PvP:UpdateAllDRStages()
			elseif AC.RefreshDRLayout then
				AC:RefreshDRLayout()
			end
		end

		local borderStyleRow = CreateFrame("Frame", nil, groupGeneral)
		borderStyleRow:SetPoint("TOPLEFT", 20, -190)
		borderStyleRow:SetPoint("TOPRIGHT", -20, -190)
		borderStyleRow:SetHeight(26)

		local borderStyleLabel = AC:CreateStyledText(borderStyleRow, "Border Style", 11, AC.COLORS.TEXT_2, "OVERLAY", "")
		borderStyleLabel:SetPoint("LEFT", 0, 0)
		borderStyleLabel:SetWidth(100)
		borderStyleLabel:SetJustifyH("LEFT")

		local borderStyleDropdown = AC:CreateFlatDropdown(borderStyleRow, 200, 24, {"Arena Core", "Skill Issue Outline"}, GetBorderStyleDisplay(), SaveBorderStyle)
		borderStyleDropdown:SetPoint("LEFT", borderStyleLabel, "RIGHT", 10, 0)

		local function GetBorderColor()
			local c = db.borderColor
			if type(c) == "table" then
				local r = c.r or c[1] or 0
				local g = c.g or c[2] or 0
				local b = c.b or c[3] or 0
				local a = c.a or c[4] or 1
				return r, g, b, a
			end
			return 0, 0, 0, 1
		end

		local function SaveBorderColor(r, g, b, a)
			local value = { r = r, g = g, b = b, a = a or 1 }
			if AC.ProfileManager and AC.ProfileManager.SetSetting then
				AC.ProfileManager:SetSetting("diminishingReturns.borderColor", value)
			else
				db.borderColor = value
			end
			if AC.DR_PvP and AC.DR_PvP.UpdateAllDRStages then
				AC.DR_PvP:UpdateAllDRStages()
			elseif AC.RefreshDRLayout then
				AC:RefreshDRLayout()
			end
		end

		local borderColorRow = CreateFrame("Frame", nil, groupGeneral)
		borderColorRow:SetPoint("TOPLEFT", 20, -220)
		borderColorRow:SetPoint("TOPRIGHT", -20, -220)
		borderColorRow:SetHeight(26)

		local borderColorLabel = AC:CreateStyledText(borderColorRow, "Border Color Picker", 11, AC.COLORS.TEXT_2, "OVERLAY", "")
		borderColorLabel:SetPoint("LEFT", 0, 0)
		borderColorLabel:SetWidth(120)
		borderColorLabel:SetJustifyH("LEFT")

		local borderColorButton = CreateFrame("Button", nil, borderColorRow)
		borderColorButton:SetSize(150, 24)
		borderColorButton:SetPoint("LEFT", borderColorLabel, "RIGHT", 10, 0)

		local borderColorButtonBorder = AC:CreateFlatTexture(borderColorButton, "BACKGROUND", 1, {0.196, 0.196, 0.196, 1}, 1)
		borderColorButtonBorder:SetAllPoints()

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

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

		AC:CreateStyledText(borderColorButton, "Pick", 11, {0.706, 0.706, 0.706, 1}, "OVERLAY", ""):SetPoint("LEFT", borderColorSwatch, "RIGHT", 8, 0)

		local function RefreshBorderColorDisplay()
			local r, g, b, a = GetBorderColor()
			borderColorSwatch:SetVertexColor(r, g, b, a or 1)
		end
		RefreshBorderColorDisplay()

		local borderThicknessRow = CreateFrame("Frame", nil, groupGeneral)
		borderThicknessRow:SetPoint("TOPLEFT", 20, -250)
		borderThicknessRow:SetPoint("TOPRIGHT", -20, -250)
		borderThicknessRow:SetHeight(26)

		local borderThicknessLabel = AC:CreateStyledText(borderThicknessRow, "Border Thickness", 11, AC.COLORS.TEXT_2, "OVERLAY", "")
		borderThicknessLabel:SetPoint("LEFT", 0, 0)
		borderThicknessLabel:SetWidth(100)
		borderThicknessLabel:SetJustifyH("LEFT")

		local borderThicknessValueText = AC:CreateStyledText(borderThicknessRow, "", 11, AC.COLORS.TEXT_2, "OVERLAY", "")
		borderThicknessValueText:SetPoint("RIGHT", borderThicknessRow, "RIGHT", -10, 0)
		borderThicknessValueText:SetWidth(30)
		borderThicknessValueText:SetJustifyH("RIGHT")

		local function GetBorderThickness()
			local v = tonumber(db.borderThickness) or 1
			if v < 1 then v = 1 end
			if v > 5 then v = 5 end
			return v
		end

		local function SaveBorderThickness(value)
			local v = tonumber(value) or 1
			if v < 1 then v = 1 end
			if v > 5 then v = 5 end
			if AC.ProfileManager and AC.ProfileManager.SetSetting then
				AC.ProfileManager:SetSetting("diminishingReturns.borderThickness", v)
			else
				db.borderThickness = v
			end
			borderThicknessValueText:SetText(tostring(v))
			if AC.DR_PvP and AC.DR_PvP.UpdateAllDRStages then
				AC.DR_PvP:UpdateAllDRStages()
			elseif AC.RefreshDRLayout then
				AC:RefreshDRLayout()
			end
		end

		local borderThicknessSlider = AC:CreateFlatSlider(borderThicknessRow, 120, 18, 1, 5, GetBorderThickness(), false, SaveBorderThickness)
		borderThicknessSlider:SetPoint("LEFT", borderThicknessLabel, "RIGHT", 10, 0)
		if borderThicknessSlider and borderThicknessSlider.slider then
			borderThicknessSlider.slider:SetValueStep(1)
			borderThicknessSlider.slider:SetObeyStepOnDrag(true)
			borderThicknessSlider.slider:SetScript("OnValueChanged", function(self, value)
				SaveBorderThickness(value)
			end)
		end
		borderThicknessValueText:SetText(tostring(GetBorderThickness()))

		UpdateBorderColorEnabledState = function()
			local colorToggleEnabled = (db.borderStyle ~= "pixel_black")
			if colorCodedBordersRow and colorCodedBordersRow.label and colorCodedBordersRow.checkbox and colorCodedBordersRow.checkbox.checkButton then
				if colorToggleEnabled then
					colorCodedBordersRow.label:SetTextColor(AC.COLORS.TEXT_2[1], AC.COLORS.TEXT_2[2], AC.COLORS.TEXT_2[3], AC.COLORS.TEXT_2[4] or 1)
					colorCodedBordersRow.checkbox:SetAlpha(1)
					colorCodedBordersRow.checkbox.checkButton:Enable()
				else
					colorCodedBordersRow.label:SetTextColor(AC.COLORS.TEXT_MUTED[1], AC.COLORS.TEXT_MUTED[2], AC.COLORS.TEXT_MUTED[3], AC.COLORS.TEXT_MUTED[4] or 1)
					colorCodedBordersRow.checkbox:SetAlpha(0.5)
					colorCodedBordersRow.checkbox.checkButton:Disable()
				end
			end

			local enabled = (db.borderStyle == "pixel_black")
			if enabled then
				borderColorLabel:SetTextColor(AC.COLORS.TEXT_2[1], AC.COLORS.TEXT_2[2], AC.COLORS.TEXT_2[3], AC.COLORS.TEXT_2[4] or 1)
				borderColorButton:Enable()
				borderColorButton:SetAlpha(1)
				borderThicknessLabel:SetTextColor(AC.COLORS.TEXT_2[1], AC.COLORS.TEXT_2[2], AC.COLORS.TEXT_2[3], AC.COLORS.TEXT_2[4] or 1)
				if borderThicknessSlider and borderThicknessSlider.slider and borderThicknessSlider.slider.Enable then
					borderThicknessSlider.slider:Enable()
				end
				if borderThicknessSlider and borderThicknessSlider.SetAlpha then
					borderThicknessSlider:SetAlpha(1)
				end
			else
				borderColorLabel:SetTextColor(AC.COLORS.TEXT_MUTED[1], AC.COLORS.TEXT_MUTED[2], AC.COLORS.TEXT_MUTED[3], AC.COLORS.TEXT_MUTED[4] or 1)
				borderColorButton:Disable()
				borderColorButton:SetAlpha(0.5)
				borderThicknessLabel:SetTextColor(AC.COLORS.TEXT_MUTED[1], AC.COLORS.TEXT_MUTED[2], AC.COLORS.TEXT_MUTED[3], AC.COLORS.TEXT_MUTED[4] or 1)
				if borderThicknessSlider and borderThicknessSlider.slider and borderThicknessSlider.slider.Disable then
					borderThicknessSlider.slider:Disable()
				end
				if borderThicknessSlider and borderThicknessSlider.SetAlpha then
					borderThicknessSlider:SetAlpha(0.5)
				end
			end
		end
		UpdateBorderColorEnabledState()

		local borderStyleClickTarget = (borderStyleDropdown and borderStyleDropdown.button) or borderStyleDropdown
		if borderStyleClickTarget and borderStyleClickTarget.HookScript then
			borderStyleClickTarget:HookScript("OnClick", function()
				if C_Timer and C_Timer.After then
					C_Timer.After(0, function()
						UpdateBorderColorEnabledState()
						RefreshBorderColorDisplay()
					end)
				else
					UpdateBorderColorEnabledState()
					RefreshBorderColorDisplay()
				end
			end)
		end

		borderColorButton:SetScript("OnClick", function()
			if not ColorPickerFrame then return end
			if db.borderStyle ~= "pixel_black" then return end

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

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

			local function OnColorChanged()
				local nr, ng, nb = ColorPickerFrame:GetColorRGB()
				local na = 1 - (GetOpacity() or 0)
				SaveBorderColor(nr, ng, nb, na)
				RefreshBorderColorDisplay()
			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
					SaveBorderColor(pr, pg, pb, pa)
				end
				RefreshBorderColorDisplay()
			end

			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)

		-- Spiral Animation controls
		db.spiralAnimation = db.spiralAnimation or {}
		CreateLinkedControl(groupGeneral, -270, "Checkbox", { label = "Spiral Animation", path = "spiralAnimation.enabled", val = db.spiralAnimation.enabled, default = true })
		CreateLinkedControl(groupGeneral, -300, "Slider", { label = "Spiral Opacity", path = "spiralAnimation.opacity", val = db.spiralAnimation.opacity or 100, min = 1, max = 100, default = 100, isPct = true })

		-- MIDNIGHT 12.0+ NOTICE: PvP DR Categories Only (4 categories)
		local isMidnight = AC.Midnight and AC.Midnight.isMidnight
		if isMidnight then
			local midnightNotice = AC:CreateStyledText(groupGeneral, "WoW 12.0+ PvP DR: Stun, Incapacitate, Silence, Disorient", 10, {0.2, 1.0, 0.2, 1}, "OVERLAY", "")
			midnightNotice:SetPoint("TOPLEFT", 20, -350)
			midnightNotice:SetWidth(380)
			midnightNotice:SetJustifyH("LEFT")
		else
			local legacyNotice = AC:CreateStyledText(groupGeneral, "Legacy DR System: 4 PvP categories with custom icons", 10, {1.0, 0.8, 0.2, 1}, "OVERLAY", "")
			legacyNotice:SetPoint("TOPLEFT", 20, -350)
			legacyNotice:SetWidth(380)
			legacyNotice:SetJustifyH("LEFT")
		end
	end

	local function BuildRows()
		local f = EnsureContentFrame("rows")
		if f._built then return end
		f._built = true

		local groupRows = CreateFrame("Frame", nil, f)
		groupRows:SetPoint("TOPLEFT", f, "TOPLEFT", 18, -12)
		groupRows:SetPoint("TOPRIGHT", f, "TOPRIGHT", -18, -12)
		groupRows:SetHeight(170)
		DRHairlineGroupBox(groupRows)
		AC:CreateStyledText(groupRows, "ROWS", 13, AC.COLORS.PRIMARY, "OVERLAY", ""):SetPoint("TOPLEFT", 20, -18)

		-- SIMPLIFIED: Single "Layout Mode" dropdown with growth directions
		-- CRITICAL FIX: Ensure we're using the same rows table as the theme system
		if db.rows ~= AC.DB.profile.diminishingReturns.rows then
			db.rows = AC.DB.profile.diminishingReturns.rows
		end
		db.rows = db.rows or {}

		local isMidnight = AC.Midnight and AC.Midnight.isMidnight
		local layoutModeValues = isMidnight and {[3] = "Right", [4] = "Left"} or {[1] = "Up", [2] = "Down", [3] = "Right", [4] = "Left"}
		local currentGrowth = db.rows.growthDirection or 4
		if isMidnight then
			if currentGrowth ~= 3 and currentGrowth ~= 4 then
				currentGrowth = 4
			end
		end
		local currentLayoutName = layoutModeValues[currentGrowth] or "Left"

		local layoutLabel = AC:CreateStyledText(groupRows, "Layout Mode", 11, AC.COLORS.TEXT_2, "OVERLAY", "")
		layoutLabel:SetPoint("TOPLEFT", 20, -50)
		layoutLabel:SetWidth(100)
		layoutLabel:SetJustifyH("LEFT")

		local dropdownValues = isMidnight and {"Right", "Left"} or {"Up", "Down", "Right", "Left"}
		local layoutDropdown = AC:CreateFlatDropdown(groupRows, 200, 24, dropdownValues, currentLayoutName, function(value)
			local growthMap = isMidnight and {Right = 3, Left = 4} or {Up = 1, Down = 2, Right = 3, Left = 4}
			db.rows.growthDirection = growthMap[value] or 4

			if AC.SaveDatabase then
				AC:SaveDatabase()
			end

			if AC.DR_PvP then
				if AC.RefreshDRLayout then
					AC:RefreshDRLayout()
				end
			else
				if AC.MasterFrameManager and AC.MasterFrameManager.frames then
					for i = 1, 3 do
						local frame = AC.MasterFrameManager.frames[i]
						if frame and AC.UpdateDRPositions then
							AC:UpdateDRPositions(frame)
						end
					end
				end
			end
		end)
		layoutDropdown:SetPoint("LEFT", layoutLabel, "RIGHT", 10, 0)

		-- ICON LAYOUT DROPDOWN (straight vs stacked)
		local iconLayoutLabel = AC:CreateStyledText(groupRows, "Icon Layout", 11, AC.COLORS.TEXT_2, "OVERLAY", "")
		iconLayoutLabel:SetPoint("TOPLEFT", 20, -80)
		iconLayoutLabel:SetWidth(100)
		iconLayoutLabel:SetJustifyH("LEFT")

		local stackingModeValues = isMidnight and {"Straight"} or {"Straight", "Stacked"}
		local currentStacking = db.rows.stackingMode or "straight"
		if isMidnight then
			currentStacking = "straight"
			db.rows.stackingMode = "straight"
		end
		local currentStackingName = (currentStacking == "stacked") and "Stacked" or "Straight"

		local iconLayoutDropdown = AC:CreateFlatDropdown(groupRows, 200, 24, stackingModeValues, currentStackingName, function(value)
			db.rows.stackingMode = (value == "Stacked") and "stacked" or "straight"
			if isMidnight then
				db.rows.stackingMode = "straight"
			end
			if AC.DR_PvP and AC.RefreshDRLayout then
				AC:RefreshDRLayout()
			end
		end)
		iconLayoutDropdown:SetPoint("LEFT", iconLayoutLabel, "RIGHT", 10, 0)

		-- DYNAMIC POSITIONING CHECKBOX (collapse gaps when DRs expire)
		local dynamicLabel = AC:CreateStyledText(groupRows, "Dynamic Positioning", 11, AC.COLORS.TEXT_2, "OVERLAY", "")
		dynamicLabel:SetPoint("TOPLEFT", 20, -110)
		dynamicLabel:SetWidth(150)
		dynamicLabel:SetJustifyH("LEFT")

		local dynamicEnabled = (db.rows.dynamicPositioning ~= false)
		if isMidnight then
			dynamicEnabled = true
			db.rows.dynamicPositioning = true
		end
		local dynamicCheckbox = AC:CreateFlatCheckbox(groupRows, 16, dynamicEnabled, function(checked)
			db.rows.dynamicPositioning = checked
			if AC.DR_PvP and AC.RefreshDRLayout then
				AC:RefreshDRLayout()
			end
		end)
		dynamicCheckbox:SetPoint("LEFT", dynamicLabel, "RIGHT", 10, 0)
		if isMidnight and dynamicCheckbox.checkButton and dynamicCheckbox.checkButton.Disable then
			dynamicCheckbox.checkButton:Disable()
			dynamicLabel:SetTextColor(AC.COLORS.TEXT_MUTED[1], AC.COLORS.TEXT_MUTED[2], AC.COLORS.TEXT_MUTED[3], AC.COLORS.TEXT_MUTED[4] or 1)
		end

		local dynamicTooltip = AC:CreateStyledText(groupRows, "Icons slide together to fill gaps when DRs expire", 9, AC.COLORS.TEXT_MUTED, "OVERLAY", "")
		dynamicTooltip:SetPoint("TOPLEFT", dynamicLabel, "BOTTOMLEFT", 0, -4)
		dynamicTooltip:SetWidth(380)
		dynamicTooltip:SetJustifyH("LEFT")
	end

	local function BuildPosSize()
		local f = EnsureContentFrame("possize")
		if f._built then return end
		f._built = true

		local groupPos = CreateFrame("Frame", nil, f)
		groupPos:SetPoint("TOPLEFT", f, "TOPLEFT", 18, -12)
		groupPos:SetPoint("TOPRIGHT", f, "TOPRIGHT", -18, -12)
		groupPos:SetHeight(110)
		DRHairlineGroupBox(groupPos)
		AC:CreateStyledText(groupPos, "POSITIONING", 13, AC.COLORS.PRIMARY, "OVERLAY", ""):SetPoint("TOPLEFT", 20, -18)
		AC:CreateEnhancedSliderRow(groupPos, "Horizontal", -50, "diminishingReturns.positioning.horizontal", "dr_positioning_horizontal")
		AC:CreateEnhancedSliderRow(groupPos, "Vertical", -80, "diminishingReturns.positioning.vertical", "dr_positioning_vertical")

		local groupSize = CreateFrame("Frame", nil, f)
		groupSize:SetPoint("TOP", groupPos, "BOTTOM", 0, -12)
		groupSize:SetPoint("LEFT", groupPos, "LEFT", 0, 0)
		groupSize:SetPoint("RIGHT", groupPos, "RIGHT", 0, 0)
		groupSize:SetHeight(140)
		DRHairlineGroupBox(groupSize)
		AC:CreateStyledText(groupSize, "SIZING", 13, AC.COLORS.PRIMARY, "OVERLAY", ""):SetPoint("TOPLEFT", 20, -18)
		AC:CreateEnhancedSliderRow(groupSize, "Size", -50, "diminishingReturns.sizing.size", "dr_size")
		AC:CreateEnhancedSliderRow(groupSize, "Font Size", -80, "diminishingReturns.sizing.fontSize", "dr_font")
		AC:CreateEnhancedSliderRow(groupSize, "Stage Font Size", -110, "diminishingReturns.sizing.stageFontSize", "dr_stage_font")
	end


	tabGeneral:SetScript("OnClick", function()
		BuildGeneral()
		SetTab("general")
	end)
	tabRows:SetScript("OnClick", function()
		BuildRows()
		SetTab("rows")
	end)
	tabPosSize:SetScript("OnClick", function()
		BuildPosSize()
		SetTab("possize")
	end)

	BuildGeneral()
	SetTab("general")
	
	-- CRITICAL: Force DR layout refresh when page loads to ensure settings take effect
	if AC.RefreshDRLayout then
		C_Timer.After(0.1, function()
			if AC.RefreshDRLayout then
				AC:RefreshDRLayout()
			end
		end)
	end
end

AC:RegisterPage("DiminishingReturns", CreateDiminishingReturnsPage)
AC:RegisterPage("dr", CreateDiminishingReturnsPage)