-- Portal Authority — options/register.lua
-- Root/home panel, Blizzard compatibility stubs, and final settings registration.
--
-- Depends on: PortalAuthority.OptionsInternal shared helpers and panel factories; PortalAuthority
-- Exposes:    settingsCategory, rootPanel, rootCategoryID, defaultCategoryID, settingsWindowSectionMeta, settingsWindowNavOrder, settingsPanelWalkOrder, settingsPanelRegistry
-- DB keys:    none direct
-- Events:     none
-- Search key: none

PortalAuthority = PortalAuthority or {}

if PortalAuthority.IsSettingsBaselineGateEnabled and PortalAuthority:IsSettingsBaselineGateEnabled() then
    return
end

if not Settings or not Settings.RegisterCanvasLayoutCategory then
    return
end

PortalAuthority.OptionsInternal = PortalAuthority.OptionsInternal or {}
local OptionsInternal = PortalAuthority.OptionsInternal
local L = PortalAuthority.L

local settingsSearchRuntime = OptionsInternal.SearchRuntime
local trim = OptionsInternal.trim
local rgba255 = OptionsInternal.rgba255
local unpackColor = OptionsInternal.unpackColor
local applyGlobalFontToObject = OptionsInternal.applyGlobalFontToObject
local getPortalMedia = OptionsInternal.getPortalMedia
local normalizeSoundChoiceValue = OptionsInternal.normalizeSoundChoiceValue
local compareChoiceLabels = OptionsInternal.compareChoiceLabels
local normalizeChoicePathKey = OptionsInternal.normalizeChoicePathKey
local resolveFontChoicePath = OptionsInternal.resolveFontChoicePath
local getSoundChoiceValueKey = OptionsInternal.getSoundChoiceValueKey
local buildFallbackSoundChoices = OptionsInternal.buildFallbackSoundChoices
local getSummonSoundChoices = OptionsInternal.getSummonSoundChoices
local getAvailableFontChoices = OptionsInternal.getAvailableFontChoices
local buildSharedFontPickerChoices = OptionsInternal.buildSharedFontPickerChoices
local SUMMON_SOUND_CHANNEL_CHOICES = OptionsInternal.SUMMON_SOUND_CHANNEL_CHOICES
local debugSettingsLog = OptionsInternal.debugSettingsLog or function() end
local FLAT_SETTINGS_BACKDROP = OptionsInternal.FLAT_SETTINGS_BACKDROP
local SETTINGS_WINDOW_HOSTED_TOP_RHYTHM_NUDGE = OptionsInternal.SETTINGS_WINDOW_HOSTED_TOP_RHYTHM_NUDGE
local SETTINGS_WINDOW_SCROLLBAR_WIDTH = OptionsInternal.SETTINGS_WINDOW_SCROLLBAR_WIDTH
local SETTINGS_WINDOW_SCROLLBAR_GAP = OptionsInternal.SETTINGS_WINDOW_SCROLLBAR_GAP
local SETTINGS_WINDOW_SCROLLBAR_MIN_THUMB_HEIGHT = OptionsInternal.SETTINGS_WINDOW_SCROLLBAR_MIN_THUMB_HEIGHT
local SETTINGS_WINDOW_HOST_COLORS = OptionsInternal.SETTINGS_WINDOW_HOST_COLORS
local SETTINGS_WINDOW_SCROLLBAR_TRACK = OptionsInternal.SETTINGS_WINDOW_SCROLLBAR_TRACK
local SETTINGS_WINDOW_SCROLLBAR_THUMB = OptionsInternal.SETTINGS_WINDOW_SCROLLBAR_THUMB
local SETTINGS_WINDOW_SCROLLBAR_THUMB_HOVER = OptionsInternal.SETTINGS_WINDOW_SCROLLBAR_THUMB_HOVER
local frameIsAlive = OptionsInternal.frameIsAlive
local isDescendedFromFrame = OptionsInternal.isDescendedFromFrame
local markSettingsWindowVisualOptIn = OptionsInternal.markSettingsWindowVisualOptIn
local isUsingCustomSettingsWindowVisualStyle = OptionsInternal.isUsingCustomSettingsWindowVisualStyle
local registerSettingsWindowVisualRefresh = OptionsInternal.registerSettingsWindowVisualRefresh
local setTextureSolidColor = OptionsInternal.setTextureSolidColor
local hideDefaultScrollBarPart = OptionsInternal.hideDefaultScrollBarPart
local getTemplateScrollBar = OptionsInternal.getTemplateScrollBar
local hideDefaultScrollBarChrome = OptionsInternal.hideDefaultScrollBarChrome
local refreshCustomSettingsScrollBarThumb = OptionsInternal.refreshCustomSettingsScrollBarThumb
local settingsScrollRuntime = PortalAuthority._settingsScrollRuntime or OptionsInternal.settingsScrollRuntime
local createStyledFontString = OptionsInternal.createStyledFontString
local createTopRightHeader = OptionsInternal.createTopRightHeader
local PA_SafeBool = OptionsInternal.PA_SafeBool
local getClassHex = OptionsInternal.getClassHex
local createCheckbox = OptionsInternal.createCheckbox
local createActionButton = OptionsInternal.createActionButton
local styleSecondaryActionButtonShared = OptionsInternal.styleSecondaryActionButtonShared
local createNumeric = OptionsInternal.createNumeric
local createDropdown = OptionsInternal.createDropdown
local createDynamicDropdown = OptionsInternal.createDynamicDropdown
local createPremiumSegmentedChoice = OptionsInternal.createPremiumSegmentedChoice
local CreatePicker = OptionsInternal.CreatePicker
local CreateStepperControl = OptionsInternal.CreateStepperControl
local createCanonicalDockFontSizeStepperControl = OptionsInternal.CreateStepperControl or OptionsInternal.createCanonicalDockFontSizeStepperControl
local createTextPlacement = OptionsInternal.createTextPlacement
local setSettingsControlEnabled = OptionsInternal.setSettingsControlEnabled
local setSettingsTextEnabled = OptionsInternal.setSettingsTextEnabled
local createScrollableChild = OptionsInternal.createScrollableChild
local updateScrollBehavior = OptionsInternal.updateScrollBehavior
local withPanelHydration = OptionsInternal.withPanelHydration
local panelHasSizedViewport = OptionsInternal.panelHasSizedViewport
local handleSettingsFirstOpenSizeReady = OptionsInternal.handleSettingsFirstOpenSizeReady
local handleSettingsFirstOpenPanelShow = OptionsInternal.handleSettingsFirstOpenPanelShow
local handleSettingsFirstOpenPanelHide = OptionsInternal.handleSettingsFirstOpenPanelHide
local shouldSuppressSettingsFirstOpenExternalRefresh = OptionsInternal.shouldSuppressSettingsFirstOpenExternalRefresh
local isPanelUsingCustomSettingsWindowHost = OptionsInternal.isPanelUsingCustomSettingsWindowHost
local refreshPanel = OptionsInternal.refreshPanel
local createScrollableTextArea = OptionsInternal.createScrollableTextArea
local createSettingsSectionDescriptor = OptionsInternal.createSettingsSectionDescriptor
local layoutSettingsSectionDescriptor = OptionsInternal.layoutSettingsSectionDescriptor
local registerRefreshCallback = OptionsInternal.registerRefreshCallback
local ensureDatabase = OptionsInternal.ensureDatabase
local IsPointerInsideActivePickerSafeZone = OptionsInternal.IsPointerInsideActivePickerSafeZone
local CloseActivePortalPicker = OptionsInternal.CloseActivePortalPicker
local settingsFirstOpenHost = OptionsInternal.settingsFirstOpenHost
local resetSettingsFirstOpenPanelState = OptionsInternal.resetSettingsFirstOpenPanelState

