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
if type(RequireApi) ~= "function" then
  error("LidCouncil missing shared editor page helpers.")
end

local RootDB = RequireApi("LIDCOUNCIL_RootDB", _G.LIDCOUNCIL_RootDB)
local ApplyFrameSkin = RequireApi("LIDCOUNCIL_ApplyFrameSkin", _G.LIDCOUNCIL_ApplyFrameSkin)
local MakeYellowSubHeader = RequireApi("LIDCOUNCIL_MakeYellowSubHeader", _G.LIDCOUNCIL_MakeYellowSubHeader)
local MakeSlider = RequireApi("LIDCOUNCIL_MakeSlider", _G.LIDCOUNCIL_MakeSlider)
local CreateCustomDropdownControl = RequireApi("LIDCOUNCIL_CreateCustomDropdownControl", _G.LIDCOUNCIL_CreateCustomDropdownControl)

local UI_BUTTON_THEME_OPTIONS = {
  {
    key = "arcane_purple",
    field = "uiButtonThemeArcanePurpleBtn",
    label = "Arcane Purple",
    normal = { 59 / 255, 35 / 255, 74 / 255, 0.95 },
    hover = { 90 / 255, 47 / 255, 115 / 255, 0.30 },
    active = { 123 / 255, 63 / 255, 166 / 255, 0.92 },
    border = { 203 / 255, 170 / 255, 98 / 255, 0.92 },
    summary = "Recommended: gem-like and magical.",
  },
  {
    key = "arcane_blue",
    field = "uiButtonThemeArcaneBlueBtn",
    label = "Arcane Blue",
    normal = { 31 / 255, 53 / 255, 82 / 255, 0.95 },
    hover = { 47 / 255, 91 / 255, 138 / 255, 0.30 },
    active = { 75 / 255, 132 / 255, 199 / 255, 0.92 },
    border = { 149 / 255, 185 / 255, 232 / 255, 0.88 },
    summary = "Cooler and more technical.",
  },
  {
    key = "bronze_gold",
    field = "uiButtonThemeBronzeBtn",
    label = "Bronze Gold",
    normal = { 90 / 255, 58 / 255, 26 / 255, 0.95 },
    hover = { 138 / 255, 90 / 255, 34 / 255, 0.30 },
    active = { 192 / 255, 138 / 255, 58 / 255, 0.92 },
    border = { 213 / 255, 176 / 255, 110 / 255, 0.90 },
    summary = "Warmer, more treasure-focused.",
  },
  {
    key = "crimson_gold",
    field = "uiButtonThemeCrimsonGoldBtn",
    label = "Crimson Gold",
    normal = { 90 / 255, 16 / 255, 34 / 255, 0.95 },
    hover = { 122 / 255, 24 / 255, 51 / 255, 0.30 },
    active = { 163 / 255, 38 / 255, 74 / 255, 0.92 },
    border = { 200 / 255, 155 / 255, 60 / 255, 0.92 },
    summary = "Royal raid-UI feel with gold trim.",
  },
  {
    key = "ember_red",
    field = "uiButtonThemeEmberRedBtn",
    label = "Ember Red",
    normal = { 74 / 255, 30 / 255, 18 / 255, 0.95 },
    hover = { 122 / 255, 48 / 255, 24 / 255, 0.30 },
    active = { 184 / 255, 74 / 255, 30 / 255, 0.92 },
    border = { 214 / 255, 132 / 255, 74 / 255, 0.90 },
    summary = "Fiery and forge-like.",
  },
  {
    key = "ruby_arcane",
    field = "uiButtonThemeRubyArcaneBtn",
    label = "Ruby Arcane",
    normal = { 59 / 255, 15 / 255, 26 / 255, 0.95 },
    hover = { 94 / 255, 24 / 255, 48 / 255, 0.30 },
    active = { 142 / 255, 42 / 255, 82 / 255, 0.92 },
    border = { 190 / 255, 122 / 255, 164 / 255, 0.90 },
    summary = "Gem-like and premium with arcane undertones.",
  },
}

