local API = rawget(_G, "LIDCOUNCIL_API")
local INTERNAL_API = type(API) == "table" and type(API.__internal) == "table" and API.__internal or nil
if type(INTERNAL_API) ~= "table" then
  error("LidCouncil missing internal API registry.")
end

local RequireApi = INTERNAL_API.LIDCOUNCIL_RequireApi_Impl
local SetDropdownSelection = INTERNAL_API.LIDCOUNCIL_SetDropdownSelection_Impl
if type(RequireApi) ~= "function" or type(SetDropdownSelection) ~= "function" then
  error("LidCouncil missing shared editor page helpers.")
end

local DB = RequireApi("LIDCOUNCIL_DB", _G.LIDCOUNCIL_DB)
local OpenColorPickerRGBOnly = RequireApi("LIDCOUNCIL_OpenColorPickerRGBOnly", _G.LIDCOUNCIL_OpenColorPickerRGBOnly)
local MakeYellowSubHeader = RequireApi("LIDCOUNCIL_MakeYellowSubHeader", _G.LIDCOUNCIL_MakeYellowSubHeader)
local MakeSlider = RequireApi("LIDCOUNCIL_MakeSlider", _G.LIDCOUNCIL_MakeSlider)
local RebuildAllPanels = RequireApi("LIDCOUNCIL_RebuildAllPanels", _G.LIDCOUNCIL_RebuildAllPanels)
local EnsureGradientTables = RequireApi("LIDCOUNCIL_EnsureGradientTables", _G.LIDCOUNCIL_EnsureGradientTables)
local GetSelectedPanelName = RequireApi("LIDCOUNCIL_GetSelectedPanelName", _G.LIDCOUNCIL_GetSelectedPanelName)

local PANEL_STAT_CHOICES = {
  { key = "agility", label = "Agility" },
  { key = "stamina", label = "Stamina" },
  { key = "armor", label = "Armor" },
  { key = "speed", label = "Speed" },
  { key = "crit", label = "Critical Strike" },
  { key = "haste", label = "Haste" },
  { key = "mastery", label = "Mastery" },
  { key = "versatility", label = "Versatility" },
  { key = "leech", label = "Leech" },
  { key = "avoidance", label = "Avoidance" },
}

local PANEL_SPECIAL_FONT_CHOICES = {
  "GameFontNormal",
  "GameFontHighlight",
  "GameFontNormalLarge",
  "GameFontHighlightSmall",
  "GameFontNormalSmall",
  "ChatFontNormal",
  "NumberFontNormalLarge",
  "QuestFontNormalSmall",
}

local BORDER_CHOICES = {
  { text = "Tooltip", value = "tooltip" },
  { text = "Thin", value = "thin" },
  { text = "Medium", value = "medium" },
  { text = "Thick", value = "thick" },
  { text = "Frame", value = "frame" },
  { text = "Wide", value = "wide" },
  { text = "Rounded", value = "rounded" },
  { text = "Dialog", value = "dialog" },
  { text = "Soft", value = "soft" },
  { text = "None", value = "none" },
}

local TINTABLE_BORDER_CHOICES = {
  thin = true,
  medium = true,
  thick = true,
  frame = true,
  wide = true,
}

local function RefreshPanelProperties(editor)
  if editor and editor.RefreshPanelPropertiesSection then
    editor:RefreshPanelPropertiesSection()
  elseif editor and editor.RefreshPanelsSection then
    editor:RefreshPanelsSection()
  elseif editor and editor.Refresh then
    editor:Refresh()
  end
end

local function EnsureColorPreviewSwatch(button)
  if not button or button.__lid_colorSwatch then return end
  local swatchFrame = CreateFrame("Frame", nil, button, "BackdropTemplate")
  swatchFrame:SetSize(14, 14)
  swatchFrame:SetPoint("LEFT", 8, 0)
  swatchFrame:SetBackdrop({
    bgFile = "Interface/Buttons/WHITE8x8",
    edgeFile = "Interface/Buttons/WHITE8x8",
    edgeSize = 1,
  })
  swatchFrame:SetBackdropColor(0.08, 0.08, 0.10, 1)
  swatchFrame:SetBackdropBorderColor(0.55, 0.55, 0.60, 0.95)

  local swatch = swatchFrame:CreateTexture(nil, "ARTWORK")
  swatch:SetAllPoints(true)
  swatch:SetTexture("Interface/Buttons/WHITE8x8")
  swatch:SetVertexColor(1, 1, 1, 1)

  button.__lid_colorSwatchFrame = swatchFrame
  button.__lid_colorSwatch = swatch
end

local function SetColorPreviewSwatch(button, rgba)
  if not button then return end
  EnsureColorPreviewSwatch(button)
  local c = rgba or { 1, 1, 1, 1 }
  local a = tonumber(c[4])
  if a == nil then a = 1 end
  button.__lid_colorSwatch:SetVertexColor(c[1] or 1, c[2] or 1, c[3] or 1, a)
end

local function NormalizeRGBA(src, fallback)
  local out = {}
  out[1] = tonumber(src and src[1]) or fallback[1]
  out[2] = tonumber(src and src[2]) or fallback[2]
  out[3] = tonumber(src and src[3]) or fallback[3]
  out[4] = tonumber(src and src[4]) or fallback[4] or 1
  if out[1] < 0 then out[1] = 0 elseif out[1] > 1 then out[1] = 1 end
  if out[2] < 0 then out[2] = 0 elseif out[2] > 1 then out[2] = 1 end
  if out[3] < 0 then out[3] = 0 elseif out[3] > 1 then out[3] = 1 end
  if out[4] < 0 then out[4] = 0 elseif out[4] > 1 then out[4] = 1 end
  return out
end

