-- =============================================================================
-- Core/Pages/Frames.lua - Frames Configuration Page
-- =============================================================================
-- Party and Unit frame modifications configuration

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

-- Localization helper
local function L(key)
    if AC.UILocalization then
        return AC.UILocalization:Get("FRAMES", key, key)
    end
    return key
end



-- =============================================================================
-- PAGE CREATION FUNCTION
-- =============================================================================

local function CreateFramesSubTabButton(parent, text, width, height)
  local COLORS = AC.COLORS or {}

  local btn = CreateFrame("Button", nil, parent)
  btn:SetSize(width or 120, height or 26)

  local bg = AC:CreateFlatTexture(btn, "BACKGROUND", 0, {0.06, 0.06, 0.06, 1}, 1)
  bg:SetAllPoints()
  btn.bg = bg

  local hover = AC:CreateFlatTexture(btn, "ARTWORK", 1, COLORS.BORDER_LIGHT or {0.278, 0.278, 0.278, 1}, 0.15)
  hover:SetAllPoints()
  hover:Hide()
  btn.hover = hover

  local glow = btn:CreateTexture(nil, "OVERLAY")
  glow:SetTexture("Interface\\AddOns\\ArenaCore\\Media\\UI\\tab-purple-matte.tga")
  glow:SetAllPoints()
  glow:SetBlendMode("ADD")
  glow:SetAlpha(0)
  btn.glow = glow

  local function CreateGlowLine()
    local t = btn:CreateTexture(nil, "OVERLAY")
    local c = COLORS.PRIMARY or {0.545, 0.271, 1.000, 1}
    t:SetColorTexture(c[1], c[2], c[3], 1)
    t:SetDrawLayer("OVERLAY")
    if t.SetSnapToPixelGrid then
      t:SetTexelSnappingBias(0)
      t:SetSnapToPixelGrid(false)
    end
    t:Hide()
    return t
  end

  local outlineTop = CreateGlowLine()
  outlineTop:SetPoint("TOPLEFT", btn, "TOPLEFT", 1, 0)
  outlineTop:SetPoint("TOPRIGHT", btn, "TOPRIGHT", -1, 0)
  outlineTop:SetHeight(1)

  local outlineBottom = CreateGlowLine()
  outlineBottom:SetPoint("BOTTOMLEFT", btn, "BOTTOMLEFT", 1, 1)
  outlineBottom:SetPoint("BOTTOMRIGHT", btn, "BOTTOMRIGHT", -1, 1)
  outlineBottom:SetHeight(1)

  local outlineLeft = CreateGlowLine()
  outlineLeft:SetPoint("TOPLEFT", btn, "TOPLEFT", 0, -1)
  outlineLeft:SetPoint("BOTTOMLEFT", btn, "BOTTOMLEFT", 0, 1)
  outlineLeft:SetWidth(1)

  local outlineRight = CreateGlowLine()
  outlineRight:SetPoint("TOPRIGHT", btn, "TOPRIGHT", 0, -1)
  outlineRight:SetPoint("BOTTOMRIGHT", btn, "BOTTOMRIGHT", 0, 1)
  outlineRight:SetWidth(1)

  btn.outlineTop = outlineTop
  btn.outlineBottom = outlineBottom
  btn.outlineLeft = outlineLeft
  btn.outlineRight = outlineRight

  local label = AC:CreateStyledText(btn, text or "", 11, (COLORS.TEXT_2 or {0.706, 0.706, 0.706, 1}), "OVERLAY", "")
  label:SetPoint("CENTER", 0, 0)
  btn.label = label

  btn.isSelected = false

  function btn:SetSelected(selected)
    self.isSelected = selected and true or false

    if self.isSelected then
      self.bg:SetColorTexture(0.11, 0.11, 0.11, 1)
      self.hover:Hide()
      self.outlineTop:Show()
      self.outlineBottom:Show()
      self.outlineLeft:Show()
      self.outlineRight:Show()
      if self.glow then
        self.glow:SetAlpha(0.22)
      end
      self.label:SetTextColor((COLORS.TEXT and COLORS.TEXT[1]) or 1, (COLORS.TEXT and COLORS.TEXT[2]) or 1, (COLORS.TEXT and COLORS.TEXT[3]) or 1, 1)
    else
      self.bg:SetColorTexture(0.06, 0.06, 0.06, 1)
      self.outlineTop:Hide()
      self.outlineBottom:Hide()
      self.outlineLeft:Hide()
      self.outlineRight:Hide()
      if self.glow then
        self.glow:SetAlpha(0)
      end
      self.label:SetTextColor((COLORS.TEXT_2 and COLORS.TEXT_2[1]) or 0.706, (COLORS.TEXT_2 and COLORS.TEXT_2[2]) or 0.706, (COLORS.TEXT_2 and COLORS.TEXT_2[3]) or 0.706, 1)
    end
  end

  btn:SetScript("OnEnter", function(selfBtn)
    if not selfBtn.isSelected then
      selfBtn.hover:Show()
      selfBtn.outlineTop:Show()
      selfBtn.outlineBottom:Show()
      selfBtn.outlineLeft:Show()
      selfBtn.outlineRight:Show()
      if selfBtn.glow then
        selfBtn.glow:SetAlpha(0.22)
      end
      selfBtn.label:SetTextColor((COLORS.TEXT and COLORS.TEXT[1]) or 1, (COLORS.TEXT and COLORS.TEXT[2]) or 1, (COLORS.TEXT and COLORS.TEXT[3]) or 1, 1)
    end
  end)

  btn:SetScript("OnLeave", function(selfBtn)
    if not selfBtn.isSelected then
      selfBtn.hover:Hide()
      selfBtn.outlineTop:Hide()
      selfBtn.outlineBottom:Hide()
      selfBtn.outlineLeft:Hide()
      selfBtn.outlineRight:Hide()
      if selfBtn.glow then
        selfBtn.glow:SetAlpha(0)
      end
      selfBtn.label:SetTextColor((COLORS.TEXT_2 and COLORS.TEXT_2[1]) or 0.706, (COLORS.TEXT_2 and COLORS.TEXT_2[2]) or 0.706, (COLORS.TEXT_2 and COLORS.TEXT_2[3]) or 0.706, 1)
    end
  end)

  return btn