local settingsEagerBuildGateEnabled = PortalAuthority.IsSettingsEagerBuildGateEnabled and PortalAuthority:IsSettingsEagerBuildGateEnabled() or false
local settingsWindowHostGateEnabled = PortalAuthority.IsSettingsWindowHostEnabled and PortalAuthority:IsSettingsWindowHostEnabled() or false
local createAnnouncementsPanelLegacy = OptionsInternal.createAnnouncementsPanelLegacy
local createAnnouncementsPanel = OptionsInternal.createAnnouncementsPanel
local createDockPanel = OptionsInternal.createDockPanel
local createTimersPanel = OptionsInternal.createTimersPanel
local createInterruptTrackerPanel = OptionsInternal.createInterruptTrackerPanel
local createKeystoneUtilityPanel = OptionsInternal.createKeystoneUtilityPanel
local createCombatAlertsPanel = OptionsInternal.createCombatAlertsPanel
local createProfilesPanel = OptionsInternal.createProfilesPanel
local root
local announcementsPanel
local dockPanel
local timersPanel
local interruptTrackerPanel
local combatAlertsPanel
local keystoneUtilityPanel
local profilesPanel
local rootCategoryPanel
local rootCategory
local initialSettingsWindowSectionMeta
local refreshSettingsRootLocalizedDisplay
local refreshCompatibilityStubLocalizedDisplay
local syncSettingsPanelRegistryDisplayFields

local SETTINGS_BANNER_FALLBACK = "01.PA_banner_wow_1024x256_centered.png"
local SETTINGS_BANNER_BY_LOCALE = {
    deDE = "PA_banner_deDE_1024x256.png",
    enUS = SETTINGS_BANNER_FALLBACK,
    esES = "PA_banner_esES_1024x256.png",
    esMX = "PA_banner_esES_1024x256.png",
    frFR = "PA_banner_frFR_1024x256.png",
    itIT = "PA_banner_itIT_1024x256.png",
    koKR = "PA_banner_koKR_1024x256.png",
    ptBR = "PA_banner_ptBR_1024x256.png",
    ruRU = "PA_banner_ruRU_1024x256.png",
    zhCN = "PA_banner_zhCN_1024x256.png",
    zhTW = "PA_banner_zhTW_1024x256.png",
}

local function getEffectiveSettingsLocaleCode()
    local coreInternal = PortalAuthority and PortalAuthority.CoreInternal
    local normalize = coreInternal and coreInternal.PA_NormalizeSupportedLocaleCode
    local localeCode = PortalAuthority and PortalAuthority._activeLocaleCode or nil
    if type(normalize) == "function" then
        return normalize(localeCode) or normalize(GetLocale and GetLocale()) or "enUS"
    end
    return localeCode or (GetLocale and GetLocale()) or "enUS"
end

local function getSettingsBannerTexturePath()
    local filename = SETTINGS_BANNER_BY_LOCALE[getEffectiveSettingsLocaleCode()] or SETTINGS_BANNER_FALLBACK
    return "Interface\\AddOns\\PortalAuthority\\Media\\Images\\" .. filename
end

local function getPortalAuthorityLandingVersionText()
    local version = nil
    if C_AddOns and C_AddOns.GetAddOnMetadata then
        version = C_AddOns.GetAddOnMetadata("PortalAuthority", "Version")
    end
    if (type(version) ~= "string" or trim(version) == "") and GetAddOnMetadata then
        version = GetAddOnMetadata("PortalAuthority", "Version")
    end
    if (type(version) ~= "string" or trim(version) == "")
        and PortalAuthority and type(PortalAuthority.GetAnnouncementReleaseVersionString) == "function"
    then
        version = PortalAuthority:GetAnnouncementReleaseVersionString()
    end

    version = trim(tostring(version or ""))
    if version == "" then
        version = "1.0.0"
    end
    if not version:match("^[vV]") then
        version = "v" .. version
    end
    return version
end

local function createPortalAuthorityLandingDivider(parent, width)
    local divider = parent:CreateTexture(nil, "ARTWORK")
    divider:SetTexture("Interface\\Buttons\\WHITE8x8")
    divider:SetVertexColor(0.27, 0.27, 0.27, 0.60)
    divider:SetSize(width or 40, 1)
    return divider
end

local function configurePortalAuthorityLandingFontString(fontString, size, flags, justifyH)
    if not fontString then
        return nil
    end
    fontString._paLandingFontSize = size
    fontString._paLandingFontFlags = flags
    applyGlobalFontToObject(fontString, size, flags)
    fontString:SetJustifyH(justifyH or "CENTER")
    fontString:SetJustifyV("MIDDLE")
    if fontString.SetWordWrap then
        fontString:SetWordWrap(false)
    end
    if fontString.SetNonSpaceWrap then
        fontString:SetNonSpaceWrap(false)
    end
    if fontString.SetMaxLines then
        fontString:SetMaxLines(1)
    end
    return fontString
end

local function createPortalAuthorityLandingStyledFontString(parent, layer, template, size, justifyH)
    local fontString = createStyledFontString(parent, layer, template, size)
    return configurePortalAuthorityLandingFontString(fontString, size, nil, justifyH)
end

local function createPortalAuthorityLandingRawFontString(parent, layer, template, size, flags, justifyH)
    local fontString = parent:CreateFontString(nil, layer, template)
    return configurePortalAuthorityLandingFontString(fontString, size, flags, justifyH)
end

local function refreshPortalAuthorityLandingFontString(fontString)
    if not fontString or not fontString._paLandingFontSize then
        return
    end
    applyGlobalFontToObject(fontString, fontString._paLandingFontSize, fontString._paLandingFontFlags)
end

local function isOnboardingD3GateEnabled()
    return PortalAuthority
        and PortalAuthority.IsOnboardingD3DevGateEnabled
        and PortalAuthority:IsOnboardingD3DevGateEnabled()
end

local function applyPremiumAuthoredFontToObject(object, size, flags)
    if PortalAuthority and PortalAuthority.ApplyPremiumAuthoredFont then
        PortalAuthority:ApplyPremiumAuthoredFont(object, size, flags)
        return
    end
    if object and object.SetFont then
        object:SetFont("Fonts\\FRIZQT__.TTF", size or select(2, object:GetFont()) or 12, flags or "")
    end
end

local function configurePortalAuthorityPremiumFontString(fontString, size, flags, justifyH)
    if not fontString then
        return nil
    end
    fontString._paPremiumLandingFontSize = size
    fontString._paPremiumLandingFontFlags = flags
    applyPremiumAuthoredFontToObject(fontString, size, flags)
    fontString:SetJustifyH(justifyH or "CENTER")
    fontString:SetJustifyV("MIDDLE")
    if fontString.SetWordWrap then
        fontString:SetWordWrap(false)
    end
    if fontString.SetNonSpaceWrap then
        fontString:SetNonSpaceWrap(false)
    end
    if fontString.SetMaxLines then
        fontString:SetMaxLines(1)
    end
    return fontString
end

local function createPortalAuthorityPremiumStyledFontString(parent, layer, template, size, justifyH)
    local fontString = createStyledFontString(parent, layer, template, size)
    return configurePortalAuthorityPremiumFontString(fontString, size, nil, justifyH)
end

