-- =============================================================================
-- 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



-- =============================================================================
-- 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
    }
  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 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("More Features coming soon, working on experimenting things we can still do and ensure it is done properly.")
  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 = "Enemy Names" },
    { id = "classPortraits", text = "Class Portraits" },
    { id = "classIcons", text = "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(170)
    AC:HairlineGroupBox(nameplateGroup)

    local nameplateTitle = AC:CreateStyledText(nameplateGroup, "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, "Display Mode:", -50, "arenaNameplates.mode", {
      ["Player Name (Default)"] = "default",
      ["Arena Number (1/2/3)"] = "arena",
      ["Spec Name"] = "spec",
      ["Spec + Arena Number"] = "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, "Enable Arena Nameplate Customization", -80, "arenaNameplates.enabled", function(enabled)
      if AC.RefreshArenaNameplates then
        AC:RefreshArenaNameplates()
      end
    end)

    -- Short Names Checkbox
    CreateCleanCheckbox(nameplateGroup, "Use Short Spec Names (Aff, Ret, Sub)", -110, "arenaNameplates.useShortNames", function(enabled)
      if AC.RefreshArenaNameplates then
        AC:RefreshArenaNameplates()
      end
    end)

    -- Class Colors Checkbox
    CreateCleanCheckbox(nameplateGroup, "Use Class Colors", -140, "arenaNameplates.useClassColors", 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, "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, "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, "Swap all player portraits to class icons.", 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, "Use Arena Core Custom Icons", 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, "When checked, uses original ArenaCore custom icons. When unchecked, uses alternate theme icons (Midnight Chill, etc).", 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(780)
    AC:HairlineGroupBox(group)

    local title = AC:CreateStyledText(group, "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, "Party Class Icons", 11, AC.COLORS.TEXT_2, "OVERLAY", "")
      l:SetPoint("LEFT", 0, 0)
      l:SetWidth(120)
      l:SetJustifyH("LEFT")

      local optionTexts = { "Off", "Party Members", "All Players" }
      local textToValue = {
        ["Off"] = "off",
        ["Party Members"] = "party",
        ["All Players"] = "all",
      }
      local valueToText = {
        off = "Off",
        party = "Party Members",
        all = "All Players",
      }

      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.")
        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, "Shows class icons above players' heads using custom class icons", 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, "Use Arena Core Custom Icons", 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 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, "When checked, uses original ArenaCore custom icons. When unchecked, uses alternate theme icons (Midnight Chill, etc).", 10, AC.COLORS.TEXT_MUTED, "OVERLAY", "")
    useCustomDesc:SetPoint("TOPLEFT", 20, -130)
    useCustomDesc:SetPoint("TOPRIGHT", -20, -130)
    useCustomDesc:SetJustifyH("LEFT")
    useCustomDesc:SetWordWrap(true)

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

    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, -165)

    local healerDescText = AC:CreateStyledText(group, "Shows a custom Arena Core healer icon ONLY for your team's healers (not enemies). If you ARE the healer, this feature does nothing to avoid confusion.", 10, AC.COLORS.TEXT_MUTED, "OVERLAY", "")
    healerDescText:SetPoint("TOPLEFT", 20, -190)
    healerDescText:SetPoint("TOPRIGHT", -20, -190)
    healerDescText:SetJustifyH("LEFT")
    healerDescText:SetWordWrap(true)

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

    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, -235)

    local hideHealthDesc = AC:CreateStyledText(group, "Hides friendly nameplate health bars while keeping class icons visible. Friendly nameplates must be enabled in WoW settings.", 10, AC.COLORS.TEXT_MUTED, "OVERLAY", "")
    hideHealthDesc:SetPoint("TOPLEFT", 20, -260)
    hideHealthDesc:SetPoint("TOPRIGHT", -20, -260)
    hideHealthDesc:SetJustifyH("LEFT")
    hideHealthDesc:SetWordWrap(true)

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

    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, -300)

    local showPointersDesc = AC:CreateStyledText(group, "Shows class color party pointers above players' heads using custom icons", 10, AC.COLORS.TEXT_MUTED, "OVERLAY", "")
    showPointersDesc:SetPoint("TOPLEFT", 20, -325)
    showPointersDesc:SetPoint("TOPRIGHT", -20, -325)
    showPointersDesc:SetJustifyH("LEFT")
    showPointersDesc:SetWordWrap(true)

    -- CLASS ICON SETTINGS
    local classIconTitle = AC:CreateStyledText(group, "Class Icon Settings", 12, AC.COLORS.PRIMARY, "OVERLAY", "")
    classIconTitle:SetPoint("TOPLEFT", 20, -360)

    AC:CreateEnhancedSliderRow(
      group,
      "Scale",
      -385,
      "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,
      "Horizontal",
      -410,
      "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,
      "Vertical",
      -435,
      "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, "Pointer Settings", 12, AC.COLORS.PRIMARY, "OVERLAY", "")
    pointerTitle:SetPoint("TOPLEFT", 20, -470)

    local linkHorizLabel = AC:CreateStyledText(group, "Link Horizontal", 12, AC.COLORS.TEXT_2, "OVERLAY", "")
    linkHorizLabel:SetPoint("TOPLEFT", 20, -492)

    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, -492)

    local linkHorizDesc = AC:CreateStyledText(group, "When ON, Class Icon Horizontal controls both. Pointer slider is disabled.", 10, AC.COLORS.TEXT_MUTED, "OVERLAY", "")
    linkHorizDesc:SetPoint("TOPLEFT", 20, -512)
    linkHorizDesc:SetPoint("TOPRIGHT", -20, -512)
    linkHorizDesc:SetJustifyH("LEFT")
    linkHorizDesc:SetWordWrap(true)

    AC:CreateEnhancedSliderRow(
      group,
      "Pointer Scale",
      -545,
      "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,
      "Pointer Horizontal",
      -570,
      "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,
      "Pointer Vertical",
      -595,
      "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)
