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, 0)
  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 uiHeaderMonitoring = MakeYellowSubHeader(uiContent, "Header", 0, -142)
  local uiHeaderMinimap = MakeYellowSubHeader(uiContent, "Minimap", 0, -250)
  editor.uiHeaderGeneral = uiHeaderGeneral
  editor.uiHeaderButtons = nil
  editor.uiHeaderMonitoring = uiHeaderMonitoring
  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 headerMonitoringCheck = CreateFrame("CheckButton", "LIDCOUNCIL_HeaderMonitoringCheck", uiContent, "UICheckButtonTemplate")
  headerMonitoringCheck:SetPoint("TOPLEFT", 0, -168)
  local headerMonitoringCheckText = _G[headerMonitoringCheck:GetName() .. "Text"]
  headerMonitoringCheckText:SetText("Enable Header Monitoring")
  headerMonitoringCheck:SetScript("OnClick", function(self)
    local ui = RootDB().ui
    -- This template's default click handler is replaced below, so toggle from
    -- the saved value rather than trusting its previous visual state.
    ui.headerMonitoringEnabled = ui.headerMonitoringEnabled == false
    self:SetChecked(ui.headerMonitoringEnabled)
    if editor.SetHeaderMonitoringEnabled then
      editor:SetHeaderMonitoringEnabled(ui.headerMonitoringEnabled)
    end
    if editor.RefreshHeaderMonitoringPreview then
      editor:RefreshHeaderMonitoringPreview()
    end
  end)
  editor.headerMonitoringCheck = headerMonitoringCheck
  editor.headerMonitoringCheckText = headerMonitoringCheckText

  local headerMonitoringHint = uiContent:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
  headerMonitoringHint:SetPoint("TOPLEFT", 0, -198)
  headerMonitoringHint:SetWidth(520)
  headerMonitoringHint:SetJustifyH("LEFT")
  headerMonitoringHint:SetText("Shows session state, sync activity, local queued data, pending-roll, and Auto-Pass indicators in the header.")
  editor.headerMonitoringHint = headerMonitoringHint

  local headerMonitoringPreview = uiContent:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
  headerMonitoringPreview:SetPoint("TOPLEFT", 0, -220)
  headerMonitoringPreview:SetWidth(520)
  headerMonitoringPreview:SetJustifyH("LEFT")
  editor.headerMonitoringPreview = headerMonitoringPreview
  editor.RefreshHeaderMonitoringPreview = function(self)
    local ui = RootDB().ui
    local enabled = ui.headerMonitoringEnabled ~= false
    if not self.headerMonitoringPreview then
      return
    end
    if enabled then
      self.headerMonitoringPreview:SetText("Preview: session, sync, queued-data, pending-roll, and Auto-Pass indicators are visible.")
      self.headerMonitoringPreview:SetTextColor(0.30, 0.90, 0.42, 1.00)
    else
      self.headerMonitoringPreview:SetText("Preview: title and version only. Header monitoring indicators are hidden.")
      self.headerMonitoringPreview:SetTextColor(0.72, 0.78, 0.84, 1.00)
    end
  end

  local minimapSizeSlider = MakeSlider(uiContent, "Minimap Icon Size", 0, -276, 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, -322, 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, -360)
  _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, -392)
  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 type(ui.headerMonitoringEnabled) ~= "boolean" then
      ui.headerMonitoringEnabled = true
    end
    if self.uiSkinDropdown then
      self.uiSkinDropdown:SetSelectedValue(skinOption.key)
      self.uiSkinDropdown:SetText(skinOption.text)
    end
    if self.headerMonitoringCheck then
      self.headerMonitoringCheck:SetChecked(ui.headerMonitoringEnabled ~= false)
    end
    if self.RefreshHeaderMonitoringPreview then
      self:RefreshHeaderMonitoringPreview()
    end
    if self.ApplyHeaderMonitoringVisibility then
      self:ApplyHeaderMonitoringVisibility()
    end

    -- The header monitoring switch is still under development. Keep it out of
    -- the normal settings page unless a developer deliberately enables it.
    local showHeaderMonitoringControl = ui.developerMode == true and ui.showHeaderMonitoringCheck == true
    if self.uiHeaderMonitoring then self.uiHeaderMonitoring:SetShown(showHeaderMonitoringControl) end
    if self.headerMonitoringCheck then self.headerMonitoringCheck:SetShown(showHeaderMonitoringControl) end
    if self.headerMonitoringCheckText then self.headerMonitoringCheckText:SetShown(showHeaderMonitoringControl) end
    if self.headerMonitoringHint then self.headerMonitoringHint:SetShown(showHeaderMonitoringControl) end
    if self.headerMonitoringPreview then self.headerMonitoringPreview:SetShown(showHeaderMonitoringControl) end

    local minimapTop = showHeaderMonitoringControl and -250 or -142
    local minimapSizeTop = showHeaderMonitoringControl and -276 or -168
    local minimapAlphaTop = showHeaderMonitoringControl and -322 or -214
    local minimapHoverTop = showHeaderMonitoringControl and -360 or -252
    local minimapResetTop = showHeaderMonitoringControl and -392 or -284
    if self.uiHeaderMinimap then
      self.uiHeaderMinimap:ClearAllPoints()
      self.uiHeaderMinimap:SetPoint("TOPLEFT", 0, minimapTop)
    end
    if self.minimapSizeSlider then
      self.minimapSizeSlider:ClearAllPoints()
      self.minimapSizeSlider:SetPoint("TOPLEFT", 0, minimapSizeTop)
    end
    if self.minimapAlphaSlider then
      self.minimapAlphaSlider:ClearAllPoints()
      self.minimapAlphaSlider:SetPoint("TOPLEFT", 0, minimapAlphaTop)
    end
    if self.minimapHoverCheck then
      self.minimapHoverCheck:ClearAllPoints()
      self.minimapHoverCheck:SetPoint("TOPLEFT", 0, minimapHoverTop)
    end
    if self.minimapResetBtn then
      self.minimapResetBtn:ClearAllPoints()
      self.minimapResetBtn:SetPoint("TOPLEFT", 0, minimapResetTop)
    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, showHeaderMonitoringControl and 466 or 358))
    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
