-- ============================================================================
-- File: ArenaCore/Core/Pages/_Loader.lua - v8.0 RENAMED
-- Purpose: Robust page system; compatible CreateFlatTexture; no UI spam.
-- ============================================================================

local addonName, _ns = ...
if type(_G.ArenaCore) ~= "table" then _G.ArenaCore = {} end
local addon = _G.ArenaCore

addon.Pages         = addon.Pages         or {}
-- CRITICAL FIX: Use Shade-style container caching system
-- This preserves search state and other UI state across page navigation
addon.__pageContainers = {}
addon.__currentPage = nil

addon.COLORS = addon.COLORS or {
  PRIMARY      = {0.545, 0.271, 1.000, 1},
  TEXT         = {1,1,1,1},
  TEXT_2       = {0.706,0.706,0.706,1},
  BORDER       = {0.196,0.196,0.196,1},
  BORDER_LIGHT = {0.278,0.278,0.278,1},
  -- INPUT_DARK removed - using centralized definition from UI.lua
}


-- Shared mini‑scaffold: vanity section frame
function addon:CreateVanitySection(parent, title)
  local C = self.COLORS or {}
  local section = CreateFrame("Frame", nil, parent)

  -- Check if the motto strip from UI.Vanity.lua exists on this page
  if parent._mottoStrip and parent._mottoStrip:IsShown() then
    -- If it exists, anchor the section frame below it with padding
    section:SetPoint("TOPLEFT", parent._mottoStrip, "BOTTOMLEFT", 0, -8)
  else
    -- Fallback to the original positioning if there's no motto strip
    section:SetPoint("TOPLEFT", 8, -44)
  end
  
  section:SetPoint("BOTTOMRIGHT", -8, 8)

  local border = self:CreateFlatTexture(section, "BACKGROUND", 0, C.BORDER_LIGHT or {0.278,0.278,0.278,1}, 0.9)
  border:SetAllPoints()
  local bg = self:CreateFlatTexture(section, "BACKGROUND", 1, self.COLORS.INPUT_DARK or {0.102,0.102,0.102,1}, 1)
  bg:SetPoint("TOPLEFT", 1, -1); bg:SetPoint("BOTTOMRIGHT", -1, 1)
  local accent = self:CreateFlatTexture(section, "OVERLAY", 1, C.PRIMARY or {0.545,0.271,1.0,1}, 0.95)
  accent:SetPoint("TOPLEFT", 0, 0); accent:SetPoint("TOPRIGHT", 0, 0); accent:SetHeight(2)

  local fs = section:CreateFontString(nil, "OVERLAY")
  -- CRITICAL FIX: Use double backslashes and SafeSetFont
  local fontPath = (self.CUSTOM_FONT) or "Interface\\\\AddOns\\\\ArenaCore\\\\Media\\\\Fonts\\\\arenacore.ttf"
  if AC and AC.SafeSetFont then
    AC.SafeSetFont(fs, fontPath, 12, "")
  elseif not fs:SetFont(fontPath, 12, "") then
    fs:SetFont(STANDARD_TEXT_FONT, 12, "")
  end
  fs:SetText(title or ""); fs:SetTextColor((C.PRIMARY and C.PRIMARY[1]) or 0.545, (C.PRIMARY and C.PRIMARY[2]) or 0.271, (C.PRIMARY and C.PRIMARY[3]) or 1.0, 1)
  fs:SetPoint("TOPLEFT", 12, -10)
  section._title = fs
  return section
end

-- Registry
function addon:RegisterPage(name, builder)
  -- Registering page with builder
  if type(name) ~= "string" or type(builder) ~= "function" then 
    -- Invalid registration parameters
    return 
  end
  self.Pages[name] = builder
  -- Page registered successfully
end

-- Display
-- File: ArenaCore/Core/Pages/_Loader.lua
-- Purpose: Shade-style container caching system for proper search state persistence

