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 BUTTON_FIELDS = {
  "panelsTab",
  "profilesTab",
  "liveBoardTab",
  "backgroundsTab",
  "lootPresetsTab",
  "lootLiveBoardLandingAction",
  "uiTab",
  "tutorialTab",
  "aboutTab",
  "tutorialNavBeginnerBtn",
  "tutorialNavPanelsBtn",
  "tutorialNavProfilesBtn",
  "tutorialNavCustomBtn",
  "tutorialNavSimulationBtn",
  "tutorialNavAddFolderBtn",
  "tutorialNavGroupsBtn",
  "tutorialNavWorkflowBtn",
  "tutorialNavAutoPassBtn",
  "tutorialNavSyncBtn",
  "tutorialNavSyncPriorityBtn",
  "tutorialNavCombatBtn",
  "tutorialNavSyncAuditBtn",
  "tutorialNavSyncProgressBtn",
  "tutorialNavSyncWorkflow4Btn",
  "tutorialNavSyncWorkflow5Btn",
  "tutorialNavSyncWorkflow6Btn",
  "tutorialNavSyncWorkflow7Btn",
  "tutorialNavSyncWorkflow8Btn",
  "tutorialNavSyncWorkflow10Btn",
  "tutorialNavSyncWorkflow11Btn",
  "tutorialNavSyncWorkflow12Btn",
  "tutorialNavSyncWorkflow13Btn",
  "tutorialNavSyncWorkflow14Btn",
  "tutorialNavSyncWorkflow15Btn",
  "tutorialNavPossibleFeaturesBtn",
  "tutorialNavPreflightBtn",
  "tutorialNavProfileRecoveryBtn",
  "tutorialNavRolesBtn",
  "tutorialNavRightsBtn",
  "color1Btn",
  "color2Btn",
  "colorSingleBtn",
  "borderColorBtn",
  "resetPanelBtn",
  "specialGoldColorBtn",
  "specialCustomTextColorBtn",
  "specialFpsLowColorBtn",
  "specialFpsMidColorBtn",
  "specialFpsHighColorBtn",
  "specialFpsResetBtn",
  "diagGraphFpsIntervalBtn",
  "diagGraphAvgIntervalBtn",
  "diagGraphLowIntervalBtn",
  "newBtn",
  "delBtn",
  "panelPrevBtn",
  "panelNextBtn",
  "renameBtn",
  "copyBtn",
  "iconPickBtn",
  "iconPrevBtn",
  "iconNextBtn",
  "texturePickBtn",
  "modelPickBtn",
  "minimapResetBtn",
  "uiButtonThemeArcanePurpleBtn",
  "uiButtonThemeArcaneBlueBtn",
  "uiButtonThemeBronzeBtn",
  "uiButtonThemeCrimsonGoldBtn",
  "uiButtonThemeEmberRedBtn",
  "uiButtonThemeRubyArcaneBtn",
  "delProfBtn",
  "exportBtn",
  "importBtn",
  "renameProfBtn",
  "activateBtn",
  "deactivateBtn",
  "copyProfBtn",
  "newProfBtn",
  "newProfGroupBtn",
  "renameProfGroupBtn",
  "delProfGroupBtn",
  "profPrevBtn",
  "profNextBtn",
  "errorLogBtn",
  "silentLogBtn",
  "collapseBtn",
  "bgAddBtn",
  "bgAddCatBtn",
  "bgAddCatGroupBtn",
  "bgDeleteCatBtn",
  "bgDeleteListBtn",
  "bgRenameBtn",
  "bgDeleteBtn",
  "bgRenameCatBtn",
  "bgDeleteCatPropsBtn",
  "bgRenameCatGroupBtn",
  "bgDeleteCatGroupPropsBtn",
  "bgCatPrevBtn",
  "bgCatNextBtn",
  "bgPrevBtn",
  "bgNextBtn",
  "lootCopyProfileBtn",
  "lootProfilesPrevBtn",
  "lootProfilesNextBtn",
  "lootAddGroupBtn",
  "lootAddProfileBtn",
  "lootDeleteGroupBtn",
  "lootDeleteProfileBtn",
  "lootActivateProfileBtn",
  "lootDeactivateProfileBtn",
  "lootClearSimulationContentBtn",
  "lootProfileOverviewToggleBtn",
  "lootProfileAccessToggleBtn",
  "lootProfileRaidToggleBtn",
  "lootProfileRollToggleBtn",
  "lootProfilePointsToggleBtn",
  "lootProfileBackupToggleBtn",
  "lootProfileTransferToggleBtn",
  "lootProfileSaveBackupBtn",
  "lootProfileLoadBackupBtn",
  "lootProfileDeleteBackupBtn",
  "lootProfileTransferExportBtn",
  "lootProfileTransferPreviousBtn",
  "lootProfileTransferCopyPartBtn",
  "lootProfileTransferNextBtn",
  "lootProfileTransferPastePartBtn",
  "lootProfileTransferClearPartsBtn",
  "lootProfileTransferRefreshReviewBtn",
  "lootProfileTransferApplyBtn",
  "lootProfileTransferRestoreBtn",
  "lootSaveRaidBtn",
  "lootAddRollOptionBtn",
  "lootRemoveRollOptionBtn",
  "lootTestRollPopupBtn",
  "lootPreviewHostBoardBtn",
  "lootRollExportBtn",
  "lootRollImportStringBtn",
  "lootAddPointRuleBtn",
  "lootAddItemPointRuleBtn",
  "lootRemovePointRuleBtn",
  "lootPointExportBtn",
  "lootPointImportStringBtn",
  "sessionNavCurrentBtn",
  "sessionNavHistoryBtn",
  "sessionNavSyncManagementBtn",
  "sessionNavRoleSimBtn",
  "sessionNavAutoPassSettingsBtn",
  "sessionStartBtn",
  "sessionActivateBtn",
  "sessionStopBtn",
  "sessionLeaveBtn",
  "sessionInviteBtn",
  "sessionRefreshReadinessBtn",
  "sessionRemoveMemberBtn",
  "sessionCheckSyncBtn",
  "sessionPushProfileBtn",
  "sessionRequestProfileBtn",
  "sessionPreviewProfileBtn",
  "sessionOpenSyncDetailBtn",
  "sessionSyncBoardBtn",
  "lootSessionSyncDetailPreviewBtn",
  "lootSessionSyncDetailPullBtn",
  "lootSessionSyncDetailPushBtn",
  "lootSessionSyncDetailApplyBtn",
  "lootSessionSyncArchivePauseBtn",
  "lootSessionSyncArchivePauseInfoBtn",
  "sessionRoleSimMasterBtn",
  "sessionRoleSimSessionHostBtn",
  "sessionRoleSimCouncilBtn",
  "sessionRoleSimRaiderBtn",
  "sessionAutoPassLocalBtn",
  "lootLiveBoardEmbedBtn",
  "lootLiveBoardHistoryBtn",
  "lootLiveBoardPopoutBtn",
  "lootLiveBoardSimulateBtn",
  "lootLiveBoardRealSimulateBtn",
  "lootLedgerSeedTestBtn",
  "lootLedgerSummaryLinkBtn",
  "lootLedgerSummaryClearBtn",
  "lootLedgerAddEntryBtn",
  "lootLedgerDeleteEntryBtn",
  "lootLedgerDeleteCharacterBtn",
  "lootLedgerAddGroupBtn",
  "lootLedgerDeleteGroupBtn",
  "aboutNavLoadedBtn",
  "aboutNavErrorsBtn",
  "aboutNavSilentBtn",
  "aboutNavUpdatesBtn",
  "aboutNavFaqBtn",
  "aboutNavCreditsBtn",
  "aboutNavStressBtn",
  "aboutNavTutorialImagesBtn",
  "aboutNavDeveloperBtn",
  "aboutUpdateNewsBtn",
  "aboutTutorialImagesToggleBtn",
  "aboutCreateSimulationBtn",
  "aboutDeleteSimulationBtn",
}

