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
local BindMouseWheelScroll = INTERNAL_API.LIDCOUNCIL_BindMouseWheelScroll_Impl
local BindScrollChildWidth = INTERNAL_API.LIDCOUNCIL_BindScrollChildWidth_Impl
if type(RequireApi) ~= "function"
  or type(BindMouseWheelScroll) ~= "function"
  or type(BindScrollChildWidth) ~= "function" then
  error("LidCouncil missing shared editor page helpers.")
end

local ApplyFrameSkin = RequireApi("LIDCOUNCIL_ApplyFrameSkin", _G.LIDCOUNCIL_ApplyFrameSkin)
local GetSelectedBackgroundName = RequireApi("LIDCOUNCIL_GetSelectedBackgroundName", _G.LIDCOUNCIL_GetSelectedBackgroundName)
local GetSelectedBackgroundCategory = RequireApi("LIDCOUNCIL_GetSelectedBackgroundCategory", _G.LIDCOUNCIL_GetSelectedBackgroundCategory)

local LogSilent = rawget(_G, "LIDCOUNCIL_LogSilent")

local function RequestBackgroundCategoryListRefresh(editor)
  if not editor then
    return false
  end
  if editor.RefreshBackgroundCategoryListSection then
    editor:RefreshBackgroundCategoryListSection()
    return true
  end
  if editor.RefreshBackgroundsSection then
    editor:RefreshBackgroundsSection()
    return true
  end
  if editor.Refresh then
    editor:Refresh()
    return true
  end
  return false
end

local function RequestBackgroundListRefresh(editor)
  if not editor then
    return false
  end
  if editor.RefreshBackgroundListSection then
    editor:RefreshBackgroundListSection()
    return true
  end
  if editor.RefreshBackgroundListDetailsSection then
    editor:RefreshBackgroundListDetailsSection()
    return true
  end
  if editor.RefreshBackgroundsSection then
    editor:RefreshBackgroundsSection()
    return true
  end
  if editor.Refresh then
    editor:Refresh()
    return true
  end
  return false
end

local function RefreshBackgroundCategoryList(editor)
  RequestBackgroundCategoryListRefresh(editor)
end

local function RefreshBackgroundList(editor)
  RequestBackgroundListRefresh(editor)
end