function addon:ShowPage(name)
  -- ShowPage called for page navigation
  local contentBox = _G.ArenaCore.contentBox
  if not contentBox then 
    -- Error: contentBox is nil
    return 
  end
  if addon.__currentPage == name then 
    -- Already on requested page
    return 
  end

  -- Initialize cache if needed (Shade pattern)
  if not addon.__pageContainers then
    addon.__pageContainers = {}
  end
  
  -- Hide all cached page containers (Shade pattern)
  for pageName, pageData in pairs(addon.__pageContainers) do
    if pageData.container and pageData.container.Hide then
      pageData.container:Hide()
    end
  end
  
  -- Hide any remaining direct children in the content box (legacy cleanup)
  local children = { contentBox:GetChildren() }
  for _, ch in ipairs(children) do 
    if ch and ch.Hide and not addon.__pageContainers[name] or ch ~= addon.__pageContainers[name].container then
      ch:Hide() 
    end
  end
  
  -- CRITICAL FIX: Close all open dropdown menus when switching pages
  if addon.openDropdowns then
    for _, dropdown in ipairs(addon.openDropdowns) do
      if dropdown.menu and dropdown.menu:IsShown() then
        dropdown.menu:Hide()
      end
    end
  end
  
  -- RESET SCROLL POSITION: Always start each page at the top
  if _G.ArenaCore.contentArea then
    _G.ArenaCore.contentArea:SetVerticalScroll(0)
  end
  if _G.ArenaCore.scrollbar then
    _G.ArenaCore.scrollbar:SetValue(0)
  end
  
  -- Check if page container is already cached (Shade pattern)
  if addon.__pageContainers[name] and addon.__pageContainers[name].container then
    -- Reuse cached container - this preserves search state!
    addon.__pageContainers[name].container:Show()
    addon.__currentPage = name
    
    -- Update navigation for the active page
    if addon.UpdateNavigationForPage then
      addon:UpdateNavigationForPage(name)
    end
    
    -- Refresh theme once after page change
    if addon.ThemeManager and addon.ThemeManager.RefreshMainUI then
      C_Timer.After(0.1, function()
        addon.ThemeManager:RefreshMainUI()
      end)
    end
    
    return
  end
  
  -- Create page container for caching (Shade pattern)
  local pageContainer = CreateFrame("Frame", nil, contentBox)
  pageContainer:SetAllPoints(contentBox)
  pageContainer:Show()
  
  -- Store in cache
  addon.__pageContainers[name] = { container = pageContainer }
  
  -- Temporarily swap contentBox so Create functions parent to pageContainer (Shade pattern)
  local originalContentBox = addon.contentBox
  addon.contentBox = pageContainer
  
  -- Create page content (runs once per page - this is the key!)
  local builder = addon.Pages[name]
  if builder then
    -- Wrap in pcall to catch any errors during page build
    local success, err = pcall(function()
      builder(pageContainer)
    end)
    if not success then
      print("|cffFF0000ArenaCore:|r Error building page '" .. name .. "': " .. tostring(err))
    end
  else
    local placeholder = pageContainer:CreateFontString(nil, "OVERLAY")
    placeholder:SetFont(STANDARD_TEXT_FONT, 14, "")
    placeholder:SetText("Page '" .. name .. "' not implemented yet")
    placeholder:SetTextColor(1, 1, 1, 1)
    placeholder:SetPoint("CENTER")
  end
  
  -- Restore original contentBox reference
  addon.contentBox = originalContentBox
  
  addon.__currentPage = name
  
  -- Update navigation for the active page
  if addon.UpdateNavigationForPage then
    addon:UpdateNavigationForPage(name)
  end
  
  -- Refresh theme once after page change
  if addon.ThemeManager and addon.ThemeManager.RefreshMainUI then
    C_Timer.After(0.1, function()
      addon.ThemeManager:RefreshMainUI()
    end)
  end
  
  -- Add motto bar to the page (rotating text)
  if addon.Vanity and addon.Vanity.EnsureMottoStrip then
    addon.Vanity:EnsureMottoStrip(pageContainer)
  end
  
  -- Update content height after showing the new page
  if _G.ArenaCore.UpdateContentHeight then
    C_Timer.After(0.1, _G.ArenaCore.UpdateContentHeight)
  end
end

-- Search page registration moved to Search.lua to follow proper page pattern