local BUTTON_COLLECTION_FIELDS = {
  "specialStatTitleBtns",
  "specialStatValueBtns",
  "listButtons",
  "bgListButtons",
  "bgCatButtons",
  "iconCategoryButtons",
  "iconSubButtons",
  "textureCategoryButtons",
  "textureSubButtons",
  "modelCategoryButtons",
  "modelListButtons",
  "profButtons",
  "lootProfileButtons",
  "lootSessionNavButtons",
  "lootLedgerCharacterButtons",
}

local FONT_FIELDS = {
  "selLabel",
  "profileLabel",
  "profilesTitle",
  "profilesCurrentLabel",
  "panelsTitle",
  "panelsCurrentLabel",
  "backgroundsTitle",
  "backgroundsCurrentLabel",
  "lootProfilesNavTitle",
  "lootLedgerNavTitle",
  "lootProfilesTitle",
  "lootProfileStatus",
  "lootProfileSummary",
  "lootProfileHeroRaidPreviewTitle",
  "lootProfileHeroRaidPreviewLabel",
  "lootProfileHeroRaidPreviewEmpty",
  "lootRaidSeasonLabel",
  "lootRaidLabel",
  "lootRaidHint",
  "lootRollOptionsText",
  "lootRollResponsiveHint",
  "lootPointRulesText",
  "lootSessionTitle",
  "lootSessionStatus",
  "lootSessionAutoPassStatus",
  "lootSessionAutoPassState",
  "lootSessionLiveSummary",
  "lootSessionBody",
  "lootListTitle",
  "lootLedgerSearchLabel",
  "lootLedgerSelectedLabel",
  "lootLedgerTotalLabel",
  "lootLedgerSummaryText",
  "lootLedgerMembersText",
  "lootLedgerDragHint",
  "lootLedgerHistoryText",
  "bgSelLabel",
  "bgSourceText",
  "bgEmptyText",
  "colorDesc",
  "bgLabel",
  "customBgLabel",
  "textureBgLabel",
  "textureName",
  "iconBgLabel",
  "iconName",
  "modelBgLabel",
  "modelName",
  "uiPageTitle",
  "uiCurrentLabel",
  "uiSkinLabel",
  "uiSkinHint",
  "uiHeaderLogoLabel",
  "uiButtonThemeValue",
  "uiButtonThemeHint",
  "tutorialPageTitle",
  "tutorialCurrentLabel",
  "aboutPageTitle",
  "aboutCurrentLabel",
  "selProfLabel",
  "selProfGroupLabel",
  "profGroupInfoLabel",
  "panelPageText",
  "bgCatPageText",
  "bgPageText",
  "profPageText",
  "profileBarText",
  "versionText",
  "editModeLabel",
  "specialStatsLabel",
  "specialStatsColorHeader",
  "specialGoldConfigLabel",
  "specialGoldFontLabel",
  "specialFpsFontLabel",
  "specialFpsColorLabel",
  "specialFpsRuleLabel",
  "specialFpsMidLabel",
  "diagGraphSettingsLabel",
  "diagGraphStyleLabel",
  "diagGraphUpdateLabel",
  "aboutMeta",
  "aboutDesc",
  "aboutDetails",
  "aboutErrors",
  "aboutSilent",
  "aboutUpdates",
  "aboutFaqTitle",
  "aboutFaqSearchLabel",
  "aboutCreditsTitle",
  "aboutStressTitle",
  "aboutStressText",
  "aboutTutorialImagesTitle",
  "aboutTutorialImagesText",
  "aboutDeveloperTitle",
  "aboutDeveloperText",
  "aboutSimulationState",
  "tutorialAddFolderIntro",
  "tutorialAddFolderStepTitle",
  "tutorialAddFolderNote",
  "tutorialAddFolderAfter",
  "tutorialAddFolderPost",
  "tutorialAddFolderPreviewNote",
  "tutorialGroupsIntro",
  "tutorialGroupsNote",
  "tutorialGroupsAfter",
  "tutorialGroupsPost",
  "tutorialWorkflowIntro",
  "tutorialWorkflowNote",
  "tutorialWorkflowAfter",
  "tutorialWorkflowLive",
  "tutorialWorkflowPost",
  "tutorialSyncIntro",
  "tutorialSyncTriggers",
  "tutorialSyncPaths",
}

