-- ============================================================================
-- File: ArenaCore/Core/Pages/Textures.lua (CLEAN REBUILD)
-- Purpose: Clean rebuild of Textures settings page matching Cast Bars pattern
-- ============================================================================

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

local V = AC.Vanity

-- Localization helper
local function L(key)
    if AC.UILocalization then
        return AC.UILocalization:Get("TEXTURES", key, key)
    end
    return key
end

local function TexturesHairlineGroupBox(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

-- SINGLE SOURCE OF TRUTH: All defaults come from AC.DEFAULTS.textures
local function GetDefaults()
    return AC.DEFAULTS and AC.DEFAULTS.textures or {
        healthBarTexture = "Interface\\AddOns\\ArenaCore\\Media\\Frametextures\\texture1.tga",
        useDifferentPowerBarTexture = true,
        powerBarTexture = "Interface\\AddOns\\ArenaCore\\Media\\Frametextures\\texture1.tga",
        useDifferentCastBarTexture = false,
        castBarTexture = "Interface\\AddOns\\ArenaCore\\Media\\Frametextures\\texture1.tga",
        uninterruptibleCastBarTexture = "Interface\\AddOns\\ArenaCore\\Media\\Frametextures\\texture24.tga",
        positioning = { horizontal = 56, vertical = 6, spacing = 8 },
        sizing = {
            healthWidth = 128, healthHeight = 18,
            resourceWidth = 136, resourceHeight = 8
        }
    }
end

-- Get current database values with proper fallbacks
local function GetDB()
    if not AC.DB or not AC.DB.profile then return GetDefaults() end
    return AC.DB.profile.textures or GetDefaults()
end

-- Update textures immediately when settings change (NO INFINITE LOOP)
local function RefreshTextures()
    print("|cff00FFFF[Textures Clean]:|r Refreshing textures...")
    if AC.RefreshTexturesLayout then
        AC:RefreshTexturesLayout()
    else
        print("|cff00FFFF[Textures Clean]:|r RefreshTexturesLayout function not found")
    end
end

local TEXTURE_PATH = "Interface\\AddOns\\ArenaCore\\Media\\Frametextures\\"
local TEXTURE_LIST = {}
for i = 1, 27 do
    table.insert(TEXTURE_LIST, "Texture " .. i)
end

local function GetTexturePath(textureName)
    local index = string.match(textureName or "", "%d+")
    if index then return TEXTURE_PATH .. "texture" .. index .. ".tga" end
    return TEXTURE_PATH .. "texture1.tga"
end

local function GetTextureName(texturePath)
    local index = string.match(texturePath or "", "texture(%d+).tga")
    if index then return "Texture " .. index end
    return "Texture 1"
end

-- Texture dropdown with live preview using CreateFlatDropdownWithPreview
local function CreateTextureDropdown(parent, label, y, dbKey, options)
    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, AC.COLORS.TEXT_2, "OVERLAY", "")
    labelText:SetPoint("LEFT", 0, 0)
    labelText:SetWidth(120)
    labelText:SetJustifyH("LEFT")

    -- Get current value from database
    local db = GetDB()
    local currentValue = db[dbKey]
    
    -- If no value in DB, use the default from GetDefaults()
    if not currentValue then
        local defaults = GetDefaults()
        currentValue = defaults[dbKey]
    end
    
    -- Convert stored path back to display name for texture dropdowns
    local displayValue = "Texture 1" -- fallback
    if currentValue and type(currentValue) == "string" and currentValue:match("texture%d+%.tga") then
        displayValue = GetTextureName(currentValue)
    end

    local function OnSelect(selectedText)
        local path = "textures." .. dbKey
        local texturePath = GetTexturePath(selectedText)
        if AC.ProfileManager and AC.ProfileManager.SetSetting then
            AC.ProfileManager:SetSetting(path, texturePath)
        else
            AC.DB.profile = AC.DB.profile or {}
            AC.DB.profile.textures = AC.DB.profile.textures or {}
            AC.DB.profile.textures[dbKey] = texturePath
        end
        if AC.RefreshBarTextures then AC:RefreshBarTextures() end
    end

    -- Dropdown with preview swatch
    local dropdown = AC:CreateFlatDropdownWithPreview(row, 200, 24, options, displayValue, OnSelect, GetTexturePath)
    dropdown:SetPoint("LEFT", labelText, "RIGHT", 10, 0)

    -- Overlay blocker to disable interactions when needed
    local blocker = CreateFrame("Frame", nil, row)
    blocker:SetAllPoints(dropdown)
    blocker:EnableMouse(true)
    blocker:Hide()

    -- Provide a simple enable/disable API on the row
    row.dropdown = dropdown
    row.blocker = blocker
    function row:SetEnabled(enabled)
        if enabled then
            self.blocker:Hide()
            self.dropdown:SetAlpha(1)
        else
            self.blocker:Show()
            self.dropdown:SetAlpha(0.4)
        end
    end

    return row