local function EnsurePanelExtraData(p)
  if not p then return nil, nil end
  p.diagnostic = p.diagnostic or {}
  p.specialContent = p.specialContent or {}
  local special = p.specialContent
  local diag = p.diagnostic

  diag.graph = diag.graph or {}
  if diag.graph.showFPS == nil then diag.graph.showFPS = true end
  if diag.graph.showAvg == nil then diag.graph.showAvg = false end
  if diag.graph.showLow == nil then diag.graph.showLow = false end
  diag.graph.updateInterval = tonumber(diag.graph.updateInterval) or 0.1
  if diag.graph.updateInterval < 0.1 then diag.graph.updateInterval = 0.1 end
  if diag.graph.updateInterval > 2.0 then diag.graph.updateInterval = 2.0 end
  diag.graph.updateInterval = math.floor((diag.graph.updateInterval * 10) + 0.5) / 10
  diag.graph.avgWindowSec = math.floor((tonumber(diag.graph.avgWindowSec) or 10) + 0.5)
  if diag.graph.avgWindowSec < 5 then diag.graph.avgWindowSec = 5 end
  if diag.graph.avgWindowSec > 300 then diag.graph.avgWindowSec = 300 end
  diag.graph.infoIntervalFPS = tonumber(diag.graph.infoIntervalFPS) or 0.1
  if diag.graph.infoIntervalFPS < 0.1 then diag.graph.infoIntervalFPS = 0.1 end
  if diag.graph.infoIntervalFPS > 300 then diag.graph.infoIntervalFPS = 300 end
  diag.graph.infoIntervalFPS = math.floor((diag.graph.infoIntervalFPS * 10) + 0.5) / 10
  diag.graph.infoIntervalAVG = tonumber(diag.graph.infoIntervalAVG) or 10
  if diag.graph.infoIntervalAVG < 0.1 then diag.graph.infoIntervalAVG = 0.1 end
  if diag.graph.infoIntervalAVG > 300 then diag.graph.infoIntervalAVG = 300 end
  diag.graph.infoIntervalAVG = math.floor((diag.graph.infoIntervalAVG * 10) + 0.5) / 10
  diag.graph.infoIntervalLOW = tonumber(diag.graph.infoIntervalLOW) or 0.1
  if diag.graph.infoIntervalLOW < 0.1 then diag.graph.infoIntervalLOW = 0.1 end
  if diag.graph.infoIntervalLOW > 300 then diag.graph.infoIntervalLOW = 300 end
  diag.graph.infoIntervalLOW = math.floor((diag.graph.infoIntervalLOW * 10) + 0.5) / 10
  if diag.graph.style ~= "WAVE" then diag.graph.style = "BARS" end

  if not special.mode then
    if p.diagnostic and p.diagnostic.fpsGraph then
      special.mode = "FPS_GRAPH"
    elseif special.showGold then
      special.mode = "GOLD"
    elseif special.showFPS then
      special.mode = "FPS"
    elseif special.showStats then
      special.mode = "STATS"
    elseif special.showCustomText then
      special.mode = "CUSTOM_TEXT"
    else
      special.mode = "NONE"
    end
  end
  if special.mode ~= "GOLD"
    and special.mode ~= "FPS"
    and special.mode ~= "STATS"
    and special.mode ~= "FPS_GRAPH"
    and special.mode ~= "CUSTOM_TEXT" then
    special.mode = "NONE"
  end

  special.gold = special.gold or {}
  special.gold.color = NormalizeRGBA(special.gold.color, { 1.00, 0.82, 0.00, 1.00 })
  special.gold.font = (special.gold.font and _G[special.gold.font]) and special.gold.font or "GameFontHighlightSmall"
  special.gold.size = tonumber(special.gold.size) or 14
  if special.gold.size < 8 then special.gold.size = 8 end
  if special.gold.size > 40 then special.gold.size = 40 end

  special.fps = special.fps or {}
  special.fps.font = (special.fps.font and _G[special.fps.font]) and special.fps.font or "GameFontHighlightSmall"
  special.fps.size = tonumber(special.fps.size) or 14
  if special.fps.size < 8 then special.fps.size = 8 end
  if special.fps.size > 40 then special.fps.size = 40 end
  special.fps.alpha = tonumber(special.fps.alpha)
  if special.fps.alpha == nil then special.fps.alpha = 1 end
  if special.fps.alpha < 0 then special.fps.alpha = 0 elseif special.fps.alpha > 1 then special.fps.alpha = 1 end
  special.fps.lowValue = math.floor((tonumber(special.fps.lowValue) or 30) + 0.5)
  special.fps.highValue = math.floor((tonumber(special.fps.highValue) or 60) + 0.5)
  if special.fps.lowValue < 1 then special.fps.lowValue = 1 end
  if special.fps.highValue <= special.fps.lowValue then
    special.fps.highValue = special.fps.lowValue + 1
  end
  special.fps.lowColor = NormalizeRGBA(special.fps.lowColor, { 0.95, 0.24, 0.24, 1.00 })
  special.fps.midColor = NormalizeRGBA(special.fps.midColor, { 1.00, 0.62, 0.16, 1.00 })
  special.fps.highColor = NormalizeRGBA(special.fps.highColor, { 0.20, 0.90, 0.20, 1.00 })

  special.stats = special.stats or {}
  special.statsTitleColors = special.statsTitleColors or {}
  special.statsValueColors = special.statsValueColors or {}
  special.statsSize = tonumber(special.statsSize) or 14
  if special.statsSize < 8 then special.statsSize = 8 end
  if special.statsSize > 40 then special.statsSize = 40 end
  special.statsFont = (special.statsFont and _G[special.statsFont]) and special.statsFont or "GameFontHighlightSmall"
  special.statsAlpha = tonumber(special.statsAlpha)
  if special.statsAlpha == nil then special.statsAlpha = 1 end
  if special.statsAlpha < 0 then special.statsAlpha = 0 elseif special.statsAlpha > 1 then special.statsAlpha = 1 end
  for _, def in ipairs(PANEL_STAT_CHOICES) do
    special.statsTitleColors[def.key] = NormalizeRGBA(special.statsTitleColors[def.key], { 0.84, 0.91, 1.00, 1.00 })
    special.statsValueColors[def.key] = NormalizeRGBA(special.statsValueColors[def.key], { 1.00, 1.00, 1.00, 1.00 })
  end

  special.customText = special.customText or {}
  if special.customText.text == nil then special.customText.text = "Custom Text" end
  special.customText.color = NormalizeRGBA(special.customText.color, { 1.00, 1.00, 1.00, 1.00 })
  special.customText.font = (special.customText.font and _G[special.customText.font]) and special.customText.font or "GameFontHighlightSmall"
  special.customText.size = tonumber(special.customText.size) or 14
  if special.customText.size < 8 then special.customText.size = 8 end
  if special.customText.size > 40 then special.customText.size = 40 end

  special.showGold = (special.mode == "GOLD")
  special.showFPS = (special.mode == "FPS")
  special.showStats = (special.mode == "STATS")
  special.showCustomText = (special.mode == "CUSTOM_TEXT")
  p.diagnostic.fpsGraph = (special.mode == "FPS_GRAPH")
  return p.diagnostic, special
end