local function createPortalAuthorityPremiumRawFontString(parent, layer, template, size, flags, justifyH)
    local fontString = parent:CreateFontString(nil, layer, template)
    return configurePortalAuthorityPremiumFontString(fontString, size, flags, justifyH)
end

local function refreshPortalAuthorityPremiumFontString(fontString)
    if not fontString or not fontString._paPremiumLandingFontSize then
        return
    end
    applyPremiumAuthoredFontToObject(fontString, fontString._paPremiumLandingFontSize, fontString._paPremiumLandingFontFlags)
end

local function refreshPortalAuthorityManagedLandingFontString(fontString)
    refreshPortalAuthorityLandingFontString(fontString)
    refreshPortalAuthorityPremiumFontString(fontString)
end

local function printPortalAuthorityCompatMessage(message)
    message = trim(tostring(message or ""))
    if message == "" then
        return
    end
    print("|cffE88BC7Portal Authority:|r " .. message)
end

local function createPortalAuthorityCompatStubButton(parent, label)
    local button = CreateFrame("Button", nil, parent, "BackdropTemplate")
    button:SetBackdrop({
        bgFile = "Interface\\Buttons\\WHITE8x8",
        edgeFile = "Interface\\Buttons\\WHITE8x8",
        edgeSize = 1,
        insets = { left = 0, right = 0, top = 0, bottom = 0 },
    })

    local text = button:CreateFontString(nil, "ARTWORK", "GameFontHighlight")
    applyGlobalFontToObject(text, 12, "")
    text:SetPoint("CENTER")
    text:SetText(label or L["COMMON_OPEN_SETTINGS"])
    text:SetTextColor(0.98, 0.96, 0.88, 1.0)
    text:SetShadowOffset(0, -1)
    text:SetShadowColor(0, 0, 0, 0.35)

    button._text = text

    local function setVisual(state)
        local bgR, bgG, bgB, bgA = 0.11, 0.09, 0.06, 0.97
        local borderR, borderG, borderB, borderA = 0.74, 0.60, 0.24, 0.92
        local textR, textG, textB = 0.99, 0.97, 0.90

        if state == "hover" then
            bgR, bgG, bgB = 0.16, 0.12, 0.07
            borderR, borderG, borderB = 0.90, 0.74, 0.32
            textR, textG, textB = 1.0, 0.98, 0.94
        elseif state == "down" then
            bgR, bgG, bgB = 0.09, 0.07, 0.05
            borderR, borderG, borderB = 0.68, 0.52, 0.18
            textR, textG, textB = 0.96, 0.94, 0.86
        end

        button:SetBackdropColor(bgR, bgG, bgB, bgA)
        button:SetBackdropBorderColor(borderR, borderG, borderB, borderA)
        text:SetTextColor(textR, textG, textB, 1.0)
    end

    button:SetSize(164, 36)
    setVisual("idle")

    button:SetScript("OnEnter", function()
        setVisual("hover")
    end)
    button:SetScript("OnLeave", function()
        setVisual("idle")
    end)
    button:SetScript("OnMouseDown", function()
        setVisual("down")
    end)
    button:SetScript("OnMouseUp", function(selfBtn)
        if selfBtn:IsMouseOver() then
            setVisual("hover")
        else
            setVisual("idle")
        end
    end)

    return button
end

local function createBlizzardCompatibilityStubPanel(sectionKey, name)
    local panel = CreateFrame("Frame")
    panel.name = name
    panel._compatStubSectionKey = sectionKey

    panel.EnsureBuilt = function(self)
        if self._initialized then
            return
        end
        self._initialized = true

        local widgets = {}
        self._compatStubWidgets = widgets

        widgets.group = CreateFrame("Frame", nil, self)

        widgets.banner = widgets.group:CreateTexture(nil, "ARTWORK")
        widgets.banner:SetTexture("Interface\\AddOns\\PortalAuthority\\Media\\Images\\01.PA_banner_wow_1024x256_centered.png")
        widgets.banner:SetTexCoord(0, 1, 0, 1)

        widgets.button = createPortalAuthorityCompatStubButton(widgets.group, L["COMMON_OPEN_SETTINGS"])
        widgets.button:SetScript("OnClick", function()
            if not PortalAuthority or type(PortalAuthority.OpenSettingsWindowFromBlizzardStub) ~= "function" then
                printPortalAuthorityCompatMessage(L["SETTINGS_WINDOW_UNAVAILABLE"])
                return
            end

            local ok, err = PortalAuthority:OpenSettingsWindowFromBlizzardStub(self._compatStubSectionKey)
            if not ok and err then
                printPortalAuthorityCompatMessage(err)
            end
        end)

        self._layout = function(frame)
            local stub = frame and frame._compatStubWidgets or nil
            if not stub then
                return
            end

            local panelWidth = tonumber(frame:GetWidth()) or 0
            if panelWidth <= 1 and frame.GetParent then
                local parent = frame:GetParent()
                panelWidth = parent and tonumber(parent:GetWidth()) or 0
            end

            local bannerWidth = math.min(480, math.max(1, panelWidth - 64))
            local bannerHeight = math.max(1, math.floor((bannerWidth / 4) + 0.5))
            local buttonWidth = math.max(156, math.ceil((stub.button._text:GetStringWidth() or 0) + 28))
            local buttonHeight = 36
            local groupWidth = math.max(bannerWidth, buttonWidth)
            local groupHeight = bannerHeight + 18 + buttonHeight

            stub.group:SetSize(groupWidth, groupHeight)
            stub.group:ClearAllPoints()
            stub.group:SetPoint("CENTER", frame, "CENTER", 0, 0)

            stub.banner:SetSize(bannerWidth, bannerHeight)
            stub.banner:ClearAllPoints()
            stub.banner:SetPoint("TOP", stub.group, "TOP", 0, 0)

            stub.button:SetSize(buttonWidth, buttonHeight)
            stub.button:ClearAllPoints()
            stub.button:SetPoint("TOP", stub.banner, "BOTTOM", 0, -18)
        end

        self._refresh = function(frame)
            if frame and frame._layout then
                frame._layout(frame)
            end
        end
    end

    panel:SetScript("OnShow", function(self)
        self:EnsureBuilt()
        if self._refresh then
            self._refresh(self)
        end
    end)

    panel:SetScript("OnSizeChanged", function(self)
        if self._initialized and self._layout then
            self._layout(self)
        end
    end)

    return panel
end

