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

local RootDB = RequireApi("LIDCOUNCIL_RootDB", _G.LIDCOUNCIL_RootDB)
local DB = RequireApi("LIDCOUNCIL_DB", _G.LIDCOUNCIL_DB)
local ApplyFrameSkin = RequireApi("LIDCOUNCIL_ApplyFrameSkin", _G.LIDCOUNCIL_ApplyFrameSkin)
local MakeYellowSubHeader = RequireApi("LIDCOUNCIL_MakeYellowSubHeader", _G.LIDCOUNCIL_MakeYellowSubHeader)
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 GetSelectedPanelName = RequireApi("LIDCOUNCIL_GetSelectedPanelName", _G.LIDCOUNCIL_GetSelectedPanelName)

local LogSilent = rawget(_G, "LIDCOUNCIL_LogSilent")

local function RequestPanelsSectionRefreshInternal(editor)
  if type(editor) ~= "table" then
    return false
  end
  if editor.RefreshPanelsSection then
    editor:RefreshPanelsSection()
    return true
  end
  if editor.Refresh then
    editor:Refresh()
    return true
  end
  return false
end

local function RequestPanelListRefreshInternal(editor)
  if type(editor) ~= "table" then
    return false
  end
  if editor.RefreshPanelsListSection then
    editor:RefreshPanelsListSection()
    return true
  end
  return RequestPanelsSectionRefreshInternal(editor)
end

local function RequestPanelPropertiesRefreshInternal(editor)
  if type(editor) ~= "table" then
    return false
  end
  if editor.RefreshPanelPropertiesSection then
    editor:RefreshPanelPropertiesSection()
    return true
  end
  return RequestPanelsSectionRefreshInternal(editor)
end

local function RefreshPanelList(editor)
  return RequestPanelListRefreshInternal(editor)
end

local function RefreshPanelProperties(editor)
  return RequestPanelPropertiesRefreshInternal(editor)
end

local function SetPanelEditModeSetting(editor, mode)
  local root = RootDB()
  root.ui = root.ui or {}
  root.ui.panelEditMode = (mode == "PREVIEW") and "PREVIEW" or "EDITOR"
  RebuildAllPanels()
  RefreshPanelProperties(editor)
end