end

-- EXACT COPY of Cast Bars slider pattern for perfect compatibility
local function CreateCleanSlider(parent, label, y, dbPath, min, max, isPct)
    local row = CreateFrame("Frame", nil, parent)
    row:SetPoint("TOPLEFT", 20, y)
    row:SetPoint("TOPRIGHT", -20, y)
    row:SetHeight(26)

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

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

    -- Min/Max labels
    local minText = AC:CreateStyledText(row, isPct and (min .. "%") or tostring(min), 9, AC.COLORS.TEXT_MUTED, "OVERLAY", "")
    minText:SetPoint("LEFT", downBtn, "RIGHT", 6, 0)
    minText:SetWidth(25)
    minText:SetJustifyH("RIGHT")

    -- Value display
    local valueText = AC:CreateStyledText(row, "", 11, AC.COLORS.TEXT_2, "OVERLAY", "")
    valueText:SetWidth(70)
    valueText:SetJustifyH("CENTER")

    -- Get current value from database
    local db = GetDB()
    local keys = {}
    for k in string.gmatch(dbPath, "([^%.]+)") do
        table.insert(keys, k)
    end
    
    local currentValue = db
    for _, key in ipairs(keys) do
        currentValue = currentValue and currentValue[key]
    end
    
    -- Use default if no value exists
    local defaults = GetDefaults()
    local defaultValue = defaults
    for _, key in ipairs(keys) do
        defaultValue = defaultValue and defaultValue[key]
    end
    currentValue = currentValue or defaultValue or (isPct and 100 or 0)

    -- OnChange function - ONLY called by user interaction
    local function OnChange(value)
        local fullPath = "textures." .. dbPath
        if AC.ProfileManager and AC.ProfileManager.SetSetting then
            AC.ProfileManager:SetSetting(fullPath, value)
        else
            AC.DB.profile = AC.DB.profile or {}
            AC.DB.profile.textures = AC.DB.profile.textures or {}

            local target = AC.DB.profile.textures
            for i = 1, #keys - 1 do
                target[keys[i]] = target[keys[i]] or {}
                target = target[keys[i]]
            end
            target[keys[#keys]] = value
        end

        -- Update display
        if isPct then
            valueText:SetText(string.format("%.0f%%", value))
        else
            valueText:SetText(string.format("%.0f", value))
        end

        -- Refresh textures
        RefreshTextures()
    end

    -- Create slider
    local slider = AC:CreateFlatSlider(row, 120, 18, min, max, currentValue, isPct, OnChange)
    slider:SetPoint("LEFT", minText, "RIGHT", 10, 0)

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

    -- Max label
    local maxText = AC:CreateStyledText(row, isPct and (max .. "%") or tostring(max), 9, AC.COLORS.TEXT_MUTED, "OVERLAY", "")
    maxText:SetPoint("LEFT", upBtn, "RIGHT", 6, 0)
    maxText:SetWidth(20)
    maxText:SetJustifyH("LEFT")

    -- Position value text
    valueText:SetPoint("LEFT", maxText, "RIGHT", 8, 0)

    -- Initialize display WITHOUT calling OnChange
    if isPct then
        valueText:SetText(string.format("%.0f%%", currentValue))
    else
        valueText:SetText(string.format("%.0f", currentValue))
    end

    -- Button handlers
    downBtn:SetScript("OnClick", function()
        local current = slider.slider:GetValue()
        local newValue = math.max(min, current - 1)
        slider.slider:SetValue(newValue)
    end)
    
    upBtn:SetScript("OnClick", function()
        local current = slider.slider:GetValue()
        local newValue = math.min(max, current + 1)
        slider.slider:SetValue(newValue)
    end)

    return row
end

-- Clean checkbox creation
local function CreateCleanCheckbox(parent, label, y, dbPath, onToggle)
    local row = CreateFrame("Frame", nil, parent)
    row:SetPoint("TOPLEFT", 20, y)
    row:SetPoint("TOPRIGHT", -20, y)
    row:SetHeight(26)

    local db = GetDB()
    local keys = {}
    for k in string.gmatch(dbPath, "([^%.]+)") do
        table.insert(keys, k)
    end

    local currentValue = db
    for _, key in ipairs(keys) do
        currentValue = currentValue and currentValue[key]
    end
    currentValue = currentValue or false

    local function OnChange(value)
        local path = "textures." .. dbPath
        if AC.ProfileManager and AC.ProfileManager.SetSetting then
            AC.ProfileManager:SetSetting(path, value)
        else
            AC.DB.profile = AC.DB.profile or {}
            AC.DB.profile.textures = AC.DB.profile.textures or {}
            if dbPath == "useDifferentPowerBarTexture" then
                AC.DB.profile.textures.useDifferentPowerBarTexture = value
            elseif dbPath == "useDifferentCastBarTexture" then
                AC.DB.profile.textures.useDifferentCastBarTexture = value
            end
        end
        if onToggle then pcall(onToggle, value) end
        if AC.RefreshBarTextures then AC:RefreshBarTextures() end
    end

    local checkbox = AC:CreateFlatCheckbox(row, 20, currentValue, OnChange)
    checkbox:SetPoint("LEFT", 0, 0)

    local labelText = AC:CreateStyledText(row, label, 12, AC.COLORS.TEXT_2, "OVERLAY", "")
    labelText:SetPoint("LEFT", checkbox, "RIGHT", 8, 0)

    return row
end

-- Main page creation function
local function CreateCleanTexturesPage(parent)
    local db = GetDB()

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

    -- Create the top button bar
    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 CreateTexturesSubTabButton(parentFrame, text, width, height)
        local COLORS = AC.COLORS or {}

        local btn = CreateFrame("Button", nil, parentFrame)
        btn:SetSize(width or 102, height or 30)
        btn:SetFrameLevel(parentFrame:GetFrameLevel() + 1)

        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)
            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", 1, -1)
        outlineLeft:SetPoint("BOTTOMLEFT", btn, "BOTTOMLEFT", 1, 1)
        outlineLeft:SetWidth(1)

        local outlineRight = CreateGlowLine()
        outlineRight:SetPoint("TOPRIGHT", btn, "TOPRIGHT", -1, -1)
        outlineRight:SetPoint("BOTTOMRIGHT", btn, "BOTTOMRIGHT", -1, 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

    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.__texturesContentFrames = parent.__texturesContentFrames or {}
        if parent.__texturesContentFrames[key] then
            return parent.__texturesContentFrames[key]
        end
        local f = CreateFrame("Frame", nil, contentRoot)
        f:SetAllPoints(contentRoot)
        f:Hide()
        parent.__texturesContentFrames[key] = f
        return f
    end

    local tabs = {}
    local selectedTab

    local function HideAllContent()
        if not parent.__texturesContentFrames then return end
        for _, f in pairs(parent.__texturesContentFrames) do
            if f and f.Hide then
                f:Hide()
            end
        end
    end

    local function SelectTab(key)
        selectedTab = key
        for k, t in pairs(tabs) do
            t:SetSelected(k == key)
        end
        HideAllContent()
        local f = EnsureContentFrame(key)
        f:Show()

        if key == "textures" then
            if not f.__built then
                -- Group 1: BAR TEXTURES
                local groupTextures = CreateFrame("Frame", nil, f)
                groupTextures:SetPoint("TOPLEFT", f, "TOPLEFT", 18, -18)
                groupTextures:SetPoint("TOPRIGHT", f, "TOPRIGHT", -18, -18)
                groupTextures:SetHeight(260)
                TexturesHairlineGroupBox(groupTextures)
                local titleTextures = AC:CreateStyledText(groupTextures, L("bar_textures"), 13, AC.COLORS.PRIMARY, "OVERLAY", "")
                titleTextures:SetPoint("TOPLEFT", 20, -18)

                local healthRow        = CreateTextureDropdown(groupTextures, L("health_bar"), -50, "healthBarTexture", TEXTURE_LIST)
                local powerRow         = CreateTextureDropdown(groupTextures, L("power_bar"), -115, "powerBarTexture", TEXTURE_LIST)
                local castRow          = CreateTextureDropdown(groupTextures, L("cast_bar"), -180, "castBarTexture", TEXTURE_LIST)
                local unintRow         = CreateTextureDropdown(groupTextures, L("cast_bar_uninterruptible"), -215, "uninterruptibleCastBarTexture", TEXTURE_LIST)

                -- Checkboxes that control the dependent dropdowns
                CreateCleanCheckbox(groupTextures, L("use_different_power_texture"), -85, "useDifferentPowerBarTexture", function(enabled)
                    if powerRow and powerRow.SetEnabled then powerRow:SetEnabled(enabled) end
                end)

                CreateCleanCheckbox(groupTextures, L("use_different_cast_texture"), -150, "useDifferentCastBarTexture", function(enabled)
                    if castRow and castRow.SetEnabled then castRow:SetEnabled(enabled) end
                end)

                -- Initialize enabled state based on current DB
                if powerRow and powerRow.SetEnabled then powerRow:SetEnabled(db.useDifferentPowerBarTexture ~= false) end
                if castRow  and castRow.SetEnabled  then castRow:SetEnabled(db.useDifferentCastBarTexture  == true)  end
                -- Uninterruptible row is always active (no checkbox needed)
                if unintRow and unintRow.SetEnabled then unintRow:SetEnabled(true) end

                f.__built = true
            end
        elseif key == "positioning" then
            if not f.__built then
                -- Group 2: POSITIONING
                local groupPos = CreateFrame("Frame", nil, f)
                groupPos:SetPoint("TOPLEFT", f, "TOPLEFT", 18, -18)
                groupPos:SetPoint("TOPRIGHT", f, "TOPRIGHT", -18, -18)
                groupPos:SetHeight(140)
                TexturesHairlineGroupBox(groupPos)
                local titlePos = AC:CreateStyledText(groupPos, L("positioning"), 13, AC.COLORS.PRIMARY, "OVERLAY", "")
                titlePos:SetPoint("TOPLEFT", 20, -18)

                -- Enhanced sliders with ultra-fine precision for bar positioning
                AC:CreateEnhancedSliderRow(groupPos, L("horizontal"), -50, "textures.positioning.horizontal", "texture_positioning_horizontal")
                AC:CreateEnhancedSliderRow(groupPos, L("vertical"), -80, "textures.positioning.vertical", "texture_positioning_vertical")
                AC:CreateEnhancedSliderRow(groupPos, L("spacing"), -110, "textures.positioning.spacing", "texture_spacing_ultra")

                f.__built = true
            end
        elseif key == "sizing" then
            if not f.__built then
                -- Group 3: SIZING
                local groupSize = CreateFrame("Frame", nil, f)
                groupSize:SetPoint("TOPLEFT", f, "TOPLEFT", 18, -18)
                groupSize:SetPoint("TOPRIGHT", f, "TOPRIGHT", -18, -18)
                groupSize:SetHeight(170)
                TexturesHairlineGroupBox(groupSize)
                local titleSize = AC:CreateStyledText(groupSize, L("sizing"), 13, AC.COLORS.PRIMARY, "OVERLAY", "")
                titleSize:SetPoint("TOPLEFT", 20, -18)

                -- Enhanced sliders with custom ranges
                AC:CreateEnhancedSliderRow(groupSize, L("health_resource_width"), -50, "textures.sizing.healthWidth", nil, { scaleMin = 1, scaleMax = 10, pixelMin = 80, pixelMax = 200, tooltip = "Health and resource bar width" })
                AC:CreateEnhancedSliderRow(groupSize, L("health_height"), -80, "textures.sizing.healthHeight", nil, { scaleMin = 1, scaleMax = 10, pixelMin = 10, pixelMax = 40, tooltip = "Health bar height" })
                AC:CreateEnhancedSliderRow(groupSize, L("resource_height"), -110, "textures.sizing.resourceHeight", nil, { scaleMin = 1, scaleMax = 10, pixelMin = 1, pixelMax = 20, tooltip = "Resource bar height" })

                f.__built = true
            end
        end
    end

    local tabTextures = CreateTexturesSubTabButton(buttonBar, L("bar_textures"), 110, 30)
    tabTextures:SetPoint("LEFT", buttonBar, "LEFT", 18, 0)
    tabs.textures = tabTextures

    local tabPos = CreateTexturesSubTabButton(buttonBar, L("positioning"), 110, 30)
    tabPos:SetPoint("LEFT", tabTextures, "RIGHT", 8, 0)
    tabs.positioning = tabPos

    local tabSize = CreateTexturesSubTabButton(buttonBar, L("sizing"), 90, 30)
    tabSize:SetPoint("LEFT", tabPos, "RIGHT", 8, 0)
    tabs.sizing = tabSize

    tabTextures:SetScript("OnClick", function() SelectTab("textures") end)
    tabPos:SetScript("OnClick", function() SelectTab("positioning") end)
    tabSize:SetScript("OnClick", function() SelectTab("sizing") end)

    SelectTab("textures")
end

-- Register the clean page
AC:RegisterPage("Textures", CreateCleanTexturesPage)