local function BuildBackgroundsPage(editor, backgroundsPage)
  if not editor or not backgroundsPage then return end

  local function SelectedBackgroundCategory()
    return GetSelectedBackgroundCategory()
  end

  local function SelectedBackgroundName()
    return GetSelectedBackgroundName()
  end

  local function SetBackgroundCategoryPage(page)
    local value = math.max(1, math.floor((tonumber(page) or 1) + 0.5))
    editor.bgCatPage = value
    return value
  end

  local function SetBackgroundListPage(page)
    local value = math.max(1, math.floor((tonumber(page) or 1) + 0.5))
    editor.bgListPage = value
    return value
  end

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

  local catScroll = CreateFrame("ScrollFrame", nil, catBg, "UIPanelScrollFrameTemplate")
  catScroll:SetPoint("TOPLEFT", 6, -6)
  catScroll:SetPoint("BOTTOMRIGHT", -28, 90)
  editor.bgCatScroll = catScroll

  local catContent = CreateFrame("Frame", nil, catScroll)
  catContent:SetSize(1, 1)
  catScroll:SetScrollChild(catContent)
  editor.bgCatContent = catContent
  editor.bgCatButtons = {}
  editor.bgCatGroupButtons = {}
  editor.bgCatDropButtons = {}

  local bgCatPrevBtn = CreateFrame("Button", nil, catBg, "UIPanelButtonTemplate")
  bgCatPrevBtn:SetSize(60, 20)
  bgCatPrevBtn:SetPoint("BOTTOMLEFT", 6, 60)
  bgCatPrevBtn:SetText("< Prev")
  bgCatPrevBtn:SetScript("OnClick", function()
    SetBackgroundCategoryPage((editor.bgCatPage or 1) - 1)
    RefreshBackgroundCategoryList(editor)
  end)
  editor.bgCatPrevBtn = bgCatPrevBtn

  local bgCatNextBtn = CreateFrame("Button", nil, catBg, "UIPanelButtonTemplate")
  bgCatNextBtn:SetSize(60, 20)
  bgCatNextBtn:SetPoint("BOTTOMLEFT", 138, 60)
  bgCatNextBtn:SetText("Next >")
  bgCatNextBtn:SetScript("OnClick", function()
    SetBackgroundCategoryPage((editor.bgCatPage or 1) + 1)
    RefreshBackgroundCategoryList(editor)
  end)
  editor.bgCatNextBtn = bgCatNextBtn

  local bgCatPageText = catBg:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
  bgCatPageText:SetPoint("LEFT", bgCatPrevBtn, "RIGHT", 8, 0)
  bgCatPageText:SetWidth(64)
  bgCatPageText:SetJustifyH("CENTER")
  editor.bgCatPageText = bgCatPageText

  local addCatBtn = CreateFrame("Button", nil, catBg, "UIPanelButtonTemplate")
  addCatBtn:SetSize(96, 22)
  addCatBtn:SetPoint("BOTTOMLEFT", 6, 34)
  addCatBtn:SetText("Add Category")
  addCatBtn:SetScript("OnClick", function()
    StaticPopup_Show("LIDCOUNCIL_CREATE_BG_CATEGORY")
  end)
  editor.bgAddCatBtn = addCatBtn

  local addCatGroupBtn = CreateFrame("Button", nil, catBg, "UIPanelButtonTemplate")
  addCatGroupBtn:SetSize(96, 22)
  addCatGroupBtn:SetPoint("LEFT", addCatBtn, "RIGHT", 8, 0)
  addCatGroupBtn:SetText("Add Group")
  addCatGroupBtn:SetScript("OnClick", function()
    StaticPopup_Show("LIDCOUNCIL_CREATE_BG_CATEGORY_GROUP")
  end)
  editor.bgAddCatGroupBtn = addCatGroupBtn

  local delCatBtn = CreateFrame("Button", nil, catBg, "UIPanelButtonTemplate")
  delCatBtn:SetSize(200, 22)
  delCatBtn:SetPoint("BOTTOMLEFT", 6, 8)
  delCatBtn:SetText("Delete Category")
  delCatBtn:SetScript("OnClick", function()
    local category = SelectedBackgroundCategory()
    if not category then return end
    StaticPopup_Show("LIDCOUNCIL_DELETE_BG_CATEGORY", category)
  end)
  editor.bgDeleteCatBtn = delCatBtn

  local listBg = CreateFrame("Frame", nil, backgroundsPage, "BackdropTemplate")
  listBg:SetPoint("TOPLEFT", catBg, "TOPRIGHT", 12, 0)
  listBg:SetPoint("BOTTOMLEFT", catBg, "BOTTOMRIGHT", 12, 0)
  listBg:SetWidth(240)
  ApplyFrameSkin(listBg)
  editor.bgListBg = listBg

  local scroll = CreateFrame("ScrollFrame", nil, listBg, "UIPanelScrollFrameTemplate")
  scroll:SetPoint("TOPLEFT", 6, -6)
  scroll:SetPoint("BOTTOMRIGHT", -28, 90)
  editor.bgListScroll = scroll

  local content = CreateFrame("Frame", nil, scroll)
  content:SetSize(1, 1)
  scroll:SetScrollChild(content)
  editor.bgListContent = content
  editor.bgListButtons = {}

  local bgPrevBtn = CreateFrame("Button", nil, listBg, "UIPanelButtonTemplate")
  bgPrevBtn:SetSize(60, 20)
  bgPrevBtn:SetPoint("BOTTOMLEFT", 6, 60)
  bgPrevBtn:SetText("< Prev")
  bgPrevBtn:SetScript("OnClick", function()
    SetBackgroundListPage((editor.bgListPage or 1) - 1)
    RefreshBackgroundList(editor)
  end)
  editor.bgPrevBtn = bgPrevBtn

  local bgNextBtn = CreateFrame("Button", nil, listBg, "UIPanelButtonTemplate")
  bgNextBtn:SetSize(60, 20)
  bgNextBtn:SetPoint("BOTTOMLEFT", 138, 60)
  bgNextBtn:SetText("Next >")
  bgNextBtn:SetScript("OnClick", function()
    SetBackgroundListPage((editor.bgListPage or 1) + 1)
    RefreshBackgroundList(editor)
  end)
  editor.bgNextBtn = bgNextBtn

  local bgPageText = listBg:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
  bgPageText:SetPoint("LEFT", bgPrevBtn, "RIGHT", 8, 0)
  bgPageText:SetWidth(64)
  bgPageText:SetJustifyH("CENTER")
  editor.bgPageText = bgPageText

  local addBtn = CreateFrame("Button", nil, listBg, "UIPanelButtonTemplate")
  addBtn:SetSize(200, 22)
  addBtn:SetPoint("BOTTOMLEFT", 6, 34)
  addBtn:SetText("Add Background")
  addBtn:SetScript("OnClick", function()
    local category = SelectedBackgroundCategory()
    if not category or category == "" then
      StaticPopup_Show("LIDCOUNCIL_NEED_BG_CATEGORY")
      return
    end
    StaticPopup_Show("LIDCOUNCIL_CREATE_BG")
  end)
  editor.bgAddBtn = addBtn

  local deleteListBtn = CreateFrame("Button", nil, listBg, "UIPanelButtonTemplate")
  deleteListBtn:SetSize(200, 22)
  deleteListBtn:SetPoint("BOTTOMLEFT", 6, 8)
  deleteListBtn:SetText("Delete Background")
  deleteListBtn:SetScript("OnClick", function()
    local backgroundName = SelectedBackgroundName()
    if not backgroundName then return end
    StaticPopup_Show("LIDCOUNCIL_DELETE_BG", backgroundName)
  end)
  editor.bgDeleteListBtn = deleteListBtn

  local propsBg = CreateFrame("Frame", nil, backgroundsPage, "BackdropTemplate")
  propsBg:SetPoint("TOPLEFT", listBg, "TOPRIGHT", 12, 0)
  propsBg:SetPoint("BOTTOMRIGHT", 0, 0)
  ApplyFrameSkin(propsBg)
  editor.bgPropsBg = propsBg

  local propsScroll = CreateFrame("ScrollFrame", nil, propsBg, "UIPanelScrollFrameTemplate")
  propsScroll:SetPoint("TOPLEFT", 18, -12)
  propsScroll:SetPoint("BOTTOMRIGHT", -28, 12)
  BindMouseWheelScroll(propsScroll)
  editor.bgPropsScroll = propsScroll

  local props = CreateFrame("Frame", nil, propsScroll)
  props:SetSize(1, 1)
  propsScroll:SetScrollChild(props)
  editor.bgProps = props

  local sel = props:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
  sel:SetPoint("TOPLEFT", 0, 0)
  sel:SetText("Selected: (none)")
  editor.bgSelLabel = sel

  local renameBtn = CreateFrame("Button", nil, props, "UIPanelButtonTemplate")
  renameBtn:SetSize(120, 22)
  renameBtn:SetPoint("TOPLEFT", 0, -28)
  renameBtn:SetText("Rename")
  renameBtn:SetScript("OnClick", function()
    if not SelectedBackgroundName() then return end
    StaticPopup_Show("LIDCOUNCIL_RENAME_BG")
  end)
  renameBtn:Hide()
  editor.bgRenameBtn = renameBtn

  local delBtn = CreateFrame("Button", nil, props, "UIPanelButtonTemplate")
  delBtn:SetSize(120, 22)
  delBtn:SetPoint("TOPLEFT", renameBtn, "BOTTOMLEFT", 0, -6)
  delBtn:SetText("Delete")
  delBtn:SetScript("OnClick", function()
    local backgroundName = SelectedBackgroundName()
    if not backgroundName then return end
    StaticPopup_Show("LIDCOUNCIL_DELETE_BG", backgroundName)
  end)
  delBtn:Hide()
  editor.bgDeleteBtn = delBtn

  local renameCatBtn = CreateFrame("Button", nil, props, "UIPanelButtonTemplate")
  renameCatBtn:SetSize(120, 22)
  renameCatBtn:SetPoint("TOPLEFT", 0, -28)
  renameCatBtn:SetText("Rename Category")
  renameCatBtn:SetScript("OnClick", function()
    if not SelectedBackgroundCategory() then return end
    StaticPopup_Show("LIDCOUNCIL_RENAME_BG_CATEGORY")
  end)
  renameCatBtn:Hide()
  editor.bgRenameCatBtn = renameCatBtn

  local deleteCatPropsBtn = CreateFrame("Button", nil, props, "UIPanelButtonTemplate")
  deleteCatPropsBtn:SetSize(120, 22)
  deleteCatPropsBtn:SetPoint("TOPLEFT", renameCatBtn, "BOTTOMLEFT", 0, -6)
  deleteCatPropsBtn:SetText("Delete Category")
  deleteCatPropsBtn:SetScript("OnClick", function()
    local category = SelectedBackgroundCategory()
    if not category then return end
    StaticPopup_Show("LIDCOUNCIL_DELETE_BG_CATEGORY", category)
  end)
  deleteCatPropsBtn:Hide()
  editor.bgDeleteCatPropsBtn = deleteCatPropsBtn

  local renameCatGroupBtn = CreateFrame("Button", nil, props, "UIPanelButtonTemplate")
  renameCatGroupBtn:SetSize(120, 22)
  renameCatGroupBtn:SetPoint("TOPLEFT", 0, -28)
  renameCatGroupBtn:SetText("Rename Group")
  renameCatGroupBtn:SetScript("OnClick", function()
    StaticPopup_Show("LIDCOUNCIL_RENAME_BG_CATEGORY_GROUP")
  end)
  renameCatGroupBtn:Hide()
  editor.bgRenameCatGroupBtn = renameCatGroupBtn

  local deleteCatGroupPropsBtn = CreateFrame("Button", nil, props, "UIPanelButtonTemplate")
  deleteCatGroupPropsBtn:SetSize(120, 22)
  deleteCatGroupPropsBtn:SetPoint("TOPLEFT", renameCatGroupBtn, "BOTTOMLEFT", 0, -6)
  deleteCatGroupPropsBtn:SetText("Delete Group")
  deleteCatGroupPropsBtn:SetScript("OnClick", function()
    if not editor or not editor.bgSelectedCategoryGroupName then return end
    StaticPopup_Show("LIDCOUNCIL_DELETE_BG_CATEGORY_GROUP", editor.bgSelectedCategoryGroupName)
  end)
  deleteCatGroupPropsBtn:Hide()
  editor.bgDeleteCatGroupPropsBtn = deleteCatGroupPropsBtn

  local source = props:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
  source:SetPoint("TOPLEFT", 0, -90)
  source:SetWidth(560)
  source:SetJustifyH("LEFT")
  source:SetText("Source:\nAddOns/LidCouncil_UserMedia/Your_Backgrounds/")
  source:Hide()
  editor.bgSourceText = source

  local reloadNote = props:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
  reloadNote:SetPoint("TOPLEFT", source, "BOTTOMLEFT", 0, -10)
  reloadNote:SetWidth(560)
  reloadNote:SetJustifyH("LEFT")
  reloadNote:SetText("(!) After adding a new image, do a /reload. Otherwise, it won't appear in the dropdown selection of the Panel Settings")
  reloadNote:Hide()
  editor.bgReloadNote = reloadNote

  local function UpdateBgPropsLayout()
    local width = props:GetWidth() or 0
    if width < 1 then return end
    local textWidth = width - 12
    if textWidth < 200 then textWidth = 200 end

    source:SetWidth(textWidth)
    reloadNote:SetWidth(textWidth)
    if editor.bgEmptyText then editor.bgEmptyText:SetWidth(textWidth) end
    if editor.bgPreviewFrame then editor.bgPreviewFrame:SetHeight(260) end
    if editor.UpdateBgPreviewLayout then editor:UpdateBgPreviewLayout() end

    local bottomAnchor
    if editor.bgPreviewFrame and editor.bgPreviewFrame:IsShown() then
      bottomAnchor = editor.bgPreviewFrame
    elseif editor.bgReloadNote and editor.bgReloadNote:IsShown() then
      bottomAnchor = editor.bgReloadNote
    elseif editor.bgEmptyText and editor.bgEmptyText:IsShown() then
      bottomAnchor = editor.bgEmptyText
    else
      bottomAnchor = source
    end

    local topY = sel:GetTop() or props:GetTop() or 0
    local bottomY = bottomAnchor and bottomAnchor:GetBottom() or 0
    local contentHeight = math.ceil((topY - bottomY) + 18)
    local viewportHeight = (editor.bgPropsScroll and editor.bgPropsScroll:GetHeight()) or 0
    if contentHeight < viewportHeight then contentHeight = viewportHeight end
    if contentHeight < 1 then contentHeight = 1 end
    props:SetHeight(contentHeight)
    if editor.bgPropsScroll and editor.bgPropsScroll.UpdateScrollChildRect then
      editor.bgPropsScroll:UpdateScrollChildRect()
    end
  end
  editor.UpdateBgPropsLayout = UpdateBgPropsLayout

  BindScrollChildWidth(propsScroll, props, {
    onResize = UpdateBgPropsLayout,
    logSilent = LogSilent,
    warningPrefix = "Backgrounds props scroll OnSizeChanged failed: ",
  })

  local previewFrame = CreateFrame("Frame", nil, props, "BackdropTemplate")
  previewFrame:SetPoint("TOPLEFT", reloadNote, "BOTTOMLEFT", 0, -12)
  previewFrame:SetPoint("RIGHT", props, "RIGHT", -6, 0)
  previewFrame:SetHeight(260)
  previewFrame:SetBackdrop({
    bgFile = "Interface/Buttons/WHITE8x8",
    edgeFile = "Interface/Buttons/WHITE8x8",
    tile = false, edgeSize = 1,
    insets = { left = 1, right = 1, top = 1, bottom = 1 }
  })
  previewFrame:SetBackdropColor(0, 0, 0, 0)
  previewFrame:SetBackdropBorderColor(0, 0, 0, 0.9)
  previewFrame:Hide()
  editor.bgPreviewFrame = previewFrame

  local previewTex = previewFrame:CreateTexture(nil, "ARTWORK")
  previewTex:SetAllPoints(true)
  previewTex:SetTexCoord(0, 1, 0, 1)
  editor.bgPreviewTex = previewTex

  local emptyText = props:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
  emptyText:SetPoint("TOPLEFT", 0, -90)
  emptyText:SetText("Select or create a category first.")
  editor.bgEmptyText = emptyText

  UpdateBgPropsLayout()
  if propsScroll.UpdateScrollChildRect then
    propsScroll:UpdateScrollChildRect()
  end
end

INTERNAL_API.LIDCOUNCIL_BuildBackgroundsPage_Impl = BuildBackgroundsPage