root = CreateFrame("Frame")
root.name = "Portal Authority"
root._paSearchSectionKey = "root"
root._paSearchSectionName = L["COMMON_HOME"]
settingsSearchRuntime.setPanelSearchTerms(root, L["SETTINGS_SEARCH_SECTION_TERMS_ROOT"])
debugSettingsLog("create frame:", root.name)
root.EnsureBuilt = function(self)
    debugSettingsLog("EnsureBuilt:", self.name, "initialized=", self._initialized and "true" or "false")
    if self._initialized then return end
    self._initialized = true
    resetSettingsFirstOpenPanelState(self)
    ensureDatabase()
    self._sizingFrame = self

    local widgets = {}
    self._landingWidgets = widgets

    local PORTAL_AUTHORITY_LANDING_PERCEPTUAL_CENTER_RATIO = 0.45
    local PORTAL_AUTHORITY_LANDING_MIN_TOP_INSET = 20

    local function getPortalAuthorityLandingElementHeight(element, fallback)
        fallback = math.max(0, tonumber(fallback) or 0)
        if not element then
            return fallback
        end

        local objectType = element.GetObjectType and element:GetObjectType() or nil
        if objectType == "FontString" and element.GetStringHeight then
            local stringHeight = tonumber(element:GetStringHeight()) or 0
            if stringHeight > 0 then
                return math.max(fallback, math.ceil(stringHeight))
            end
        end

        local height = tonumber(element.GetHeight and element:GetHeight()) or 0
        if height > 0 then
            return math.max(fallback, math.ceil(height))
        end

        return fallback
    end

    local function getPortalAuthorityLandingGroupTopOffset(panel, items)
        if type(items) ~= "table" or #items <= 0 then
            return -PORTAL_AUTHORITY_LANDING_MIN_TOP_INSET
        end

        local groupHeight = 0
        for i = 1, #items do
            local item = items[i]
            if type(item) == "table" then
                groupHeight = groupHeight + getPortalAuthorityLandingElementHeight(item.ref, item.fallback)
                groupHeight = groupHeight + math.max(0, tonumber(item.gapAfter) or 0)
            end
        end

        if groupHeight <= 0 then
            return -PORTAL_AUTHORITY_LANDING_MIN_TOP_INSET
        end

        local panelHeight = tonumber(panel and panel.GetHeight and panel:GetHeight()) or 0
        if panelHeight <= 1 then
            return -PORTAL_AUTHORITY_LANDING_MIN_TOP_INSET
        end

        local topInset = (panelHeight * PORTAL_AUTHORITY_LANDING_PERCEPTUAL_CENTER_RATIO) - (groupHeight * 0.5)
        topInset = math.max(PORTAL_AUTHORITY_LANDING_MIN_TOP_INSET, topInset)
        return -math.floor(topInset + 0.5)
    end

    if isOnboardingD3GateEnabled() then
        widgets.banner = self:CreateTexture(nil, "ARTWORK")
        widgets.banner:SetTexture(getSettingsBannerTexturePath())
        widgets.banner:SetTexCoord(0, 1, 0, 1)
        widgets.banner:SetSize(460, 115)

        widgets.separator1 = createPortalAuthorityLandingDivider(self, 80)

        widgets.dedicatedLabel = createPortalAuthorityLandingStyledFontString(self, "ARTWORK", "GameFontNormalSmall", 12)
        widgets.dedicatedLabel:SetText(L["COMMON_DEDICATED_TO"])
        widgets.dedicatedLabel:SetTextColor(1.0, 0.82, 0.0, 1.0)

        widgets.characterName = createPortalAuthorityPremiumRawFontString(self, "ARTWORK", "GameFontHighlight", 15)
        widgets.characterName:SetText("|cFF33937FImbabyuwu|r|cFF555555-Illidan|r")

        widgets.alias = createPortalAuthorityPremiumStyledFontString(self, "ARTWORK", "GameFontHighlightSmall", 12)
        widgets.alias:SetText("Navarone")
        widgets.alias:SetTextColor(0.54, 0.54, 0.56, 1.0)

        widgets.separator2 = createPortalAuthorityLandingDivider(self, 40)

        widgets.inspiredLabel = createPortalAuthorityLandingStyledFontString(self, "ARTWORK", "GameFontNormalSmall", 12)
        widgets.inspiredLabel:SetText(L["COMMON_INSPIRED_BY"])
        widgets.inspiredLabel:SetTextColor(1.0, 0.82, 0.0, 1.0)

        widgets.guildRow = CreateFrame("Button", nil, self)
        widgets.guildRow:SetSize(1, 28)
        widgets.guildRow:SetHitRectInsets(-8, -8, -4, -4)

        widgets.guildLogo = widgets.guildRow:CreateTexture(nil, "ARTWORK")
        widgets.guildLogo:SetTexture("Interface\\AddOns\\PortalAuthority\\Media\\Images\\overclock_logo_wow_64x64.png")
        widgets.guildLogo:SetTexCoord(0, 1, 0, 1)
        widgets.guildLogo:SetSize(28, 28)

        widgets.guildName = createPortalAuthorityPremiumStyledFontString(widgets.guildRow, "ARTWORK", "GameFontHighlight", 15, "LEFT")
        widgets.guildName:SetText("Overclock")
        widgets.guildName:SetTextColor(1.0, 1.0, 1.0, 1.0)

        widgets.separator3 = createPortalAuthorityLandingDivider(self, 40)

        widgets.author = createPortalAuthorityLandingRawFontString(self, "ARTWORK", "GameFontNormal", 12)
        widgets.author:SetText(L["COMMON_BY"] .. "|cFF3FC7EBStormyeyes|r|cFF555555-Mal'Ganis|r")

        widgets.version = createPortalAuthorityPremiumStyledFontString(self, "ARTWORK", "GameFontHighlightSmall", 11)
        widgets.version:SetTextColor(0.34, 0.34, 0.36, 1.0)

        widgets.showMeAround = CreateFrame("Button", nil, self)
        widgets.showMeAround:SetSize(1, 18)
        widgets.showMeAround:SetHitRectInsets(-8, -8, -4, -4)
        widgets.showMeAroundText = createPortalAuthorityLandingStyledFontString(widgets.showMeAround, "ARTWORK", "GameFontHighlightSmall", 11)
        widgets.showMeAroundText:SetPoint("CENTER")
        widgets.showMeAroundText:SetText(L["COMMON_SHOW_ME_AROUND"])
        widgets.showMeAroundText:SetTextColor(0.78, 0.78, 0.82, 1.0)

        widgets.fontStrings = {
            widgets.dedicatedLabel,
            widgets.characterName,
            widgets.alias,
            widgets.inspiredLabel,
            widgets.guildName,
            widgets.author,
            widgets.version,
            widgets.showMeAroundText,
        }

        local function setGuildRowHoverState(isHover)
            if isHover then
                widgets.guildName:SetTextColor(0.96, 0.96, 0.98, 1.0)
            else
                widgets.guildName:SetTextColor(1.0, 1.0, 1.0, 1.0)
            end
        end

        widgets.guildRow:SetScript("OnEnter", function()
            setGuildRowHoverState(true)
        end)
        widgets.guildRow:SetScript("OnLeave", function()
            setGuildRowHoverState(false)
        end)
        widgets.guildRow:SetScript("OnClick", function()
            if PortalAuthority and PortalAuthority.ShowOverclockLinkPopup then
                PortalAuthority:ShowOverclockLinkPopup()
            end
        end)

        widgets.showMeAround:SetScript("OnEnter", function()
            widgets.showMeAroundText:SetTextColor(0.92, 0.92, 0.95, 1.0)
        end)
        widgets.showMeAround:SetScript("OnLeave", function()
            widgets.showMeAroundText:SetTextColor(0.78, 0.78, 0.82, 1.0)
        end)
        widgets.showMeAround:SetScript("OnMouseDown", function()
            widgets.showMeAroundText:SetTextColor(0.98, 0.98, 1.0, 1.0)
        end)
        widgets.showMeAround:SetScript("OnMouseUp", function()
            if widgets.showMeAround:IsMouseOver() then
                widgets.showMeAroundText:SetTextColor(0.92, 0.92, 0.95, 1.0)
            else
                widgets.showMeAroundText:SetTextColor(0.78, 0.78, 0.82, 1.0)
            end
        end)
        widgets.showMeAround:SetScript("OnClick", function()
            if PortalAuthority and PortalAuthority.StartPremiumOnboardingExperience then
                PortalAuthority:StartPremiumOnboardingExperience("root-show-me-around")
            end
        end)

        self._layout = function()
            local landing = self._landingWidgets
            if not landing then
                return
            end

            local guildRowWidth = tonumber(self._landingGuildRowWidth) or 1
            landing.guildRow:SetSize(guildRowWidth, 28)

            local showMeAroundWidth = tonumber(self._landingShowMeAroundWidth) or 1
            landing.showMeAround:SetSize(showMeAroundWidth, 18)

            local groupTopOffset = getPortalAuthorityLandingGroupTopOffset(self, {
                { ref = landing.banner, fallback = 115, gapAfter = 20 },
                { ref = landing.separator1, fallback = 1, gapAfter = 20 },
                { ref = landing.dedicatedLabel, fallback = 12, gapAfter = 8 },
                { ref = landing.characterName, fallback = 15, gapAfter = 2 },
                { ref = landing.alias, fallback = 12, gapAfter = 18 },
                { ref = landing.separator2, fallback = 1, gapAfter = 18 },
                { ref = landing.inspiredLabel, fallback = 12, gapAfter = 8 },
                { ref = landing.guildRow, fallback = 28, gapAfter = 18 },
                { ref = landing.separator3, fallback = 1, gapAfter = 18 },
                { ref = landing.author, fallback = 12, gapAfter = 16 },
                { ref = landing.version, fallback = 11, gapAfter = 22 },
                { ref = landing.showMeAround, fallback = 18, gapAfter = 0 },
            })

            landing.guildLogo:ClearAllPoints()
            landing.guildLogo:SetPoint("LEFT", landing.guildRow, "LEFT", 0, 0)

            landing.guildName:ClearAllPoints()
            landing.guildName:SetPoint("LEFT", landing.guildLogo, "RIGHT", 8, 0)

            landing.banner:ClearAllPoints()
            landing.banner:SetPoint("TOP", self, "TOP", 0, groupTopOffset)

            landing.separator1:ClearAllPoints()
            landing.separator1:SetPoint("TOP", landing.banner, "BOTTOM", 0, -20)

            landing.dedicatedLabel:ClearAllPoints()
            landing.dedicatedLabel:SetPoint("TOP", landing.separator1, "BOTTOM", 0, -20)

            landing.characterName:ClearAllPoints()
            landing.characterName:SetPoint("TOP", landing.dedicatedLabel, "BOTTOM", 0, -8)

            landing.alias:ClearAllPoints()
            landing.alias:SetPoint("TOP", landing.characterName, "BOTTOM", 0, -2)

            landing.separator2:ClearAllPoints()
            landing.separator2:SetPoint("TOP", landing.alias, "BOTTOM", 0, -18)

            landing.inspiredLabel:ClearAllPoints()
            landing.inspiredLabel:SetPoint("TOP", landing.separator2, "BOTTOM", 0, -18)

            landing.guildRow:ClearAllPoints()
            landing.guildRow:SetPoint("TOP", landing.inspiredLabel, "BOTTOM", 0, -8)

            landing.separator3:ClearAllPoints()
            landing.separator3:SetPoint("TOP", landing.guildRow, "BOTTOM", 0, -18)

            landing.author:ClearAllPoints()
            landing.author:SetPoint("TOP", landing.separator3, "BOTTOM", 0, -18)

            landing.version:ClearAllPoints()
            landing.version:SetPoint("TOP", landing.author, "BOTTOM", 0, -16)

            landing.showMeAround:ClearAllPoints()
            landing.showMeAround:SetPoint("TOP", landing.version, "BOTTOM", 0, -22)
        end

        self._refresh = function()
            local landing = self._landingWidgets
            if not landing then
                return
            end

            for _, fontString in ipairs(landing.fontStrings or {}) do
                refreshPortalAuthorityManagedLandingFontString(fontString)
            end

            local versionText = getPortalAuthorityLandingVersionText()
            if landing.version:GetText() ~= versionText then
                landing.version:SetText(versionText)
            end

            local guildNameWidth = math.max(1, math.ceil(tonumber((landing.guildName.GetStringWidth and landing.guildName:GetStringWidth()) or 0) or 0))
            self._landingGuildRowWidth = 28 + 8 + guildNameWidth
            self._landingShowMeAroundWidth = math.max(1, math.ceil(tonumber((landing.showMeAroundText.GetStringWidth and landing.showMeAroundText:GetStringWidth()) or 0) or 0))

            if self._layout then
                self._layout()
            end
        end

        registerRefreshCallback(function()
            if shouldSuppressSettingsFirstOpenExternalRefresh(self) then
                return
            end
            if self and self._refresh then
                self._refresh()
            end
        end, self)

        self:SetScript("OnSizeChanged", function(panel)
            if handleSettingsFirstOpenSizeReady(panel, "size_changed") then
                return
            end
            if shouldSuppressSettingsFirstOpenExternalRefresh(panel) then
                return
            end
            if panel and panel._initialized and panel._layout and panel:IsShown() then
                panel._layout()
            end
        end)

        self._settingsFirstOpenKey = "root"
        self._settingsFirstOpenSizeTarget = self
        self._settingsFirstOpenRender = function(panel)
            if panel._refresh then
                panel._refresh()
            elseif panel._layout then
                panel._layout()
            end
        end
        self._settingsFirstOpenIsReady = function(panel)
            local landing = panel and panel._landingWidgets or nil
            return panelHasSizedViewport(panel)
                and landing ~= nil
                and landing.banner ~= nil and landing.banner:IsShown()
                and landing.version ~= nil and landing.version:IsShown()
                and landing.author ~= nil and landing.author:IsShown()
        end

        self._refresh()
        return
    end

    widgets.banner = self:CreateTexture(nil, "ARTWORK")
    widgets.banner:SetTexture(getSettingsBannerTexturePath())
    widgets.banner:SetTexCoord(0, 1, 0, 1)
    widgets.banner:SetSize(460, 115)

    widgets.separator1 = createPortalAuthorityLandingDivider(self, 80)

    widgets.dedicatedLabel = createPortalAuthorityLandingStyledFontString(self, "ARTWORK", "GameFontNormalSmall", 11)
    widgets.dedicatedLabel:SetText(L["COMMON_DEDICATED_TO"])
    widgets.dedicatedLabel:SetTextColor(1.0, 0.82, 0.0, 1.0)

    -- Use raw font strings for inline color escapes so their embedded colors remain untouched.
    widgets.characterName = createPortalAuthorityLandingRawFontString(self, "ARTWORK", "GameFontHighlight", 14)
    widgets.characterName:SetText("|cFF33937FImbabyuwu|r|cFF555555-Illidan|r")

    widgets.alias = createPortalAuthorityLandingStyledFontString(self, "ARTWORK", "GameFontHighlightSmall", 11)
    widgets.alias:SetText("Navarone")
    widgets.alias:SetTextColor(0.40, 0.40, 0.40, 1.0)

    widgets.separator2 = createPortalAuthorityLandingDivider(self, 40)

    widgets.inspiredLabel = createPortalAuthorityLandingStyledFontString(self, "ARTWORK", "GameFontNormalSmall", 11)
    widgets.inspiredLabel:SetText(L["COMMON_INSPIRED_BY"])
    widgets.inspiredLabel:SetTextColor(1.0, 0.82, 0.0, 1.0)

    widgets.guildRow = CreateFrame("Frame", nil, self)
    widgets.guildRow:SetSize(1, 28)

    widgets.guildLogo = widgets.guildRow:CreateTexture(nil, "ARTWORK")
    widgets.guildLogo:SetTexture("Interface\\AddOns\\PortalAuthority\\Media\\Images\\overclock_logo_wow_64x64.png")
    widgets.guildLogo:SetTexCoord(0, 1, 0, 1)
    widgets.guildLogo:SetSize(28, 28)

    widgets.guildName = createPortalAuthorityLandingStyledFontString(widgets.guildRow, "ARTWORK", "GameFontHighlight", 13, "LEFT")
    widgets.guildName:SetText("Overclock")
    widgets.guildName:SetTextColor(0.80, 0.80, 0.80, 1.0)

    widgets.separator3 = createPortalAuthorityLandingDivider(self, 40)

    widgets.author = createPortalAuthorityLandingRawFontString(self, "ARTWORK", "GameFontNormal", 11)
    widgets.author:SetText(L["COMMON_BY"] .. "|cFF3FC7EBStormyeyes|r|cFF555555-Mal'Ganis|r")

    widgets.version = createPortalAuthorityLandingStyledFontString(self, "ARTWORK", "GameFontHighlightSmall", 10)
    widgets.version:SetTextColor(0.22, 0.22, 0.22, 1.0)

    widgets.fontStrings = {
        widgets.dedicatedLabel,
        widgets.characterName,
        widgets.alias,
        widgets.inspiredLabel,
        widgets.guildName,
        widgets.author,
        widgets.version,
    }

    self._layout = function()
        local landing = self._landingWidgets
        if not landing then
            return
        end

        local guildRowWidth = tonumber(self._landingGuildRowWidth) or 1
        landing.guildRow:SetSize(guildRowWidth, 28)

        local groupTopOffset = getPortalAuthorityLandingGroupTopOffset(self, {
            { ref = landing.banner, fallback = 115, gapAfter = 20 },
            { ref = landing.separator1, fallback = 1, gapAfter = 20 },
            { ref = landing.dedicatedLabel, fallback = 11, gapAfter = 6 },
            { ref = landing.characterName, fallback = 14, gapAfter = 2 },
            { ref = landing.alias, fallback = 11, gapAfter = 18 },
            { ref = landing.separator2, fallback = 1, gapAfter = 18 },
            { ref = landing.inspiredLabel, fallback = 11, gapAfter = 8 },
            { ref = landing.guildRow, fallback = 28, gapAfter = 18 },
            { ref = landing.separator3, fallback = 1, gapAfter = 18 },
            { ref = landing.author, fallback = 11, gapAfter = 16 },
            { ref = landing.version, fallback = 10, gapAfter = 0 },
        })

        landing.guildLogo:ClearAllPoints()
        landing.guildLogo:SetPoint("LEFT", landing.guildRow, "LEFT", 0, 0)

        landing.guildName:ClearAllPoints()
        landing.guildName:SetPoint("LEFT", landing.guildLogo, "RIGHT", 8, 0)

        landing.banner:ClearAllPoints()
        landing.banner:SetPoint("TOP", self, "TOP", 0, groupTopOffset)

        landing.separator1:ClearAllPoints()
        landing.separator1:SetPoint("TOP", landing.banner, "BOTTOM", 0, -20)

        landing.dedicatedLabel:ClearAllPoints()
        landing.dedicatedLabel:SetPoint("TOP", landing.separator1, "BOTTOM", 0, -20)

        landing.characterName:ClearAllPoints()
        landing.characterName:SetPoint("TOP", landing.dedicatedLabel, "BOTTOM", 0, -6)

        landing.alias:ClearAllPoints()
        landing.alias:SetPoint("TOP", landing.characterName, "BOTTOM", 0, -2)

        landing.separator2:ClearAllPoints()
        landing.separator2:SetPoint("TOP", landing.alias, "BOTTOM", 0, -18)

        landing.inspiredLabel:ClearAllPoints()
        landing.inspiredLabel:SetPoint("TOP", landing.separator2, "BOTTOM", 0, -18)

        landing.guildRow:ClearAllPoints()
        landing.guildRow:SetPoint("TOP", landing.inspiredLabel, "BOTTOM", 0, -8)

        landing.separator3:ClearAllPoints()
        landing.separator3:SetPoint("TOP", landing.guildRow, "BOTTOM", 0, -18)

        landing.author:ClearAllPoints()
        landing.author:SetPoint("TOP", landing.separator3, "BOTTOM", 0, -18)

        landing.version:ClearAllPoints()
        landing.version:SetPoint("TOP", landing.author, "BOTTOM", 0, -16)
    end

    self._refresh = function()
        local landing = self._landingWidgets
        if not landing then
            return
        end

        for _, fontString in ipairs(landing.fontStrings or {}) do
            refreshPortalAuthorityManagedLandingFontString(fontString)
        end

        local versionText = getPortalAuthorityLandingVersionText()
        if landing.version:GetText() ~= versionText then
            landing.version:SetText(versionText)
        end

        local guildNameWidth = math.max(1, math.ceil(tonumber((landing.guildName.GetStringWidth and landing.guildName:GetStringWidth()) or 0) or 0))
        self._landingGuildRowWidth = 28 + 8 + guildNameWidth

        if self._layout then
            self._layout()
        end
    end

    registerRefreshCallback(function()
        if shouldSuppressSettingsFirstOpenExternalRefresh(self) then
            return
        end
        if self and self._refresh then
            self._refresh()
        end
    end, self)

    self:SetScript("OnSizeChanged", function(panel)
        if handleSettingsFirstOpenSizeReady(panel, "size_changed") then
            return
        end
        if shouldSuppressSettingsFirstOpenExternalRefresh(panel) then
            return
        end
        if panel and panel._initialized and panel._layout and panel:IsShown() then
            panel._layout()
        end
    end)

    self._settingsFirstOpenKey = "root"
    self._settingsFirstOpenSizeTarget = self
    self._settingsFirstOpenRender = function(panel)
        if panel._refresh then
            panel._refresh()
        elseif panel._layout then
            panel._layout()
        end
    end
    self._settingsFirstOpenIsReady = function(panel)
        local landing = panel and panel._landingWidgets or nil
        return panelHasSizedViewport(panel)
            and landing ~= nil
            and landing.banner ~= nil and landing.banner:IsShown()
            and landing.version ~= nil and landing.version:IsShown()
            and landing.author ~= nil and landing.author:IsShown()
    end

    self._refresh()
