-- File: ArenaCore/Core/Pages/TrinketsOther.lua
local addonName, _ns = ...
local addon = _G.ArenaCore
if not addon then return end

local V = addon.Vanity
local C = addon.COLORS

-- Helper function to get the database profile
local function DB()
  return (addon.DB and addon.DB.profile) or {}
end
-- File: TrinketsOther.lua
-- Purpose: Corrected reset function that includes the 'enabled' state.

-- Store slider references for direct updates
local sliderWidgets = {}

local function ResetTrinketSettings()
  local db = DB()
  if not db then return end

  -- Use ACTUAL defaults from Init.lua instead of hardcoded values
  if addon.DEFAULTS then
    -- Deep copy function 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
    
    -- Reset to actual defaults (your current coordinates)
    if addon.DEFAULTS.trinkets then
      db.trinkets = DeepCopy(addon.DEFAULTS.trinkets)
      print("|cffFFAA00Debug:|r Reset trinkets to horizontal=" .. db.trinkets.positioning.horizontal .. ", vertical=" .. db.trinkets.positioning.vertical)
    end
    if addon.DEFAULTS.specIcons then
      db.specIcons = DeepCopy(addon.DEFAULTS.specIcons)
      print("|cffFFAA00Debug:|r Reset specIcons to horizontal=" .. db.specIcons.positioning.horizontal .. ", vertical=" .. db.specIcons.positioning.vertical)
    end
    if addon.DEFAULTS.racials then
      db.racials = DeepCopy(addon.DEFAULTS.racials)
      print("|cffFFAA00Debug:|r Reset racials to horizontal=" .. db.racials.positioning.horizontal .. ", vertical=" .. db.racials.positioning.vertical)
    end
  end

  -- Force a refresh of the ARENA FRAMES to update their layout
  if addon.RefreshTrinketsOtherLayout then
    addon:RefreshTrinketsOtherLayout()
  end

  if addon.ArenaFrameThemes and addon.ArenaFrameThemes.SaveCurrentThemeSettings then
    addon.ArenaFrameThemes:SaveCurrentThemeSettings()
  end
  
  -- Spec icons are now handled by main Arena Frames - no separate logic needed

  -- CRITICAL FIX: Directly update slider widgets using WoW API SetValue()
  print("|cff8B45FFArenaCore:|r Resetting sliders directly using SetValue()...")
  
  -- Update each slider widget directly
  for path, slider in pairs(sliderWidgets) do
    if slider and slider.SetValue then
      local value = addon.Settings:Get(path)
      if value then
        slider:SetValue(value)
        print("|cffFFAA00Debug:|r Set slider " .. path .. " to value " .. tostring(value))
      end
    end
  end
  
  print("|cff8B45FFArenaCore:|r Trinkets/Other reset complete!")
end
-- File: Core/Pages/TrinketsOther.lua
-- Purpose: Correctly define the two helper functions in the proper scope.

