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

local BUTTON_FIELDS = {
  "panelsTab",
  "profilesTab",
  "backgroundsTab",
  "uiTab",
  "tutorialTab",
  "aboutTab",
  "tutorialNavPanelsBtn",
  "tutorialNavProfilesBtn",
  "tutorialNavCustomBtn",
  "tutorialNavAddFolderBtn",
  "tutorialNavGroupsBtn",
  "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",
  "delProfBtn",
  "exportBtn",
  "importBtn",
  "renameProfBtn",
  "activateBtn",
  "deactivateBtn",
  "copyProfBtn",
  "newProfBtn",
  "newProfGroupBtn",
  "renameProfGroupBtn",
  "delProfGroupBtn",
  "profPrevBtn",
  "profNextBtn",
  "errorLogBtn",
  "silentLogBtn",
  "bgAddBtn",
  "bgAddCatBtn",
  "bgAddCatGroupBtn",
  "bgDeleteCatBtn",
  "bgDeleteListBtn",
  "bgRenameBtn",
  "bgDeleteBtn",
  "bgRenameCatBtn",
  "bgDeleteCatPropsBtn",
  "bgRenameCatGroupBtn",
  "bgDeleteCatGroupPropsBtn",
  "bgCatPrevBtn",
  "bgCatNextBtn",
  "bgPrevBtn",
  "bgNextBtn",
  "aboutNavLoadedBtn",
  "aboutNavErrorsBtn",
  "aboutNavSilentBtn",
  "aboutNavUpdatesBtn",
  "aboutNavFaqBtn",
  "aboutNavCreditsBtn",
  "aboutNavStressBtn",
  "aboutNavTutorialImagesBtn",
  "aboutNavDeveloperBtn",
  "aboutUpdateNewsBtn",
  "aboutTutorialImagesToggleBtn",
}

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

local FONT_FIELDS = {
  "selLabel",
  "profileLabel",
  "panelsTitle",
  "panelsCurrentLabel",
  "backgroundsTitle",
  "backgroundsCurrentLabel",
  "bgSelLabel",
  "bgSourceText",
  "bgEmptyText",
  "colorDesc",
  "bgLabel",
  "customBgLabel",
  "textureBgLabel",
  "textureName",
  "iconBgLabel",
  "iconName",
  "modelBgLabel",
  "modelName",
  "uiPageTitle",
  "uiCurrentLabel",
  "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",
  "tutorialAddFolderIntro",
  "tutorialAddFolderStepTitle",
  "tutorialAddFolderNote",
  "tutorialAddFolderAfter",
  "tutorialAddFolderPost",
  "tutorialAddFolderPreviewNote",
  "tutorialGroupsIntro",
  "tutorialGroupsNote",
  "tutorialGroupsAfter",
  "tutorialGroupsPost",
}

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

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

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

  function editor:ApplyTheme()
    if self.__applyingTheme then return end
    self.__applyingTheme = true

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

      local buttonColor = { 0.2235, 0.1647, 0.3490, 0.95 }
      local hoverColor = { 0.65, 0.85, 1.00, 0.20 }
      local textColor = { 1.00, 1.00, 1.00, 1.00 }
      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] then
          fontString:SetFontObject(_G[fontKey])
        end
        local resolved = color or fontColor
        fontString:SetTextColor(resolved[1], resolved[2], resolved[3], resolved[4] or 1)
      end

      local function ApplyFontObjectOnly(fontString)
        if not fontString then return end
        if _G[fontKey] 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

        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 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(1, 1, 1, 0.16)
        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

        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", function()
          if editor and editor.ApplyTheme then editor:ApplyTheme() end
        end)
        SafeHookScript(button, "OnEnable", function()
          if editor and editor.ApplyTheme then editor:ApplyTheme() end
        end)
        SafeHookScript(button, "OnDisable", function()
          if editor and editor.ApplyTheme then editor:ApplyTheme() end
        end)
      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)
        ApplyFont(self[name])
      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 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 aboutTitleR, aboutTitleG, aboutTitleB = 0.6588, 0.4784, 0.9098
      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

      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
    if not ok then
      error(err)
    end
  end
end

INTERNAL_API.LIDPANELS_BindEditorTheme = BindEditorTheme