end

local function ensureRootPanelAnchored(self)
    local parent = self and self:GetParent() or nil
    if not parent then
        return false
    end
    if self._paAnchorParent ~= parent or not self._paAnchored then
        self:ClearAllPoints()
        self:SetAllPoints(parent)
        self._paAnchorParent = parent
    end
    self._paAnchored = true
    return true
end

root:SetScript("OnShow", function(self)
    debugSettingsLog("OnShow:", self.name)
    ensureRootPanelAnchored(self)
    self:EnsureBuilt()
    if not handleSettingsFirstOpenPanelShow(self) then
        withPanelHydration(self, function()
            if self._refresh then
                self._refresh()
            elseif self._layout then
                self._layout()
            end
        end)
    end
end)

root:HookScript("OnHide", function(self)
    handleSettingsFirstOpenPanelHide(self)
end)

announcementsPanel = createAnnouncementsPanel()
dockPanel = createDockPanel()
timersPanel = createTimersPanel()
interruptTrackerPanel = createInterruptTrackerPanel()
combatAlertsPanel = createCombatAlertsPanel()
keystoneUtilityPanel = createKeystoneUtilityPanel()
profilesPanel = createProfilesPanel()
rootCategoryPanel = settingsWindowHostGateEnabled and createBlizzardCompatibilityStubPanel("root", root.name) or root

