-- LidPanels_Editor_Pages.lua
-- Split from Editor.lua to reduce CreateEditor locals

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 function TutorialImagesDisabled()
  local getRoot = _G.LIDPANELS_RootDB
  local root = getRoot and getRoot()
  local ui = root and root.ui
  return ui and ui.disableTutorialImages == true
end

local function ApplyTutorialTextureMode(editor)
  if not editor or not editor.__tutorialTextures then return end
  local disabled = TutorialImagesDisabled()
  for _, tex in ipairs(editor.__tutorialTextures) do
    if tex and tex.SetTexture then
      if disabled then
        tex:SetTexture(nil)
        if tex.Hide then tex:Hide() end
      else
        tex:SetTexture(tex.__lidTutorialPath)
        if tex.Show then tex:Show() end
      end
    end
  end
end

local function RegisterTutorialTexture(editor, tex, path)
  if not editor or not tex then return end
  editor.__tutorialTextures = editor.__tutorialTextures or {}
  if not tex.__lidTutorialRegistered then
    tex.__lidTutorialRegistered = true
    editor.__tutorialTextures[#editor.__tutorialTextures + 1] = tex
  end
  tex.__lidTutorialPath = path
  if not editor.ApplyTutorialTextureMode then
    function editor:ApplyTutorialTextureMode()
      ApplyTutorialTextureMode(self)
    end
  end
  if TutorialImagesDisabled() then
    tex:SetTexture(nil)
    if tex.Hide then tex:Hide() end
  else
    tex:SetTexture(path)
    if tex.Show then tex:Show() end
  end
end

local function RequireApi(name, value)
  if value == nil then
    value = rawget(_G, name)
  end
  if value == nil then
    local api = rawget(_G, "LIDPANELS_API")
    if type(api) == "table" then
      value = api[name]
    end
  end
  if value == nil then
    error("LidPanels missing API: " .. tostring(name))
  end
  return value
end

local function ResolveOptionalApiFunction(name)
  local api = rawget(_G, "LIDPANELS_API")
  if type(api) == "table" and type(api[name]) == "function" then
    return api[name]
  end
  local fallback = rawget(_G, name)
  if type(fallback) == "function" then
    return fallback
  end
  return nil
end

local RootDB = RequireApi("LIDPANELS_RootDB", _G.LIDPANELS_RootDB)
local DB = RequireApi("LIDPANELS_DB", _G.LIDPANELS_DB)
local EnsureDefaults = RequireApi("LIDPANELS_EnsureDefaults", _G.LIDPANELS_EnsureDefaults)
local Print = RequireApi("LIDPANELS_Print", _G.LIDPANELS_Print)

local ApplyFrameSkin = RequireApi("LIDPANELS_ApplyFrameSkin", _G.LIDPANELS_ApplyFrameSkin)
local OpenColorPickerRGBOnly = RequireApi("LIDPANELS_OpenColorPickerRGBOnly", _G.LIDPANELS_OpenColorPickerRGBOnly)
local BuildBackgroundList = RequireApi("LIDPANELS_BuildBackgroundList", _G.LIDPANELS_BuildBackgroundList)
local GetBackgroundPath = RequireApi("LIDPANELS_GetBackgroundPath", _G.LIDPANELS_GetBackgroundPath)
local MakeYellowSubHeader = RequireApi("LIDPANELS_MakeYellowSubHeader", _G.LIDPANELS_MakeYellowSubHeader)
local MakeSlider = RequireApi("LIDPANELS_MakeSlider", _G.LIDPANELS_MakeSlider)
local CARD_W = RequireApi("LIDPANELS_CARD_W", _G.LIDPANELS_CARD_W)
local CARD_H = RequireApi("LIDPANELS_CARD_H", _G.LIDPANELS_CARD_H)

local RebuildAllPanels = RequireApi("LIDPANELS_RebuildAllPanels", _G.LIDPANELS_RebuildAllPanels)
local EnsureGradientTables = RequireApi("LIDPANELS_EnsureGradientTables", _G.LIDPANELS_EnsureGradientTables)
local ResetPanelToCenterDefaultSize = RequireApi("LIDPANELS_ResetPanelToCenterDefaultSize", _G.LIDPANELS_ResetPanelToCenterDefaultSize)
local GetSelectedPanelName = RequireApi("LIDPANELS_GetSelectedPanelName", _G.LIDPANELS_GetSelectedPanelName)
local GetSelectedBackgroundName = RequireApi("LIDPANELS_GetSelectedBackgroundName", _G.LIDPANELS_GetSelectedBackgroundName)
local GetSelectedBackgroundCategory = RequireApi("LIDPANELS_GetSelectedBackgroundCategory", _G.LIDPANELS_GetSelectedBackgroundCategory)
local ShowErrorLogWindow = RequireApi("LIDPANELS_ShowErrorLogWindow", _G.LIDPANELS_ShowErrorLogWindow)
local ShowSilentLogWindow = RequireApi("LIDPANELS_ShowSilentLogWindow", _G.LIDPANELS_ShowSilentLogWindow)
local CreateCustomDropdownControl = RequireApi("LIDPANELS_CreateCustomDropdownControl", _G.LIDPANELS_CreateCustomDropdownControl)

local LogSilent = _G.LIDPANELS_LogSilent
local Compat = _G.LIDPANELS_Compat

local function SetDropdownSelection(dropdown, value, text)
  if not dropdown then return end
  if dropdown.__lidpanelsCustomDropdown then
    if value ~= nil and dropdown.SetSelectedValue then dropdown:SetSelectedValue(value) end
    if text ~= nil and dropdown.SetText then dropdown:SetText(text) end
    return
  end
  if value ~= nil then
    UIDropDownMenu_SetSelectedValue(dropdown, value)
  end
  if text ~= nil then
    UIDropDownMenu_SetText(dropdown, text)
  end
end

local function GetDropdownMenuWidth(editor, measurerKey, minWidth, options, extraLabels, maxWidth)
  local measurer = editor and editor[measurerKey]
  if not measurer then
    measurer = UIParent:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
    measurer:Hide()
    if editor then
      editor[measurerKey] = measurer
    end
  end

  local maxMeasuredWidth = 0
  local function Measure(text)
    measurer:SetText(tostring(text or ""))
    local width = measurer:GetStringWidth() or 0
    if width > maxMeasuredWidth then
      maxMeasuredWidth = width
    end
  end

  for _, opt in ipairs(options or {}) do
    if type(opt) == "table" then
      Measure(opt.text or opt.label or opt.value or "")
    else
      Measure(opt)
    end
  end
  for _, label in ipairs(extraLabels or {}) do
    Measure(label)
  end

  local width = math.floor(maxMeasuredWidth + 46 + 0.5)
  local minimum = tonumber(minWidth) or 220
  local maximum = tonumber(maxWidth) or 420
  if width < minimum then width = minimum end
  if width > maximum then width = maximum end
  return width
end

local function BindMouseWheelScroll(scrollFrame, step)
  if not scrollFrame then return end
  step = tonumber(step) or 20
  scrollFrame:EnableMouseWheel(true)
  scrollFrame:SetScript("OnMouseWheel", function(self, delta)
    local scrollBar = self.ScrollBar
    if not scrollBar then return end
    local current = scrollBar:GetValue()
    local minValue, maxValue = scrollBar:GetMinMaxValues()
    local nextValue = current - (delta * step)
    if nextValue < minValue then nextValue = minValue end
    if nextValue > maxValue then nextValue = maxValue end
    scrollBar:SetValue(nextValue)
  end)
end

local function BindScrollChildWidth(scrollFrame, child, opts)
  if not scrollFrame or not child then return end
  opts = opts or {}
  local onResize = opts.onResize
  local logSilent = opts.logSilent
  local warningPrefix = opts.warningPrefix or "Editor scroll OnSizeChanged failed: "
  local warned = false

  scrollFrame:SetScript("OnSizeChanged", function(self)
    local ok, err = pcall(function()
      local width = self:GetWidth() - 28
      if width < 1 then width = 1 end
      child:SetWidth(width)
      if onResize then
        onResize()
      end
      if self.UpdateScrollChildRect then
        self:UpdateScrollChildRect()
      end
    end)
    if ok then return end
    if not warned and type(logSilent) == "function" then
      warned = true
      logSilent(warningPrefix .. tostring(err))
    end
  end)
end

INTERNAL_API.LIDPANELS_RequireApi_Impl = RequireApi
INTERNAL_API.LIDPANELS_ResolveOptionalApiFunction_Impl = ResolveOptionalApiFunction
INTERNAL_API.LIDPANELS_RegisterTutorialTexture_Impl = RegisterTutorialTexture
INTERNAL_API.LIDPANELS_SetDropdownSelection_Impl = SetDropdownSelection
INTERNAL_API.LIDPANELS_GetDropdownMenuWidth_Impl = GetDropdownMenuWidth
INTERNAL_API.LIDPANELS_BindMouseWheelScroll_Impl = BindMouseWheelScroll
INTERNAL_API.LIDPANELS_BindScrollChildWidth_Impl = BindScrollChildWidth

function LIDPANELS_BuildTutorialPage(editor, tutorialPage)
  local buildTutorialPage = INTERNAL_API.LIDPANELS_BuildTutorialPage_Impl
  if type(buildTutorialPage) ~= "function" then
    error("LidPanels missing tutorial page builder implementation.")
  end
  return buildTutorialPage(editor, tutorialPage)
end

function LIDPANELS_BuildPanelsPage(editor, panelsPage)
  local buildPanelsPage = INTERNAL_API.LIDPANELS_BuildPanelsPage_Impl
  if type(buildPanelsPage) ~= "function" then
    error("LidPanels missing panels page builder implementation.")
  end
  return buildPanelsPage(editor, panelsPage)
end

function LIDPANELS_BuildBackgroundsPage(editor, backgroundsPage)
  local buildBackgroundsPage = INTERNAL_API.LIDPANELS_BuildBackgroundsPage_Impl
  if type(buildBackgroundsPage) ~= "function" then
    error("LidPanels missing backgrounds page builder implementation.")
  end
  return buildBackgroundsPage(editor, backgroundsPage)
end

function LIDPANELS_BuildProfilesPage(editor, profilesPage)
  local buildProfilesPage = INTERNAL_API.LIDPANELS_BuildProfilesPage_Impl
  if type(buildProfilesPage) ~= "function" then
    error("LidPanels missing profiles page builder implementation.")
  end
  return buildProfilesPage(editor, profilesPage)
end

function LIDPANELS_BuildUIPage(editor, uiPage)
  local buildUIPage = INTERNAL_API.LIDPANELS_BuildUIPage_Impl
  if type(buildUIPage) ~= "function" then
    error("LidPanels missing UI page builder implementation.")
  end
  return buildUIPage(editor, uiPage)
end

function LIDPANELS_BuildAboutPage(editor, aboutPage)
  local buildAboutPage = INTERNAL_API.LIDPANELS_BuildAboutPage_Impl
  if type(buildAboutPage) ~= "function" then
    error("LidPanels missing about page builder implementation.")
  end
  return buildAboutPage(editor, aboutPage)
end