local CHECKBOX_LABEL_FIELDS = {
  "specAutoCheck",
  "lockCheck",
  "editModeEditorCheck",
  "editModePreviewCheck",
  "modeSingleCheck",
  "modeDualCheck",
  "modeBgCheck",
  "modeTextureCheck",
  "modeIconCheck",
  "modeModelCheck",
  "minimapHoverCheck",
  "diagFpsGraphCheck",
  "diagGraphShowFpsCheck",
  "diagGraphShowAvgCheck",
  "diagGraphShowLowCheck",
  "specialGoldCheck",
  "specialFpsCheck",
  "specialStatsCheck",
  "aboutDeveloperModeCheck",
  "aboutChecklistDevCheck",
  "aboutChangelogDevCheck",
  "aboutShowSimulationCheck",
}

local ABOUT_TITLE_FIELDS = {
  "aboutFaqTitle",
  "aboutCreditsTitle",
  "aboutStressTitle",
  "aboutTutorialImagesTitle",
  "aboutDeveloperTitle",
}

local BUTTON_THEME_PRESETS = {
  arcane_purple = {
    key = "arcane_purple",
    label = "Dark Arcane Purple",
    normal = { 59 / 255, 35 / 255, 74 / 255, 0.95 },
    hover = { 90 / 255, 47 / 255, 115 / 255, 0.26 },
    active = { 123 / 255, 63 / 255, 166 / 255, 0.92 },
    border = { 203 / 255, 170 / 255, 98 / 255, 0.92 },
    text = { 1.00, 0.98, 1.00, 1.00 },
  },
  arcane_blue = {
    key = "arcane_blue",
    label = "Dark Blue Arcane",
    normal = { 31 / 255, 53 / 255, 82 / 255, 0.95 },
    hover = { 47 / 255, 91 / 255, 138 / 255, 0.26 },
    active = { 75 / 255, 132 / 255, 199 / 255, 0.92 },
    border = { 149 / 255, 185 / 255, 232 / 255, 0.88 },
    text = { 0.95, 0.98, 1.00, 1.00 },
  },
  bronze_gold = {
    key = "bronze_gold",
    label = "Bronze / Dark Gold",
    normal = { 90 / 255, 58 / 255, 26 / 255, 0.95 },
    hover = { 138 / 255, 90 / 255, 34 / 255, 0.28 },
    active = { 192 / 255, 138 / 255, 58 / 255, 0.92 },
    border = { 213 / 255, 176 / 255, 110 / 255, 0.90 },
    text = { 1.00, 0.97, 0.92, 1.00 },
  },
  crimson_gold = {
    key = "crimson_gold",
    label = "Dark Crimson + Gold",
    normal = { 90 / 255, 16 / 255, 34 / 255, 0.95 },
    hover = { 122 / 255, 24 / 255, 51 / 255, 0.28 },
    active = { 163 / 255, 38 / 255, 74 / 255, 0.92 },
    border = { 200 / 255, 155 / 255, 60 / 255, 0.92 },
    text = { 1.00, 0.96, 0.94, 1.00 },
  },
  ember_red = {
    key = "ember_red",
    label = "Ember Red",
    normal = { 74 / 255, 30 / 255, 18 / 255, 0.95 },
    hover = { 122 / 255, 48 / 255, 24 / 255, 0.28 },
    active = { 184 / 255, 74 / 255, 30 / 255, 0.92 },
    border = { 214 / 255, 132 / 255, 74 / 255, 0.90 },
    text = { 1.00, 0.95, 0.92, 1.00 },
  },
  ruby_arcane = {
    key = "ruby_arcane",
    label = "Ruby Arcane",
    normal = { 59 / 255, 15 / 255, 26 / 255, 0.95 },
    hover = { 94 / 255, 24 / 255, 48 / 255, 0.28 },
    active = { 142 / 255, 42 / 255, 82 / 255, 0.92 },
    border = { 190 / 255, 122 / 255, 164 / 255, 0.90 },
    text = { 1.00, 0.95, 0.98, 1.00 },
  },
  lootpilot = {
    key = "lootpilot",
    label = "LootPilot",
    normal = { 7 / 255, 14 / 255, 25 / 255, 0.98 },
    hover = { 24 / 255, 38 / 255, 62 / 255, 0.28 },
    active = { 12 / 255, 24 / 255, 42 / 255, 0.94 },
    border = { 1.00, 0.88, 0.56, 0.95 },
    text = { 1.00, 1.00, 1.00, 1.00 },
    dropdownButtonBg = { 7 / 255, 14 / 255, 25 / 255, 0.98 },
    dropdownPopupBg = { 4 / 255, 8 / 255, 14 / 255, 0.98 },
    dropdownRowText = { 1.00, 1.00, 1.00, 1.00 },
  },
}