local DEFAULT_UI_BUTTON_THEME_KEY = "arcane_blue"
local UI_HEADER_LOGO_OPTIONS = {
  { key = "HeaderLogo", text = "LidCouncil_HeaderLogo" },
  { key = "HeaderLogo2", text = "LidCouncil_HeaderLogo2" },
  { key = "HeaderLogo3", text = "LidCouncil_HeaderLogo3" },
  { key = "HeaderLogo4", text = "LidCouncil_HeaderLogo4" },
  { key = "HeaderLogo5", text = "LidCouncil_HeaderLogo5" },
  { key = "HeaderLogo6", text = "LidCouncil_HeaderLogo6" },
  { key = "HeaderLogo7", text = "LidCouncil_HeaderLogo7" },
  { key = "HeaderLogo8", text = "LidCouncil_HeaderLogo8" },
  { key = "HeaderLogo9", text = "LidCouncil_HeaderLogo9" },
}

local DEFAULT_UI_HEADER_LOGO_KEY = "HeaderLogo"
local UI_SKIN_OPTIONS = {
  {
    key = "lidcouncil",
    text = "LidCouncil",
    buttonTheme = DEFAULT_UI_BUTTON_THEME_KEY,
    headerLogo = "HeaderLogo",
  },
  {
    key = "lootpilot",
    text = "LootPilot",
    buttonTheme = "lootpilot",
    headerLogo = "NONE",
  },
}

local function NormalizeUISkinKey(key)
  local resolvedKey = type(key) == "string" and string.lower(key) or "lidcouncil"
  if resolvedKey == "white_orange" then
    return "lootpilot"
  end
  for _, option in ipairs(UI_SKIN_OPTIONS) do
    if option.key == resolvedKey then
      return resolvedKey
    end
  end
  return "lidcouncil"
end

local function GetUISkinOption(key)
  local resolvedKey = NormalizeUISkinKey(key)
  for _, option in ipairs(UI_SKIN_OPTIONS) do
    if option.key == resolvedKey then
      return option
    end
  end
  return UI_SKIN_OPTIONS[1]
end

local function NormalizeUIButtonThemeKey(key)
  local resolvedKey = type(key) == "string" and string.lower(key) or DEFAULT_UI_BUTTON_THEME_KEY
  for _, option in ipairs(UI_BUTTON_THEME_OPTIONS) do
    if option.key == resolvedKey then
      return resolvedKey
    end
  end
  return DEFAULT_UI_BUTTON_THEME_KEY
end

local function GetUIButtonThemeOption(key)
  local resolvedKey = NormalizeUIButtonThemeKey(key)
  for _, option in ipairs(UI_BUTTON_THEME_OPTIONS) do
    if option.key == resolvedKey then
      return option
    end
  end
  return UI_BUTTON_THEME_OPTIONS[1]
end

local function NormalizeUIHeaderLogoKey(key)
  local resolvedKey = type(key) == "string" and key or DEFAULT_UI_HEADER_LOGO_KEY
  for _, option in ipairs(UI_HEADER_LOGO_OPTIONS) do
    if option.key == resolvedKey then
      return resolvedKey
    end
  end
  return DEFAULT_UI_HEADER_LOGO_KEY
end

local function GetUIHeaderLogoOption(key)
  local resolvedKey = NormalizeUIHeaderLogoKey(key)
  for _, option in ipairs(UI_HEADER_LOGO_OPTIONS) do
    if option.key == resolvedKey then
      return option
    end
  end
  return UI_HEADER_LOGO_OPTIONS[1]
end

local function TryUpdateMinimapButton()
  local updateFn = _G.LIDCOUNCIL_UpdateMinimapButton
  if type(updateFn) == "function" then
    updateFn()
  end
end