end

function AC:CreateFramesPage(parent)
  -- Ensure database exists
  if not AC.DB or not AC.DB.profile then
    AC:EnsureDB()
  end
  
  -- Ensure arenaNameplates section exists (for databases created before this feature)
  if AC.DB.profile and not AC.DB.profile.arenaNameplates then
    AC.DB.profile.arenaNameplates = {
      enabled = true,
      mode = "both",
      useShortNames = false,
      useClassColors = false,
      showHealerIndicator = false
    }
  end
  -- Ensure useClassColors exists for older databases
  if AC.DB.profile.arenaNameplates and AC.DB.profile.arenaNameplates.useClassColors == nil then
    AC.DB.profile.arenaNameplates.useClassColors = false
  end
  -- Ensure showHealerIndicator exists for older databases
  if AC.DB.profile.arenaNameplates and AC.DB.profile.arenaNameplates.showHealerIndicator == nil then
    AC.DB.profile.arenaNameplates.showHealerIndicator = false
  end
  
  -- Ensure motto strip
  if AC.Vanity and AC.Vanity.EnsureMottoStrip then 
    AC.Vanity:EnsureMottoStrip(parent) 
  end
  
  -- Alert frame with icon and message (directly below motto bar)
  local alertFrame = CreateFrame("Frame", nil, parent, "BackdropTemplate")
  alertFrame:SetHeight(70)
  if parent._mottoStrip then
    alertFrame:SetPoint("TOPLEFT", parent._mottoStrip, "BOTTOMLEFT", 10, -10)
    alertFrame:SetPoint("TOPRIGHT", parent._mottoStrip, "BOTTOMRIGHT", -10, -10)
  else
    alertFrame:SetPoint("TOPLEFT", 10, -10)
    alertFrame:SetPoint("TOPRIGHT", -10, -10)
  end
  alertFrame:SetBackdrop({
    bgFile = "Interface\\ChatFrame\\ChatFrameBackground",
    edgeFile = "Interface\\ChatFrame\\ChatFrameBackground",
    tile = true, tileSize = 16, edgeSize = 1,
  })
  alertFrame:SetBackdropColor(0.3, 0.1, 0.1, 0.8)
  alertFrame:SetBackdropBorderColor(0.8, 0.2, 0.2, 1)

  -- Alert icon (blue alert icon like Shade UI)
  local alertIcon = alertFrame:CreateTexture(nil, "OVERLAY")
  alertIcon:SetSize(40, 40)
  alertIcon:SetPoint("LEFT", 15, 0)
  alertIcon:SetAtlas("Crosshair_Important_128")
  alertIcon:SetVertexColor(0.4, 0.6, 1, 1)

  -- Alert text
  local alertText = alertFrame:CreateFontString(nil, "OVERLAY", "GameFontNormal")
  alertText:SetPoint("LEFT", alertIcon, "RIGHT", 12, 0)
  alertText:SetPoint("RIGHT", -15, 0)
  alertText:SetJustifyH("LEFT")
  alertText:SetWordWrap(true)
  alertText:SetText(L("coming_soon_alert"))
  alertText:SetTextColor(1, 1, 1, 1)
  alertText:SetFont(alertText:GetFont(), 13, "OUTLINE")

  local COLORS = AC.COLORS or {}

  local tabBar = CreateFrame("Frame", nil, parent)
  tabBar:SetHeight(44)
  if tabBar.SetClipsChildren then
    tabBar:SetClipsChildren(false)
  end
  tabBar:SetPoint("TOPLEFT", alertFrame, "BOTTOMLEFT", 0, -10)
  tabBar:SetPoint("TOPRIGHT", alertFrame, "BOTTOMRIGHT", 0, -10)

  local tabBorder = AC:CreateFlatTexture(tabBar, "BACKGROUND", 1, COLORS.BORDER_LIGHT, 0.6)
  tabBorder:SetAllPoints()
  local tabFill = AC:CreateFlatTexture(tabBar, "BACKGROUND", 2, COLORS.INPUT_DARK, 1)
  tabFill:SetPoint("TOPLEFT", 1, -1)
  tabFill:SetPoint("BOTTOMRIGHT", -1, 1)
  tabBorder.__acSkipThemeRefresh = true
  tabFill.__acSkipThemeRefresh = true

  local contentRoot = CreateFrame("Frame", nil, parent)
  contentRoot:SetPoint("TOPLEFT", tabBar, "BOTTOMLEFT", 0, -10)
  contentRoot:SetPoint("TOPRIGHT", tabBar, "BOTTOMRIGHT", 0, -10)
  contentRoot:SetPoint("BOTTOMLEFT", 0, 0)
  contentRoot:SetPoint("BOTTOMRIGHT", 0, 0)

  parent.__framesContentFrames = parent.__framesContentFrames or {}

  local pages = {
    { id = "enemyNames", text = L("tab_enemy_names") },
    { id = "classPortraits", text = L("tab_class_portraits") },
    { id = "classIcons", text = L("tab_class_icons") },
  }

  local activeTab = "enemyNames"
  local tabs = {}

  local function GetContentFrame(pageId)
    if parent.__framesContentFrames[pageId] then
      return parent.__framesContentFrames[pageId]
    end

    local f = CreateFrame("Frame", nil, contentRoot)
    f:SetAllPoints(contentRoot)
    f:Hide()
    parent.__framesContentFrames[pageId] = f
    return f
  end

  local function BuildEnemyNames(f)
    if f.__built then return end
    f.__built = true

    -- Arena Nameplate Customization Section
    local nameplateGroup = CreateFrame("Frame", nil, f)
    nameplateGroup:SetPoint("TOPLEFT", 12, -12)
    nameplateGroup:SetPoint("TOPRIGHT", -12, -12)
    nameplateGroup:SetHeight(200)
    AC:HairlineGroupBox(nameplateGroup)

    local nameplateTitle = AC:CreateStyledText(nameplateGroup, L("arena_nameplate_names"), 13, AC.COLORS.PRIMARY, "OVERLAY", "")
    nameplateTitle:SetPoint("TOPLEFT", 20, -18)

    -- Helper function to create dropdown (inline version from TrinketsOther.lua)
    local function CreateNameplateDropdown(parent2, label, y, path, optionsMap, defaultValue)
      local row = CreateFrame("Frame", nil, parent2)
      row:SetPoint("TOPLEFT", 20, y)
      row:SetPoint("TOPRIGHT", -20, y)
      row:SetHeight(26)

      local l = AC:CreateStyledText(row, label, 11, AC.COLORS.TEXT, "OVERLAY", "")
      l:SetPoint("LEFT", 0, 0)
      l:SetWidth(120)
      l:SetJustifyH("LEFT")

      local keys = {}
      for k in string.gmatch(path, "([^%.]+)") do
        table.insert(keys, k)
      end

      local displayOptions = {}
      local displayToValue = {}
      local valueToDisplay = {}

      for displayText, internalValue in pairs(optionsMap) do
        table.insert(displayOptions, displayText)
        displayToValue[displayText] = internalValue
        valueToDisplay[internalValue] = displayText
      end

      local function GetValue()
        local target = AC.DB.profile
        for i = 1, #keys do
          target = target and target[keys[i]]
        end
        local currentValue = target or defaultValue
        return valueToDisplay[currentValue] or displayOptions[1]
      end

      local function OnChange(displayText)
        local internalValue = displayToValue[displayText]
        local target = AC.DB.profile
        for i = 1, #keys - 1 do
          target[keys[i]] = target[keys[i]] or {}
          target = target[keys[i]]
        end
        target[keys[#keys]] = internalValue

        if AC.RefreshArenaNameplates then
          AC:RefreshArenaNameplates()
        end
      end

      local dropdown = AC:CreateFlatDropdown(row, 200, 26, displayOptions, GetValue(), OnChange)
      dropdown:SetPoint("LEFT", l, "RIGHT", 10, 0)

      return dropdown
    end

    -- Display Mode Dropdown
    CreateNameplateDropdown(nameplateGroup, L("display_mode"), -50, "arenaNameplates.mode", {
      [L("display_mode_default")] = "default",
      [L("display_mode_arena")] = "arena",
      [L("display_mode_spec")] = "spec",
      [L("display_mode_both")] = "both"
    }, "both")

    -- Helper function to create clean checkbox (matches Textures page)
    local function CreateCleanCheckbox(parent2, label, y, dbPath, onToggle)
      local row = CreateFrame("Frame", nil, parent2)
      row:SetPoint("TOPLEFT", 20, y)
      row:SetPoint("TOPRIGHT", -20, y)
      row:SetHeight(26)

      -- Get current value from database
      local keys = {}
      for k in string.gmatch(dbPath, "([^%.]+)") do
        table.insert(keys, k)
      end

      local currentValue = AC.DB.profile
      for _, key in ipairs(keys) do
        currentValue = currentValue and currentValue[key]
      end
      currentValue = currentValue or false

      local function OnChange(value)
        -- Save to database
        local target = AC.DB.profile
        for i = 1, #keys - 1 do
          target[keys[i]] = target[keys[i]] or {}
          target = target[keys[i]]
        end
        target[keys[#keys]] = value

        -- Call custom toggle function
        if onToggle then pcall(onToggle, value) end
      end

      local checkbox = AC:CreateFlatCheckbox(row, 20, currentValue, OnChange)
      checkbox:SetPoint("LEFT", 0, 0)

      local labelText = AC:CreateStyledText(row, label, 11, AC.COLORS.TEXT, "OVERLAY", "")
      labelText:SetPoint("LEFT", checkbox, "RIGHT", 8, 0)

      return row
    end

    -- Enable/Disable Checkbox
    CreateCleanCheckbox(nameplateGroup, L("enable_nameplate_customization"), -80, "arenaNameplates.enabled", function(enabled)
      if AC.RefreshArenaNameplates then
        AC:RefreshArenaNameplates()
      end
    end)

    -- Short Names Checkbox
    CreateCleanCheckbox(nameplateGroup, L("use_short_spec_names"), -110, "arenaNameplates.useShortNames", function(enabled)
      if AC.RefreshArenaNameplates then
        AC:RefreshArenaNameplates()
      end
    end)

    -- Class Colors Checkbox
    CreateCleanCheckbox(nameplateGroup, L("use_class_colors"), -140, "arenaNameplates.useClassColors", function(enabled)
      if AC.RefreshArenaNameplates then
        AC:RefreshArenaNameplates()
      end
    end)

    -- Enemy Healer Indicator Checkbox
    CreateCleanCheckbox(nameplateGroup, "Enemy Healer Indicator", -170, "arenaNameplates.showHealerIndicator", function(enabled)
      if AC.RefreshArenaNameplates then
        AC:RefreshArenaNameplates()
      end
    end)
  end

  local function BuildClassPortraits(f)
    if f.__built then return end
    f.__built = true

    local portraitsGroup = CreateFrame("Frame", nil, f)
    portraitsGroup:SetPoint("TOPLEFT", 12, -12)
    portraitsGroup:SetPoint("TOPRIGHT", -12, -12)
    portraitsGroup:SetHeight(190)
    AC:HairlineGroupBox(portraitsGroup)

    local portraitsTitle = AC:CreateStyledText(portraitsGroup, L("class_portraits"), 13, AC.COLORS.PRIMARY, "OVERLAY", "")
    portraitsTitle:SetPoint("TOPLEFT", 20, -18)

    local function EnsurePortraitDB()
      AC.DB = AC.DB or {}
      AC.DB.profile = AC.DB.profile or {}
      AC.DB.profile.classPortraitSwap = AC.DB.profile.classPortraitSwap or {}
      return AC.DB.profile.classPortraitSwap
    end

    local function RefreshPortraits()
      if AC.ClassPortraitSwap and AC.ClassPortraitSwap.RefreshAll then
        C_Timer.After(0.05, function() AC.ClassPortraitSwap:RefreshAll() end)
      end
    end

    local dbPortrait = EnsurePortraitDB()
    local enabledRow = CreateFrame("Frame", nil, portraitsGroup)
    enabledRow:SetPoint("TOPLEFT", 20, -50)
    enabledRow:SetPoint("TOPRIGHT", -20, -50)
    enabledRow:SetHeight(26)

    local enabledLabel = AC:CreateStyledText(enabledRow, L("class_portrait_swap"), 11, AC.COLORS.TEXT, "OVERLAY", "")
    enabledLabel:SetPoint("LEFT", 0, 0)

    local enabledBox = AC:CreateFlatCheckbox(enabledRow, 20, dbPortrait.enabled == true, function(value)
      local db = EnsurePortraitDB()
      db.enabled = value
      RefreshPortraits()
    end)
    enabledBox:SetPoint("RIGHT", 0, 0)

    local enabledDesc = AC:CreateStyledText(portraitsGroup, L("class_portrait_swap_desc"), 10, AC.COLORS.TEXT_MUTED, "OVERLAY", "")
    enabledDesc:SetPoint("TOPLEFT", enabledRow, "BOTTOMLEFT", 0, -8)
    enabledDesc:SetPoint("TOPRIGHT", enabledRow, "BOTTOMRIGHT", 0, -8)
    enabledDesc:SetJustifyH("LEFT")
    enabledDesc:SetWordWrap(true)

    local customRow = CreateFrame("Frame", nil, portraitsGroup)
    customRow:SetPoint("TOPLEFT", enabledDesc, "BOTTOMLEFT", 0, -10)
    customRow:SetPoint("TOPRIGHT", enabledDesc, "BOTTOMRIGHT", 0, -10)
    customRow:SetHeight(26)

    local customLabel = AC:CreateStyledText(customRow, L("use_custom_icons_portraits"), 11, AC.COLORS.TEXT, "OVERLAY", "")
    customLabel:SetPoint("LEFT", 0, 0)

    local customBox = AC:CreateFlatCheckbox(customRow, 20, dbPortrait.useCustomIcons ~= false, function(value)
      local db = EnsurePortraitDB()
      db.useCustomIcons = value
      RefreshPortraits()
    end)
    customBox:SetPoint("RIGHT", 0, 0)

    local customDesc = AC:CreateStyledText(portraitsGroup, L("use_custom_icons_portraits_desc"), 10, AC.COLORS.TEXT_MUTED, "OVERLAY", "")
    customDesc:SetPoint("TOPLEFT", customRow, "BOTTOMLEFT", 0, -8)
    customDesc:SetPoint("TOPRIGHT", customRow, "BOTTOMRIGHT", 0, -8)
    customDesc:SetJustifyH("LEFT")
    customDesc:SetWordWrap(true)
  end

  local function BuildClassIcons(f)
    if f.__built then return end
    f.__built = true

    if not AC.DB or not AC.DB.profile then
      AC:EnsureDB()
    end

    AC.DB.profile.moreGoodies = AC.DB.profile.moreGoodies or {}
    AC.DB.profile.moreGoodies.partyClassSpecs = AC.DB.profile.moreGoodies.partyClassSpecs or {
      mode = "off",
      scale = 100,
      showHealerIcon = true,
      hideHealthBars = false,
      showPointers = true,
    }

    local db = AC.DB.profile.moreGoodies
    local partyClassDb = db.partyClassSpecs

    local group = CreateFrame("Frame", nil, f)
    group:SetPoint("TOPLEFT", 12, -12)
    group:SetPoint("TOPRIGHT", -12, -12)
    group:SetHeight(870)
    AC:HairlineGroupBox(group)

    local title = AC:CreateStyledText(group, L("class_icons"), 13, AC.COLORS.PRIMARY, "OVERLAY", "")
    title:SetPoint("TOPLEFT", 20, -18)

    -- Dropdown row (copied behavior from MoreGoodies page)
    do
      local row = CreateFrame("Frame", nil, group)
      row:SetPoint("TOPLEFT", 20, -50)
      row:SetPoint("TOPRIGHT", -20, -50)
      row:SetHeight(26)

      local l = AC:CreateStyledText(row, L("party_class_icons"), 11, AC.COLORS.TEXT_2, "OVERLAY", "")
      l:SetPoint("LEFT", 0, 0)
      l:SetWidth(120)
      l:SetJustifyH("LEFT")

      local optionTexts = { L("off"), L("party_members"), L("all_players"), L("only_arena") }
      local textToValue = {
        [L("off")] = "off",
        [L("party_members")] = "party",
        [L("all_players")] = "all",
        [L("only_arena")] = "arena",
      }
      local valueToText = {
        off = L("off"),
        party = L("party_members"),
        all = L("all_players"),
        arena = L("only_arena"),
      }

      local function GetValue()
        return valueToText[partyClassDb.mode or "off"] or "Off"
      end

      local function OnChange(selectedText)
        local value = textToValue[selectedText] or "off"
        partyClassDb.mode = value

        _G.ArenaCoreDB = AC.DB

        do
          local sv = _G.ArenaCoreDB
          local profileName = sv and sv.profileSettings and sv.profileSettings.currentProfile
          local stored = profileName and sv and sv.profiles and sv.profiles[profileName]
          if stored and type(stored) == "table" then
            stored.moreGoodies = stored.moreGoodies or {}
            stored.moreGoodies.partyClassSpecs = stored.moreGoodies.partyClassSpecs or {}
            stored.moreGoodies.partyClassSpecs.mode = value
          end
        end

        if value == "off" then
          print("|cff8B45FFArena Core:|r Party class indicators disabled.")
        elseif value == "party" then
          print("|cff8B45FFArena Core:|r Party class indicators enabled for party members.")
        elseif value == "all" then
          print("|cff8B45FFArena Core:|r Party class indicators enabled for all players.")
        elseif value == "arena" then
          print("|cff8B45FFArena Core:|r Party class indicators enabled for Arena/BG only.")
        end

        C_Timer.After(0.1, function()
          if AC.RefreshPartyClassIcons then
            AC:RefreshPartyClassIcons()
          end
        end)
        C_Timer.After(0.5, function()
          if AC.RefreshPartyClassIcons then
            AC:RefreshPartyClassIcons()
          end
        end)
      end

      local dropdown = AC:CreateFlatDropdown(row, 150, 24, optionTexts, GetValue(), OnChange)
      dropdown:SetPoint("LEFT", l, "RIGHT", 10, 0)
    end

    local partyDescText = AC:CreateStyledText(group, L("party_class_icons_desc"), 10, AC.COLORS.TEXT_MUTED, "OVERLAY", "")
    partyDescText:SetPoint("TOPLEFT", 20, -78)
    partyDescText:SetPoint("TOPRIGHT", -20, -78)
    partyDescText:SetJustifyH("LEFT")
    partyDescText:SetWordWrap(true)

    -- Use Custom Icons
    local useCustomLabel = AC:CreateStyledText(group, L("use_custom_icons_class"), 12, AC.COLORS.TEXT_2, "OVERLAY", "")
    useCustomLabel:SetPoint("TOPLEFT", 20, -105)

    local useCustomCheckbox = AC:CreateFlatCheckbox(group, 20, partyClassDb.useCustomIcons == true, function(value)
      partyClassDb.useCustomIcons = value
      if value and partyClassDb.useSpecIcons then
        partyClassDb.useSpecIcons = false
        if specIconsCheckbox then specIconsCheckbox:SetChecked(false) end
      end
      if AC.RefreshPartyClassIcons then
        AC:RefreshPartyClassIcons()
      end
      if value then
        print("|cff8B45FFArena Core:|r Party class icons now using ArenaCore custom icons")
      else
        print("|cff8B45FFArena Core:|r Party class icons now using theme icons (Midnight Chill/etc)")
      end
    end)
    useCustomCheckbox:SetPoint("TOPRIGHT", -25, -105)

    local useCustomDesc = AC:CreateStyledText(group, L("use_custom_icons_class_desc"), 10, AC.COLORS.TEXT_MUTED, "OVERLAY", "")
    useCustomDesc:SetPoint("TOPLEFT", 20, -130)
    useCustomDesc:SetPoint("TOPRIGHT", -20, -130)
    useCustomDesc:SetJustifyH("LEFT")
    useCustomDesc:SetWordWrap(true)

    -- Use Spec Icons Instead (mutually exclusive with custom icons)
    local specIconsLabel = AC:CreateStyledText(group, L("use_spec_icons_instead"), 12, AC.COLORS.TEXT_2, "OVERLAY", "")
    specIconsLabel:SetPoint("TOPLEFT", 20, -155)

    local specIconsCheckbox = AC:CreateFlatCheckbox(group, 20, partyClassDb.useSpecIcons == true, function(value)
      partyClassDb.useSpecIcons = value
      if value and partyClassDb.useCustomIcons then
        partyClassDb.useCustomIcons = false
        if useCustomCheckbox then useCustomCheckbox:SetChecked(false) end
      end
      if value and AC.PartyClassIndicators and AC.PartyClassIndicators.PreCacheGroupSpecs then
        AC.PartyClassIndicators.PreCacheGroupSpecs()
      end
      if AC.RefreshPartyClassIcons then
        AC:RefreshPartyClassIcons()
      end
      if value then
        print("|cff8B45FFArena Core:|r Party class icons now using in-game spec icons")
      else
        print("|cff8B45FFArena Core:|r Spec icons disabled")
      end
    end)
    specIconsCheckbox:SetPoint("TOPRIGHT", -25, -155)

    local specIconsDesc = AC:CreateStyledText(group, L("use_spec_icons_instead_desc"), 10, AC.COLORS.TEXT_MUTED, "OVERLAY", "")
    specIconsDesc:SetPoint("TOPLEFT", 20, -180)
    specIconsDesc:SetPoint("TOPRIGHT", -20, -180)
    specIconsDesc:SetJustifyH("LEFT")
    specIconsDesc:SetWordWrap(true)

    -- Turn OFF Targetting Glow
    local disableTargetGlowLabel = AC:CreateStyledText(group, "Turn OFF Targetting Glow", 12, AC.COLORS.TEXT_2, "OVERLAY", "")
    disableTargetGlowLabel:SetPoint("TOPLEFT", 20, -205)

    local disableTargetGlowCheckbox = AC:CreateFlatCheckbox(group, 20, partyClassDb.disableTargetGlow == true, function(value)
      partyClassDb.disableTargetGlow = value
      if AC.RefreshPartyClassIcons then
        AC:RefreshPartyClassIcons()
      end
      if value then
        print("|cff8B45FFArena Core:|r Target glow disabled - party class icons will no longer pulse on target")
      else
        print("|cff8B45FFArena Core:|r Target glow enabled - party class icons will pulse on target")
      end
    end)
    disableTargetGlowCheckbox:SetPoint("TOPRIGHT", -25, -205)

    local disableTargetGlowDesc = AC:CreateStyledText(group, "When enabled, disables the orange outline glow on the class icon of your current target.", 10, AC.COLORS.TEXT_MUTED, "OVERLAY", "")
    disableTargetGlowDesc:SetPoint("TOPLEFT", 20, -230)
    disableTargetGlowDesc:SetPoint("TOPRIGHT", -20, -230)
    disableTargetGlowDesc:SetJustifyH("LEFT")
    disableTargetGlowDesc:SetWordWrap(true)

    -- Where's My Healer
    local healerLabel = AC:CreateStyledText(group, L("wheres_my_healer"), 12, AC.COLORS.TEXT_2, "OVERLAY", "")
    healerLabel:SetPoint("TOPLEFT", 20, -255)

    local healerCheckbox = AC:CreateFlatCheckbox(group, 20, partyClassDb.showHealerIcon ~= false, function(value)
      partyClassDb.showHealerIcon = value
      if AC.RefreshPartyClassIcons then
        AC:RefreshPartyClassIcons()
      end
      if value then
        print("|cff8B45FFArena Core:|r Where's My Healer enabled - friendly team healers will show special icons!")
      else
        print("|cff8B45FFArena Core:|r Where's My Healer disabled - showing normal class icons")
      end
    end)
    healerCheckbox:SetPoint("TOPRIGHT", -25, -255)

    local healerDescText = AC:CreateStyledText(group, L("wheres_my_healer_desc"), 10, AC.COLORS.TEXT_MUTED, "OVERLAY", "")
    healerDescText:SetPoint("TOPLEFT", 20, -280)
    healerDescText:SetPoint("TOPRIGHT", -20, -280)
    healerDescText:SetJustifyH("LEFT")
    healerDescText:SetWordWrap(true)

    -- Hide Friendly Health Bars
    local hideHealthLabel = AC:CreateStyledText(group, L("hide_friendly_health_bars"), 12, AC.COLORS.TEXT_2, "OVERLAY", "")
    hideHealthLabel:SetPoint("TOPLEFT", 20, -325)

    local hideHealthCheckbox = AC:CreateFlatCheckbox(group, 20, partyClassDb.hideHealthBars == true, function(value)
      partyClassDb.hideHealthBars = value
      if AC.RefreshPartyClassIcons then
        AC:RefreshPartyClassIcons()
      end
      if value then
        print("|cff8B45FFArena Core:|r Friendly health bars hidden - only class icons visible!")
      else
        print("|cff8B45FFArena Core:|r Friendly health bars restored")
      end
    end)
    hideHealthCheckbox:SetPoint("TOPRIGHT", -25, -325)

    local hideHealthDesc = AC:CreateStyledText(group, L("hide_friendly_health_bars_desc"), 10, AC.COLORS.TEXT_MUTED, "OVERLAY", "")
    hideHealthDesc:SetPoint("TOPLEFT", 20, -350)
    hideHealthDesc:SetPoint("TOPRIGHT", -20, -350)
    hideHealthDesc:SetJustifyH("LEFT")
    hideHealthDesc:SetWordWrap(true)

    -- Show Pointers
    local showPointersLabel = AC:CreateStyledText(group, L("show_pointers"), 12, AC.COLORS.TEXT_2, "OVERLAY", "")
    showPointersLabel:SetPoint("TOPLEFT", 20, -390)

    local showPointersCheckbox = AC:CreateFlatCheckbox(group, 20, partyClassDb.showPointers ~= false, function(value)
      partyClassDb.showPointers = value
      if AC.RefreshPartyClassIcons then
        AC:RefreshPartyClassIcons()
      end
      if value then
        print("|cff8B45FFArena Core:|r Pointers enabled - triangle arrows will show above players!")
      else
        print("|cff8B45FFArena Core:|r Pointers disabled")
      end
    end)
    showPointersCheckbox:SetPoint("TOPRIGHT", -25, -390)

    local showPointersDesc = AC:CreateStyledText(group, L("show_pointers_desc"), 10, AC.COLORS.TEXT_MUTED, "OVERLAY", "")
    showPointersDesc:SetPoint("TOPLEFT", 20, -415)
    showPointersDesc:SetPoint("TOPRIGHT", -20, -415)
    showPointersDesc:SetJustifyH("LEFT")
    showPointersDesc:SetWordWrap(true)

    -- Class Color Borders
    local classColorBordersLabel = AC:CreateStyledText(group, "Class Color Borders", 12, AC.COLORS.TEXT_2, "OVERLAY", "")
    classColorBordersLabel:SetPoint("TOPLEFT", 20, -440)

    local classColorBordersCheckbox = AC:CreateFlatCheckbox(group, 20, partyClassDb.useClassColorBorders == true, function(value)
      partyClassDb.useClassColorBorders = value
      if AC.RefreshPartyClassIcons then
        AC:RefreshPartyClassIcons()
      end
      if value then
        print("|cff8B45FFArena Core:|r Class color borders enabled - borders will match class colors!")
      else
        print("|cff8B45FFArena Core:|r Class color borders disabled - using orange borders")
      end
    end)
    classColorBordersCheckbox:SetPoint("TOPRIGHT", -25, -440)

    local classColorBordersDesc = AC:CreateStyledText(group, "When enabled, class icon borders will use the class color instead of orange.", 10, AC.COLORS.TEXT_MUTED, "OVERLAY", "")
    classColorBordersDesc:SetPoint("TOPLEFT", 20, -465)
    classColorBordersDesc:SetPoint("TOPRIGHT", -20, -465)
    classColorBordersDesc:SetJustifyH("LEFT")
    classColorBordersDesc:SetWordWrap(true)

    -- CLASS ICON SETTINGS
    local classIconTitle = AC:CreateStyledText(group, L("class_icon_settings"), 12, AC.COLORS.PRIMARY, "OVERLAY", "")
    classIconTitle:SetPoint("TOPLEFT", 20, -490)

    AC:CreateEnhancedSliderRow(
      group,
      L("scale"),
      -515,
      "moreGoodies.partyClassSpecs.scale",
      "sizing_scale",
      { scaleMin = 1, scaleMax = 12, pixelMin = 50, pixelMax = 360, isPercent = true,
        tooltip = "Scales the party class icons and their visuals. 1 = smallest, 12 = extra large." }
    )

    AC:CreateEnhancedSliderRow(
      group,
      L("horizontal"),
      -540,
      "moreGoodies.partyClassSpecs.offsetX",
      "direct_pixel_offset",
      { scaleMin = -100, scaleMax = 100, pixelMin = -100, pixelMax = 100, valueStep = 1,
        tooltip = "Horizontal offset in pixels. 0 = centered above player." }
    )

    AC:CreateEnhancedSliderRow(
      group,
      L("vertical"),
      -565,
      "moreGoodies.partyClassSpecs.offsetY",
      "direct_pixel_offset",
      { scaleMin = -100, scaleMax = 100, pixelMin = -100, pixelMax = 100, valueStep = 1,
        tooltip = "Vertical offset in pixels. 0 = default height above player." }
    )

    -- POINTER SETTINGS
    local pointerTitle = AC:CreateStyledText(group, L("pointer_settings"), 12, AC.COLORS.PRIMARY, "OVERLAY", "")
    pointerTitle:SetPoint("TOPLEFT", 20, -600)

    local linkHorizLabel = AC:CreateStyledText(group, L("link_horizontal"), 12, AC.COLORS.TEXT_2, "OVERLAY", "")
    linkHorizLabel:SetPoint("TOPLEFT", 20, -622)

    local linkHorizCheckbox = AC:CreateFlatCheckbox(group, 20, partyClassDb.linkHorizontal == true, function(value)
      partyClassDb.linkHorizontal = value

      C_Timer.After(0.05, function()
        local ptrSlider = AC.sliderWidgets and AC.sliderWidgets["moreGoodies.partyClassSpecs.pointerOffsetX"]
        if ptrSlider then
          if value then
            local classOffsetX = partyClassDb.offsetX or 0
            partyClassDb.pointerOffsetX = classOffsetX
            ptrSlider:SetValue(classOffsetX)
            ptrSlider:SetAlpha(0.4)
            ptrSlider:EnableMouse(false)
            if ptrSlider.minusBtn then ptrSlider.minusBtn:EnableMouse(false) end
            if ptrSlider.plusBtn then ptrSlider.plusBtn:EnableMouse(false) end
            if ptrSlider.editBox then ptrSlider.editBox:EnableMouse(false) end
          else
            ptrSlider:SetAlpha(1.0)
            ptrSlider:EnableMouse(true)
            if ptrSlider.minusBtn then ptrSlider.minusBtn:EnableMouse(true) end
            if ptrSlider.plusBtn then ptrSlider.plusBtn:EnableMouse(true) end
            if ptrSlider.editBox then ptrSlider.editBox:EnableMouse(true) end
          end
        end
      end)

      if AC.RefreshPointersOnly then AC:RefreshPointersOnly() end
    end)
    linkHorizCheckbox:SetPoint("TOPRIGHT", -25, -622)

    local linkHorizDesc = AC:CreateStyledText(group, L("link_horizontal_desc"), 10, AC.COLORS.TEXT_MUTED, "OVERLAY", "")
    linkHorizDesc:SetPoint("TOPLEFT", 20, -642)
    linkHorizDesc:SetPoint("TOPRIGHT", -20, -642)
    linkHorizDesc:SetJustifyH("LEFT")
    linkHorizDesc:SetWordWrap(true)

    AC:CreateEnhancedSliderRow(
      group,
      L("pointer_scale"),
      -675,
      "moreGoodies.partyClassSpecs.pointerScale",
      "sizing_scale",
      { scaleMin = 1, scaleMax = 12, pixelMin = 50, pixelMax = 360, isPercent = true,
        tooltip = "Scales the triangle pointer arrows. 1 = smallest, 12 = extra large." }
    )

    AC:CreateEnhancedSliderRow(
      group,
      L("pointer_horizontal"),
      -700,
      "moreGoodies.partyClassSpecs.pointerOffsetX",
      "direct_pixel_offset",
      { scaleMin = -100, scaleMax = 100, pixelMin = -100, pixelMax = 100, valueStep = 1,
        tooltip = "Horizontal offset in pixels. 0 = centered. (Ignored when Link Horizontal is on)" }
    )

    AC:CreateEnhancedSliderRow(
      group,
      L("pointer_vertical"),
      -725,
      "moreGoodies.partyClassSpecs.pointerOffsetY",
      "direct_pixel_offset",
      { scaleMin = -100, scaleMax = 100, pixelMin = -100, pixelMax = 100, valueStep = 1,
        tooltip = "Vertical offset in pixels. 0 = default height above class icon." }
    )

    C_Timer.After(0.1, function()
      if AC.sliderWidgets then
        local hookClassIconOnly = function(sl)
          if sl and sl.HookScript then
            sl:HookScript("OnValueChanged", function()
              if AC.RefreshClassIconsOnly then AC:RefreshClassIconsOnly() end
            end)
          end
        end

        local hookClassIconHorizontal = function(sl)
          if sl and sl.HookScript then
            sl:HookScript("OnValueChanged", function(self, value)
              if AC.RefreshClassIconsOnly then AC:RefreshClassIconsOnly() end
              if partyClassDb.linkHorizontal then
                partyClassDb.pointerOffsetX = value
                local ptrSlider = AC.sliderWidgets["moreGoodies.partyClassSpecs.pointerOffsetX"]
                if ptrSlider and ptrSlider.SetValue then
                  ptrSlider:SetValue(value)
                end
                if AC.RefreshPointersOnly then AC:RefreshPointersOnly() end
              end
            end)
          end
        end

        local hookPointer = function(sl)
          if sl and sl.HookScript then
            sl:HookScript("OnValueChanged", function()
              if AC.RefreshPointersOnly then AC:RefreshPointersOnly() end
            end)
          end
        end

        hookClassIconOnly(AC.sliderWidgets["moreGoodies.partyClassSpecs.scale"])
        hookClassIconHorizontal(AC.sliderWidgets["moreGoodies.partyClassSpecs.offsetX"])
        hookClassIconOnly(AC.sliderWidgets["moreGoodies.partyClassSpecs.offsetY"])

        hookPointer(AC.sliderWidgets["moreGoodies.partyClassSpecs.pointerScale"])
        hookPointer(AC.sliderWidgets["moreGoodies.partyClassSpecs.pointerOffsetX"])
        hookPointer(AC.sliderWidgets["moreGoodies.partyClassSpecs.pointerOffsetY"])

        if partyClassDb.linkHorizontal then
          local ptrSlider = AC.sliderWidgets["moreGoodies.partyClassSpecs.pointerOffsetX"]
          if ptrSlider then
            ptrSlider:SetAlpha(0.4)
            ptrSlider:EnableMouse(false)
            if ptrSlider.minusBtn then ptrSlider.minusBtn:EnableMouse(false) end
            if ptrSlider.plusBtn then ptrSlider.plusBtn:EnableMouse(false) end
            if ptrSlider.editBox then ptrSlider.editBox:EnableMouse(false) end
          end
        end
      end
    end)
  end

  
  local function ShowSubPage(pageId)
    activeTab = pageId

    for _, page in ipairs(pages) do
      local f = GetContentFrame(page.id)
      f:Hide()
    end

    for _, tab in ipairs(tabs) do
      tab:SetSelected(tab.pageId == pageId)
    end

    local f = GetContentFrame(pageId)
    f:Show()

    if pageId == "enemyNames" then
      BuildEnemyNames(f)
    elseif pageId == "classPortraits" then
      BuildClassPortraits(f)
    elseif pageId == "classIcons" then
      BuildClassIcons(f)
    end
  end

  local x = 12
  for _, page in ipairs(pages) do
    local btn = CreateFramesSubTabButton(tabBar, page.text, 120, 26)
    btn:SetPoint("LEFT", tabBar, "LEFT", x, 0)
    btn.pageId = page.id
    btn:SetScript("OnClick", function()
      ShowSubPage(page.id)
    end)
    table.insert(tabs, btn)
    x = x + 120 + 8
  end

  ShowSubPage(activeTab)

  return parent
end

-- Register the page with the AC system
AC:RegisterPage("frames", function(parent)
  return AC:CreateFramesPage(parent)
end)