-- Helper function to create a standardized slider row for this page
local function CreateSliderSetting(parent, label, y, path, min, max, isPct, compactDisplay)
  local row = CreateFrame("Frame", nil, parent)
  row:SetPoint("TOPLEFT", 20, y); row:SetPoint("TOPRIGHT", -20, y); row:SetHeight(26)

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

  local l = addon:CreateStyledText(row, label, 11, C.TEXT_2, "OVERLAY", ""); l:SetPoint("LEFT", 0, 0); l:SetWidth(70); l:SetJustifyH("LEFT")
  local minT = addon:CreateStyledText(row, isPct and (displayMin .. "%") or tostring(displayMin), 9, C.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 keys = {}; for k in string.gmatch(path, "([^%.]+)") do table.insert(keys, k) end
  
  local function GetValue()
    local target = DB(); for i=1, #keys do target = target and target[keys[i]] end
    return target
  end
  
  local val = GetValue() or (isPct and 100 or 0)
  local valT = addon:CreateStyledText(row, "", 11, C.TEXT_2, "OVERLAY", ""); valT:SetWidth(70); valT:SetJustifyH("CENTER")

  local function OnChange(value)
    -- DEBUG: Show what's being changed
    print("|cff00FFFF[SLIDER CHANGE]|r path=" .. path .. ", newValue=" .. tostring(value))
    
    -- Save to global database
    local target = addon.DB.profile; for i=1, #keys - 1 do target[keys[i]] = target[keys[i]] or {}; target = target[keys[i]] end
    local oldValue = target[keys[#keys]]
    target[keys[#keys]] = value
    
    print("|cff00FFFF[SLIDER CHANGE]|r   Global DB: " .. tostring(oldValue) .. " → " .. tostring(value))
    
    -- CRITICAL FIX: Also save to theme-specific location for theme switching
    local currentTheme = addon.ArenaFrameThemes and addon.ArenaFrameThemes:GetCurrentTheme()
    if currentTheme and addon.DB.profile.themeData and addon.DB.profile.themeData[currentTheme] then
      local themeTarget = addon.DB.profile.themeData[currentTheme]
      for i=1, #keys - 1 do 
        themeTarget[keys[i]] = themeTarget[keys[i]] or {}
        themeTarget = themeTarget[keys[i]]
      end
      local oldThemeValue = themeTarget[keys[#keys]]
      themeTarget[keys[#keys]] = value
      print("|cff00FFFF[SLIDER CHANGE]|r   Theme DB: " .. tostring(oldThemeValue) .. " → " .. tostring(value))
    end
    
    if isPct then 
      valT:SetText(string.format("%.1f%%", value))  -- Show 1 decimal for percentages
    elseif compactDisplay then
      valT:SetText(string.format("%.0f", math.floor(value / 100)))
    else 
      valT:SetText(string.format("%.1f", value))  -- CRITICAL FIX: Show 1 decimal to display exact position (202.4 instead of 202)
    end
    
    if addon.RefreshTrinketsOtherLayout then
      addon:RefreshTrinketsOtherLayout()
    end
  end

  local slider = addon:CreateFlatSlider(row, 120, 18, min, max, val, isPct, OnChange)
  slider:SetPoint("LEFT", downBtn, "RIGHT", 4, 0)
  
  -- CRITICAL FIX: Store slider reference for direct updates during reset
  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 = addon:CreateStyledText(row, isPct and (displayMax .. "%") or tostring(displayMax), 9, C.TEXT_MUTED, "OVERLAY", ""); maxT:SetPoint("LEFT", upBtn, "RIGHT", 6, 0); maxT:SetWidth(20); maxT:SetJustifyH("LEFT")
  valT:SetPoint("LEFT", maxT, "RIGHT", 8, 0)
  
  -- Initialize the value display
  OnChange(val)

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

  return row
end

-- Helper function to create a dropdown setting
local function CreateDropdownSetting(parent, label, y, path, optionsMap, defaultValue, dropdownWidth, menuWidth)
  local row = CreateFrame("Frame", nil, parent)
  row:SetPoint("TOPLEFT", 20, y); row:SetPoint("TOPRIGHT", -20, y); row:SetHeight(26)

  -- Use custom width or default to 180 for button
  dropdownWidth = dropdownWidth or 180
  -- Menu width can be different (wider) than button width
  menuWidth = menuWidth or dropdownWidth

  local l = addon:CreateStyledText(row, label, 12, C.TEXT_2, "OVERLAY", ""); l:SetPoint("LEFT", 0, 0); l:SetWidth(120); l:SetJustifyH("LEFT")
  
  local keys = {}; for k in string.gmatch(path, "([^%.]+)") do table.insert(keys, k) end
  
  -- Create display options array and mapping
  local displayOptions = {}
  local displayToValue = {}
  local valueToDisplay = {}
  
  for displayText, internalValue in pairs(optionsMap) do
    table.insert(displayOptions, displayText)
    displayToValue[displayText] = internalValue
    valueToDisplay[internalValue] = displayText
  end

  local function GetValue()
    local target = DB(); for i=1, #keys do target = target and target[keys[i]] end
    local currentValue = target or defaultValue
    return valueToDisplay[currentValue] or displayOptions[1]
  end
  
  local function OnChange(displayText)
    local internalValue = displayToValue[displayText]
    
    -- Detect what setting is being changed for appropriate messaging and refresh
    local isClassIconTheme = path:find("classIcons%.theme")
    local isClassIconBorderStyle = path:find("classIcons%.sizing%.borderStyle")
    local isTrinketDesign = path:find("trinkets%.iconDesign")
    local isTrinketStyle = path:find("trinkets%.style")
    local isRacialStyle = path:find("racials%.style")
    local isRacialThickness = path:find("racials%.borderThickness")
    local isSpecIconBorderStyle = path:find("specIcons%.sizing%.borderStyle")
    
    -- User-friendly confirmation message with display text
    if isClassIconTheme then
      print("|cff8B45FF[CLASS ICON THEME]|r Class Icon Theme changed to: " .. displayText)
    elseif isClassIconBorderStyle then
      print("|cff8B45FF[CLASS ICON BORDER]|r Class Icon Border Style changed to: " .. displayText)
    elseif isTrinketDesign then
      print("|cff8B45FF[TRINKET CHANGE]|r Trinket Design changed to: " .. displayText)
    elseif isTrinketStyle then
      print("|cff8B45FF[TRINKET CHANGE]|r Trinket Style changed to: " .. displayText)
    elseif isRacialStyle then
      print("|cff8B45FF[RACIAL CHANGE]|r Racial Style changed to: " .. displayText)
    elseif isRacialThickness then
      print("|cff8B45FF[RACIAL CHANGE]|r Racial Border Thickness changed to: " .. displayText)
    elseif isSpecIconBorderStyle then
      print("|cff8B45FF[SPEC ICON BORDER]|r Spec Icon Border Style changed to: " .. displayText)
    end
    
    -- Use the same saving mechanism as sliders
    if addon.ProfileManager and addon.ProfileManager.SetSetting then
      addon.ProfileManager:SetSetting(path, internalValue)
    end
    if addon.FrameSystem and addon.FrameSystem.SetSetting then
      addon.FrameSystem:SetSetting(path, internalValue)
    end
    if addon.Settings and addon.Settings.Set then
      addon.Settings:Set(path, internalValue)
    end
    
    -- Fallback direct setting (same as before)
    local target = addon.DB.profile; for i=1, #keys - 1 do target[keys[i]] = target[keys[i]] or {}; target = target[keys[i]] end
    target[keys[#keys]] = internalValue
    
    -- Refresh appropriate system based on what changed
    if isClassIconTheme then
      -- Refresh class icons for all arena frames
      if addon.RefreshClassIcons then
        addon:RefreshClassIcons()
      elseif addon.RefreshTrinketsOtherLayout then
        addon:RefreshTrinketsOtherLayout()
      end
      
      -- CRITICAL: Also refresh Class Portrait Swap system to respect new theme
      if addon.ClassPortraitSwap and addon.ClassPortraitSwap.RefreshAll then
        C_Timer.After(0.1, function()
          addon.ClassPortraitSwap:RefreshAll()
        end)
      end
    elseif isClassIconBorderStyle then
      if addon.__UpdateClassIconBorderThicknessEnabled then
        addon.__UpdateClassIconBorderThicknessEnabled()
      end
      if addon.RefreshClassIcons then
        addon:RefreshClassIcons()
      elseif addon.RefreshTrinketsOtherLayout then
        addon:RefreshTrinketsOtherLayout()
      end
    elseif isTrinketDesign then
      -- CRITICAL FIX: Only refresh trinket icons, don't call full layout refresh
      -- Full refresh can trigger checkbox re-creation which toggles enabled state
      if addon.RefreshTrinketIcons then
        addon:RefreshTrinketIcons()
      elseif addon.RefreshTrinketsOtherLayout then
        addon:RefreshTrinketsOtherLayout()
      end
    elseif isTrinketStyle then
      -- CRITICAL FIX: Refresh trinket icons to apply new border style in real-time
      if addon.__UpdateTrinketBorderThicknessEnabled then
        addon.__UpdateTrinketBorderThicknessEnabled()
      end
      if addon.RefreshTrinketIcons then
        addon:RefreshTrinketIcons()
      elseif addon.TrinketsRacials and addon.TrinketsRacials.RefreshAll then
        addon.TrinketsRacials:RefreshAll()
      elseif addon.RefreshTrinketsOtherLayout then
        addon:RefreshTrinketsOtherLayout()
      end
    elseif isRacialStyle then
      if addon.__UpdateRacialBorderThicknessEnabled then
        addon.__UpdateRacialBorderThicknessEnabled()
      end
      if addon.RefreshRacials then
        addon:RefreshRacials()
      elseif addon.TrinketsRacials and addon.TrinketsRacials.RefreshAll then
        addon.TrinketsRacials:RefreshAll()
      elseif addon.RefreshTrinketsOtherLayout then
        addon:RefreshTrinketsOtherLayout()
      end
    elseif isRacialThickness then
      if addon.RefreshRacials then
        addon:RefreshRacials()
      elseif addon.TrinketsRacials and addon.TrinketsRacials.RefreshAll then
        addon.TrinketsRacials:RefreshAll()
      elseif addon.RefreshTrinketsOtherLayout then
        addon:RefreshTrinketsOtherLayout()
      end
    elseif isSpecIconBorderStyle then
      if addon.__UpdateSpecIconBorderThicknessEnabled then
        addon.__UpdateSpecIconBorderThicknessEnabled()
      end

      if addon.RefreshTrinketsOtherLayout then
        addon:RefreshTrinketsOtherLayout()
      end
    end
  end

  -- Create dropdown with custom menu width support
  local dropdown = addon:CreateFlatDropdown(row, dropdownWidth, 24, displayOptions, GetValue(), OnChange)
  dropdown:SetPoint("LEFT", l, "RIGHT", 10, 0)
  
  -- CUSTOM: If menuWidth is different from dropdownWidth, adjust the menu
  if menuWidth ~= dropdownWidth and dropdown.menu then
    dropdown.menu:SetWidth(menuWidth)
    if dropdown.menu.scrollChild then
      dropdown.menu.scrollChild:SetWidth(menuWidth - 4)
    end
  end
  
  -- Store dropdown reference on the row for external access
  row.dropdown = dropdown
  
  return row
end

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

  local l = addon:CreateStyledText(row, label, 12, C.TEXT_2, "OVERLAY", "")
  l:SetPoint("LEFT", 0, 0)
  l:SetWidth(120)
  l:SetJustifyH("LEFT")

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

  local function GetValue()
    local target = DB(); for i=1, #keys do target = target and target[keys[i]] end
    if type(target) == "table" then
      local r = target.r or target[1] or 0
      local g = target.g or target[2] or 0
      local b = target.b or target[3] or 0
      local a = target.a or target[4] or 1
      return r, g, b, a
    end
    return 0, 0, 0, 1
  end

  local function SaveValue(r, g, b, a)
    local value = { r = r, g = g, b = b, a = a or 1 }

    if addon.ProfileManager and addon.ProfileManager.SetSetting then
      addon.ProfileManager:SetSetting(path, value)
    else
      local target = addon.DB.profile
      for i=1, #keys - 1 do
        target[keys[i]] = target[keys[i]] or {}
        target = target[keys[i]]
      end
      target[keys[#keys]] = value

      local currentTheme = addon.ArenaFrameThemes and addon.ArenaFrameThemes:GetCurrentTheme()
      if currentTheme then
        addon.DB.profile.themeData = addon.DB.profile.themeData or {}
        addon.DB.profile.themeData[currentTheme] = addon.DB.profile.themeData[currentTheme] or {}
        local themeTarget = addon.DB.profile.themeData[currentTheme]
        for i=1, #keys - 1 do
          themeTarget[keys[i]] = themeTarget[keys[i]] or {}
          themeTarget = themeTarget[keys[i]]
        end
        themeTarget[keys[#keys]] = value
      end
    end
  end

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

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

  local bg = addon: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 = addon: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 = GetValue()
    swatch:SetVertexColor(r, g, b, a or 1)
  end
  RefreshDisplay()

  local function OpenPicker()
    if not ColorPickerFrame then return end

    local r, g, b, a = GetValue()

    local function ApplyRefresh()
      if path == "trinkets.borderColor" then
        if addon.RefreshTrinketIcons then
          addon:RefreshTrinketIcons()
        elseif addon.RefreshTrinketsOtherLayout then
          addon:RefreshTrinketsOtherLayout()
        end
      elseif path == "racials.borderColor" then
        if addon.RefreshRacials then
          addon:RefreshRacials()
        elseif addon.TrinketsRacials and addon.TrinketsRacials.RefreshAll then
          addon.TrinketsRacials:RefreshAll()
        elseif addon.RefreshTrinketsOtherLayout then
          addon:RefreshTrinketsOtherLayout()
        end
      elseif path == "classIcons.sizing.borderColor" then
        if addon.RefreshClassIcons then
          addon:RefreshClassIcons()
        elseif addon.RefreshTrinketsOtherLayout then
          addon:RefreshTrinketsOtherLayout()
        end
      elseif path == "specIcons.sizing.borderColor" then
        if addon.RefreshTrinketsOtherLayout then
          addon:RefreshTrinketsOtherLayout()
        end
      end
    end

    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)
      SaveValue(nr, ng, nb, na)
      RefreshDisplay()
      ApplyRefresh()
    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()
    end

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

    if ColorPickerFrame.SetupColorPickerAndShow then
      local info = {
        r = r,
        g = g,
        b = b,
        opacity = opacity,
        hasOpacity = true,
        swatchFunc = OnColorChanged,
        opacityFunc = OnColorChanged,
        cancelFunc = OnCancel,
      }
      ColorPickerFrame:SetupColorPickerAndShow(info)
    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

-- A new helper function to create linked checkboxes.
local function CreateCheckboxSetting(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 = addon:CreateStyledText(row, label, 12, C.TEXT_2, "OVERLAY", ""); l:SetPoint("LEFT", 0, 0)
  
  local keys = {}; for k in string.gmatch(path, "([^%.]+)") do table.insert(keys, k) end

  local function GetValue()
    local target = DB(); for i=1, #keys do target = target and target[keys[i]] end
    return target
  end
  
  local isChecked = GetValue()
  if isChecked == nil then
    if defaultValue == nil then
      isChecked = true
    else
      isChecked = defaultValue
    end
  end

  local function OnChange(value)
    if addon.ProfileManager and addon.ProfileManager.SetSetting then
      addon.ProfileManager:SetSetting(path, value)
    else
      local target = addon.DB.profile; for i=1, #keys - 1 do target[keys[i]] = target[keys[i]] or {}; target = target[keys[i]] end
      target[keys[#keys]] = value
    end

    local currentTheme = addon.ArenaFrameThemes and addon.ArenaFrameThemes:GetCurrentTheme()
    if currentTheme then
      addon.DB.profile.themeData = addon.DB.profile.themeData or {}
      addon.DB.profile.themeData[currentTheme] = addon.DB.profile.themeData[currentTheme] or {}
      local themeTarget = addon.DB.profile.themeData[currentTheme]
      for i=1, #keys - 1 do
        themeTarget[keys[i]] = themeTarget[keys[i]] or {}
        themeTarget = themeTarget[keys[i]]
      end
      themeTarget[keys[#keys]] = value
    end
    
    -- print("|cffFFAA00[CHECKBOX DEBUG]|r " .. path .. " changed to: " .. tostring(value))
    
    if addon.RefreshTrinketsOtherLayout then
      addon:RefreshTrinketsOtherLayout()
      -- print("|cffFFAA00[CHECKBOX DEBUG]|r Called RefreshTrinketsOtherLayout()")
    else
      print("|cffFF0000[CHECKBOX ERROR]|r RefreshTrinketsOtherLayout not found!")
    end

    if path == "classIcons.showSpecInstead" then
      local db = DB()
      if db and db.classIcons and db.classIcons.showSpecInstead == true then
        if db.specIcons then
          db.specIcons.enabled = false
        end
        local currentTheme = addon.ArenaFrameThemes and addon.ArenaFrameThemes:GetCurrentTheme()
        if currentTheme then
          addon.DB.profile.themeData = addon.DB.profile.themeData or {}
          addon.DB.profile.themeData[currentTheme] = addon.DB.profile.themeData[currentTheme] or {}
          addon.DB.profile.themeData[currentTheme].specIcons = addon.DB.profile.themeData[currentTheme].specIcons or {}
          addon.DB.profile.themeData[currentTheme].specIcons.enabled = false
        end
      else
        -- CRITICAL FIX: Re-enable spec icons when toggle is turned OFF
        -- This ensures spec icons show again in test mode after toggling
        if db and db.specIcons then
          db.specIcons.enabled = true
        end
        local currentTheme = addon.ArenaFrameThemes and addon.ArenaFrameThemes:GetCurrentTheme()
        if currentTheme then
          addon.DB.profile.themeData = addon.DB.profile.themeData or {}
          addon.DB.profile.themeData[currentTheme] = addon.DB.profile.themeData[currentTheme] or {}
          addon.DB.profile.themeData[currentTheme].specIcons = addon.DB.profile.themeData[currentTheme].specIcons or {}
          addon.DB.profile.themeData[currentTheme].specIcons.enabled = true
        end
      end
      if addon.__UpdateSpecIconsEnableLock then
        addon.__UpdateSpecIconsEnableLock()
      end
      if addon.RefreshClassIcons then
        addon:RefreshClassIcons()
      end

      if addon.testModeEnabled and addon.MasterFrameManager and addon.MasterFrameManager.ApplyTestData then
        addon.MasterFrameManager:ApplyTestData()
      end
    elseif path == "specIcons.enabled" then
      if addon.__UpdateSpecIconsEnableLock then
        addon.__UpdateSpecIconsEnableLock()
      end
    end
  end

  local box = addon:CreateFlatCheckbox(row, 20, isChecked, OnChange)
  box:SetPoint("RIGHT", -25, 0)

  row.checkbox = box
  
  return row
end

-- Main page creation
-- File: Core/Pages/TrinketsOther.lua
-- Purpose: Final, stable version using the same self-contained logic as the working Arena Frames page.

-- File: Core/Pages/TrinketsOther.lua
-- Purpose: Final version rebuilt with the correct, stable architecture from CastBars.lua.

-- File: Core/Pages/TrinketsOther.lua
-- Purpose: Final version with a simplified structure to fix the "double box" visual bug.

-- File: Core/Pages/TrinketsOther.lua
-- Purpose: Final, stable version using the proven architecture from other working pages.

addon:RegisterPage("trinketsother", function(root)
  if V and V.EnsureMottoStrip then V:EnsureMottoStrip(root) end
  
  -- Create the top button bar first
  local buttonBar = CreateFrame("Frame", nil, root)
  if root._mottoStrip then
    buttonBar:SetPoint("TOPLEFT", root._mottoStrip, "BOTTOMLEFT", 2, -8)
    buttonBar:SetPoint("TOPRIGHT", root._mottoStrip, "BOTTOMRIGHT", -2, -8)
  else
    buttonBar:SetPoint("TOPLEFT", 10, -52)
  end
  buttonBar:SetHeight(44)
  local sBorder = addon:CreateFlatTexture(buttonBar, "BACKGROUND", 1, C.BORDER_LIGHT, 0.6); sBorder:SetAllPoints()
  local sFill = addon:CreateFlatTexture(buttonBar, "BACKGROUND", 2, C.INPUT_DARK, 1); sFill:SetPoint("TOPLEFT", 1, -1); sFill:SetPoint("BOTTOMRIGHT", -1, 1)
    -- REMOVED: TEST and HIDE buttons - replaced by new unified architecture

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

    local fill = group:CreateTexture(nil, "BACKGROUND", nil, 2)
    local bgColor = addon.COLORS and addon.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

  local function CreateTrinketsSubTabButton(parentFrame, text, width, height)
    local btn = CreateFrame("Button", nil, parentFrame)
    btn:SetSize(width or 102, height or 30)

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

    local hover = addon:CreateFlatTexture(btn, "ARTWORK", 1, C.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", nil, 7)
      local c = C.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, -1)
    outlineTop:SetPoint("TOPRIGHT", btn, "TOPRIGHT", -1, -1)
    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 = addon:CreateStyledText(btn, text or "", 11, (C.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((C.TEXT and C.TEXT[1]) or 1, (C.TEXT and C.TEXT[2]) or 1, (C.TEXT and C.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((C.TEXT_2 and C.TEXT_2[1]) or 0.706, (C.TEXT_2 and C.TEXT_2[2]) or 0.706, (C.TEXT_2 and C.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((C.TEXT and C.TEXT[1]) or 1, (C.TEXT and C.TEXT[2]) or 1, (C.TEXT and C.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((C.TEXT_2 and C.TEXT_2[1]) or 0.706, (C.TEXT_2 and C.TEXT_2[2]) or 0.706, (C.TEXT_2 and C.TEXT_2[3]) or 0.706, 1)
      end
    end)

    return btn
  end

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

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

  local tabs = {}
  local activeTab
  local function SetTab(key)
    if activeTab == key then return end
    activeTab = key
    for k, frame in pairs(contentFrames) 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 btnTrinkets = CreateTrinketsSubTabButton(buttonBar, "Trinkets", 92, 30)
  btnTrinkets:SetPoint("LEFT", buttonBar, "LEFT", 12, 0)
  tabs.trinkets = btnTrinkets

  local btnSpecIcons = CreateTrinketsSubTabButton(buttonBar, "Spec Icons", 105, 30)
  btnSpecIcons:SetPoint("LEFT", btnTrinkets, "RIGHT", 8, 0)
  tabs.specIcons = btnSpecIcons

  local btnRacials = CreateTrinketsSubTabButton(buttonBar, "Racials", 92, 30)
  btnRacials:SetPoint("LEFT", btnSpecIcons, "RIGHT", 8, 0)
  tabs.racials = btnRacials
  if btnRacials.outlineRight then
    btnRacials.outlineRight:ClearAllPoints()
    btnRacials.outlineRight:SetPoint("TOPRIGHT", btnRacials, "TOPRIGHT", -2, -1)
    btnRacials.outlineRight:SetPoint("BOTTOMRIGHT", btnRacials, "BOTTOMRIGHT", -2, 1)
  end

  local btnClassIcons = CreateTrinketsSubTabButton(buttonBar, "Class Icons", 100, 30)
  btnClassIcons:SetPoint("LEFT", btnRacials, "RIGHT", 8, 0)
  tabs.classIcons = btnClassIcons

  local function BuildTrinkets()
    local f = EnsureContentFrame("trinkets")
    if f._built then return end
    f._built = true

    local groupTrinkets = CreateFrame("Frame", nil, f)
    groupTrinkets:SetPoint("TOPLEFT", f, "TOPLEFT", 18, -12)
    groupTrinkets:SetPoint("TOPRIGHT", f, "TOPRIGHT", -18, -12)
    groupTrinkets:SetHeight(330)
    TrinketsHairlineGroupBox(groupTrinkets)
    addon:CreateStyledText(groupTrinkets, "TRINKETS", 13, C.PRIMARY, "OVERLAY", ""):SetPoint("TOPLEFT", 20, -18)
    CreateDropdownSetting(groupTrinkets, "Trinket Icon Design", -50, "trinkets.iconDesign", {
      ["Retail Medallion"] = "retail",
      ["Horde Vanilla"] = "horde", 
      ["Alliance Vanilla"] = "alliance"
    }, "retail")
    CreateDropdownSetting(groupTrinkets, "Border Styles", -80, "trinkets.style", {
      ["Arena Core"] = "arenacore",
      ["Arena Core Black"] = "arenacore_black",
      ["Skill Issue Outline"] = "pixel_black"
    }, "arenacore")

    local borderColorRow = CreateColorPickerSetting(groupTrinkets, "Border Color Picker", -110, "trinkets.borderColor")
    local borderThicknessRow = addon:CreateEnhancedSliderRow(groupTrinkets, "Border Thickness", -140, "trinkets.borderThickness", "target_border_thickness")
    addon:CreateEnhancedSliderRow(groupTrinkets, "Horizontal", -170, "trinkets.positioning.horizontal", "positioning_horizontal_ultra")
    addon:CreateEnhancedSliderRow(groupTrinkets, "Vertical", -200, "trinkets.positioning.vertical", "positioning_vertical_ultra")
    addon:CreateEnhancedSliderRow(groupTrinkets, "Scale", -230, "trinkets.sizing.scale", "sizing_scale")
    addon:CreateEnhancedSliderRow(groupTrinkets, "Font Size", -260, "trinkets.sizing.fontSize", "cooldown_font")
    CreateCheckboxSetting(groupTrinkets, "Enable", -290, "trinkets.enabled")

    addon.__UpdateTrinketBorderThicknessEnabled = function()
      local db = DB()
      local style = db and db.trinkets and db.trinkets.style or "arenacore"

      -- Backward compat: treat old pixel_orange as Skill Issue Outline
      if style == "pixel_orange" then
        style = "pixel_black"
        if db and db.trinkets then
          db.trinkets.style = "pixel_black"
        end
      end

      local isPixel = (style == "pixel_black")

      local slider = addon.sliderWidgets and addon.sliderWidgets["trinkets.borderThickness"]
      if slider and slider.SetEnabled then
        slider:SetEnabled(isPixel)
      end

      if borderThicknessRow then
        if not borderThicknessRow.__disableOverlay then
          local overlay = CreateFrame("Frame", nil, borderThicknessRow)
          overlay:SetAllPoints(borderThicknessRow)
          overlay:EnableMouse(true)
          overlay:SetFrameLevel(borderThicknessRow:GetFrameLevel() + 100)
          overlay:Hide()
          borderThicknessRow.__disableOverlay = overlay
        end

        if isPixel then
          borderThicknessRow:SetAlpha(1)
          borderThicknessRow.__disableOverlay:Hide()
        else
          borderThicknessRow:SetAlpha(0.5)
          borderThicknessRow.__disableOverlay:Show()
        end
      end

      if borderColorRow and borderColorRow.button then
        if isPixel then
          borderColorRow:SetAlpha(1)
          borderColorRow.button:EnableMouse(true)
        else
          borderColorRow:SetAlpha(0.5)
          borderColorRow.button:EnableMouse(false)
        end
      end
    end

    addon.__UpdateTrinketBorderThicknessEnabled()

    C_Timer.After(0.1, function()
      local slider = addon.sliderWidgets and addon.sliderWidgets["trinkets.borderThickness"]
      if slider and slider.HookScript then
        slider:HookScript("OnValueChanged", function()
          if addon.__UpdateTrinketBorderThicknessEnabled then
            addon.__UpdateTrinketBorderThicknessEnabled()
          end
          if addon.RefreshTrinketIcons then
            addon:RefreshTrinketIcons()
          end
        end)
      end
    end)
  end

  local function BuildSpecIcons()
    local f = EnsureContentFrame("specIcons")
    if f._built then return end
    f._built = true

    local groupSpecIcons = CreateFrame("Frame", nil, f)
    groupSpecIcons:SetPoint("TOPLEFT", f, "TOPLEFT", 18, -12)
    groupSpecIcons:SetPoint("TOPRIGHT", f, "TOPRIGHT", -18, -12)
    groupSpecIcons:SetHeight(270)
    TrinketsHairlineGroupBox(groupSpecIcons)
    addon:CreateStyledText(groupSpecIcons, "SPEC ICONS", 13, C.PRIMARY, "OVERLAY", ""):SetPoint("TOPLEFT", 20, -18)
    addon:CreateEnhancedSliderRow(groupSpecIcons, "Horizontal", -50, "specIcons.positioning.horizontal", "positioning_horizontal_ultra")
    addon:CreateEnhancedSliderRow(groupSpecIcons, "Vertical", -80, "specIcons.positioning.vertical", "positioning_vertical_ultra")
    addon:CreateEnhancedSliderRow(groupSpecIcons, "Scale", -110, "specIcons.sizing.scale", "sizing_scale")
    CreateDropdownSetting(groupSpecIcons, "Border Styles", -140, "specIcons.sizing.borderStyle", {
      ["Skill Issue Outline"] = "default",
      ["Arena Core"] = "arenacore",
      ["Arena Core Black"] = "arenacore_black"
    }, "default", 150)

    local borderColorRow = CreateColorPickerSetting(groupSpecIcons, "Border Color Picker", -170, "specIcons.sizing.borderColor")
    local borderThicknessRow = addon:CreateEnhancedSliderRow(groupSpecIcons, "Border Thickness", -200, "specIcons.sizing.borderThickness", "target_border_thickness")

    addon.__UpdateSpecIconBorderThicknessEnabled = function()
      local db = DB()
      local style = db and db.specIcons and db.specIcons.sizing and db.specIcons.sizing.borderStyle or "default"
      local isPixel = (style == "default")

      local slider = addon.sliderWidgets and addon.sliderWidgets["specIcons.sizing.borderThickness"]
      if slider and slider.SetEnabled then
        slider:SetEnabled(isPixel)
      end

      if borderThicknessRow then
        if not borderThicknessRow.__disableOverlay then
          local overlay = CreateFrame("Frame", nil, borderThicknessRow)
          overlay:SetAllPoints(borderThicknessRow)
          overlay:EnableMouse(true)
          overlay:SetFrameLevel(borderThicknessRow:GetFrameLevel() + 100)
          overlay:Hide()
          borderThicknessRow.__disableOverlay = overlay
        end

        if isPixel then
          borderThicknessRow:SetAlpha(1)
          borderThicknessRow.__disableOverlay:Hide()
        else
          borderThicknessRow:SetAlpha(0.5)
          borderThicknessRow.__disableOverlay:Show()
        end
      end

      if borderColorRow and borderColorRow.button then
        if isPixel then
          borderColorRow:SetAlpha(1)
          borderColorRow.button:EnableMouse(true)
        else
          borderColorRow:SetAlpha(0.5)
          borderColorRow.button:EnableMouse(false)
        end
      end
    end

    addon.__UpdateSpecIconBorderThicknessEnabled()

    local enableRow = CreateCheckboxSetting(groupSpecIcons, "Enable", -230, "specIcons.enabled")
    addon.__SpecIconsEnableRow = enableRow

    local function UpdateSpecIconsEnableLock()
      local db = DB()
      local locked = db and db.classIcons and db.classIcons.showSpecInstead == true
      local row = addon.__SpecIconsEnableRow
      local box = row and row.checkbox
      if not box then return end

      if locked then
        if db and db.specIcons then
          db.specIcons.enabled = false
        end
        local currentTheme = addon.ArenaFrameThemes and addon.ArenaFrameThemes:GetCurrentTheme()
        if currentTheme then
          addon.DB.profile.themeData = addon.DB.profile.themeData or {}
          addon.DB.profile.themeData[currentTheme] = addon.DB.profile.themeData[currentTheme] or {}
          addon.DB.profile.themeData[currentTheme].specIcons = addon.DB.profile.themeData[currentTheme].specIcons or {}
          addon.DB.profile.themeData[currentTheme].specIcons.enabled = false
        end
        if box.SetChecked then
          box:SetChecked(false)
        end
        local btn = box.checkButton
        if btn and btn.Disable then
          btn:Disable()
        elseif btn and btn.SetEnabled then
          btn:SetEnabled(false)
        end
        row:SetAlpha(0.55)
      else
        local btn = box.checkButton
        if btn and btn.Enable then
          btn:Enable()
        elseif btn and btn.SetEnabled then
          btn:SetEnabled(true)
        end
        row:SetAlpha(1)
      end
    end

    addon.__UpdateSpecIconsEnableLock = UpdateSpecIconsEnableLock
    addon.__UpdateSpecIconsEnableLock()
  end

  local function BuildRacials()
    local f = EnsureContentFrame("racials")
    if f._built then return end
    f._built = true

    local groupRacials = CreateFrame("Frame", nil, f)
    groupRacials:SetPoint("TOPLEFT", f, "TOPLEFT", 18, -12)
    groupRacials:SetPoint("TOPRIGHT", f, "TOPRIGHT", -18, -12)
    groupRacials:SetHeight(330)
    TrinketsHairlineGroupBox(groupRacials)
    addon:CreateStyledText(groupRacials, "RACIALS", 13, C.PRIMARY, "OVERLAY", ""):SetPoint("TOPLEFT", 20, -18)

    CreateDropdownSetting(groupRacials, "Border Styles", -50, "racials.style", {
      ["Arena Core"] = "arenacore",
      ["Arena Core Black"] = "arenacore_black",
      ["Skill Issue Outline"] = "pixel_black"
    }, "arenacore")

    local borderColorRow = CreateColorPickerSetting(groupRacials, "Border Color Picker", -80, "racials.borderColor")
    local borderThicknessRow = addon:CreateEnhancedSliderRow(groupRacials, "Border Thickness", -110, "racials.borderThickness", "target_border_thickness")
    addon:CreateEnhancedSliderRow(groupRacials, "Horizontal", -140, "racials.positioning.horizontal", "positioning_horizontal_ultra")
    addon:CreateEnhancedSliderRow(groupRacials, "Vertical", -170, "racials.positioning.vertical", "positioning_vertical_ultra")
    addon:CreateEnhancedSliderRow(groupRacials, "Scale", -200, "racials.sizing.scale", "sizing_scale")
    addon:CreateEnhancedSliderRow(groupRacials, "Font Size", -230, "racials.sizing.fontSize", "racial_font")
    CreateCheckboxSetting(groupRacials, "Enable", -260, "racials.enabled")

    addon.__UpdateRacialBorderThicknessEnabled = function()
      local db = DB()
      local style = db and db.racials and db.racials.style or "arenacore"

      -- Backward compat: treat old pixel_orange as Skill Issue Outline
      if style == "pixel_orange" then
        style = "pixel_black"
        if db and db.racials then
          db.racials.style = "pixel_black"
        end
      end

      local isPixel = (style == "pixel_black")

      local slider = addon.sliderWidgets and addon.sliderWidgets["racials.borderThickness"]
      if slider and slider.SetEnabled then
        slider:SetEnabled(isPixel)
      end

      if borderThicknessRow then
        if not borderThicknessRow.__disableOverlay then
          local overlay = CreateFrame("Frame", nil, borderThicknessRow)
          overlay:SetAllPoints(borderThicknessRow)
          overlay:EnableMouse(true)
          overlay:SetFrameLevel(borderThicknessRow:GetFrameLevel() + 100)
          overlay:Hide()
          borderThicknessRow.__disableOverlay = overlay
        end

        if isPixel then
          borderThicknessRow:SetAlpha(1)
          borderThicknessRow.__disableOverlay:Hide()
        else
          borderThicknessRow:SetAlpha(0.5)
          borderThicknessRow.__disableOverlay:Show()
        end
      end

      if borderColorRow and borderColorRow.button then
        if isPixel then
          borderColorRow:SetAlpha(1)
          borderColorRow.button:EnableMouse(true)
        else
          borderColorRow:SetAlpha(0.5)
          borderColorRow.button:EnableMouse(false)
        end
      end
    end

    addon.__UpdateRacialBorderThicknessEnabled()

    C_Timer.After(0.1, function()
      local slider = addon.sliderWidgets and addon.sliderWidgets["racials.borderThickness"]
      if slider and slider.HookScript then
        slider:HookScript("OnValueChanged", function()
          if addon.__UpdateRacialBorderThicknessEnabled then
            addon.__UpdateRacialBorderThicknessEnabled()
          end
          if addon.RefreshRacials then
            addon:RefreshRacials()
          elseif addon.TrinketsRacials and addon.TrinketsRacials.RefreshAll then
            addon.TrinketsRacials:RefreshAll()
          elseif addon.RefreshTrinketsOtherLayout then
            addon:RefreshTrinketsOtherLayout()
          end
        end)
      end
    end)
  end

  local function BuildClassIcons()
    local f = EnsureContentFrame("classIcons")
    if f._built then return end
    f._built = true

    local groupClassIcons = CreateFrame("Frame", nil, f)
    groupClassIcons:SetPoint("TOPLEFT", f, "TOPLEFT", 18, -12)
    groupClassIcons:SetPoint("TOPRIGHT", f, "TOPRIGHT", -18, -12)
    groupClassIcons:SetHeight(330)
    TrinketsHairlineGroupBox(groupClassIcons)
    addon:CreateStyledText(groupClassIcons, "CLASS ICONS", 13, C.PRIMARY, "OVERLAY", ""):SetPoint("TOPLEFT", 20, -18)

    CreateCheckboxSetting(groupClassIcons, "Disable Class Icons & Show Spec Instead", -50, "classIcons.showSpecInstead", false)

    C_Timer.After(0, function()
      local db = DB()
      if db and db.classIcons and db.classIcons.showSpecInstead == true then
        if db.specIcons then
          db.specIcons.enabled = false
        end
        local currentTheme = addon.ArenaFrameThemes and addon.ArenaFrameThemes:GetCurrentTheme()
        if currentTheme then
          addon.DB.profile.themeData = addon.DB.profile.themeData or {}
          addon.DB.profile.themeData[currentTheme] = addon.DB.profile.themeData[currentTheme] or {}
          addon.DB.profile.themeData[currentTheme].specIcons = addon.DB.profile.themeData[currentTheme].specIcons or {}
          addon.DB.profile.themeData[currentTheme].specIcons.enabled = false
        end
      end

      if addon.__UpdateSpecIconsEnableLock then
        addon.__UpdateSpecIconsEnableLock()
      end

      if addon.RefreshClassIcons then
        addon:RefreshClassIcons()
      elseif addon.RefreshTrinketsOtherLayout then
        addon:RefreshTrinketsOtherLayout()
      end
    end)

    local classIconThemeRow = CreateDropdownSetting(groupClassIcons, "Class Icon Theme", -80, "classIcons.theme", {
      ["ArenaCore Custom"] = "arenacore",
      ["Midnight Chill"] = "coldclasses"
    }, "arenacore", 200)

    local currentTheme = addon.ArenaFrameThemes and addon.ArenaFrameThemes:GetCurrentTheme()
    if currentTheme == "Just Blastin'" then
      local dropdown = classIconThemeRow.dropdown
      if dropdown and dropdown.button and dropdown.text then
        dropdown.button:Disable()
        dropdown.button:SetAlpha(0.5)
        dropdown.text:SetTextColor(0.5, 0.5, 0.5, 1)

        local db = DB()
        if db and db.classIcons then
          db.classIcons.theme = "arenacore"
        end

        dropdown:SetValue("ArenaCore Custom")
        dropdown:SetScript("OnEnter", function(self)
          GameTooltip:SetOwner(self, "ANCHOR_TOP")
          GameTooltip:SetText("Class Icon Theme is locked to ArenaCore Custom for Just Blastin' theme", 1, 1, 1, true)
          GameTooltip:Show()
        end)
        dropdown:SetScript("OnLeave", function()
          GameTooltip:Hide()
        end)
      end
    end

    CreateDropdownSetting(groupClassIcons, "Border Styles", -110, "classIcons.sizing.borderStyle", {
      ["Arena Core"] = "arenacore",
      ["Skill Issue Outline"] = "pixel_black"
    }, "arenacore")

    local borderColorRow = CreateColorPickerSetting(groupClassIcons, "Border Color Picker", -140, "classIcons.sizing.borderColor")
    local borderThicknessRow = addon:CreateEnhancedSliderRow(groupClassIcons, "Border Thickness", -170, "classIcons.sizing.borderThickness", "target_border_thickness")

    function addon.__UpdateClassIconBorderThicknessEnabled()
      local db = DB()
      local style = db and db.classIcons and db.classIcons.sizing and db.classIcons.sizing.borderStyle or "arenacore"

      -- Backward compat: treat old pixel_orange as Skill Issue Outline
      if style == "pixel_orange" then
        style = "pixel_black"
        if db and db.classIcons and db.classIcons.sizing then
          db.classIcons.sizing.borderStyle = "pixel_black"
        end
      end

      local isPixel = (style == "pixel_black")

      if borderThicknessRow then
        if not borderThicknessRow.__disableOverlay then
          local overlay = CreateFrame("Frame", nil, borderThicknessRow)
          overlay:SetAllPoints(borderThicknessRow)
          overlay:EnableMouse(true)
          overlay:SetFrameLevel(borderThicknessRow:GetFrameLevel() + 100)
          overlay:Hide()
          borderThicknessRow.__disableOverlay = overlay
        end

        if isPixel then
          borderThicknessRow:SetAlpha(1)
          borderThicknessRow.__disableOverlay:Hide()
        else
          borderThicknessRow:SetAlpha(0.5)
          borderThicknessRow.__disableOverlay:Show()
        end
      end

      if borderColorRow and borderColorRow.button then
        if isPixel then
          borderColorRow:SetAlpha(1)
          borderColorRow.button:EnableMouse(true)
        else
          borderColorRow:SetAlpha(0.5)
          borderColorRow.button:EnableMouse(false)
        end
      end
    end

    addon.__UpdateClassIconBorderThicknessEnabled()

    C_Timer.After(0.1, function()
      local slider = addon.sliderWidgets and addon.sliderWidgets["classIcons.sizing.borderThickness"]
      if slider and slider.HookScript then
        slider:HookScript("OnValueChanged", function()
          if addon.__UpdateClassIconBorderThicknessEnabled then
            addon.__UpdateClassIconBorderThicknessEnabled()
          end
          if addon.RefreshClassIcons then
            addon:RefreshClassIcons()
          elseif addon.RefreshTrinketsOtherLayout then
            addon:RefreshTrinketsOtherLayout()
          end
        end)
      end
    end)

    addon:CreateEnhancedSliderRow(groupClassIcons, "Horizontal", -200, "classIcons.positioning.horizontal", "positioning_horizontal_ultra")
    addon:CreateEnhancedSliderRow(groupClassIcons, "Vertical", -230, "classIcons.positioning.vertical", "positioning_vertical_ultra")
    addon:CreateEnhancedSliderRow(groupClassIcons, "Scale", -260, "classIcons.sizing.scale", "sizing_scale")
  end

  btnTrinkets:SetScript("OnClick", function()
    BuildTrinkets()
    SetTab("trinkets")
  end)
  btnSpecIcons:SetScript("OnClick", function()
    BuildSpecIcons()
    SetTab("specIcons")
  end)
  btnRacials:SetScript("OnClick", function()
    BuildRacials()
    SetTab("racials")
  end)
  btnClassIcons:SetScript("OnClick", function()
    BuildClassIcons()
    SetTab("classIcons")
  end)

  BuildTrinkets()
  SetTab("trinkets")
end)