local function CreatePanelDesignSection(editor, props, deps)
  if not editor or not props then
    return {}
  end

  deps = deps or {}
  local GetColorMode = deps.GetColorMode
  local BuildCustomBackgroundOptions = deps.BuildCustomBackgroundOptions
  local CopyTexCoord = deps.CopyTexCoord
  local SameTexCoord = deps.SameTexCoord
  local FindTalentOptionForPanel = deps.FindTalentOptionForPanel
  local UpdateBgPreview = deps.UpdateBgPreview
  local bgOptions = deps.bgOptions or {}
  if type(GetColorMode) ~= "function"
    or type(CopyTexCoord) ~= "function"
    or type(SameTexCoord) ~= "function"
    or type(FindTalentOptionForPanel) ~= "function"
    or type(UpdateBgPreview) ~= "function" then
    error("LidCouncil panel design section missing required dependencies.")
  end

  local modeSingleCheck = editor.modeSingleCheck
  local modeDualCheck = editor.modeDualCheck
  local modeBgCheck = editor.modeBgCheck
  local modeTextureCheck = editor.modeTextureCheck
  local modeIconCheck = editor.modeIconCheck
  local modeModelCheck = editor.modeModelCheck
  local bgLabel = editor.bgLabel
  local bgDrop = editor.bgDrop
  local customBgDrop = editor.customBgDrop
  local bgPreview = editor.bgPreview
  if not modeSingleCheck
    or not modeDualCheck
    or not modeBgCheck
    or not modeTextureCheck
    or not modeIconCheck
    or not modeModelCheck
    or not bgLabel
    or not bgDrop
    or not customBgDrop
    or not bgPreview then
    error("LidCouncil panel design section missing required editor controls.")
  end

  editor.panelStatChoices = PANEL_STAT_CHOICES
  editor.panelSpecialFontChoices = PANEL_SPECIAL_FONT_CHOICES
  editor.borderOptions = BORDER_CHOICES

  local colorSingleBtn = CreateFrame("Button", nil, props, "UIPanelButtonTemplate")
  colorSingleBtn:SetSize(160, 22)
  colorSingleBtn:SetPoint("TOPLEFT", 0, -556)
  colorSingleBtn:SetText("Set Color")
  EnsureColorPreviewSwatch(colorSingleBtn)
  editor.colorSingleBtn = colorSingleBtn

  local color1Btn = CreateFrame("Button", nil, props, "UIPanelButtonTemplate")
  color1Btn:SetSize(140, 22)
  color1Btn:SetPoint("TOPLEFT", 0, -556)
  color1Btn:SetText("Set Color 1")
  EnsureColorPreviewSwatch(color1Btn)
  editor.color1Btn = color1Btn

  local color2Btn = CreateFrame("Button", nil, props, "UIPanelButtonTemplate")
  color2Btn:SetSize(140, 22)
  color2Btn:SetPoint("TOPLEFT", 160, -556)
  color2Btn:SetText("Set Color 2")
  EnsureColorPreviewSwatch(color2Btn)
  editor.color2Btn = color2Btn

  local dirLabel = props:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
  dirLabel:SetPoint("TOPLEFT", 0, -588)
  dirLabel:SetText("Gradient Direction:")
  editor.dirLabel = dirLabel

  local dirDrop = CreateFrame("Frame", "LIDCOUNCIL_GradientDirDropdown", props, "UIDropDownMenuTemplate")
  dirDrop:SetPoint("TOPLEFT", -12, -602)
  editor.dirDrop = dirDrop

  UIDropDownMenu_Initialize(dirDrop, function(self, level)
    local cur = "VERTICAL"
    if GetSelectedPanelName() then
      local p = DB().panels[GetSelectedPanelName()]
      if p and p.gradient and p.gradient.dir then cur = p.gradient.dir end
    end
    local function add(text, value)
      local info = UIDropDownMenu_CreateInfo()
      info.text = text
      info.value = value
      info.func = function()
        UIDropDownMenu_SetSelectedValue(dirDrop, value)
        if not GetSelectedPanelName() then return end
        local p = DB().panels[GetSelectedPanelName()]
        if not p or not p.gradient then return end
        p.gradient.dir = value
        RebuildAllPanels()
        RefreshPanelProperties(editor)
      end
      info.checked = (value == cur)
      UIDropDownMenu_AddButton(info, level)
    end
    add("Horizontal", "HORIZONTAL")
    add("Vertical", "VERTICAL")
  end)

  UIDropDownMenu_SetWidth(dirDrop, 220)

  local function PickColor(isSecond)
    if not GetSelectedPanelName() then return end
    local p = DB().panels[GetSelectedPanelName()]
    if not p then return end
    p.color = p.color or { 0.05, 0.05, 0.07, 0.8 }
    if p.gradient then EnsureGradientTables(p) end

    local src = p.color
    if p.gradient then
      src = isSecond and p.gradient.c2 or p.gradient.c1
    end
    local initial = { (src[1] or 0.05), (src[2] or 0.05), (src[3] or 0.07) }
    local initialAlpha
    if p.gradient then
      initialAlpha = p.gradient.c1 and p.gradient.c1[4]
      if initialAlpha == nil then initialAlpha = 0.8 end
    else
      initialAlpha = (p.color and p.color[4] ~= nil) and p.color[4] or 0.8
    end

    OpenColorPickerRGBOnly(initial, function(r, g, b, a)
      if p.gradient then
        EnsureGradientTables(p)
        if isSecond then
          p.gradient.c2[1], p.gradient.c2[2], p.gradient.c2[3] = r, g, b
        else
          p.gradient.c1[1], p.gradient.c1[2], p.gradient.c1[3] = r, g, b
        end
        local alpha = (a ~= nil) and a or initialAlpha or 0.8
        p.gradient.c1[4] = alpha
        p.gradient.c2[4] = alpha
      else
        local alpha = (a ~= nil) and a or initialAlpha or 0.8
        p.color = { r, g, b, alpha }
      end
      RebuildAllPanels()
      RefreshPanelProperties(editor)
    end, initialAlpha)
  end

  colorSingleBtn:SetScript("OnClick", function() PickColor(false) end)
  color1Btn:SetScript("OnClick", function() PickColor(false) end)
  color2Btn:SetScript("OnClick", function() PickColor(true) end)

  local alphaSlider = CreateFrame("Slider", "LIDCOUNCIL_AlphaSlider", props, "OptionsSliderTemplate")
  alphaSlider:SetPoint("TOPLEFT", 0, -618)
  alphaSlider:SetWidth(300)
  alphaSlider:SetMinMaxValues(0, 1)
  alphaSlider:SetValueStep(0.01)
  alphaSlider:SetObeyStepOnDrag(true)
  _G[alphaSlider:GetName() .. "Low"]:SetText("0")
  _G[alphaSlider:GetName() .. "High"]:SetText("1")
  _G[alphaSlider:GetName() .. "Text"]:SetText("Transparency")
  editor.alphaSlider = alphaSlider

  alphaSlider:SetScript("OnValueChanged", function(_, val)
    if editor and editor.__refreshing then return end
    if not GetSelectedPanelName() then return end
    local p = DB().panels[GetSelectedPanelName()]
    if not p then return end
    p.color = p.color or { 0.05, 0.05, 0.07, 0.8 }
    if p.gradient then
      EnsureGradientTables(p)
      p.gradient.c1[4] = val
      p.gradient.c2[4] = val
    else
      p.color[4] = val
    end
    RebuildAllPanels()
  end)

  local function UpdateColorDesignUI()
    if not GetSelectedPanelName() then return end
    local p = DB().panels[GetSelectedPanelName()]
    if not p then return end
    local diag, special = EnsurePanelExtraData(p)

    local mode = GetColorMode(p)
    modeSingleCheck:SetChecked(mode == "SINGLE")
    modeDualCheck:SetChecked(mode == "DUAL")
    modeBgCheck:SetChecked(mode == "BG")
    modeTextureCheck:SetChecked(mode == "TEX")
    modeIconCheck:SetChecked(mode == "ICON")
    modeModelCheck:SetChecked(mode == "MODEL")

    local showBg = (mode == "BG")
    local showTexture = (mode == "TEX")
    local showIcon = (mode == "ICON")
    local showModel = (mode == "MODEL")
    local showDual = (mode == "DUAL")
    local showSingle = (mode == "SINGLE")

    bgLabel:SetShown(showBg)
    bgDrop:SetShown(showBg)
    if editor.customBgLabel then editor.customBgLabel:SetShown(showBg) end
    if editor.customBgDrop then editor.customBgDrop:SetShown(showBg) end
    if editor.textureBgLabel then editor.textureBgLabel:SetShown(showTexture) end
    if editor.texturePickBtn then editor.texturePickBtn:SetShown(showTexture) end
    if editor.textureName then editor.textureName:SetShown(showTexture) end
    if editor.modelBgLabel then editor.modelBgLabel:SetShown(showModel) end
    if editor.modelPickBtn then editor.modelPickBtn:SetShown(showModel) end
    if editor.modelName then editor.modelName:SetShown(showModel) end
    if editor.iconBgLabel then editor.iconBgLabel:SetShown(showIcon) end
    if editor.iconPickBtn then editor.iconPickBtn:SetShown(showIcon) end
    if editor.iconName then editor.iconName:SetShown(showIcon) end
    if editor.texturePickBorder then editor.texturePickBorder:SetShown(false) end
    if editor.iconPickBorder then editor.iconPickBorder:SetShown(false) end
    if editor.modelPickBorder then editor.modelPickBorder:SetShown(false) end
    if editor.bgDropBorder then editor.bgDropBorder:SetShown(false) end
    if editor.customBgBorder then editor.customBgBorder:SetShown(false) end

    if showBg or showTexture or showIcon or showModel then
      local bgVal = p.bg or "NONE"
      local isIcon = (mode == "ICON")
      local isTexture = (mode == "TEX")
      local isModel = (mode == "MODEL")
      local isCustom = false
      local talentOption = nil
      local customText = "None"
      local options = editor.customBgOptions
      if not options and BuildCustomBackgroundOptions then
        options = BuildCustomBackgroundOptions()
        editor.customBgOptions = options
      end
      if not options then options = { { text = "None", value = "NONE" } } end
      for _, opt in ipairs(options) do
        if opt.value == bgVal and bgVal ~= "NONE" then
          isCustom = true
          customText = opt.text
          break
        end
      end

      local isTalent = (mode == "BG")
      if isTalent then
        talentOption = FindTalentOptionForPanel(p, editor.bgOptions or bgOptions)
        if talentOption then
          if p.bg ~= talentOption.bg
            or (not SameTexCoord(p.bgTexCoord, talentOption.texCoord))
            or p.bgChoiceKey ~= talentOption.value then
            p.bg = talentOption.bg
            p.bgTexCoord = CopyTexCoord(talentOption.texCoord)
            p.bgChoiceKey = talentOption.value
            bgVal = p.bg
            RebuildAllPanels()
          end
        end
      end

      if isIcon then
        SetDropdownSelection(bgDrop, "NONE", "None")
        SetDropdownSelection(customBgDrop, "NONE", "None")
        if editor.iconName then
          editor.iconName:SetText("Selected: " .. tostring(p.bgIconName or "None"))
        end
        if editor.iconPickBorder then editor.iconPickBorder:SetShown(true) end
        if editor.textureName then editor.textureName:SetText("Selected: None") end
        if editor.modelName then editor.modelName:SetText("Selected: None") end
      elseif isTexture then
        SetDropdownSelection(bgDrop, "NONE", "None")
        SetDropdownSelection(customBgDrop, "NONE", "None")
        if editor.iconName then editor.iconName:SetText("Selected: None") end
        if editor.textureName then
          editor.textureName:SetText("Selected: " .. tostring(p.bgTextureName or "None"))
        end
        if editor.texturePickBorder then editor.texturePickBorder:SetShown(true) end
        if editor.modelName then editor.modelName:SetText("Selected: None") end
      elseif isModel then
        SetDropdownSelection(bgDrop, "NONE", "None")
        SetDropdownSelection(customBgDrop, "NONE", "None")
        if editor.iconName then editor.iconName:SetText("Selected: None") end
        if editor.textureName then editor.textureName:SetText("Selected: None") end
        if editor.modelName then
          local label = p.bgModelName or "None"
          if p.bgModelId then
            label = label .. " (" .. tostring(p.bgModelId) .. ")"
          end
          editor.modelName:SetText("Selected: " .. label)
        end
        if editor.modelPickBorder then editor.modelPickBorder:SetShown(true) end
      elseif isCustom then
        SetDropdownSelection(customBgDrop, bgVal, customText)
        SetDropdownSelection(bgDrop, "NONE", "None")
        if editor.iconName then editor.iconName:SetText("Selected: None") end
        if editor.textureName then editor.textureName:SetText("Selected: None") end
        if editor.modelName then editor.modelName:SetText("Selected: None") end
        if editor.customBgBorder then editor.customBgBorder:SetShown(true) end
      else
        local bgText = "None"
        if talentOption then
          bgText = talentOption.text or "None"
          SetDropdownSelection(bgDrop, talentOption.value)
        else
          SetDropdownSelection(bgDrop, "NONE")
        end
        SetDropdownSelection(bgDrop, nil, bgText)
        SetDropdownSelection(customBgDrop, "NONE", "None")
        if editor.iconName then editor.iconName:SetText("Selected: None") end
        if editor.textureName then editor.textureName:SetText("Selected: None") end
        if editor.modelName then editor.modelName:SetText("Selected: None") end
      end

      if showBg and isTalent and not isCustom and editor.bgDropBorder then
        editor.bgDropBorder:SetShown(true)
      end
      if isModel then
        bgPreview:Hide()
      else
        UpdateBgPreview(bgVal, p.bgTexCoord)
      end
    else
      bgPreview:Hide()
    end

    colorSingleBtn:SetShown(showSingle)
    color1Btn:SetShown(showDual)
    color2Btn:SetShown(showDual)
    dirLabel:SetShown(showDual)
    dirDrop:SetShown(showDual)

    if p.gradient then
      EnsureGradientTables(p)
    end
    SetColorPreviewSwatch(colorSingleBtn, p.color or { 0.05, 0.05, 0.07, 0.8 })
    SetColorPreviewSwatch(color1Btn, (p.gradient and p.gradient.c1) or p.color or { 0.05, 0.05, 0.07, 0.8 })
    SetColorPreviewSwatch(color2Btn, (p.gradient and p.gradient.c2) or p.color or { 0.05, 0.05, 0.07, 0.8 })

    if showDual then
      local dir = (p.gradient and p.gradient.dir) or "VERTICAL"
      local dirText = (dir == "VERTICAL") and "Vertical" or "Horizontal"
      UIDropDownMenu_SetSelectedValue(dirDrop, dir)
      UIDropDownMenu_SetText(dirDrop, dirText)
    end

    alphaSlider:ClearAllPoints()
    local alphaY
    if showSingle then
      alphaY = -620
      alphaSlider:SetPoint("TOPLEFT", 0, alphaY)
    elseif showDual then
      alphaY = -674
      alphaSlider:SetPoint("TOPLEFT", 0, alphaY)
    else
      alphaY = -672
      alphaSlider:SetPoint("TOPLEFT", 0, alphaY)
    end

    if editor.borderHeader then
      local borderY = alphaY - 70
      local borderKey = p.border or "tooltip"
      local showBorderColor = TINTABLE_BORDER_CHOICES[borderKey] and true or false
      local showBorderAlpha = (borderKey ~= "none") and (not showBorderColor)
      editor.borderHeader:ClearAllPoints()
      editor.borderHeader:SetPoint("TOPLEFT", 0, borderY)
      if editor.borderDesc then
        editor.borderDesc:ClearAllPoints()
        editor.borderDesc:SetPoint("TOPLEFT", 0, borderY - 20)
      end
      if editor.borderDrop then
        editor.borderDrop:ClearAllPoints()
        editor.borderDrop:SetPoint("TOPLEFT", -12, borderY - 36)
      end
      if editor.borderColorBtn then
        editor.borderColorBtn:ClearAllPoints()
        editor.borderColorBtn:SetPoint("TOPLEFT", 0, borderY - 72)
        editor.borderColorBtn:SetShown(showBorderColor)
        SetColorPreviewSwatch(editor.borderColorBtn, p.borderColor or { 0, 0, 0, 0.9 })
      end
      if editor.borderAlphaSlider then
        editor.borderAlphaSlider:ClearAllPoints()
        editor.borderAlphaSlider:SetPoint("TOPLEFT", 0, borderY - 90)
        editor.borderAlphaSlider:SetShown(showBorderAlpha)
        if editor.borderAlphaSlider.valueBox then
          editor.borderAlphaSlider.valueBox:SetShown(showBorderAlpha)
        end
        local sliderName = editor.borderAlphaSlider.GetName and editor.borderAlphaSlider:GetName()
        if sliderName then
          if _G[sliderName .. "Low"] then _G[sliderName .. "Low"]:SetShown(showBorderAlpha) end
          if _G[sliderName .. "High"] then _G[sliderName .. "High"]:SetShown(showBorderAlpha) end
          if _G[sliderName .. "Text"] then _G[sliderName .. "Text"]:SetShown(showBorderAlpha) end
        end
        if showBorderAlpha then
          editor.borderAlphaSlider:SetValueSilent((tonumber(p.borderAlpha) or 0.9) * 100)
        end
      end

      local sectionY
      if showBorderColor then
        sectionY = borderY - 146
      elseif showBorderAlpha then
        sectionY = borderY - 164
      else
        sectionY = borderY - 110
      end
      local specialMode = (special and special.mode) or "NONE"
      if editor.specialHeader then
        editor.specialHeader:ClearAllPoints()
        editor.specialHeader:SetPoint("TOPLEFT", 0, sectionY)
      end
      if editor.diagHeader then
        editor.diagHeader:ClearAllPoints()
        editor.diagHeader:SetPoint("TOPLEFT", 250, sectionY)
      end
      if editor.specialGoldCheck then
        editor.specialGoldCheck:ClearAllPoints()
        editor.specialGoldCheck:SetPoint("TOPLEFT", 0, sectionY - 24)
        editor.specialGoldCheck:SetChecked(specialMode == "GOLD")
      end
      if editor.specialStatsCheck then
        editor.specialStatsCheck:ClearAllPoints()
        editor.specialStatsCheck:SetPoint("TOPLEFT", 0, sectionY - 46)
        editor.specialStatsCheck:SetChecked(specialMode == "STATS")
      end
      if editor.specialCustomTextCheck then
        editor.specialCustomTextCheck:ClearAllPoints()
        editor.specialCustomTextCheck:SetPoint("TOPLEFT", 0, sectionY - 68)
        editor.specialCustomTextCheck:SetChecked(specialMode == "CUSTOM_TEXT")
      end
      if editor.diagFpsGraphCheck then
        editor.diagFpsGraphCheck:ClearAllPoints()
        editor.diagFpsGraphCheck:SetPoint("TOPLEFT", 250, sectionY - 24)
        editor.diagFpsGraphCheck:SetChecked(specialMode == "FPS_GRAPH")
      end
      if editor.specialFpsCheck then
        editor.specialFpsCheck:ClearAllPoints()
        editor.specialFpsCheck:SetPoint("TOPLEFT", 250, sectionY - 46)
        editor.specialFpsCheck:SetChecked(specialMode == "FPS")
      end

      local function ShowControl(ctrl, shown)
        if ctrl then
          local vis = shown and true or false
          ctrl:SetShown(vis)
          if ctrl.valueBox then ctrl.valueBox:SetShown(vis) end
        end
      end

      local function HideSpecialSubmenus()
        ShowControl(editor.specialGoldConfigLabel, false)
        ShowControl(editor.specialGoldColorBtn, false)
        ShowControl(editor.specialGoldFontLabel, false)
        ShowControl(editor.specialGoldFontDrop, false)
        ShowControl(editor.specialGoldSizeSlider, false)
        ShowControl(editor.specialGoldAlphaSlider, false)
        ShowControl(editor.specialFpsFontLabel, false)
        ShowControl(editor.specialFpsFontDrop, false)
        ShowControl(editor.specialFpsSizeSlider, false)
        ShowControl(editor.specialFpsAlphaSlider, false)
        ShowControl(editor.specialFpsColorLabel, false)
        ShowControl(editor.specialFpsLowColorBtn, false)
        ShowControl(editor.specialFpsMidColorBtn, false)
        ShowControl(editor.specialFpsHighColorBtn, false)
        ShowControl(editor.specialFpsRuleLabel, false)
        ShowControl(editor.specialFpsLowEdit, false)
        ShowControl(editor.specialFpsMidLabel, false)
        ShowControl(editor.specialFpsHighEdit, false)
        ShowControl(editor.specialFpsResetBtn, false)
        ShowControl(editor.diagGraphSettingsLabel, false)
        ShowControl(editor.diagGraphShowFpsCheck, false)
        ShowControl(editor.diagGraphShowAvgCheck, false)
        ShowControl(editor.diagGraphShowLowCheck, false)
        ShowControl(editor.diagGraphFpsIntervalBtn, false)
        ShowControl(editor.diagGraphAvgIntervalBtn, false)
        ShowControl(editor.diagGraphLowIntervalBtn, false)
        ShowControl(editor.diagGraphUpdateLabel, false)
        ShowControl(editor.diagGraphUpdateEdit, false)
        ShowControl(editor.diagGraphStyleLabel, false)
        ShowControl(editor.diagGraphStyleDrop, false)
        ShowControl(editor.specialStatsLabel, false)
        ShowControl(editor.specialStatsColorHeader, false)
        ShowControl(editor.specialStatsSizeSlider, false)
        ShowControl(editor.specialStatsAlphaSlider, false)
        ShowControl(editor.specialCustomTextLabel, false)
        ShowControl(editor.specialCustomTextEdit, false)
        ShowControl(editor.specialCustomTextFontLabel, false)
        ShowControl(editor.specialCustomTextFontDrop, false)
        ShowControl(editor.specialCustomTextSizeSlider, false)
        ShowControl(editor.specialCustomTextAlphaSlider, false)
        ShowControl(editor.specialCustomTextColorBtn, false)
        if editor.specialStatChecks then
          for _, def in ipairs(PANEL_STAT_CHOICES) do
            local cb = editor.specialStatChecks[def.key]
            if cb then cb:SetShown(false) end
          end
        end
        if editor.specialStatTitleBtns then
          for _, def in ipairs(PANEL_STAT_CHOICES) do
            local b = editor.specialStatTitleBtns[def.key]
            if b then b:SetShown(false) end
          end
        end
        if editor.specialStatValueBtns then
          for _, def in ipairs(PANEL_STAT_CHOICES) do
            local b = editor.specialStatValueBtns[def.key]
            if b then b:SetShown(false) end
          end
        end
      end

      HideSpecialSubmenus()
      local resetAnchorY = sectionY - 116

      if specialMode == "GOLD" then
        if editor.specialGoldConfigLabel then
          editor.specialGoldConfigLabel:ClearAllPoints()
          editor.specialGoldConfigLabel:SetPoint("TOPLEFT", 0, sectionY - 96)
          editor.specialGoldConfigLabel:SetShown(true)
        end
        if editor.specialGoldFontLabel then
          editor.specialGoldFontLabel:ClearAllPoints()
          editor.specialGoldFontLabel:SetPoint("TOPLEFT", 0, sectionY - 118)
          editor.specialGoldFontLabel:SetShown(true)
        end
        if editor.specialGoldFontDrop then
          editor.specialGoldFontDrop:ClearAllPoints()
          editor.specialGoldFontDrop:SetPoint("TOPLEFT", -12, sectionY - 134)
          editor.specialGoldFontDrop:SetShown(true)
          UIDropDownMenu_SetSelectedValue(editor.specialGoldFontDrop, special.gold.font)
          UIDropDownMenu_SetText(editor.specialGoldFontDrop, special.gold.font or "GameFontHighlightSmall")
        end
        if editor.specialGoldSizeSlider then
          editor.specialGoldSizeSlider:ClearAllPoints()
          editor.specialGoldSizeSlider:SetPoint("TOPLEFT", 0, sectionY - 180)
          editor.specialGoldSizeSlider:SetShown(true)
          if editor.specialGoldSizeSlider.valueBox then editor.specialGoldSizeSlider.valueBox:SetShown(true) end
          editor.specialGoldSizeSlider:SetValueSilent(special.gold.size or 14)
        end
        if editor.specialGoldAlphaSlider then
          editor.specialGoldAlphaSlider:ClearAllPoints()
          editor.specialGoldAlphaSlider:SetPoint("TOPLEFT", 0, sectionY - 228)
          editor.specialGoldAlphaSlider:SetShown(true)
          if editor.specialGoldAlphaSlider.valueBox then editor.specialGoldAlphaSlider.valueBox:SetShown(true) end
          editor.specialGoldAlphaSlider:SetValueSilent(math.floor(((special.gold.color and special.gold.color[4]) or 1) * 100 + 0.5))
        end
        if editor.specialGoldColorBtn then
          editor.specialGoldColorBtn:ClearAllPoints()
          editor.specialGoldColorBtn:SetPoint("TOPLEFT", 0, sectionY - 278)
          editor.specialGoldColorBtn:SetShown(true)
        end
        resetAnchorY = sectionY - 326
      elseif specialMode == "FPS" or specialMode == "FPS_GRAPH" then
        local fontY = sectionY - 96
        if specialMode == "FPS_GRAPH" then
          local gy = sectionY - 96

          if editor.diagGraphUpdateLabel then
            editor.diagGraphUpdateLabel:ClearAllPoints()
            editor.diagGraphUpdateLabel:SetPoint("TOPLEFT", 0, gy)
            editor.diagGraphUpdateLabel:SetShown(true)
          end
          if editor.diagGraphUpdateEdit then
            editor.diagGraphUpdateEdit:ClearAllPoints()
            editor.diagGraphUpdateEdit:SetPoint("TOPLEFT", 0, gy - 20)
            editor.diagGraphUpdateEdit:SetText(string.format("%.1f", (diag.graph and diag.graph.updateInterval) or 0.1))
            editor.diagGraphUpdateEdit:SetShown(true)
          end

          if editor.specialFpsColorLabel then
            editor.specialFpsColorLabel:ClearAllPoints()
            editor.specialFpsColorLabel:SetPoint("TOPLEFT", 0, gy - 52)
            editor.specialFpsColorLabel:SetShown(true)
          end
          if editor.specialFpsLowColorBtn then
            editor.specialFpsLowColorBtn:ClearAllPoints()
            editor.specialFpsLowColorBtn:SetPoint("TOPLEFT", 0, gy - 74)
            editor.specialFpsLowColorBtn:SetShown(true)
          end
          if editor.specialFpsMidColorBtn then
            editor.specialFpsMidColorBtn:ClearAllPoints()
            editor.specialFpsMidColorBtn:SetPoint("TOPLEFT", 110, gy - 74)
            editor.specialFpsMidColorBtn:SetShown(true)
          end
          if editor.specialFpsHighColorBtn then
            editor.specialFpsHighColorBtn:ClearAllPoints()
            editor.specialFpsHighColorBtn:SetPoint("TOPLEFT", 220, gy - 74)
            editor.specialFpsHighColorBtn:SetShown(true)
          end
          if editor.specialFpsLowEdit then
            editor.specialFpsLowEdit:ClearAllPoints()
            if editor.specialFpsLowColorBtn then
              editor.specialFpsLowEdit:SetPoint("TOP", editor.specialFpsLowColorBtn, "BOTTOM", 0, -8)
            else
              editor.specialFpsLowEdit:SetPoint("TOPLEFT", 0, gy - 124)
            end
            editor.specialFpsLowEdit:SetShown(true)
            editor.specialFpsLowEdit:SetText(tostring(special.fps.lowValue or 30))
          end
          if editor.specialFpsMidLabel then
            editor.specialFpsMidLabel:ClearAllPoints()
            if editor.specialFpsMidColorBtn then
              editor.specialFpsMidLabel:SetPoint("TOP", editor.specialFpsMidColorBtn, "BOTTOM", 0, -10)
            else
              editor.specialFpsMidLabel:SetPoint("TOPLEFT", 126, gy - 124)
            end
            editor.specialFpsMidLabel:SetShown(true)
          end
          if editor.specialFpsHighEdit then
            editor.specialFpsHighEdit:ClearAllPoints()
            if editor.specialFpsHighColorBtn then
              editor.specialFpsHighEdit:SetPoint("TOP", editor.specialFpsHighColorBtn, "BOTTOM", 0, -8)
            else
              editor.specialFpsHighEdit:SetPoint("TOPLEFT", 220, gy - 124)
            end
            editor.specialFpsHighEdit:SetShown(true)
            editor.specialFpsHighEdit:SetText(tostring(special.fps.highValue or 60))
          end
          if editor.specialFpsResetBtn then
            editor.specialFpsResetBtn:ClearAllPoints()
            editor.specialFpsResetBtn:SetPoint("TOPLEFT", 0, gy - 162)
            editor.specialFpsResetBtn:SetShown(true)
          end

          if editor.diagGraphStyleLabel then
            editor.diagGraphStyleLabel:ClearAllPoints()
            editor.diagGraphStyleLabel:SetPoint("TOPLEFT", 0, gy - 198)
            editor.diagGraphStyleLabel:SetShown(true)
          end
          if editor.diagGraphStyleDrop then
            editor.diagGraphStyleDrop:ClearAllPoints()
            editor.diagGraphStyleDrop:SetPoint("TOPLEFT", -12, gy - 214)
            editor.diagGraphStyleDrop:SetShown(true)
            local style = (diag.graph and diag.graph.style) or "BARS"
            local styleText = (style == "WAVE") and "Wave (Smooth)" or "Bars"
            UIDropDownMenu_SetSelectedValue(editor.diagGraphStyleDrop, style)
            UIDropDownMenu_SetText(editor.diagGraphStyleDrop, styleText)
          end

          if editor.diagGraphSettingsLabel then
            editor.diagGraphSettingsLabel:ClearAllPoints()
            editor.diagGraphSettingsLabel:SetPoint("TOPLEFT", 0, gy - 260)
            editor.diagGraphSettingsLabel:SetShown(true)
          end
          if editor.diagGraphShowFpsCheck then
            local checked = (diag.graph and diag.graph.showFPS) and true or false
            editor.diagGraphShowFpsCheck:ClearAllPoints()
            editor.diagGraphShowFpsCheck:SetPoint("TOPLEFT", 0, gy - 282)
            editor.diagGraphShowFpsCheck:SetChecked(checked)
            editor.diagGraphShowFpsCheck:SetShown(true)
            if editor.diagGraphFpsIntervalBtn then
              editor.diagGraphFpsIntervalBtn:ClearAllPoints()
              editor.diagGraphFpsIntervalBtn:SetPoint("LEFT", editor.diagGraphShowFpsCheck, "LEFT", 170, 0)
              editor.diagGraphFpsIntervalBtn:SetShown(checked)
            end
          end
          if editor.diagGraphShowAvgCheck then
            local checked = (diag.graph and diag.graph.showAvg) and true or false
            editor.diagGraphShowAvgCheck:ClearAllPoints()
            editor.diagGraphShowAvgCheck:SetPoint("TOPLEFT", 0, gy - 306)
            editor.diagGraphShowAvgCheck:SetChecked(checked)
            editor.diagGraphShowAvgCheck:SetShown(true)
            if editor.diagGraphAvgIntervalBtn then
              editor.diagGraphAvgIntervalBtn:ClearAllPoints()
              editor.diagGraphAvgIntervalBtn:SetPoint("LEFT", editor.diagGraphShowAvgCheck, "LEFT", 170, 0)
              editor.diagGraphAvgIntervalBtn:SetShown(checked)
            end
          end
          if editor.diagGraphShowLowCheck then
            local checked = (diag.graph and diag.graph.showLow) and true or false
            editor.diagGraphShowLowCheck:ClearAllPoints()
            editor.diagGraphShowLowCheck:SetPoint("TOPLEFT", 0, gy - 330)
            editor.diagGraphShowLowCheck:SetChecked(checked)
            editor.diagGraphShowLowCheck:SetShown(true)
            if editor.diagGraphLowIntervalBtn then
              editor.diagGraphLowIntervalBtn:ClearAllPoints()
              editor.diagGraphLowIntervalBtn:SetPoint("LEFT", editor.diagGraphShowLowCheck, "LEFT", 170, 0)
              editor.diagGraphLowIntervalBtn:SetShown(checked)
            end
          end

          fontY = gy - 368
        end

        if editor.specialFpsFontLabel then
          editor.specialFpsFontLabel:ClearAllPoints()
          editor.specialFpsFontLabel:SetPoint("TOPLEFT", 0, fontY)
          editor.specialFpsFontLabel:SetShown(true)
        end
        if editor.specialFpsFontDrop then
          editor.specialFpsFontDrop:ClearAllPoints()
          editor.specialFpsFontDrop:SetPoint("TOPLEFT", -12, fontY - 16)
          editor.specialFpsFontDrop:SetShown(true)
          UIDropDownMenu_SetSelectedValue(editor.specialFpsFontDrop, special.fps.font)
          UIDropDownMenu_SetText(editor.specialFpsFontDrop, special.fps.font or "GameFontHighlightSmall")
        end
        if editor.specialFpsSizeSlider then
          editor.specialFpsSizeSlider:ClearAllPoints()
          editor.specialFpsSizeSlider:SetPoint("TOPLEFT", 0, fontY - 62)
          editor.specialFpsSizeSlider:SetShown(true)
          if editor.specialFpsSizeSlider.valueBox then editor.specialFpsSizeSlider.valueBox:SetShown(true) end
          editor.specialFpsSizeSlider:SetValueSilent(special.fps.size or 14)
        end
        if editor.specialFpsAlphaSlider then
          editor.specialFpsAlphaSlider:ClearAllPoints()
          editor.specialFpsAlphaSlider:SetPoint("TOPLEFT", 0, fontY - 110)
          editor.specialFpsAlphaSlider:SetShown(true)
          if editor.specialFpsAlphaSlider.valueBox then editor.specialFpsAlphaSlider.valueBox:SetShown(true) end
          editor.specialFpsAlphaSlider:SetValueSilent(math.floor((tonumber(special.fps.alpha) or 1) * 100 + 0.5))
        end
        if specialMode ~= "FPS_GRAPH" then
          if editor.specialFpsColorLabel then
            editor.specialFpsColorLabel:ClearAllPoints()
            editor.specialFpsColorLabel:SetPoint("TOPLEFT", 0, fontY - 158)
            editor.specialFpsColorLabel:SetShown(true)
          end
          if editor.specialFpsLowColorBtn then
            editor.specialFpsLowColorBtn:ClearAllPoints()
            editor.specialFpsLowColorBtn:SetPoint("TOPLEFT", 0, fontY - 180)
            editor.specialFpsLowColorBtn:SetShown(true)
          end
          if editor.specialFpsMidColorBtn then
            editor.specialFpsMidColorBtn:ClearAllPoints()
            editor.specialFpsMidColorBtn:SetPoint("TOPLEFT", 110, fontY - 180)
            editor.specialFpsMidColorBtn:SetShown(true)
          end
          if editor.specialFpsHighColorBtn then
            editor.specialFpsHighColorBtn:ClearAllPoints()
            editor.specialFpsHighColorBtn:SetPoint("TOPLEFT", 220, fontY - 180)
            editor.specialFpsHighColorBtn:SetShown(true)
          end
          if editor.specialFpsLowEdit then
            editor.specialFpsLowEdit:ClearAllPoints()
            if editor.specialFpsLowColorBtn then
              editor.specialFpsLowEdit:SetPoint("TOP", editor.specialFpsLowColorBtn, "BOTTOM", 0, -8)
            else
              editor.specialFpsLowEdit:SetPoint("TOPLEFT", 0, fontY - 230)
            end
            editor.specialFpsLowEdit:SetShown(true)
            editor.specialFpsLowEdit:SetText(tostring(special.fps.lowValue or 30))
          end
          if editor.specialFpsMidLabel then
            editor.specialFpsMidLabel:ClearAllPoints()
            if editor.specialFpsMidColorBtn then
              editor.specialFpsMidLabel:SetPoint("TOP", editor.specialFpsMidColorBtn, "BOTTOM", 0, -10)
            else
              editor.specialFpsMidLabel:SetPoint("TOPLEFT", 126, fontY - 230)
            end
            editor.specialFpsMidLabel:SetShown(true)
          end
          if editor.specialFpsHighEdit then
            editor.specialFpsHighEdit:ClearAllPoints()
            if editor.specialFpsHighColorBtn then
              editor.specialFpsHighEdit:SetPoint("TOP", editor.specialFpsHighColorBtn, "BOTTOM", 0, -8)
            else
              editor.specialFpsHighEdit:SetPoint("TOPLEFT", 220, fontY - 230)
            end
            editor.specialFpsHighEdit:SetShown(true)
            editor.specialFpsHighEdit:SetText(tostring(special.fps.highValue or 60))
          end
          if editor.specialFpsResetBtn then
            editor.specialFpsResetBtn:ClearAllPoints()
            editor.specialFpsResetBtn:SetPoint("TOPLEFT", 0, fontY - 268)
            editor.specialFpsResetBtn:SetShown(true)
          end
        end
        if specialMode == "FPS_GRAPH" then
          resetAnchorY = sectionY - 670
        else
          resetAnchorY = sectionY - 420
        end
      elseif specialMode == "STATS" then
        if editor.specialStatsLabel then
          editor.specialStatsLabel:ClearAllPoints()
          editor.specialStatsLabel:SetPoint("TOPLEFT", 0, sectionY - 96)
          editor.specialStatsLabel:SetShown(true)
        end
        if editor.specialStatsColorHeader then
          editor.specialStatsColorHeader:ClearAllPoints()
          editor.specialStatsColorHeader:SetPoint("TOPLEFT", 206, sectionY - 96)
          editor.specialStatsColorHeader:SetShown(true)
        end
        local rowY = sectionY - 118
        for _, def in ipairs(PANEL_STAT_CHOICES) do
          local cb = editor.specialStatChecks and editor.specialStatChecks[def.key]
          local titleBtn = editor.specialStatTitleBtns and editor.specialStatTitleBtns[def.key]
          local valueBtn = editor.specialStatValueBtns and editor.specialStatValueBtns[def.key]
          local chosen = special.stats and special.stats[def.key] and true or false
          if cb then
            cb:ClearAllPoints()
            cb:SetPoint("TOPLEFT", 0, rowY)
            cb:SetChecked(chosen)
            cb:SetShown(true)
          end
          if titleBtn then
            titleBtn:ClearAllPoints()
            titleBtn:SetPoint("TOPLEFT", 206, rowY + 2)
            titleBtn:SetShown(chosen)
          end
          if valueBtn then
            valueBtn:ClearAllPoints()
            valueBtn:SetPoint("TOPLEFT", 268, rowY + 2)
            valueBtn:SetShown(chosen)
          end
          rowY = rowY - 22
        end
        if editor.specialStatsSizeSlider then
          editor.specialStatsSizeSlider:ClearAllPoints()
          editor.specialStatsSizeSlider:SetPoint("TOPLEFT", 0, rowY - 26)
          editor.specialStatsSizeSlider:SetShown(true)
          if editor.specialStatsSizeSlider.valueBox then editor.specialStatsSizeSlider.valueBox:SetShown(true) end
          editor.specialStatsSizeSlider:SetValueSilent(special.statsSize or 14)
        end
        if editor.specialStatsAlphaSlider then
          editor.specialStatsAlphaSlider:ClearAllPoints()
          editor.specialStatsAlphaSlider:SetPoint("TOPLEFT", 0, rowY - 74)
          editor.specialStatsAlphaSlider:SetShown(true)
          if editor.specialStatsAlphaSlider.valueBox then editor.specialStatsAlphaSlider.valueBox:SetShown(true) end
          editor.specialStatsAlphaSlider:SetValueSilent(math.floor((tonumber(special.statsAlpha) or 1) * 100 + 0.5))
        end
        resetAnchorY = rowY - 120
      elseif specialMode == "CUSTOM_TEXT" then
        if editor.specialCustomTextLabel then
          editor.specialCustomTextLabel:ClearAllPoints()
          editor.specialCustomTextLabel:SetPoint("TOPLEFT", 0, sectionY - 96)
          editor.specialCustomTextLabel:SetShown(true)
        end
        if editor.specialCustomTextEdit then
          editor.specialCustomTextEdit:ClearAllPoints()
          editor.specialCustomTextEdit:SetPoint("TOPLEFT", 0, sectionY - 118)
          editor.specialCustomTextEdit:SetShown(true)
          editor.specialCustomTextEdit:SetText(tostring(special.customText and special.customText.text or "Custom Text"))
        end
        if editor.specialCustomTextFontLabel then
          editor.specialCustomTextFontLabel:ClearAllPoints()
          editor.specialCustomTextFontLabel:SetPoint("TOPLEFT", 0, sectionY - 150)
          editor.specialCustomTextFontLabel:SetShown(true)
        end
        if editor.specialCustomTextFontDrop then
          editor.specialCustomTextFontDrop:ClearAllPoints()
          editor.specialCustomTextFontDrop:SetPoint("TOPLEFT", -12, sectionY - 166)
          editor.specialCustomTextFontDrop:SetShown(true)
          UIDropDownMenu_SetSelectedValue(editor.specialCustomTextFontDrop, special.customText.font)
          UIDropDownMenu_SetText(editor.specialCustomTextFontDrop, special.customText.font or "GameFontHighlightSmall")
        end
        if editor.specialCustomTextSizeSlider then
          editor.specialCustomTextSizeSlider:ClearAllPoints()
          editor.specialCustomTextSizeSlider:SetPoint("TOPLEFT", 0, sectionY - 212)
          editor.specialCustomTextSizeSlider:SetShown(true)
          if editor.specialCustomTextSizeSlider.valueBox then editor.specialCustomTextSizeSlider.valueBox:SetShown(true) end
          editor.specialCustomTextSizeSlider:SetValueSilent(special.customText.size or 14)
        end
        if editor.specialCustomTextAlphaSlider then
          editor.specialCustomTextAlphaSlider:ClearAllPoints()
          editor.specialCustomTextAlphaSlider:SetPoint("TOPLEFT", 0, sectionY - 260)
          editor.specialCustomTextAlphaSlider:SetShown(true)
          if editor.specialCustomTextAlphaSlider.valueBox then editor.specialCustomTextAlphaSlider.valueBox:SetShown(true) end
          editor.specialCustomTextAlphaSlider:SetValueSilent(math.floor(((special.customText.color and special.customText.color[4]) or 1) * 100 + 0.5))
        end
        if editor.specialCustomTextColorBtn then
          editor.specialCustomTextColorBtn:ClearAllPoints()
          editor.specialCustomTextColorBtn:SetPoint("TOPLEFT", 0, sectionY - 308)
          editor.specialCustomTextColorBtn:SetShown(true)
        end
        resetAnchorY = sectionY - 356
      end

      if editor.resetHeader then
        local baseResetY = resetAnchorY
        editor.resetHeader:ClearAllPoints()
        editor.resetHeader:SetPoint("TOPLEFT", 0, baseResetY)
        if editor.resetDesc then
          editor.resetDesc:ClearAllPoints()
          editor.resetDesc:SetPoint("TOPLEFT", 0, baseResetY - 20)
        end
        if editor.resetPanelBtn then
          editor.resetPanelBtn:ClearAllPoints()
          editor.resetPanelBtn:SetPoint("TOPLEFT", 0, baseResetY - 80)
        end
      end
    end

    if editor and editor.UpdatePanelsPropsHeight then
      editor:UpdatePanelsPropsHeight()
    end
  end
  editor.UpdateColorDesignUI = UpdateColorDesignUI

  local borderHeader = MakeYellowSubHeader(props, "Border Design", 0, -650)
  editor.borderHeader = borderHeader

  local borderDesc = props:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
  borderDesc:SetPoint("TOPLEFT", 0, -670)
  borderDesc:SetText("Choose a frame style for your panel:")
  editor.borderDesc = borderDesc

  local borderDrop = CreateFrame("Frame", "LIDCOUNCIL_BorderDropdown", props, "UIDropDownMenuTemplate")
  borderDrop:SetPoint("TOPLEFT", -12, -686)
  editor.borderDrop = borderDrop

  UIDropDownMenu_Initialize(borderDrop, function(self, level)
    local cur = "tooltip"
    if GetSelectedPanelName() then
      local p = DB().panels[GetSelectedPanelName()]
      if p and p.border then cur = p.border end
    end
    for _, opt in ipairs(BORDER_CHOICES) do
      local info = UIDropDownMenu_CreateInfo()
      info.text = opt.text
      info.value = opt.value
      info.func = function()
        UIDropDownMenu_SetSelectedValue(borderDrop, opt.value)
        if not GetSelectedPanelName() then return end
        local p = DB().panels[GetSelectedPanelName()]
        if not p then return end
        p.border = opt.value
        RebuildAllPanels()
        RefreshPanelProperties(editor)
      end
      info.checked = (opt.value == cur)
      UIDropDownMenu_AddButton(info, level)
    end
  end)

  UIDropDownMenu_SetWidth(borderDrop, 220)

  local borderColorBtn = CreateFrame("Button", nil, props, "UIPanelButtonTemplate")
  borderColorBtn:SetSize(140, 22)
  borderColorBtn:SetPoint("TOPLEFT", 0, -722)
  borderColorBtn:SetText("Border Color")
  EnsureColorPreviewSwatch(borderColorBtn)
  borderColorBtn:SetScript("OnClick", function()
    local panelName = GetSelectedPanelName()
    if not panelName then return end
    local p = DB().panels[panelName]
    if not p or not TINTABLE_BORDER_CHOICES[p.border or "tooltip"] then return end
    local c = p.borderColor or { 0, 0, 0, 0.9 }
    OpenColorPickerRGBOnly({ c[1] or 0, c[2] or 0, c[3] or 0 }, function(r, g, b, a)
      p.borderColor = { r, g, b, a or c[4] or 0.9 }
      RebuildAllPanels()
      RefreshPanelProperties(editor)
    end, c[4] or 0.9)
  end)
  editor.borderColorBtn = borderColorBtn

  local borderAlphaSlider = MakeSlider(props, "Border Transparency (%)", 0, -722, 0, 100, 1, function(val)
    if editor and editor.__refreshing then return end
    local panelName = GetSelectedPanelName()
    if not panelName then return end
    local p = DB().panels[panelName]
    if not p or TINTABLE_BORDER_CHOICES[p.border or "tooltip"] or (p.border or "tooltip") == "none" then return end
    p.borderAlpha = math.max(0, math.min(1, (tonumber(val) or 90) / 100))
    RebuildAllPanels()
  end)
  editor.borderAlphaSlider = borderAlphaSlider

  return {
    EnsurePanelExtraData = EnsurePanelExtraData,
    panelStatChoices = PANEL_STAT_CHOICES,
    panelSpecialFontChoices = PANEL_SPECIAL_FONT_CHOICES,
  }
end

INTERNAL_API.LIDCOUNCIL_CreatePanelDesignSection_Impl = CreatePanelDesignSection