local function CreatePanelsPageScaffold(editor, panelsPage)
  if not editor or not panelsPage then return nil end

  editor.RequestPanelsSectionRefresh = function(self)
    return RequestPanelsSectionRefreshInternal(type(self) == "table" and self or editor)
  end
  editor.RequestPanelListRefresh = function(self)
    return RequestPanelListRefreshInternal(type(self) == "table" and self or editor)
  end
  editor.RequestPanelPropertiesRefresh = function(self)
    return RequestPanelPropertiesRefreshInternal(type(self) == "table" and self or editor)
  end

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

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

  local listContent = CreateFrame("Frame", nil, listScroll)
  listContent:SetSize(1, 1)
  listScroll:SetScrollChild(listContent)
  editor.listContent = listContent
  editor.listButtons = {}

  local panelPrevBtn = CreateFrame("Button", nil, listBg, "UIPanelButtonTemplate")
  panelPrevBtn:SetSize(60, 20)
  panelPrevBtn:SetPoint("BOTTOMLEFT", 6, 60)
  panelPrevBtn:SetText("< Prev")
  panelPrevBtn:SetScript("OnClick", function()
    editor.panelListPage = math.max(1, (editor.panelListPage or 1) - 1)
    RefreshPanelList(editor)
  end)
  editor.panelPrevBtn = panelPrevBtn

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

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

  local newBtn = CreateFrame("Button", nil, listBg, "UIPanelButtonTemplate")
  newBtn:SetSize(200, 22)
  newBtn:SetPoint("BOTTOMLEFT", 6, 34)
  newBtn:SetText("Create Panel")
  newBtn:SetScript("OnClick", function()
    StaticPopup_Show("LIDCOUNCIL_CREATE_PANEL")
  end)
  editor.newBtn = newBtn

  local delBtn = CreateFrame("Button", nil, listBg, "UIPanelButtonTemplate")
  delBtn:SetSize(200, 22)
  delBtn:SetPoint("BOTTOMLEFT", 6, 8)
  delBtn:SetText("Delete Panel")
  delBtn:SetScript("OnClick", function()
    if not GetSelectedPanelName() then return end
    StaticPopup_Show("LIDCOUNCIL_DELETE_PANEL", GetSelectedPanelName())
  end)
  editor.delBtn = delBtn

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

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

  local props = CreateFrame("Frame", nil, propsScroll)
  props:SetSize(1, 1)
  propsScroll:SetScrollChild(props)
  editor.props = props
  editor.propsScroll = propsScroll
  BindScrollChildWidth(propsScroll, props, {
    onResize = function()
      if editor.UpdatePanelsPropsHeight then
        editor:UpdatePanelsPropsHeight()
      end
    end,
  })

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

  local noPanelFrame = CreateFrame("Frame", nil, noPanelScroll)
  noPanelFrame:SetPoint("TOPLEFT", 0, 0)
  noPanelFrame:SetSize(1, 1)
  noPanelFrame:SetClipsChildren(true)
  noPanelFrame:Hide()
  editor.noPanelFrame = noPanelFrame
  noPanelScroll:SetScrollChild(noPanelFrame)
  BindScrollChildWidth(noPanelScroll, noPanelFrame, {
    onResize = function()
      if editor.LayoutNoPanel then
        editor:LayoutNoPanel()
      end
    end,
    logSilent = LogSilent,
    warningPrefix = "Panels no-panel scroll OnSizeChanged failed: ",
  })
  noPanelScroll:SetScript("OnShow", function(self)
    if editor.LayoutNoPanel then editor:LayoutNoPanel() end
    if self.UpdateScrollChildRect then self:UpdateScrollChildRect() end
  end)

  local noPanelHeader = noPanelFrame:CreateTexture(nil, "ARTWORK")
  noPanelHeader:SetPoint("TOPLEFT", 18, -18)
  RegisterTutorialTexture(editor, noPanelHeader, "Interface\\AddOns\\LidCouncil\\Media\\LidCouncil\\Tutorials\\Panels_1_Title.tga")
  noPanelHeader:SetTexCoord(0, 1, 0, 1)
  editor.noPanelHeader = noPanelHeader

  local function MakeWelcomeCard(parent, texturePath)
    local card = CreateFrame("Frame", nil, parent)
    card:SetPoint("TOPLEFT", 0, 0)
    card:SetSize(CARD_W, CARD_H)

    local texObj = card:CreateTexture(nil, "ARTWORK")
    texObj:SetPoint("TOPLEFT", 0, 0)
    texObj:SetPoint("BOTTOMRIGHT", 0, 0)
    RegisterTutorialTexture(editor, texObj, texturePath)
    texObj:SetTexCoord(0, 1, 0, 1)
    card.texObj = texObj
    return card
  end

  editor.noPanelCards = {
    MakeWelcomeCard(noPanelFrame, "Interface\\AddOns\\LidCouncil\\Media\\LidCouncil\\Tutorials\\Panels_2_Step1.tga"),
    MakeWelcomeCard(noPanelFrame, "Interface\\AddOns\\LidCouncil\\Media\\LidCouncil\\Tutorials\\Panels_3_Step2.tga"),
    MakeWelcomeCard(noPanelFrame, "Interface\\AddOns\\LidCouncil\\Media\\LidCouncil\\Tutorials\\Panels_4_Step3.tga"),
    MakeWelcomeCard(noPanelFrame, "Interface\\AddOns\\LidCouncil\\Media\\LidCouncil\\Tutorials\\Panels_5_Step4.tga"),
  }

  function editor:LayoutNoPanel()
    if not self.noPanelFrame or not self.noPanelCards then return end
    local availableWidth = self.noPanelFrame:GetWidth()
    if not availableWidth or availableWidth < 1 then return end

    local leftPad = 18
    local cols = 2
    local cardGap = 20
    local rowWidth = availableWidth - leftPad
    local cardWidth = math.max(1, math.floor((rowWidth - cardGap) / 2))
    local cardHeight = math.floor(cardWidth * 0.75)
    local headerWidth = cardWidth * 2 + cardGap
    local headerHeight = math.floor(cardHeight * 0.6)

    if self.noPanelHeader then
      self.noPanelHeader:SetSize(headerWidth, headerHeight)
      self.noPanelHeader:ClearAllPoints()
      self.noPanelHeader:SetPoint("TOPLEFT", leftPad, -18)
    end

    local y = -18 - headerHeight - 20
    local idx = 1
    for row = 1, 2 do
      for col = 1, cols do
        local card = self.noPanelCards[idx]
        if not card then break end
        card:SetSize(cardWidth, cardHeight)
        local x = leftPad + (col - 1) * (cardWidth + cardGap)
        card:ClearAllPoints()
        card:SetPoint("TOPLEFT", x, y)
        idx = idx + 1
      end
      y = y - cardHeight - 20
    end

    local contentHeight = math.max(400, (-y) + 120)
    self.noPanelFrame:SetHeight(contentHeight)
    if self.noPanelScroll and self.noPanelScroll.UpdateScrollChildRect then
      self.noPanelScroll:UpdateScrollChildRect()
    end
    if self.noPanelScroll and self.noPanelScroll.ScrollBar then
      local scrollBar = self.noPanelScroll.ScrollBar
      local _, maxValue = scrollBar:GetMinMaxValues()
      scrollBar:SetShown(maxValue and maxValue > 0)
    end
  end

  noPanelFrame:SetScript("OnSizeChanged", function()
    if editor.LayoutNoPanel then editor:LayoutNoPanel() end
  end)

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

  MakeYellowSubHeader(props, "General", 0, -28)
  MakeYellowSubHeader(props, "Size & Position", 0, -204)
  MakeYellowSubHeader(props, "Color & Design", 0, -444)
  editor.resetHeader = MakeYellowSubHeader(props, "Reset Panel", 0, -750)

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

  local copyBtn = CreateFrame("Button", nil, props, "UIPanelButtonTemplate")
  copyBtn:SetSize(120, 22)
  copyBtn:SetPoint("TOPLEFT", renameBtn, "TOPRIGHT", 10, 0)
  copyBtn:SetText("Copy Panel")
  copyBtn:SetScript("OnClick", function()
    if not GetSelectedPanelName() then return end
    StaticPopup_Show("LIDCOUNCIL_COPY_PANEL")
  end)
  editor.copyBtn = copyBtn

  local lockCheck = CreateFrame("CheckButton", "LIDCOUNCIL_LockPanelCheck", props, "UICheckButtonTemplate")
  lockCheck:SetPoint("TOPLEFT", 0, -82)
  _G[lockCheck:GetName() .. "Text"]:SetText("Lock Panel")
  lockCheck:SetScript("OnClick", function(self)
    if not GetSelectedPanelName() then return end
    local panel = DB().panels[GetSelectedPanelName()]
    if not panel then return end
    panel.locked = self:GetChecked() and true or false
    RebuildAllPanels()
    RefreshPanelProperties(editor)
  end)
  editor.lockCheck = lockCheck

  local editModeBox = CreateFrame("Frame", nil, props, "BackdropTemplate")
  editModeBox:SetPoint("TOPLEFT", 0, -122)
  editModeBox:SetSize(500, 48)
  editModeBox:SetBackdrop({
    bgFile = "Interface/Buttons/WHITE8x8",
    edgeFile = "Interface/Buttons/WHITE8x8",
    tile = false,
    edgeSize = 1,
    insets = { left = 1, right = 1, top = 1, bottom = 1 },
  })
  editModeBox:SetBackdropColor(0.05, 0.05, 0.07, 0.45)
  editModeBox:SetBackdropBorderColor(0.20, 0.20, 0.25, 0.85)
  editModeBox:Hide()
  editor.editModeBox = editModeBox

  local editModeLabel = props:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall")
  editModeLabel:SetPoint("TOPLEFT", editModeBox, "TOPLEFT", 12, -14)
  editModeLabel:SetText("Edit View:")
  editModeLabel:Hide()
  editor.editModeLabel = editModeLabel

  local editModeEditorCheck = CreateFrame("CheckButton", "LIDCOUNCIL_EditModeEditorCheck", props, "UICheckButtonTemplate")
  editModeEditorCheck:SetPoint("TOPLEFT", editModeBox, "TOPLEFT", 92, -10)
  _G[editModeEditorCheck:GetName() .. "Text"]:SetText("Editor Mode")
  editModeEditorCheck:Hide()
  editModeEditorCheck:SetScript("OnClick", function(self)
    if self:GetChecked() then
      SetPanelEditModeSetting(editor, "EDITOR")
    else
      self:SetChecked(true)
    end
  end)
  editor.editModeEditorCheck = editModeEditorCheck

  local editModePreviewCheck = CreateFrame("CheckButton", "LIDCOUNCIL_EditModePreviewCheck", props, "UICheckButtonTemplate")
  editModePreviewCheck:SetPoint("TOPLEFT", editModeBox, "TOPLEFT", 230, -10)
  _G[editModePreviewCheck:GetName() .. "Text"]:SetText("Preview Mode")
  editModePreviewCheck:Hide()
  editModePreviewCheck:SetScript("OnClick", function(self)
    if self:GetChecked() then
      SetPanelEditModeSetting(editor, "PREVIEW")
    else
      self:SetChecked(true)
    end
  end)
  editor.editModePreviewCheck = editModePreviewCheck

  return {
    props = props,
  }
end

INTERNAL_API.LIDCOUNCIL_CreatePanelsPageScaffold_Impl = CreatePanelsPageScaffold