local DEFAULT_BUTTON_THEME_KEY = "arcane_blue"
BUTTON_THEME_PRESETS.white_orange = BUTTON_THEME_PRESETS.lootpilot
local LOOTPILOT_BUTTON_THEME_KEY = "lootpilot"

local function NormalizeEditorSkinKey(key)
  local resolvedKey = type(key) == "string" and string.lower(key) or "lidcouncil"
  if resolvedKey == "lootpilot" or resolvedKey == "white_orange" then
    return "lootpilot"
  end
  return "lidcouncil"
end

local function ResolveSkinButtonThemeKey(ui)
  if NormalizeEditorSkinKey(ui and ui.editorSkin) == "lootpilot" then
    return LOOTPILOT_BUTTON_THEME_KEY
  end
  return DEFAULT_BUTTON_THEME_KEY
end

local function ResolveButtonThemePreset(key)
  local resolvedKey = type(key) == "string" and string.lower(key) or DEFAULT_BUTTON_THEME_KEY
  local preset = BUTTON_THEME_PRESETS[resolvedKey]
  if not preset then
    resolvedKey = DEFAULT_BUTTON_THEME_KEY
    preset = BUTTON_THEME_PRESETS[resolvedKey]
  end
  return preset, resolvedKey
end

local function MixColor(colorA, colorB, weightA)
  weightA = tonumber(weightA)
  if weightA == nil then
    weightA = 0.5
  end
  local weightB = 1 - weightA
  local a = type(colorA) == "table" and colorA or { 1, 1, 1, 1 }
  local b = type(colorB) == "table" and colorB or { 0, 0, 0, 1 }
  return {
    ((a[1] or 1) * weightA) + ((b[1] or 0) * weightB),
    ((a[2] or 1) * weightA) + ((b[2] or 0) * weightB),
    ((a[3] or 1) * weightA) + ((b[3] or 0) * weightB),
    ((a[4] or 1) * weightA) + ((b[4] or 1) * weightB),
  }
