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

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 function TutorialImagesDisabled()
  local getRoot = _G.LIDCOUNCIL_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, "LIDCOUNCIL_API")
    if type(api) == "table" then
      value = api[name]
    end
  end
  if value == nil then
    error("LidCouncil missing API: " .. tostring(name))
  end
  return value
end

local function ResolveOptionalApiFunction(name)
  local api = rawget(_G, "LIDCOUNCIL_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("LIDCOUNCIL_RootDB", _G.LIDCOUNCIL_RootDB)
local DB = RequireApi("LIDCOUNCIL_DB", _G.LIDCOUNCIL_DB)
local EnsureDefaults = RequireApi("LIDCOUNCIL_EnsureDefaults", _G.LIDCOUNCIL_EnsureDefaults)
local Print = RequireApi("LIDCOUNCIL_Print", _G.LIDCOUNCIL_Print)

local ApplyFrameSkin = RequireApi("LIDCOUNCIL_ApplyFrameSkin", _G.LIDCOUNCIL_ApplyFrameSkin)
local OpenColorPickerRGBOnly = RequireApi("LIDCOUNCIL_OpenColorPickerRGBOnly", _G.LIDCOUNCIL_OpenColorPickerRGBOnly)
local BuildBackgroundList = RequireApi("LIDCOUNCIL_BuildBackgroundList", _G.LIDCOUNCIL_BuildBackgroundList)
local GetBackgroundPath = RequireApi("LIDCOUNCIL_GetBackgroundPath", _G.LIDCOUNCIL_GetBackgroundPath)
local MakeYellowSubHeader = RequireApi("LIDCOUNCIL_MakeYellowSubHeader", _G.LIDCOUNCIL_MakeYellowSubHeader)
local MakeSlider = RequireApi("LIDCOUNCIL_MakeSlider", _G.LIDCOUNCIL_MakeSlider)
local CARD_W = RequireApi("LIDCOUNCIL_CARD_W", _G.LIDCOUNCIL_CARD_W)
local CARD_H = RequireApi("LIDCOUNCIL_CARD_H", _G.LIDCOUNCIL_CARD_H)

local RebuildAllPanels = RequireApi("LIDCOUNCIL_RebuildAllPanels", _G.LIDCOUNCIL_RebuildAllPanels)
local EnsureGradientTables = RequireApi("LIDCOUNCIL_EnsureGradientTables", _G.LIDCOUNCIL_EnsureGradientTables)
local ResetPanelToCenterDefaultSize = RequireApi("LIDCOUNCIL_ResetPanelToCenterDefaultSize", _G.LIDCOUNCIL_ResetPanelToCenterDefaultSize)
local GetSelectedPanelName = RequireApi("LIDCOUNCIL_GetSelectedPanelName", _G.LIDCOUNCIL_GetSelectedPanelName)
local GetSelectedBackgroundName = RequireApi("LIDCOUNCIL_GetSelectedBackgroundName", _G.LIDCOUNCIL_GetSelectedBackgroundName)
local GetSelectedBackgroundCategory = RequireApi("LIDCOUNCIL_GetSelectedBackgroundCategory", _G.LIDCOUNCIL_GetSelectedBackgroundCategory)
local ShowErrorLogWindow = RequireApi("LIDCOUNCIL_ShowErrorLogWindow", _G.LIDCOUNCIL_ShowErrorLogWindow)
local ShowSilentLogWindow = RequireApi("LIDCOUNCIL_ShowSilentLogWindow", _G.LIDCOUNCIL_ShowSilentLogWindow)
local CreateCustomDropdownControl = RequireApi("LIDCOUNCIL_CreateCustomDropdownControl", _G.LIDCOUNCIL_CreateCustomDropdownControl)

local LogSilent = _G.LIDCOUNCIL_LogSilent
local function SetDropdownSelection(dropdown, value, text)
  if not dropdown then return end
  if dropdown.__lidcouncilCustomDropdown 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.LIDCOUNCIL_RequireApi_Impl = RequireApi
INTERNAL_API.LIDCOUNCIL_ResolveOptionalApiFunction_Impl = ResolveOptionalApiFunction
INTERNAL_API.LIDCOUNCIL_RegisterTutorialTexture_Impl = RegisterTutorialTexture
INTERNAL_API.LIDCOUNCIL_SetDropdownSelection_Impl = SetDropdownSelection
INTERNAL_API.LIDCOUNCIL_GetDropdownMenuWidth_Impl = GetDropdownMenuWidth
INTERNAL_API.LIDCOUNCIL_BindMouseWheelScroll_Impl = BindMouseWheelScroll
INTERNAL_API.LIDCOUNCIL_BindScrollChildWidth_Impl = BindScrollChildWidth

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

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

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

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

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

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