BINDING_NAME_PORTAL_AUTHORITY_OPEN_SETTINGS = L["COMMON_OPEN_SETTINGS"]

local function initializeDeferredSettingsPanelHidden(panel)
    if not panel or not panel.Hide or not panel.IsShown then
        return
    end
    if panel:IsShown() then
        panel:Hide()
    end
end

-- These panels were being created in the shown state, which means their first
-- real selection never produced an OnShow transition. Starting them hidden
-- makes first selection own the initial build/show path instead of relying on
-- later click-away/click-back or background priming.
rootCategory = Settings.RegisterCanvasLayoutCategory(rootCategoryPanel, root.name, root.name)
Settings.RegisterAddOnCategory(rootCategory)
debugSettingsLog("register category:", root.name, "id=", rootCategory and rootCategory.GetID and rootCategory:GetID() or "nil")

initializeDeferredSettingsPanelHidden(root)
initializeDeferredSettingsPanelHidden(announcementsPanel)
initializeDeferredSettingsPanelHidden(dockPanel)
initializeDeferredSettingsPanelHidden(timersPanel)
initializeDeferredSettingsPanelHidden(interruptTrackerPanel)
initializeDeferredSettingsPanelHidden(combatAlertsPanel)
initializeDeferredSettingsPanelHidden(profilesPanel)

