-- =========================================================================
-- STAGING: New BuildSettingsView (Part 1 of 2)
-- =========================================================================

function GR:BuildSettingsView()
    if not self.db then self.db = {} end
    if not self.db.theme then self.db.theme = {} end
    local d = self.db.theme
    if not d.header then d.header = {r=0.1, g=0.1, b=0.2, a=1} end
    if not d.background then d.background = {r=0.05, g=0.05, b=0.05, a=0.95} end
    if not d.buttons then d.buttons = {r=0.2, g=0.2, b=0.2, a=1} end

    local parent = CreateFrame("Frame", "GRS_SettingsView", self.ViewContainer)
    parent:SetAllPoints(); parent:Hide(); self.views[7] = parent

    local function UpdateLiveTheme() GR:ApplyTheme(nil) end

    -- =================================================================
    -- HELPER: Nav Button (black bg, white label, gold active border)
    -- =================================================================
    local function CreateNavButton(parentFrame, label, yOffset)
        local btn = CreateFrame("Button", nil, parentFrame)
        btn:SetSize(225, 30); btn:SetPoint("TOPLEFT", 10, yOffset)
        btn:SetNormalTexture(""); btn:SetHighlightTexture(""); btn:SetPushedTexture("")
        local bg = btn:CreateTexture(nil, "BORDER"); bg:SetAllPoints(); bg:SetColorTexture(0, 0, 0, 1); btn.bg = bg
        local brd = btn:CreateTexture(nil, "BACKGROUND"); brd:SetPoint("TOPLEFT", -1, 1); brd:SetPoint("BOTTOMRIGHT", 1, -1); brd:SetColorTexture(0.3, 0.3, 0.3, 1); btn.brd = brd
        local txt = btn:CreateFontString(nil, "OVERLAY", "GameFontNormal"); txt:SetPoint("LEFT", 10, 0); txt:SetText(label); txt:SetTextColor(1, 1, 1); btn.label = txt
        btn.isActive = false
        btn:SetScript("OnEnter", function(s) if not s.isActive and s.bg then s.bg:SetColorTexture(0.2, 0.2, 0.2, 1) end end)
        btn:SetScript("OnLeave", function(s) if not s.isActive and s.bg then s.bg:SetColorTexture(0, 0, 0, 1) end end)
        return btn
    end

    -- =================================================================
    -- HELPER: Option Pane (title + description, inside a scroll canvas)
    -- =================================================================
    local function CreateOptionPane(canvas, yOffset, title, description, paneHeight)
        local pane = CreateFrame("Frame", nil, canvas)
        pane:SetPoint("TOPLEFT", 10, yOffset); pane:SetPoint("RIGHT", canvas, "RIGHT", -10, 0)
        pane:SetHeight(paneHeight or 70)
        SafeCreateBg(pane, 0.08, 0.08, 0.08, 0.7); SafeCreateBorder(pane, 0.2, 0.2, 0.2, 1)
        local t = pane:CreateFontString(nil, "OVERLAY", "GameFontNormal"); t:SetPoint("TOPLEFT", 10, -8); t:SetText(title); pane.title = t
        if description then
            local dc = pane:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall"); dc:SetPoint("TOPLEFT", 10, -26); dc:SetPoint("RIGHT", pane, "RIGHT", -50, 0); dc:SetJustifyH("LEFT"); dc:SetText(description); dc:SetTextColor(0.6, 0.6, 0.6); pane.desc = dc
        end
        return pane
    end

    -- =================================================================
    -- HELPER: Scrollable Sub-Page
    -- =================================================================
    local function CreateSubPage(parentFrame)
        local page = CreateFrame("Frame", nil, parentFrame); page:SetAllPoints(); page:Hide()
        local scroll = CreateFrame("ScrollFrame", nil, page, "UIPanelScrollFrameTemplate")
        scroll:SetPoint("TOPLEFT", 5, -5); scroll:SetPoint("BOTTOMRIGHT", -28, 5)
        if NS.StyleScrollBar then NS.StyleScrollBar(scroll) end
        local canvas = CreateFrame("Frame", nil, scroll); canvas:SetWidth(750); canvas:SetHeight(600)
        scroll:SetScrollChild(canvas)
        scroll:SetScript("OnSizeChanged", function(self, w) canvas:SetWidth(w) end)
        page.scroll = scroll; page.canvas = canvas
        return page
    end

    -- =================================================================
    -- LEFT SIDEBAR (245px)
    -- =================================================================
    local sidebar = CreateFrame("Frame", nil, parent)
    sidebar:SetWidth(245); sidebar:SetPoint("TOPLEFT", 0, -30); sidebar:SetPoint("BOTTOMLEFT", 0, 0)
    SafeCreateBg(sidebar, 0.05, 0.05, 0.05, 0.95); SafeCreateBorder(sidebar, 0.2, 0.2, 0.2, 1)

    -- =================================================================
    -- CENTER PANEL
    -- =================================================================
    local center = CreateFrame("Frame", nil, parent)
    center:SetPoint("TOPLEFT", sidebar, "TOPRIGHT", 0, 0); center:SetPoint("BOTTOMRIGHT", 0, 0)
    SafeCreateBg(center, 0.06, 0.06, 0.06, 0.9)
    self.SettingsCanvas = center

    -- =================================================================
    -- CREATE 6 SUB-PAGES
    -- =================================================================
    local pages = {}
    for i = 1, 6 do pages[i] = CreateSubPage(center) end

    -- =================================================================
    -- NAV BUTTONS
    -- =================================================================
    local categories = {
        NS.L["GENERAL_SETTINGS"] or "General Settings",
        NS.L["UI_MODE"] or "UI Mode",
        NS.L["APPEARANCES"] or "Appearances",
        NS.L["TOOLS"] or "Tools",
        NS.L["LANGUAGE"] or "Language",
        NS.L["ADVANCED"] or "Advanced",
    }
    local navBtns = {}
    local function SelectCategory(index)
        for i = 1, 6 do
            if i == index then
                pages[i]:Show(); navBtns[i].isActive = true
                navBtns[i].bg:SetColorTexture(0.15, 0.15, 0.15, 1); navBtns[i].brd:SetColorTexture(0.8, 0.6, 0, 1)
            else
                pages[i]:Hide(); navBtns[i].isActive = false
                navBtns[i].bg:SetColorTexture(0, 0, 0, 1); navBtns[i].brd:SetColorTexture(0.3, 0.3, 0.3, 1)
            end
        end
    end
    for i, cat in ipairs(categories) do
        local btn = CreateNavButton(sidebar, cat, -15 - ((i - 1) * 40))
        btn:SetScript("OnClick", function() SelectCategory(i) end)
        navBtns[i] = btn
    end

    -- =================================================================
    -- PAGE 1: GENERAL SETTINGS
    -- =================================================================
    do
        local c = pages[1].canvas; local y = -10
        local p1 = CreateOptionPane(c, y, NS.L["MINIMAP_BUTTON"] or "Minimap Button", "Show or hide the A.X.I.O.M. minimap icon. When hidden, use /axiom to open.", 70)
        local chk = CreateFrame("CheckButton", "GRS_Set_Minimap", p1, "UICheckButtonTemplate"); chk:SetSize(24, 24); chk:SetPoint("TOPRIGHT", -10, -8)
        chk:SetChecked(self.db.minimapShown ~= false)
        chk:SetScript("OnClick", function(cb) GR.db.minimapShown = cb:GetChecked(); if _G["GRS_MinimapButton"] then if GR.db.minimapShown then _G["GRS_MinimapButton"]:Show() else _G["GRS_MinimapButton"]:Hide() end end end)
        y = y - 75

        local p2 = CreateOptionPane(c, y, NS.L["AUTO_OPEN"] or "Auto-Open on Login", "Whether the addon window shows automatically when you log in to your character.", 70)
        local chk2 = CreateFrame("CheckButton", "GRS_Set_AutoOpen", p2, "UICheckButtonTemplate"); chk2:SetSize(24, 24); chk2:SetPoint("TOPRIGHT", -10, -8)
        chk2:SetChecked(self.db.autoOpen or false)
        chk2:SetScript("OnClick", function(cb) GR.db.autoOpen = cb:GetChecked() end)
        y = y - 75

        local p3 = CreateOptionPane(c, y, NS.L["DEFAULT_TAB"] or "Default Tab on Open", "Which view the addon lands on when opened (Home, Blacklist, Roster, etc.).", 70)
        local tabNames = {}
        for _, tab in ipairs(NS.Constants.TABS) do if tab.id ~= 7 and tab.id ~= 8 then tabNames[#tabNames + 1] = { id = tab.id, label = NS.GetTabTitle(tab) } end end
        if not self.db.defaultTab then self.db.defaultTab = 1 end
        local defLabel = p3:CreateFontString(nil, "OVERLAY", "GameFontHighlight"); defLabel:SetPoint("TOPRIGHT", -40, -10)
        local function UpdateDefLabel() for _, t in ipairs(tabNames) do if t.id == GR.db.defaultTab then defLabel:SetText(t.label); return end end; defLabel:SetText(tabNames[1] and tabNames[1].label or "Home") end
        UpdateDefLabel()
        local btnCyc = CreateFrame("Button", nil, p3, "UIPanelButtonTemplate"); btnCyc:SetSize(24, 24); btnCyc:SetPoint("TOPRIGHT", -10, -8); btnCyc:SetText(">"); SafeSkinButton(btnCyc)
        btnCyc:SetScript("OnClick", function() local idx = 1; for i, t in ipairs(tabNames) do if t.id == GR.db.defaultTab then idx = i; break end end; idx = idx + 1; if idx > #tabNames then idx = 1 end; GR.db.defaultTab = tabNames[idx].id; UpdateDefLabel() end)
        y = y - 75

        local p4 = CreateOptionPane(c, y, NS.L["LEVEL_RANGE"] or "Level Range Defaults", "Default minimum and maximum level range used for recruitment scans.", 90)
        local lblMin = p4:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall"); lblMin:SetPoint("TOPLEFT", 10, -50); lblMin:SetText("Min: " .. (self.db.levelMin or 1))
        local sMin = CreateFrame("Slider", "GRS_Set_LvlMin", p4, "OptionsSliderTemplate"); sMin:SetPoint("TOPLEFT", 60, -48); sMin:SetWidth(260); sMin:SetMinMaxValues(1, 80); sMin:SetValueStep(1); sMin:SetObeyStepOnDrag(true); sMin:SetValue(self.db.levelMin or 1)
        local sn1 = sMin:GetName(); if _G[sn1.."Low"] then _G[sn1.."Low"]:SetText("") end; if _G[sn1.."High"] then _G[sn1.."High"]:SetText("") end; if _G[sn1.."Text"] then _G[sn1.."Text"]:SetText("") end
        sMin:SetScript("OnValueChanged", function(s, v) lblMin:SetText("Min: " .. math.floor(v)) end)
        sMin:SetScript("OnMouseUp", function(s) GR.db.levelMin = math.floor(s:GetValue()) end)
        local lblMax = p4:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall"); lblMax:SetPoint("TOPLEFT", 380, -50); lblMax:SetText("Max: " .. (self.db.levelMax or 80))
        local sMax = CreateFrame("Slider", "GRS_Set_LvlMax", p4, "OptionsSliderTemplate"); sMax:SetPoint("TOPLEFT", 430, -48); sMax:SetWidth(260); sMax:SetMinMaxValues(1, 80); sMax:SetValueStep(1); sMax:SetObeyStepOnDrag(true); sMax:SetValue(self.db.levelMax or 80)
        local sn2 = sMax:GetName(); if _G[sn2.."Low"] then _G[sn2.."Low"]:SetText("") end; if _G[sn2.."High"] then _G[sn2.."High"]:SetText("") end; if _G[sn2.."Text"] then _G[sn2.."Text"]:SetText("") end
        sMax:SetScript("OnValueChanged", function(s, v) lblMax:SetText("Max: " .. math.floor(v)) end)
        sMax:SetScript("OnMouseUp", function(s) GR.db.levelMax = math.floor(s:GetValue()) end)
        y = y - 95

        local p5 = CreateOptionPane(c, y, NS.L["SOUND_NOTIFICATIONS"] or "Sound / Notification Toggles", "Mute whisper sounds, recruitment alerts, and other notification sounds.", 80)
        local chkW = CreateFrame("CheckButton", "GRS_Set_MuteWhisper", p5, "UICheckButtonTemplate"); chkW:SetSize(24, 24); chkW:SetPoint("TOPLEFT", 10, -45)
        chkW.text = chkW:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall"); chkW.text:SetPoint("LEFT", chkW, "RIGHT", 5, 0); chkW.text:SetText(NS.L["MUTE_WHISPER"] or "Mute Whisper Sounds")
        chkW:SetChecked(self.db.muteWhisper or false); chkW:SetScript("OnClick", function(cb) GR.db.muteWhisper = cb:GetChecked() end)
        local chkA = CreateFrame("CheckButton", "GRS_Set_MuteAlerts", p5, "UICheckButtonTemplate"); chkA:SetSize(24, 24); chkA:SetPoint("LEFT", chkW.text, "RIGHT", 20, 0)
        chkA.text = chkA:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall"); chkA.text:SetPoint("LEFT", chkA, "RIGHT", 5, 0); chkA.text:SetText(NS.L["MUTE_ALERTS"] or "Mute Recruitment Alerts")
        chkA:SetChecked(self.db.muteAlerts or false); chkA:SetScript("OnClick", function(cb) GR.db.muteAlerts = cb:GetChecked() end)
        y = y - 85

        c:SetHeight(math.abs(y) + 20)
    end

    -- =================================================================
    -- PAGE 2: UI MODE
    -- =================================================================
    do
        local c = pages[2].canvas; local y = -10
        if not self.db.guildMode then self.db.guildMode = self.db.socialEnabled and "social" or nil end
        local modeCheckboxes = {}
        local modes = {
            { key = "social",  label = NS.L["SOCIAL_GUILD_MODE"] or "Social Guild Mode",  desc = "Activates a variety of options and insights into your members, set personal notes, anniversaries, birthdays and more." },
            { key = "raid",    label = NS.L["RAID_GUILD_MODE"] or "Raid Guild Mode",      desc = "Activates a variety of options with great insight into your members progression and commitment to the guild." },
            { key = "pvp",     label = NS.L["PVP_GUILD_MODE"] or "PVP Guild Mode",        desc = "Activates a variety of options with great insight into your members PVP experience and Achievements." },
            { key = "mplus",   label = NS.L["MPLUS_GUILD_MODE"] or "M+ Guild Mode",       desc = "Activates a variety of options with great insight into your members Mythic Plus races." },
            { key = "custom",  label = NS.L["CUSTOM_GUILD_MODE"] or "Custom Guild Mode",  desc = "Set and create your own Guild mode, which insights do you find important?" },
        }
        for _, mode in ipairs(modes) do
            local pane = CreateOptionPane(c, y, mode.label, mode.desc, 70)
            local chk = CreateFrame("CheckButton", "GRS_Set_Mode_" .. mode.key, pane, "UICheckButtonTemplate"); chk:SetSize(24, 24); chk:SetPoint("TOPRIGHT", -10, -8)
            chk:SetChecked(self.db.guildMode == mode.key)
            chk.modeKey = mode.key
            modeCheckboxes[mode.key] = chk
            chk:SetScript("OnClick", function(cb)
                if cb:GetChecked() then
                    GR.db.guildMode = cb.modeKey
                    for k, other in pairs(modeCheckboxes) do if k ~= cb.modeKey then other:SetChecked(false) end end
                    GR.db.socialEnabled = (cb.modeKey == "social")
                else
                    GR.db.guildMode = nil; GR.db.socialEnabled = false
                end
                if GR.UpdateRosterList then GR:UpdateRosterList() end
            end)
            y = y - 75
        end
        c:SetHeight(math.abs(y) + 20)
    end

    -- =================================================================
    -- PAGE 3: APPEARANCES
    -- =================================================================
    do
        local c = pages[3].canvas; local y = -10

        -- Transparency & Contrast
        local p1 = CreateOptionPane(c, y, NS.L["TRANSPARENCY_CONTRAST"] or "Transparency & Contrast", "Panel opacity with a high-contrast text option.", 80)
        local alphaS = CreateColorSlider(p1, "Background Alpha", function() return GR.db.theme.background.a end, function(v) GR.db.theme.background.a = v; UpdateLiveTheme() end)
        alphaS:SetPoint("TOPLEFT", 10, -45); alphaS:SetWidth(300)
        y = y - 85

        -- UI Scale
        local p2 = CreateOptionPane(c, y, NS.L["UI_SCALE"] or "UI Scale", "Adjust overall addon UI scale. Values between 0.60 and 1.40.", 80)
        local valScale = p2:CreateFontString(nil, "OVERLAY", "GameFontHighlight"); valScale:SetPoint("TOPRIGHT", -10, -10); valScale:SetText(string.format("%.2f", self.db.scale or 1.0))
        local sliderScale = CreateFrame("Slider", "GRS_ScaleSlider", p2, "OptionsSliderTemplate"); sliderScale:SetPoint("TOPLEFT", 10, -50); sliderScale:SetWidth(380); sliderScale:SetMinMaxValues(0.6, 1.4); sliderScale:SetValueStep(0.05); sliderScale:SetObeyStepOnDrag(true)
        local sName = sliderScale:GetName(); if _G[sName.."Low"] then _G[sName.."Low"]:SetText("") end; if _G[sName.."High"] then _G[sName.."High"]:SetText("") end; if _G[sName.."Text"] then _G[sName.."Text"]:SetText("") end
        sliderScale:SetValue(self.db.scale or 1.0)
        sliderScale:SetScript("OnValueChanged", function(s, val) local v = math.floor(val * 100 + 0.5) / 100; valScale:SetText(string.format("%.2f", v)) end)
        sliderScale:SetScript("OnMouseUp", function(s) local v = math.floor(s:GetValue() * 100 + 0.5) / 100; if GR.db then GR.db.scale = v end; GR:SetScale(v) end)
        y = y - 85

        -- Theme Colors: Header/Sidebar
        local function MakeColorControls(parent, yStart, dbKey, useAlpha)
            local function GetCol(k) local t = GR.db.theme[dbKey]; return t and t[k] or (k == "a" and 1 or 0) end
            local function SetCol(k, v) if GR.db.theme[dbKey] then GR.db.theme[dbKey][k] = v; UpdateLiveTheme() end end
            local rS = CreateColorSlider(parent, "Red", function() return GetCol("r") end, function(v) SetCol("r", v) end); rS:SetPoint("TOPLEFT", 10, yStart); rS:SetWidth(200)
            local gS = CreateColorSlider(parent, "Green", function() return GetCol("g") end, function(v) SetCol("g", v) end); gS:SetPoint("TOPLEFT", 10, yStart - 35); gS:SetWidth(200)
            local bS = CreateColorSlider(parent, "Blue", function() return GetCol("b") end, function(v) SetCol("b", v) end); bS:SetPoint("TOPLEFT", 10, yStart - 70); bS:SetWidth(200)
            if useAlpha then local aS = CreateColorSlider(parent, "Alpha", function() return GetCol("a") end, function(v) SetCol("a", v) end); aS:SetPoint("TOPLEFT", 10, yStart - 105); aS:SetWidth(200)
            else if GR.db.theme[dbKey] then GR.db.theme[dbKey].a = 1 end end
        end
        local p3 = CreateOptionPane(c, y, NS.L["HEADER_SIDEBAR"] or "Theme: Header / Sidebar", NS.L["TITLE_SIDEBAR_COLORS"] or "Title Bar & Sidebar Colors", 140)
        MakeColorControls(p3, -45, "header", false)
        y = y - 145

        local p4 = CreateOptionPane(c, y, NS.L["BACKGROUND_PANE"] or "Theme: Background Pane", "Background panel color and transparency.", 170)
        MakeColorControls(p4, -45, "background", true)
        y = y - 175

        local p5 = CreateOptionPane(c, y, NS.L["BUTTONS_TEXT"] or "Theme: Buttons & Text", "Button and text color scheme.", 140)
        MakeColorControls(p5, -45, "buttons", false)
        y = y - 145

        -- Compact Mode
        local p6 = CreateOptionPane(c, y, NS.L["COMPACT_MODE"] or "Compact Mode", "Enable a compact layout mode for the addon interface.", 70)
        local chkCompact = CreateFrame("CheckButton", "GRS_Settings_CompactCheck", p6, "UICheckButtonTemplate"); chkCompact:SetSize(24, 24); chkCompact:SetPoint("TOPRIGHT", -10, -8)
        chkCompact:SetChecked(self.db.compactMode or false)
        chkCompact:SetScript("OnClick", function(cb) GR.db.compactMode = cb:GetChecked(); if GR.ToggleCompactMode then GR:ToggleCompactMode(GR.db.compactMode) end end)
        y = y - 75

        -- Custom Background
        local p7 = CreateOptionPane(c, y, NS.L["CUSTOM_BACKGROUND"] or "Custom Background", "Enable and configure custom background images per tab.", 320)
        if not self.db.customBackgrounds then self.db.customBackgrounds = {} end
        local chkEnableBg = CreateFrame("CheckButton", nil, p7, "UICheckButtonTemplate"); chkEnableBg:SetSize(24, 24); chkEnableBg:SetPoint("TOPLEFT", 10, -45)
        chkEnableBg.text = chkEnableBg:CreateFontString(nil, "OVERLAY", "GameFontHighlight"); chkEnableBg.text:SetPoint("LEFT", chkEnableBg, "RIGHT", 5, 0); chkEnableBg.text:SetText(NS.L["ENABLE_CUSTOM_BG"] or "Enable Custom Background")
        chkEnableBg:SetChecked(self.db.customBackgrounds.enabled or false)
        local lblDir = p7:CreateFontString(nil, "OVERLAY", "GameFontNormal"); lblDir:SetPoint("TOPLEFT", 10, -75); lblDir:SetText(NS.L["SET_DIRECTORY"] or "Set directory")
        local edtDir = CreateFrame("EditBox", nil, p7, "InputBoxTemplate"); edtDir:SetSize(350, 20); edtDir:SetPoint("TOPLEFT", 10, -95); edtDir:SetAutoFocus(false); edtDir:SetFontObject("ChatFontSmall"); edtDir:SetText(self.db.customBackgrounds.directory or "Interface\\AddOns\\GuildRecruiterManagement\\Media")
        local btnDir = CreateFrame("Button", nil, p7, "UIPanelButtonTemplate"); btnDir:SetSize(40, 20); btnDir:SetPoint("LEFT", edtDir, "RIGHT", 5, 0); btnDir:SetText("Set"); SafeCreateBg(btnDir, 0, 0, 0, 1); SafeCreateBorder(btnDir, 0.3, 0.3, 0.3, 1)
        btnDir:SetScript("OnClick", function() GR.db.customBackgrounds.directory = edtDir:GetText(); edtDir:ClearFocus() end)
        local rowsCont = CreateFrame("Frame", nil, p7); rowsCont:SetPoint("TOPLEFT", 0, -120); rowsCont:SetPoint("BOTTOMRIGHT", 0, 0)
        local function CreateBgRow(rParent, index, labelText, defaultFile, ryOffset)
            local label = rParent:CreateFontString(nil, "OVERLAY", "GameFontHighlightSmall"); label:SetPoint("TOPLEFT", 10, ryOffset); label:SetText(labelText)
            local edit = CreateFrame("EditBox", nil, rParent, "InputBoxTemplate"); edit:SetSize(250, 20); edit:SetPoint("TOPLEFT", 10, ryOffset - 15); edit:SetAutoFocus(false)
            if not GR.db.customBackgrounds.files then GR.db.customBackgrounds.files = {} end; edit:SetText(GR.db.customBackgrounds.files[index] or defaultFile or "")
            local btn = CreateFrame("Button", nil, rParent, "UIPanelButtonTemplate"); btn:SetSize(40, 20); btn:SetPoint("LEFT", edit, "RIGHT", 5, 0); btn:SetText("Set"); SafeCreateBg(btn, 0, 0, 0, 1); SafeCreateBorder(btn, 0.3, 0.3, 0.3, 1)
            btn:SetScript("OnClick", function() GR.db.customBackgrounds.files[index] = edit:GetText(); edit:ClearFocus() end)
            return edit, btn
        end
        local bgY = 0
        if NS.Constants and NS.Constants.TABS then for i = 1, 6 do local tabData = NS.Constants.TABS[i]; local title = tabData and tabData.title or ("Tab " .. i); CreateBgRow(rowsCont, i, title, nil, bgY); bgY = bgY - 40 end end
        CreateBgRow(rowsCont, "GuildChat", "Guild Chat", "Background_G-chat.tga", bgY)
        local function ToggleCustomControls(enable) local alpha = enable and 1 or 0.5; edtDir:SetAlpha(alpha); btnDir:SetAlpha(alpha); rowsCont:SetAlpha(alpha) end
        chkEnableBg:SetScript("OnClick", function(self) GR.db.customBackgrounds.enabled = self:GetChecked(); ToggleCustomControls(GR.db.customBackgrounds.enabled) end)
        ToggleCustomControls(self.db.customBackgrounds.enabled)
        y = y - 325

        -- Reload UI
        local p8 = CreateOptionPane(c, y, NS.L["RELOAD_UI"] or "Reload UI", NS.L["RELOAD_UI_NOTE"] or "Reload UI for scale and theme changes to take full effect.", 60)
        local btnReload = CreateFrame("Button", nil, p8, "UIPanelButtonTemplate"); btnReload:SetSize(120, 25); btnReload:SetPoint("TOPRIGHT", -10, -6); btnReload:SetText(NS.L["RELOAD_UI"] or "Reload UI"); btnReload:SetScript("OnClick", function() C_UI.Reload() end); SafeSkinButton(btnReload)
        y = y - 65

        c:SetHeight(math.abs(y) + 20)
    end

    -- =================================================================
    -- PAGE 4: TOOLS
    -- =================================================================
    do
        local c = pages[4].canvas; local y = -10
        local p1 = CreateOptionPane(c, y, NS.L["ENABLE_MACRO_TOOLS"] or "Macro Tools", "Enable the Macro Tools panel for advanced recruitment macros and automation.", 70)
        local chkMacro = CreateFrame("CheckButton", "GRS_Settings_MacroCheck", p1, "UICheckButtonTemplate"); chkMacro:SetSize(24, 24); chkMacro:SetPoint("TOPRIGHT", -10, -8)
        if DB_Rmap_Tools and DB_Rmap_Tools.settings then chkMacro:SetChecked(DB_Rmap_Tools.settings.isMacroPanelOpen) else chkMacro:SetChecked(false) end
        chkMacro:SetScript("OnClick", function(self)
            local isEnabled = self:GetChecked(); if DB_Rmap_Tools then if not DB_Rmap_Tools.settings then DB_Rmap_Tools.settings = {} end; DB_Rmap_Tools.settings.isMacroPanelOpen = isEnabled end
            if isEnabled then if GR.InitMacroDashboard then GR:InitMacroDashboard() end; if GR.MacroPanel then GR.MacroPanel:Show() end else if GR.MacroPanel then GR.MacroPanel:Hide() end end
        end)
        y = y - 75
        c:SetHeight(math.abs(y) + 20)
    end

    -- =================================================================
    -- PAGE 5: LANGUAGE (4 columns x 3 rows grid)
    -- =================================================================
    do
        local c = pages[5].canvas; local y = -10
        local p1 = CreateOptionPane(c, y, NS.L["LANGUAGE"] or "Language", "Select the display language for the addon interface. Requires a UI reload to apply.", 280)
        if not self.db.selectedLanguage then self.db.selectedLanguage = nil end
        local LANGUAGES = {
            { key = "enUS", label = "English" },     { key = "deDE", label = "Deutsch" },
            { key = "esES", label = "Español (EU)" },{ key = "frFR", label = "Français" },
            { key = "itIT", label = "Italiano" },    { key = "ruRU", label = "Русский" },
            { key = "esMX", label = "Español (AL)" },{ key = "ptBR", label = "Português" },
            { key = "koKR", label = "한국어" },        { key = "zhCN", label = "简体中文" },
            { key = "zhTW", label = "繁體中文" },
        }
        local langCheckboxes = {}
        local cols = 4; local colWidth = 170; local rowHeight = 30; local startY = -45; local startX = 10
        for idx, lang in ipairs(LANGUAGES) do
            local col = (idx - 1) % cols; local row = math.floor((idx - 1) / cols)
            local chkLang = CreateFrame("CheckButton", "GRS_Set_Lang_" .. lang.key, p1, "UICheckButtonTemplate")
            chkLang:SetSize(24, 24); chkLang:SetPoint("TOPLEFT", startX + (col * colWidth), startY - (row * rowHeight))
            chkLang.text = chkLang:CreateFontString(nil, "OVERLAY", "GameFontHighlight"); chkLang.text:SetPoint("LEFT", chkLang, "RIGHT", 5, 0); chkLang.text:SetText(lang.label)
            chkLang:SetChecked(self.db.selectedLanguage == lang.key)
            chkLang.langKey = lang.key; langCheckboxes[lang.key] = chkLang
            chkLang:SetScript("OnClick", function(cb)
                for key, otherCb in pairs(langCheckboxes) do if key ~= cb.langKey then otherCb:SetChecked(false) end end
                if cb:GetChecked() then GR.db.selectedLanguage = cb.langKey else GR.db.selectedLanguage = nil end
            end)
        end
        -- Apply Language Button
        local btnApplyLang = CreateFrame("Button", nil, p1, "UIPanelButtonTemplate"); btnApplyLang:SetSize(140, 30); btnApplyLang:SetPoint("TOPLEFT", startX, startY - (math.ceil(#LANGUAGES / cols) * rowHeight) - 10)
        btnApplyLang:SetText(NS.L["APPLY_LANGUAGE"] or "Apply Language"); SafeSkinButton(btnApplyLang)
        btnApplyLang:SetScript("OnClick", function()
            local lang = GR.db.selectedLanguage
            if lang then print("|cff00ff00A.X.I.O.M.:|r " .. (NS.L["LANGUAGE_SET_TO"] or "Language set to:") .. " " .. lang); ReloadUI()
            else print("|cff00ff00A.X.I.O.M.:|r " .. (NS.L["NO_LANGUAGE_SELECTED"] or "No language selected.")) end
        end)
        y = y - 285
        c:SetHeight(math.abs(y) + 20)
    end

    -- =================================================================
    -- PAGE 6: ADVANCED
    -- =================================================================
    do
        local c = pages[6].canvas; local y = -10

        -- Advanced Character Inspection
        local p1 = CreateOptionPane(c, y, NS.L["ADVANCED_INSPECTION"] or "Advanced Character Inspection", "Enable or disable the advanced character inspection and armory system. Default is OFF.", 70)
        local chkInspect = CreateFrame("CheckButton", "GRS_Settings_InspectCheck", p1, "UICheckButtonTemplate"); chkInspect:SetSize(24, 24); chkInspect:SetPoint("TOPRIGHT", -10, -8)
        chkInspect:SetChecked(self.db.disableInspect == false)
        chkInspect:SetScript("OnClick", function(self)
            local isEnabled = self:GetChecked(); GR.db.disableInspect = not isEnabled
            if _G.AXIOM_Armory_Frame_Reboot and _G.AXIOM_Armory_Frame_Reboot.ToggleSystem then _G.AXIOM_Armory_Frame_Reboot:ToggleSystem(isEnabled) end
            if _G.AXIOM_Target_Inspect_Frame and _G.AXIOM_Target_Inspect_Frame.ToggleSystem then _G.AXIOM_Target_Inspect_Frame:ToggleSystem(isEnabled) end
            print("|cff00ff00A.X.I.O.M.:|r Advanced Inspection " .. (isEnabled and "Enabled" or "Disabled"))
        end)
        -- Ensure state is applied on load
        C_Timer.After(1, function()
            local isEnabled = (GR.db.disableInspect == false)
            if _G.AXIOM_Armory_Frame_Reboot and _G.AXIOM_Armory_Frame_Reboot.ToggleSystem then _G.AXIOM_Armory_Frame_Reboot:ToggleSystem(isEnabled) end
            if _G.AXIOM_Target_Inspect_Frame and _G.AXIOM_Target_Inspect_Frame.ToggleSystem then _G.AXIOM_Target_Inspect_Frame:ToggleSystem(isEnabled) end
        end)
        y = y - 75

        -- Advanced Guild Roster
        local p2 = CreateOptionPane(c, y, NS.L["DISABLE_ADVANCED_ROSTER"] or "Advanced Guild Roster", NS.L["DISABLE_ADVANCED_ROSTER_NOTE"] or "Hides M+ Score, Raid Progress (N/H/M), and Max Key columns from the Guild Roster.", 70)
        local chkAdvanced = CreateFrame("CheckButton", "GRS_Settings_AdvancedRosterCheck", p2, "UICheckButtonTemplate"); chkAdvanced:SetSize(24, 24); chkAdvanced:SetPoint("TOPRIGHT", -10, -8)
        chkAdvanced:SetChecked(self.db.disableAdvancedRoster or false)
        chkAdvanced:SetScript("OnClick", function(cb)
            GR.db.disableAdvancedRoster = cb:GetChecked()
            print("|cff00ff00A.X.I.O.M.:|r Advanced Roster Columns " .. (GR.db.disableAdvancedRoster and "Hidden" or "Visible"))
            if GR.RosterSplitMain then GR.RosterSplitMain:Hide(); GR.RosterSplitMain = nil; GR.RosterRows = {}; GR.Rows = {}; if GR.RosterContent then GR.RosterContent:Hide(); GR.RosterContent = nil end end
            if GR.RightPaneTop then GR.RightPaneTop:Hide(); GR.RightPaneTop = nil end
            if GR.RightPaneBottom then GR.RightPaneBottom:Hide(); GR.RightPaneBottom = nil end
            if GR.UpdateRosterList then GR:UpdateRosterList() end
        end)
        y = y - 75

        -- Import / Export
        local p3 = CreateOptionPane(c, y, NS.L["IMPORT_FROM_GRM"] or "Import from GRM", "Open the Guild Roster Manager import popup to import member data.", 60)
        local btnImport = CreateFrame("Button", nil, p3, "UIPanelButtonTemplate"); btnImport:SetSize(160, 25); btnImport:SetPoint("TOPRIGHT", -10, -6); btnImport:SetText(NS.L["IMPORT_FROM_GRM"] or "Import from GRM"); SafeSkinButton(btnImport)
        btnImport:SetScript("OnClick", function() GR:OpenGuildImportPopup("IMPORT") end)
        y = y - 65

        local p4 = CreateOptionPane(c, y, "Export to GRM", "Open the Guild Roster Manager export popup to export member data.", 60)
        local btnExport = CreateFrame("Button", nil, p4, "UIPanelButtonTemplate"); btnExport:SetSize(160, 25); btnExport:SetPoint("TOPRIGHT", -10, -6); btnExport:SetText("Export to GRM"); SafeSkinButton(btnExport)
        btnExport:SetScript("OnClick", function() GR:OpenGuildImportPopup("EXPORT") end)
        y = y - 65

        -- Bypass Filter
        local p5 = CreateOptionPane(c, y, NS.L["BYPASS_FILTER"] or "Bypass Class Rotation Filter", "Bypass the class rotation filter during recruitment scans.", 70)
        local chkBypass = CreateFrame("CheckButton", "GRS_Settings_BypassCheck", p5, "UICheckButtonTemplate"); chkBypass:SetSize(24, 24); chkBypass:SetPoint("TOPRIGHT", -10, -8)
        chkBypass:SetChecked(self.db.bypassFilter or false)
        chkBypass:SetScript("OnClick", function(cb) GR.db.bypassFilter = cb:GetChecked(); print("|cff00ff00A.X.I.O.M.:|r " .. (NS.L["SETTINGS_APPLIED"] or "Settings Applied.")) end)
        y = y - 75

        c:SetHeight(math.abs(y) + 20)
    end

    -- Default: show General Settings page
    SelectCategory(1)
end