end

local function CopyColor(color)
  local source = type(color) == "table" and color or { 1, 1, 1, 1 }
  return {
    source[1] or 1,
    source[2] or 1,
    source[3] or 1,
    source[4] or 1,
  }
end

local function GetCurrentEditorThemePalette()
  local rootDb = rawget(_G, "LIDCOUNCIL_RootDB")
  local root = type(rootDb) == "function" and rootDb() or {}
  local ui = type(root) == "table" and type(root.ui) == "table" and root.ui or {}
  local preset, resolvedKey = ResolveButtonThemePreset(ResolveSkinButtonThemeKey(ui))
  local normal = preset.normal or { 0.20, 0.12, 0.25, 0.95 }
  local hover = preset.hover or { 0.35, 0.20, 0.45, 0.26 }
  local active = preset.active or { 0.48, 0.25, 0.65, 0.92 }
  local border = preset.border or { 0.80, 0.66, 0.38, 0.92 }
  local text = preset.text or { 1.00, 1.00, 1.00, 1.00 }
  local black = { 0, 0, 0, 1 }
  local dropdownButtonBg = type(preset.dropdownButtonBg) == "table" and CopyColor(preset.dropdownButtonBg) or MixColor(normal, black, 0.88)
  dropdownButtonBg[4] = 0.96
  local dropdownPopupBg = type(preset.dropdownPopupBg) == "table" and CopyColor(preset.dropdownPopupBg) or MixColor(normal, black, 0.82)
  dropdownPopupBg[4] = 0.98
  local aboutTitle = MixColor(border, text, 0.62)
  aboutTitle[4] = 1.0
  return {
    key = resolvedKey,
    preset = preset,
    normal = normal,
    hover = hover,
    active = active,
    border = border,
    text = text,
    selectionBg = { active[1] or 1, active[2] or 1, active[3] or 1, 0.24 },
    selectionAccent = { border[1] or 1, border[2] or 1, border[3] or 1, 0.96 },
    dropdownButtonBg = dropdownButtonBg,
    dropdownPopupBg = dropdownPopupBg,
    dropdownCheckedText = aboutTitle,
    dropdownTitleText = aboutTitle,
    dropdownRowText = preset.dropdownRowText or text,
    aboutTitle = aboutTitle,
  }
end

INTERNAL_API.LIDCOUNCIL_ResolveButtonThemePreset_Impl = ResolveButtonThemePreset
INTERNAL_API.LIDCOUNCIL_GetEditorThemePalette_Impl = GetCurrentEditorThemePalette