-- Direct settings panels now build on demand when opened for the first time.

local function bootstrapKeystoneUtilityPanelBuild(attempt)
    if not keystoneUtilityPanel then
        return
    end
    if keystoneUtilityPanel._initialized and keystoneUtilityPanel._layout and keystoneUtilityPanel._refresh and keystoneUtilityPanel._fullRefresh then
        return
    end

    ensureDatabase()
    if PortalAuthorityDB then
        keystoneUtilityPanel:EnsureBuilt()
        if keystoneUtilityPanel._fullRefresh then
            keystoneUtilityPanel._fullRefresh("bootstrap-eager")
        end
        return
    end

    local n = tonumber(attempt) or 0
    if n >= 180 then
        return
    end
    if C_Timer and C_Timer.After then
        C_Timer.After(0, function()
            bootstrapKeystoneUtilityPanelBuild(n + 1)
        end)
    end
end

if PortalAuthority and PortalAuthority.SetSettingsKeystoneBootstrapState then
    if settingsEagerBuildGateEnabled then
        PortalAuthority:SetSettingsKeystoneBootstrapState("suppressed")
    else
        PortalAuthority:SetSettingsKeystoneBootstrapState("unknown")
    end
end

if settingsEagerBuildGateEnabled then
    -- The eager-build gate suppresses the delayed bootstrap kickoff entirely.
elseif C_Timer and C_Timer.After then
    if PortalAuthority and PortalAuthority.SetSettingsKeystoneBootstrapState then
        PortalAuthority:SetSettingsKeystoneBootstrapState("scheduled")
    end
    C_Timer.After(0, function()
        if PortalAuthority and PortalAuthority.SetSettingsKeystoneBootstrapState then
            PortalAuthority:SetSettingsKeystoneBootstrapState("ran")
        end
        bootstrapKeystoneUtilityPanelBuild(0)
    end)
end

local function buildSettingsWindowSectionMeta()
    local currentL = PortalAuthority and PortalAuthority.L or L or {}
    return {
        root = {
            key = "root",
            title = currentL["COMMON_HOME"],
            descriptor = "",
            navLabel = nil,
            showInNav = false,
        },
        announcements = {
            key = "announcements",
            title = currentL["SETTINGS_ANNOUNCE_TITLE"],
            descriptor = currentL["SETTINGS_ANNOUNCE_DESCRIPTOR"],
            navLabel = currentL["SETTINGS_ANNOUNCE_TITLE"],
            showInNav = true,
        },
        dock = {
            key = "dock",
            title = currentL["SETTINGS_DOCK_TITLE"],
            descriptor = currentL["SETTINGS_DOCK_DESCRIPTOR"],
            navLabel = currentL["SETTINGS_DOCK_TITLE"],
            showInNav = true,
        },
        timers = {
            key = "timers",
            title = currentL["SETTINGS_TIMERS_TITLE"],
            descriptor = currentL["SETTINGS_TIMERS_DESCRIPTOR"],
            navLabel = currentL["SETTINGS_TIMERS_TITLE"],
            showInNav = true,
        },
        interrupt = {
            key = "interrupt",
            title = currentL["SETTINGS_IT_TITLE"],
            descriptor = currentL["SETTINGS_IT_DESCRIPTOR"],
            navLabel = currentL["SETTINGS_IT_TITLE"],
            showInNav = true,
        },
        combat = {
            key = "combat",
            title = currentL["SETTINGS_COMBAT_TITLE"],
            descriptor = currentL["SETTINGS_COMBAT_DESCRIPTOR"],
            navLabel = currentL["SETTINGS_COMBAT_TITLE"],
            showInNav = true,
        },
        keystone = {
            key = "keystone",
            title = currentL["SETTINGS_KS_TITLE"],
            descriptor = currentL["SETTINGS_KS_DESCRIPTOR"],
            navLabel = currentL["SETTINGS_KS_TITLE"],
            showInNav = true,
        },
        profiles = {
            key = "profiles",
            title = currentL["SETTINGS_PROFILES_TITLE"],
            descriptor = currentL["SETTINGS_PROFILES_DESCRIPTOR"],
            navLabel = currentL["SETTINGS_PROFILES_TITLE"],
            showInNav = true,
        },
    }
end

if PortalAuthority then
    initialSettingsWindowSectionMeta = buildSettingsWindowSectionMeta()
    PortalAuthority.settingsWindowSectionMeta = initialSettingsWindowSectionMeta
    PortalAuthority._settingsLocalizationMetaLocaleCode = getEffectiveSettingsLocaleCode()

    function PortalAuthority:GetSettingsWindowSectionMeta()
        local currentLocaleCode = getEffectiveSettingsLocaleCode()
        if type(self.settingsWindowSectionMeta) == "table"
            and self._settingsLocalizationMetaLocaleCode == currentLocaleCode
        then
            return self.settingsWindowSectionMeta
        end
        return buildSettingsWindowSectionMeta()
    end

    function PortalAuthority:RefreshSettingsLocalizationMetadata()
        local currentLocaleCode = getEffectiveSettingsLocaleCode()
        if self._settingsLocalizationMetaLocaleCode == currentLocaleCode
            and type(self.settingsWindowSectionMeta) == "table"
        then
            return {
                localeChanged = false,
                didResync = false,
                effectiveLocaleCode = currentLocaleCode,
            }
        end

        local meta = buildSettingsWindowSectionMeta()
        self.settingsWindowSectionMeta = meta
        self._settingsLocalizationMetaLocaleCode = currentLocaleCode
        if type(syncSettingsPanelRegistryDisplayFields) == "function" then
            syncSettingsPanelRegistryDisplayFields(meta)
        end
        if type(refreshSettingsRootLocalizedDisplay) == "function" then
            refreshSettingsRootLocalizedDisplay()
        end
        if type(refreshCompatibilityStubLocalizedDisplay) == "function" then
            refreshCompatibilityStubLocalizedDisplay(rootCategoryPanel)
        end

        return {
            localeChanged = true,
            didResync = true,
            effectiveLocaleCode = currentLocaleCode,
        }
    end
end