local function BuildUIPage(editor, uiPage)
  if not editor or not uiPage then return end

  local uiNavBg = CreateFrame("Frame", nil, uiPage, "BackdropTemplate")
  uiNavBg:SetPoint("TOPLEFT", 0, -44)
  uiNavBg:SetPoint("BOTTOMLEFT", 0, 0)
  uiNavBg:SetWidth(240)
  ApplyFrameSkin(uiNavBg)
  editor.uiNavBg = uiNavBg

  local uiRightBg = CreateFrame("Frame", nil, uiPage, "BackdropTemplate")
  uiRightBg:SetPoint("TOPLEFT", uiNavBg, "TOPRIGHT", 12, 0)
  uiRightBg:SetPoint("BOTTOMRIGHT", 0, 0)
  ApplyFrameSkin(uiRightBg)
  uiRightBg:SetClipsChildren(true)
  editor.uiRightBg = uiRightBg

  local uiScroll = CreateFrame("ScrollFrame", nil, uiRightBg, "UIPanelScrollFrameTemplate")
  uiScroll:SetPoint("TOPLEFT", 18, -12)
  uiScroll:SetPoint("BOTTOMRIGHT", -28, 12)
  uiScroll:EnableMouseWheel(true)
  uiScroll:SetScript("OnMouseWheel", function(self, delta)
    local current = self:GetVerticalScroll() or 0
    local nextValue = current - ((tonumber(delta) or 0) * 18)
    if nextValue < 0 then
      nextValue = 0
    end
    local scrollRange = self:GetVerticalScrollRange() or 0
    if nextValue > scrollRange then
      nextValue = scrollRange
    end
    self:SetVerticalScroll(nextValue)
  end)
  editor.uiScroll = uiScroll

  local uiContent = CreateFrame("Frame", nil, uiScroll)
  uiContent:SetSize(1, 1)
  uiScroll:SetScrollChild(uiContent)
  editor.uiContent = uiContent

  uiScroll:SetScript("OnSizeChanged", function(self)
    local width = (self.GetWidth and self:GetWidth()) or 1
    width = math.max(1, math.floor(width - 28))
    uiContent:SetWidth(width)
    if editor and editor.UpdateUILayout then
      editor:UpdateUILayout()
    end
    if self.UpdateScrollChildRect then
      self:UpdateScrollChildRect()
    end
  end)

  local uiTitle = uiContent:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
  uiTitle:SetPoint("TOPLEFT", 0, 0)
  uiTitle:SetText("|cffffd100UI Settings|r")

  local uiHeaderGeneral = MakeYellowSubHeader(uiContent, "General", 0, -32)
  local uiHeaderMinimap = MakeYellowSubHeader(uiContent, "Minimap", 0, -142)
  editor.uiHeaderGeneral = uiHeaderGeneral
  editor.uiHeaderButtons = nil
  editor.uiHeaderMinimap = uiHeaderMinimap

  local uiSkinLabel = uiContent:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
  uiSkinLabel:SetPoint("TOPLEFT", 0, -58)
  uiSkinLabel:SetText("UI Skin:")
  editor.uiSkinLabel = uiSkinLabel

  local uiSkinDropdown = CreateCustomDropdownControl(editor, uiContent, {
    width = 240,
    text = "LidCouncil",
  })
  uiSkinDropdown:SetPoint("TOPLEFT", 0, -74)
  editor.uiSkinDropdown = uiSkinDropdown

  local uiSkinHint = uiContent:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
  uiSkinHint:SetPoint("TOPLEFT", 0, -106)
  uiSkinHint:SetWidth(520)
  uiSkinHint:SetJustifyH("LEFT")
  uiSkinHint:SetText("Selects the editor header artwork and global button palette.")
  editor.uiSkinHint = uiSkinHint

  uiSkinDropdown:SetMenuBuilder(function()
    local ui = RootDB().ui
    local currentSkin = NormalizeUISkinKey(ui.editorSkin)
    local entries = {}
    for _, option in ipairs(UI_SKIN_OPTIONS) do
      entries[#entries + 1] = {
        text = option.text,
        value = option.key,
        checked = (currentSkin == option.key),
        func = function()
          local selectedOption = GetUISkinOption(option.key)
          ui.editorSkin = selectedOption.key
          ui.buttonTheme = selectedOption.buttonTheme
          ui.headerLogo = selectedOption.headerLogo
          uiSkinDropdown:SetSelectedValue(selectedOption.key)
          uiSkinDropdown:SetText(selectedOption.text)
          if editor.ApplyTheme then
            editor:ApplyTheme()
          end
          if editor.UpdateUILayout then
            editor:UpdateUILayout()
          end
        end,
      }
    end
    return {
      entries = entries,
      width = 240,
    }
  end)

  editor.uiHeaderLogoLabel = nil
  editor.uiHeaderLogoValue = nil
  editor.uiButtonThemeValue = nil
  editor.uiButtonThemeHint = nil

  local minimapSizeSlider = MakeSlider(uiContent, "Minimap Icon Size", 0, -168, 16, 64, 1, function(val)
    local ui = RootDB().ui
    ui.minimap = ui.minimap or { size = 37, angle = 45, alpha = 1, onlyOnHover = false }
    ui.minimap.size = math.floor((val or 37) + 0.5)
    TryUpdateMinimapButton()
  end)
  editor.minimapSizeSlider = minimapSizeSlider

  local minimapAlphaSlider = MakeSlider(uiContent, "Minimap Icon Visibility (%)", 0, -214, 0, 100, 1, function(val)
    local ui = RootDB().ui
    ui.minimap = ui.minimap or { size = 37, angle = 45, alpha = 1, onlyOnHover = false }
    ui.minimap.alpha = (tonumber(val) or 100) / 100
    TryUpdateMinimapButton()
  end)
  editor.minimapAlphaSlider = minimapAlphaSlider

  local minimapHoverCheck = CreateFrame("CheckButton", "LIDCOUNCIL_MinimapHoverCheck", uiContent, "UICheckButtonTemplate")
  minimapHoverCheck:SetPoint("TOPLEFT", 0, -252)
  _G[minimapHoverCheck:GetName() .. "Text"]:SetText("Only show on mouseover")
  minimapHoverCheck:SetScript("OnClick", function(self)
    local ui = RootDB().ui
    ui.minimap = ui.minimap or { size = 37, angle = 45, alpha = 1, onlyOnHover = false }
    ui.minimap.onlyOnHover = self:GetChecked() and true or false
    TryUpdateMinimapButton()
  end)
  editor.minimapHoverCheck = minimapHoverCheck

  local minimapResetBtn = CreateFrame("Button", nil, uiContent, "UIPanelButtonTemplate")
  minimapResetBtn:SetSize(180, 22)
  minimapResetBtn:SetPoint("TOPLEFT", 0, -284)
  minimapResetBtn:SetText("Reset Minimap Icon")
  minimapResetBtn:SetScript("OnClick", function()
    StaticPopup_Show("LIDCOUNCIL_RESET_MINIMAP")
  end)
  editor.minimapResetBtn = minimapResetBtn

  function editor:UpdateUILayout()
    local ui = RootDB().ui
    ui.skin = "LP"
    local skinOption = GetUISkinOption(ui.editorSkin)
    ui.editorSkin = skinOption.key
    ui.buttonTheme = skinOption.buttonTheme or DEFAULT_UI_BUTTON_THEME_KEY
    ui.headerLogo = skinOption.headerLogo or DEFAULT_UI_HEADER_LOGO_KEY
    if self.uiSkinDropdown then
      self.uiSkinDropdown:SetSelectedValue(skinOption.key)
      self.uiSkinDropdown:SetText(skinOption.text)
    end
    local minHeight = (self.uiScroll and self.uiScroll.GetHeight and self.uiScroll:GetHeight()) or 1
    if self.uiContent then
      self.uiContent:SetHeight(math.max(minHeight, 370))
    end
    uiPage.__contentHeight = minHeight
    if self.UpdateScrollLayout then self:UpdateScrollLayout() end
  end

  if editor.UpdateUILayout then editor:UpdateUILayout() end
end

INTERNAL_API.LIDCOUNCIL_BuildUIPage_Impl = BuildUIPage