local function BindEditorTheme(editor, deps)
  if not editor or type(deps) ~= "table" then return end

  local RootDB = deps.RootDB
  local ApplySkinPreset = deps.ApplySkinPreset
  local ApplyEditorLogo = deps.ApplyEditorLogo
  local ApplyHeaderBackground = deps.ApplyHeaderBackground
  local SafeHookScript = deps.SafeHookScript or function(frame, scriptName, handler)
    if frame and type(frame.HookScript) == "function" and type(handler) == "function" then
      pcall(frame.HookScript, frame, scriptName, handler)
    end
  end

  local function RequestThemeRefresh()
    if editor.__applyingTheme then
      return
    end
    if editor.__lidThemeRefreshScheduled == true then
      return
    end
    if editor.IsShown and not editor:IsShown() then
      return
    end
    if type(C_Timer) ~= "table" or type(C_Timer.After) ~= "function" then
      if not editor.__applyingTheme and editor.ApplyTheme then
        editor:ApplyTheme()
      end
      return
    end
    editor.__lidThemeRefreshScheduled = true
    C_Timer.After(0, function()
      if editor.__lidThemeRefreshScheduled ~= true then
        return
      end
      editor.__lidThemeRefreshScheduled = nil
      if editor.IsShown and editor:IsShown() and editor.ApplyTheme then
        editor:ApplyTheme()
      end
    end)
  end

  function editor:ApplyTheme()
    if self.__applyingTheme then return end
    local performanceStartedAt = INTERNAL_API.LIDCOUNCIL_BeginSyncPerformanceSample_Impl("editor_theme", 1)
    -- An explicit theme pass supersedes a deferred button-state request.
    self.__lidThemeRefreshScheduled = nil
    self.__applyingTheme = true

    local ok, err = xpcall(function()
      local ui = RootDB().ui
      if ui.skin ~= "LP" then ui.skin = "LP" end
      ApplySkinPreset()

      ui.editorSkin = NormalizeEditorSkinKey(ui.editorSkin)
      ui.buttonTheme = ResolveSkinButtonThemeKey(ui)
      local buttonThemePreset, resolvedButtonThemeKey = ResolveButtonThemePreset(ui.buttonTheme)
      ui.buttonTheme = resolvedButtonThemeKey

      local buttonColor = buttonThemePreset.normal
      local hoverColor = buttonThemePreset.hover
      local activeColor = buttonThemePreset.active
      local borderColor = buttonThemePreset.border
      local textColor = buttonThemePreset.text or { 1.00, 1.00, 1.00, 1.00 }
      local themePalette = GetCurrentEditorThemePalette()
      self.__lid_themePalette = themePalette
      local fontKey = "GameFontHighlight"
      local fontColor = { 0.92, 0.96, 1.00, 1.00 }

      local function ApplyFont(fontString, color)
        if not fontString then return end
        if _G[fontKey] and fontString.SetFontObject then
          fontString:SetFontObject(_G[fontKey])
        end
        local resolved = color or fontColor
        if fontString.SetTextColor then
          fontString:SetTextColor(resolved[1], resolved[2], resolved[3], resolved[4] or 1)
        end
      end

      local function ApplyFontObjectOnly(fontString)
        if not fontString then return end
        if _G[fontKey] and fontString.SetFontObject then
          fontString:SetFontObject(_G[fontKey])
        end
      end

      local function KillTexture(texture)
        if not texture then return end
        if texture.SetTexture then texture:SetTexture(nil) end
        if texture.SetAtlas then texture:SetAtlas(nil) end
        if texture.Hide then texture:Hide() end
      end

      local function SkinButton(button)
        if not button then return end
        if not button.__lid_bg then
          button.__lid_bg = button:CreateTexture(nil, "BACKGROUND")
          button.__lid_bg:SetAllPoints(true)
          button.__lid_bg:SetTexture("Interface/Buttons/WHITE8x8")

          button.__lid_hover = button:CreateTexture(nil, "HIGHLIGHT")
          button.__lid_hover:SetAllPoints(true)
          button.__lid_hover:SetTexture("Interface/Buttons/WHITE8x8")
        end
        if not button.__lid_borderTop then
          button.__lid_borderTop = button:CreateTexture(nil, "BORDER")
          button.__lid_borderTop:SetTexture("Interface/Buttons/WHITE8x8")
          button.__lid_borderTop:SetPoint("TOPLEFT", button, "TOPLEFT", 0, 0)
          button.__lid_borderTop:SetPoint("TOPRIGHT", button, "TOPRIGHT", 0, 0)
          button.__lid_borderTop:SetHeight(1)

          button.__lid_borderBottom = button:CreateTexture(nil, "BORDER")
          button.__lid_borderBottom:SetTexture("Interface/Buttons/WHITE8x8")
          button.__lid_borderBottom:SetPoint("BOTTOMLEFT", button, "BOTTOMLEFT", 0, 0)
          button.__lid_borderBottom:SetPoint("BOTTOMRIGHT", button, "BOTTOMRIGHT", 0, 0)
          button.__lid_borderBottom:SetHeight(1)

          button.__lid_borderLeft = button:CreateTexture(nil, "BORDER")
          button.__lid_borderLeft:SetTexture("Interface/Buttons/WHITE8x8")
          button.__lid_borderLeft:SetPoint("TOPLEFT", button, "TOPLEFT", 0, 0)
          button.__lid_borderLeft:SetPoint("BOTTOMLEFT", button, "BOTTOMLEFT", 0, 0)
          button.__lid_borderLeft:SetWidth(1)

          button.__lid_borderRight = button:CreateTexture(nil, "BORDER")
          button.__lid_borderRight:SetTexture("Interface/Buttons/WHITE8x8")
          button.__lid_borderRight:SetPoint("TOPRIGHT", button, "TOPRIGHT", 0, 0)
          button.__lid_borderRight:SetPoint("BOTTOMRIGHT", button, "BOTTOMRIGHT", 0, 0)
          button.__lid_borderRight:SetWidth(1)
        end

        local name = button.GetName and button:GetName()
        if name then
          local parts = { "Left", "Middle", "Right", "LeftDisabled", "MiddleDisabled", "RightDisabled" }
          for _, suffix in ipairs(parts) do
            KillTexture(_G[name .. suffix])
          end
        end
        KillTexture(button.Left)
        KillTexture(button.Middle)
        KillTexture(button.Right)
        KillTexture(button.LeftDisabled)
        KillTexture(button.MiddleDisabled)
        KillTexture(button.RightDisabled)

        local regionCount = button.GetRegions and select("#", button:GetRegions()) or 0
        for index = 1, regionCount do
          local region = select(index, button:GetRegions())
          if region and region.GetTexture and region.SetTexture and region ~= button.__lid_bg and region ~= button.__lid_hover then
            local texture = region:GetTexture()
            if type(texture) == "string" and (texture:find("UI%-Panel%-Button") or texture:find("UIPanelButton")) then
              KillTexture(region)
            end
          end
        end

        if button.SetNormalTexture then button:SetNormalTexture("Interface/Buttons/WHITE8x8") end
        if button.SetHighlightTexture then button:SetHighlightTexture("Interface/Buttons/WHITE8x8") end
        if button.SetDisabledTexture then button:SetDisabledTexture("Interface/Buttons/WHITE8x8") end

        local resolvedButtonColor = button.__lid_customBg or buttonColor
        local resolvedHoverColor = button.__lid_customHover or hoverColor
        local resolvedActiveColor = button.__lid_customPushed or activeColor
        local resolvedBorderColor = button.__lid_customBorder or borderColor
        local resolvedTextColor = button.__lid_customText or textColor

        if not button.__lid_pushed then
          button.__lid_pushed = button:CreateTexture(nil, "ARTWORK")
          button.__lid_pushed:SetAllPoints(true)
          button.__lid_pushed:SetTexture("Interface/Buttons/WHITE8x8")
        end
        button.__lid_pushed:SetVertexColor(
          resolvedActiveColor[1] or 1,
          resolvedActiveColor[2] or 1,
          resolvedActiveColor[3] or 1,
          resolvedActiveColor[4] or 0.92
        )
        if button.SetPushedTexture then button:SetPushedTexture(button.__lid_pushed) end

        local highlightTexture = button:GetHighlightTexture()
        if highlightTexture then
          highlightTexture:SetTexture("Interface/Buttons/WHITE8x8")
          highlightTexture:SetVertexColor(1, 1, 1, 0.12)
          highlightTexture:SetBlendMode("ADD")
        end

        local normalTexture = button:GetNormalTexture()
        if normalTexture then
          normalTexture:SetTexture("Interface/Buttons/WHITE8x8")
          normalTexture:SetVertexColor(0, 0, 0, 0)
        end

        local pushedTexture = button:GetPushedTexture()
        if pushedTexture then
          pushedTexture:SetTexture("Interface/Buttons/WHITE8x8")
          pushedTexture:SetVertexColor(1, 1, 1, 0.16)
          pushedTexture:SetBlendMode("ADD")
        end

        local disabledTexture = button.GetDisabledTexture and button:GetDisabledTexture()
        if disabledTexture then
          disabledTexture:SetTexture("Interface/Buttons/WHITE8x8")
          disabledTexture:SetVertexColor(0.18, 0.18, 0.18, 0.95)
          disabledTexture:SetBlendMode("BLEND")
        end

        local enabled = (button.IsEnabled == nil) or button:IsEnabled()
        if enabled then
          button.__lid_bg:SetVertexColor(resolvedButtonColor[1], resolvedButtonColor[2], resolvedButtonColor[3], resolvedButtonColor[4] or 1)
          local hoverAlpha = resolvedHoverColor[4]
          if hoverAlpha == nil then hoverAlpha = 0.25 end
          hoverAlpha = math.min(hoverAlpha, 0.35)
          button.__lid_hover:SetVertexColor(resolvedHoverColor[1], resolvedHoverColor[2], resolvedHoverColor[3], hoverAlpha)
          button.__lid_hover:SetBlendMode("ADD")
        else
          button.__lid_bg:SetVertexColor(0.18, 0.18, 0.18, 0.95)
          button.__lid_hover:SetVertexColor(0, 0, 0, 0)
        end

        if button.__lid_borderTop then
          local borderAlpha = enabled and (resolvedBorderColor[4] or 0.9) or 0.35
          local borderR = enabled and resolvedBorderColor[1] or 0.28
          local borderG = enabled and resolvedBorderColor[2] or 0.28
          local borderB = enabled and resolvedBorderColor[3] or 0.30
          button.__lid_borderTop:SetVertexColor(borderR, borderG, borderB, borderAlpha)
          button.__lid_borderBottom:SetVertexColor(borderR, borderG, borderB, borderAlpha)
          button.__lid_borderLeft:SetVertexColor(borderR, borderG, borderB, borderAlpha)
          button.__lid_borderRight:SetVertexColor(borderR, borderG, borderB, borderAlpha)
        end

        local buttonFont = button:GetFontString()
        if buttonFont then
          if enabled then
            ApplyFont(buttonFont, resolvedTextColor)
          else
            ApplyFont(buttonFont, { 0.62, 0.62, 0.62, 1.0 })
          end
        end
        if button.__groupArrow then ApplyFontObjectOnly(button.__groupArrow) end
        if button.__bgCategoryGroupArrow then ApplyFontObjectOnly(button.__bgCategoryGroupArrow) end
      end

      local function HookButton(button)
        if not button or button.__lid_hooked then return end
        button.__lid_hooked = true
        SafeHookScript(button, "OnShow", RequestThemeRefresh)
        SafeHookScript(button, "OnEnable", RequestThemeRefresh)
        SafeHookScript(button, "OnDisable", RequestThemeRefresh)
      end

      local function SkinFieldButton(name)
        local button = self[name]
        SkinButton(button)
        HookButton(button)
      end

      local function SkinButtonCollection(name)
        local collection = self[name]
        if not collection then return end
        for _, button in pairs(collection) do
          SkinButton(button)
          HookButton(button)
        end
      end

      local function ApplyNamedFont(name)
        local fontString = self[name]
        ApplyFont(fontString, fontString and fontString.__lid_customTextColor)
      end

      local function ApplyCheckboxLabel(name)
        local check = self[name]
        if not check or not check.GetName then return end
        local text = _G[check:GetName() .. "Text"]
        ApplyFont(text)
      end

      if self.diagInfoIntervalPopup then
        if self.diagInfoIntervalPopup.okBtn then
          SkinButton(self.diagInfoIntervalPopup.okBtn)
          HookButton(self.diagInfoIntervalPopup.okBtn)
        end
        if self.diagInfoIntervalPopup.cancelBtn then
          SkinButton(self.diagInfoIntervalPopup.cancelBtn)
          HookButton(self.diagInfoIntervalPopup.cancelBtn)
        end
      end

      for _, name in ipairs(BUTTON_FIELDS) do
        SkinFieldButton(name)
      end
      for _, name in ipairs(BUTTON_COLLECTION_FIELDS) do
        SkinButtonCollection(name)
      end
      if type(self.__lidcouncilCustomDropdowns) == "table" then
        for _, dropdown in ipairs(self.__lidcouncilCustomDropdowns) do
          if dropdown and type(dropdown.ApplyTheme) == "function" then
            dropdown:ApplyTheme()
          end
        end
      end

      if self.specialStatChecks then
        for _, check in pairs(self.specialStatChecks) do
          if check and check.GetName then
            local text = _G[check:GetName() .. "Text"]
            ApplyFont(text)
          end
        end
      end

      if self.profileBar and self.profileBar.SetBackdropColor then
        self.profileBar:SetBackdropColor(0.06, 0.06, 0.08, 0.80)
        self.profileBar:SetBackdropBorderColor(0, 0, 0, 0.7)
      end

      for _, name in ipairs(FONT_FIELDS) do
        ApplyNamedFont(name)
      end
      ApplyFontObjectOnly(self.aboutStatusText)
      for _, name in ipairs(CHECKBOX_LABEL_FIELDS) do
        ApplyCheckboxLabel(name)
      end

      local aboutTitleColor = themePalette.aboutTitle or { 0.6588, 0.4784, 0.9098, 1.0 }
      local aboutTitleR, aboutTitleG, aboutTitleB = aboutTitleColor[1], aboutTitleColor[2], aboutTitleColor[3]
      local function StyleAboutTitle(fontString)
        if not fontString then return end
        local fontPath, fontSize, fontFlags = fontString:GetFont()
        if fontPath then
          local targetSize = math.max(16, math.floor(fontSize or 12))
          fontString:SetFont(fontPath, targetSize, fontFlags)
        end
        fontString:SetTextColor(aboutTitleR, aboutTitleG, aboutTitleB, 1)
      end
      for _, name in ipairs(ABOUT_TITLE_FIELDS) do
        StyleAboutTitle(self[name])
      end
      if self.aboutSection == "Updates" and self.UpdateAboutUpdatesLayout then
        self:UpdateAboutUpdatesLayout()
      end
      if self.aboutSection == "FAQ" then
        if self.UpdateFAQText then self:UpdateFAQText() end
        if self.UpdateAboutFAQLayout then self:UpdateAboutFAQLayout() end
      end
      if self.aboutSection == "Credits" and self.UpdateAboutCreditsLayout then
        self:UpdateAboutCreditsLayout()
      end
      if self.aboutSection == "Stresstest" and self.UpdateAboutStressLayout then
        self:UpdateAboutStressLayout()
      end

      ApplyEditorLogo()
      ApplyHeaderBackground()
      if self.UpdateMainTabHighlight then self:UpdateMainTabHighlight() end
    end, function(message)
      local stack = debugstack and debugstack(2, 8, 8) or ""
      if stack ~= "" then
        return tostring(message) .. "\n" .. tostring(stack)
      end
      return tostring(message)
    end)

    self.__applyingTheme = false
    INTERNAL_API.LIDCOUNCIL_RecordSyncPerformance_Impl("editor_theme", performanceStartedAt, {
      context = tostring(self.currentPage or ""),
    })
    if not ok then
      error(err)
    end
  end
end

INTERNAL_API.LIDCOUNCIL_BindEditorTheme = BindEditorTheme