refreshSettingsRootLocalizedDisplay = function()
    local panel = root
    local widgets = panel and panel._landingWidgets or nil
    if not widgets then
        return
    end

    if widgets.dedicatedLabel then
        widgets.dedicatedLabel:SetText(L["COMMON_DEDICATED_TO"])
    end
    if widgets.inspiredLabel then
        widgets.inspiredLabel:SetText(L["COMMON_INSPIRED_BY"])
    end
    if widgets.author then
        widgets.author:SetText(L["COMMON_BY"] .. "|cFF3FC7EBStormyeyes|r|cFF555555-Mal'Ganis|r")
    end
    if widgets.showMeAroundText then
        widgets.showMeAroundText:SetText(L["COMMON_SHOW_ME_AROUND"])
    end

    if panel and panel._refresh then
        panel._refresh()
    end
end

refreshCompatibilityStubLocalizedDisplay = function(panel)
    local widgets = panel and panel._compatStubWidgets or nil
    if not widgets or not widgets.button or not widgets.button._text then
        return
    end

    widgets.button._text:SetText(L["COMMON_OPEN_SETTINGS"])
    if panel and panel._refresh then
        panel._refresh(panel)
    end
end

syncSettingsPanelRegistryDisplayFields = function(meta)
    local registry = PortalAuthority and PortalAuthority.settingsPanelRegistry or nil
    if type(registry) ~= "table" then
        return
    end

    local function syncPanelEntry(sectionKey, panel, keepPanelName)
        local entry = registry[sectionKey]
        local section = meta[sectionKey]
        if type(entry) ~= "table" or type(section) ~= "table" then
            return
        end

        entry.title = section.title
        entry.descriptor = section.descriptor
        entry.navLabel = section.navLabel
        entry.showInNav = section.showInNav

        if panel and not keepPanelName then
            panel.name = section.title
        end
        if panel then
            if panel._paSearchSectionName ~= section.title then
                panel._paSearchSectionName = section.title
                panel._paSearchRegistryDirty = true
            end
        end
        if panel and type(panel.name) == "string" then
            entry.name = panel.name
        end
    end

    syncPanelEntry("root", root, true)
    syncPanelEntry("announcements", announcementsPanel)
    syncPanelEntry("dock", dockPanel)
    syncPanelEntry("timers", timersPanel)
    syncPanelEntry("interrupt", interruptTrackerPanel)
    syncPanelEntry("combat", combatAlertsPanel)
    syncPanelEntry("keystone", keystoneUtilityPanel)
    syncPanelEntry("profiles", profilesPanel)
end

if PortalAuthority then
    PortalAuthority.settingsWindowNavOrder = {
        "announcements",
        "dock",
        "timers",
        "interrupt",
        "combat",
        "keystone",
        "profiles",
    }
    PortalAuthority.settingsCategory = rootCategory
    PortalAuthority.rootPanel = root
    local rootCategoryID = rootCategory and rootCategory.GetID and rootCategory:GetID() or nil
    PortalAuthority.rootCategoryID = rootCategoryID
    PortalAuthority.rootCategory = rootCategory
    PortalAuthority.defaultCategoryID = rootCategoryID
    PortalAuthority._settingsFirstOpenHostDebug = settingsFirstOpenHost
    PortalAuthority._settingsFirstOpenDebugPanels = {
        { key = "root", name = root.name, panel = root },
        { key = "announcements", name = announcementsPanel.name, panel = announcementsPanel },
        { key = "dock", name = dockPanel.name, panel = dockPanel },
        { key = "timers", name = timersPanel.name, panel = timersPanel },
        { key = "interrupt", name = interruptTrackerPanel.name, panel = interruptTrackerPanel },
        { key = "combat", name = combatAlertsPanel.name, panel = combatAlertsPanel },
        { key = "keystone", name = keystoneUtilityPanel.name, panel = keystoneUtilityPanel },
        { key = "profiles", name = profilesPanel.name, panel = profilesPanel },
    }
    PortalAuthority.settingsPanelWalkOrder = {
        "root",
        "announcements",
        "dock",
        "timers",
        "interrupt",
        "combat",
        "keystone",
        "profiles",
    }
    PortalAuthority.settingsPanelRegistry = {
        root = {
            key = "root",
            name = root.name,
            panel = root,
            category = rootCategory,
            categoryID = PortalAuthority.rootCategoryID,
            title = initialSettingsWindowSectionMeta.root.title,
            descriptor = initialSettingsWindowSectionMeta.root.descriptor,
            navLabel = initialSettingsWindowSectionMeta.root.navLabel,
            showInNav = initialSettingsWindowSectionMeta.root.showInNav,
        },
        announcements = {
            key = "announcements",
            name = announcementsPanel.name,
            panel = announcementsPanel,
            title = initialSettingsWindowSectionMeta.announcements.title,
            descriptor = initialSettingsWindowSectionMeta.announcements.descriptor,
            navLabel = initialSettingsWindowSectionMeta.announcements.navLabel,
            showInNav = initialSettingsWindowSectionMeta.announcements.showInNav,
        },
        dock = {
            key = "dock",
            name = dockPanel.name,
            panel = dockPanel,
            title = initialSettingsWindowSectionMeta.dock.title,
            descriptor = initialSettingsWindowSectionMeta.dock.descriptor,
            navLabel = initialSettingsWindowSectionMeta.dock.navLabel,
            showInNav = initialSettingsWindowSectionMeta.dock.showInNav,
        },
        timers = {
            key = "timers",
            name = timersPanel.name,
            panel = timersPanel,
            title = initialSettingsWindowSectionMeta.timers.title,
            descriptor = initialSettingsWindowSectionMeta.timers.descriptor,
            navLabel = initialSettingsWindowSectionMeta.timers.navLabel,
            showInNav = initialSettingsWindowSectionMeta.timers.showInNav,
        },
        interrupt = {
            key = "interrupt",
            name = interruptTrackerPanel.name,
            panel = interruptTrackerPanel,
            title = initialSettingsWindowSectionMeta.interrupt.title,
            descriptor = initialSettingsWindowSectionMeta.interrupt.descriptor,
            navLabel = initialSettingsWindowSectionMeta.interrupt.navLabel,
            showInNav = initialSettingsWindowSectionMeta.interrupt.showInNav,
        },
        combat = {
            key = "combat",
            name = combatAlertsPanel.name,
            panel = combatAlertsPanel,
            title = initialSettingsWindowSectionMeta.combat.title,
            descriptor = initialSettingsWindowSectionMeta.combat.descriptor,
            navLabel = initialSettingsWindowSectionMeta.combat.navLabel,
            showInNav = initialSettingsWindowSectionMeta.combat.showInNav,
        },
        keystone = {
            key = "keystone",
            name = keystoneUtilityPanel.name,
            panel = keystoneUtilityPanel,
            title = initialSettingsWindowSectionMeta.keystone.title,
            descriptor = initialSettingsWindowSectionMeta.keystone.descriptor,
            navLabel = initialSettingsWindowSectionMeta.keystone.navLabel,
            showInNav = initialSettingsWindowSectionMeta.keystone.showInNav,
        },
        profiles = {
            key = "profiles",
            name = profilesPanel.name,
            panel = profilesPanel,
            title = initialSettingsWindowSectionMeta.profiles.title,
            descriptor = initialSettingsWindowSectionMeta.profiles.descriptor,
            navLabel = initialSettingsWindowSectionMeta.profiles.navLabel,
            showInNav = initialSettingsWindowSectionMeta.profiles.showInNav,
        },
    }
end
