-- Portal Authority — options/panel_keystone.lua
-- Keystone Utility settings panel and tooltip preview controls.
--
-- Depends on: PortalAuthority.OptionsInternal shared helpers; PortalAuthority
-- Exposes:    PortalAuthority.OptionsInternal.createKeystoneUtilityPanel
-- DB keys:    keystone*, releaseGate*
-- Events:     none
-- Search key: keystone

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 setSettingsWindowChromeVisible = OptionsInternal.setSettingsWindowChromeVisible
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 restoreColorPickerPrevious = OptionsInternal.restoreColorPickerPrevious
local settingsFirstOpenHost = OptionsInternal.settingsFirstOpenHost
local resetSettingsFirstOpenPanelState = OptionsInternal.resetSettingsFirstOpenPanelState

local function createKeystoneUtilityPanel()
    local panel = CreateFrame("Frame")
    panel.name = L["SETTINGS_KS_TITLE"]
    panel._paSearchSectionKey = "keystone"
    panel._paSearchSectionName = panel.name
    settingsSearchRuntime.setPanelSearchTerms(panel, L["SETTINGS_SEARCH_SECTION_TERMS_KEYSTONE"])
    local ensureKeystonePanelAnchored
    local renderKeystoneWhenReady
    local keystoneHasSizedViewport
    local startKeystoneRenderBootstrap

    panel.EnsureBuilt = function(self)
        if self._initialized and self._layout and self._refresh then return end
        ensureDatabase()
        if not PortalAuthorityDB then
            return
        end
        settingsSearchRuntime.beginDescriptorCapture(self)

        local scrollFrame, scrollChild = createScrollableChild(self)
        if not scrollFrame or not scrollChild then
            settingsSearchRuntime.endDescriptorCapture(self)
            return
        end
        self._sizingFrame = scrollFrame
        self._kuScrollChild = scrollChild
        local widgets = {}
        local panelRef = self

        local function onApply()
            if PortalAuthority and PortalAuthority.ApplyKeystoneUtilitySettings then
                PortalAuthority:ApplyKeystoneUtilitySettings()
            end
            if panelRef and panelRef._refresh then
                panelRef._refresh()
            end
        end

        local header = createStyledFontString(scrollChild, "ARTWORK", "GameFontNormalLarge", 14)
        header:SetText("|cffffd100" .. L["SETTINGS_KS_TITLE"] .. "|r")
        widgets.sectionDescriptor = createSettingsSectionDescriptor(scrollChild, L["SETTINGS_KS_DESCRIPTOR"])

        local helperHeader = createStyledFontString(scrollChild, "ARTWORK", "GameFontHighlight", 12)
        helperHeader:SetText(L["SETTINGS_KS_ASSISTANT_HEADER"])

        local function createSubtleCard(parent)
            local card = CreateFrame("Frame", nil, parent, "BackdropTemplate")
            card:SetBackdrop({
                bgFile = "Interface\\Buttons\\WHITE8x8",
                edgeFile = "Interface\\Buttons\\WHITE8x8",
                edgeSize = 1,
                insets = { left = 0, right = 0, top = 0, bottom = 0 },
            })
            card:SetBackdropColor(0.06, 0.07, 0.09, 0.42)
            card:SetBackdropBorderColor(0.20, 0.23, 0.29, 0.82)
            return card
        end

        local function createStatusChip(parent, titleText)
            local chip = CreateFrame("Frame", nil, parent, "BackdropTemplate")
            chip:SetBackdrop({
                bgFile = "Interface\\Buttons\\WHITE8x8",
                edgeFile = "Interface\\Buttons\\WHITE8x8",
                edgeSize = 1,
                insets = { left = 0, right = 0, top = 0, bottom = 0 },
            })
            chip:SetBackdropColor(0.09, 0.10, 0.13, 0.86)
            chip:SetBackdropBorderColor(0.23, 0.26, 0.31, 0.90)
            chip:SetSize(108, 34)

            chip.title = createStyledFontString(chip, "ARTWORK", "GameFontHighlightSmall", 10)
            chip.title:SetPoint("TOPLEFT", chip, "TOPLEFT", 8, -5)
            chip.title:SetPoint("TOPRIGHT", chip, "TOPRIGHT", -8, -5)
            chip.title:SetJustifyH("LEFT")
            chip.title:SetTextColor(0.72, 0.74, 0.78, 0.94)
            chip.title:SetText(titleText or "")

            chip.value = createStyledFontString(chip, "ARTWORK", "GameFontHighlightSmall", 11)
            chip.value:SetPoint("BOTTOMLEFT", chip, "BOTTOMLEFT", 8, 5)
            chip.value:SetPoint("BOTTOMRIGHT", chip, "BOTTOMRIGHT", -8, 5)
            chip.value:SetJustifyH("LEFT")
            chip.value:SetTextColor(0.86, 0.88, 0.92, 1)
            chip.value:SetText("")

            function chip:SetState(text, tone)
                self.value:SetText(tostring(text or ""))
                if tone == "good" then
                    self.value:SetTextColor(0.74, 0.94, 0.76, 1)
                    self:SetBackdropBorderColor(0.20, 0.39, 0.23, 0.90)
                elseif tone == "warn" then
                    self.value:SetTextColor(0.94, 0.84, 0.58, 1)
                    self:SetBackdropBorderColor(0.44, 0.34, 0.18, 0.90)
                else
                    self.value:SetTextColor(0.86, 0.88, 0.92, 1)
                    self:SetBackdropBorderColor(0.23, 0.26, 0.31, 0.90)
                end
            end

            return chip
        end

        local disabledEnabledChoices = {
            { label = L["COMMON_DISABLED"], value = false, toggleState = "off" },
            { label = L["COMMON_ENABLED"], value = true, toggleState = "on" },
        }
        local modifierChoices = {
            { label = L["COMMON_SHIFT"], value = "SHIFT" },
            { label = L["COMMON_CTRL"], value = "CTRL" },
        }

        local function createKUSettingSegment(labelText, choices, getter, setter, opts)
            opts = type(opts) == "table" and opts or {}
            local internalValue = getter and getter() or nil
            local segmented = createPremiumSegmentedChoice(
                scrollChild,
                labelText or "",
                nil,
                choices or {},
                function(value)
                    internalValue = value
                    if setter then
                        setter(value)
                    end
                    onApply()
                end,
                {
                    semantic = opts.semantic or "toggle",
                    normalizeValue = opts.normalizeValue,
                    getValue = function()
                        return internalValue
                    end,
                    setValue = function(value)
                        internalValue = value
                    end,
                    controlHeight = 22,
                    textSize = 11,
                    minWidth = opts.minWidth or 170,
                    segmentGap = opts.segmentGap or 4,
                    segmentMinWidth = opts.segmentMinWidth or 48,
                }
            )
            local spec = {}
            spec.label = segmented.label
            spec.control = segmented.control
            spec.buttons = segmented.buttons
            spec.Layout = function(_, width)
                segmented:Layout(width)
            end
            spec.SetEnabled = function(_, enabled)
                segmented:SetEnabled(enabled and true or false)
            end
            spec.SetVisualSelectedValue = function(_, value)
                internalValue = value
                segmented:SetVisualSelectedValue(value)
            end
            spec.Refresh = function()
                if getter then
                    local v = getter()
                    internalValue = v
                    segmented:SetVisualSelectedValue(v)
                end
            end
            return spec
        end

        widgets.assistantCard = createSubtleCard(scrollChild)
        widgets.releaseCard = createSubtleCard(scrollChild)
        widgets.topSectionDivider = scrollChild:CreateTexture(nil, "ARTWORK")
        widgets.topSectionDivider:SetColorTexture(0.24, 0.27, 0.32, 0.10)

        widgets.statusStrip = CreateFrame("Frame", nil, widgets.assistantCard)
        widgets.statusKeystone = createStatusChip(widgets.statusStrip, L["SETTINGS_KS_STATUS_KEYSTONE"])
        widgets.statusLeader = createStatusChip(widgets.statusStrip, L["SETTINGS_KS_STATUS_LEADER_ASSIST"])
        widgets.statusAutomation = createStatusChip(widgets.statusStrip, L["SETTINGS_KS_STATUS_AUTOMATION"])

        widgets.keystoneHelperEnabled = createKUSettingSegment(
            L["SETTINGS_KS_ENABLE_ASSISTANT"],
            disabledEnabledChoices,
            function() return PA_SafeBool(PortalAuthorityDB and PortalAuthorityDB.keystoneHelperEnabled) end,
            function(value)
                if PortalAuthorityDB then
                    PortalAuthorityDB.keystoneHelperEnabled = PA_SafeBool(value)
                end
            end,
            { semantic = "toggle" }
        )
        local helperDesc = createStyledFontString(scrollChild, "ARTWORK", "GameFontHighlightSmall", 11)
        helperDesc:SetText(L["SETTINGS_KS_ENABLE_ASSISTANT_DESC"])
        helperDesc:SetTextColor(0.72, 0.72, 0.72, 1)
        helperDesc:SetJustifyH("LEFT")

        widgets.keystoneAutoSlotEnabled = createKUSettingSegment(
            L["SETTINGS_KS_AUTO_SLOT_KEYSTONE"],
            disabledEnabledChoices,
            function() return PA_SafeBool(PortalAuthorityDB and PortalAuthorityDB.keystoneAutoSlotEnabled) end,
            function(value)
                if PortalAuthorityDB then
                    PortalAuthorityDB.keystoneAutoSlotEnabled = PA_SafeBool(value)
                end
            end,
            { semantic = "toggle" }
        )
        local autoSlotDesc = createStyledFontString(scrollChild, "ARTWORK", "GameFontHighlightSmall", 11)
        autoSlotDesc:SetText(L["SETTINGS_KS_AUTO_SLOT_KEYSTONE_DESC"])
        autoSlotDesc:SetTextColor(0.72, 0.72, 0.72, 1)
        autoSlotDesc:SetJustifyH("LEFT")

        widgets.keystoneAutoStartEnabled = createKUSettingSegment(
            L["SETTINGS_KS_AUTO_START_KEY_AFTER_PULL"],
            disabledEnabledChoices,
            function() return PA_SafeBool(PortalAuthorityDB and PortalAuthorityDB.keystoneAutoStartEnabled) end,
            function(value)
                if PortalAuthorityDB then
                    PortalAuthorityDB.keystoneAutoStartEnabled = PA_SafeBool(value)
                end
            end,
            { semantic = "toggle" }
        )
        local autoStartDesc = createStyledFontString(scrollChild, "ARTWORK", "GameFontHighlightSmall", 11)
        autoStartDesc:SetText(L["SETTINGS_KS_AUTO_START_KEY_AFTER_PULL_DESC"])
        autoStartDesc:SetTextColor(0.72, 0.72, 0.72, 1)
        autoStartDesc:SetJustifyH("LEFT")

        local releaseHeader = createStyledFontString(scrollChild, "ARTWORK", "GameFontHighlight", 12)
        releaseHeader:SetText(L["SETTINGS_KS_RELEASE_SPIRIT_RULES"])

        widgets.releaseGateEnabled = createKUSettingSegment(
            L["SETTINGS_KS_HIDE_RELEASE_SPIRIT"],
            disabledEnabledChoices,
            function() return PA_SafeBool(PortalAuthorityDB and PortalAuthorityDB.releaseGateEnabled) end,
            function(value)
                if PortalAuthorityDB then
                    PortalAuthorityDB.releaseGateEnabled = PA_SafeBool(value)
                end
            end,
            { semantic = "toggle" }
        )
        settingsSearchRuntime.attachSearchTerms(widgets.releaseGateEnabled, L["SETTINGS_SEARCH_TERMS_KEYSTONE_RELEASE_SPIRIT"])
        local releaseEnabledDesc = createStyledFontString(scrollChild, "ARTWORK", "GameFontHighlightSmall", 11)
        releaseEnabledDesc:SetText(L["SETTINGS_KS_HIDE_RELEASE_SPIRIT_DESC"])
        releaseEnabledDesc:SetTextColor(0.72, 0.72, 0.72, 1)
        releaseEnabledDesc:SetJustifyH("LEFT")
        settingsSearchRuntime.attachSearchTermsToTextRef(releaseHeader, widgets.releaseGateEnabled and widgets.releaseGateEnabled.control or releaseHeader, L["SETTINGS_SEARCH_TERMS_KEYSTONE_RELEASE_SPIRIT"])

        local function normalizeModifier(value)
            local raw = string.upper(trim(tostring(value or "")))
            if raw == "CTRL" then
                return "CTRL"
            end
            return "SHIFT"
        end

        widgets.releaseGateModifier = createKUSettingSegment(
            L["SETTINGS_KS_REVEAL_MODIFIER"],
            modifierChoices,
            function() return normalizeModifier(PortalAuthorityDB and PortalAuthorityDB.releaseGateModifier) end,
            function(value)
                if PortalAuthorityDB then
                    PortalAuthorityDB.releaseGateModifier = normalizeModifier(value)
                end
            end,
            {
                semantic = "selection",
                normalizeValue = normalizeModifier,
                minWidth = 120,
                segmentMinWidth = 54,
            }
        )

        local holdLabel = createStyledFontString(scrollChild, "ARTWORK", "GameFontHighlight", 12)
        holdLabel:SetText(L["SETTINGS_KS_HOLD_SECONDS"])
        local HOLD_STEP = 0.05
        local HOLD_SHIFT_MULTIPLIER = 5
        local HOLD_MIN = 0.00
        local HOLD_MAX = 5.00
        local holdCurrentValue = nil
        local holdEditing = false
        local holdControlEnabled = true
        widgets.releaseHoldStepper = CreateFrame("Frame", nil, scrollChild)
        widgets.releaseHoldStepper:SetSize(84, 22)

        local holdStepperBg = CreateFrame("Frame", nil, widgets.releaseHoldStepper, "BackdropTemplate")
        holdStepperBg:SetPoint("TOPLEFT", widgets.releaseHoldStepper, "TOPLEFT", 0, 0)
        holdStepperBg:SetPoint("BOTTOMRIGHT", widgets.releaseHoldStepper, "BOTTOMRIGHT", 0, 0)
        holdStepperBg:SetBackdrop({
            bgFile = "Interface\\Buttons\\WHITE8x8",
            edgeFile = "Interface\\Buttons\\WHITE8x8",
            edgeSize = 1,
            insets = { left = 0, right = 0, top = 0, bottom = 0 },
        })
        holdStepperBg:SetBackdropColor(0.10, 0.11, 0.14, 0.95)
        holdStepperBg:SetBackdropBorderColor(0.24, 0.27, 0.32, 1.0)

        local function createHoldArrow(symbol)
            local btn = CreateFrame("Button", nil, widgets.releaseHoldStepper)
            btn:SetSize(12, 16)
            btn._text = createStyledFontString(btn, "ARTWORK", "GameFontHighlight", 11)
            btn._text:SetPoint("CENTER", btn, "CENTER", 0, 0)
            btn._text:SetText(symbol)
            btn._text:SetTextColor(0.74, 0.74, 0.76, 1)
            btn:SetScript("OnEnter", function(selfBtn)
                selfBtn._text:SetTextColor(0.95, 0.95, 0.98, 1)
            end)
            btn:SetScript("OnLeave", function(selfBtn)
                selfBtn._text:SetTextColor(0.74, 0.74, 0.76, 1)
            end)
            return btn
        end

        local holdMinus = createHoldArrow("<")
        local holdPlus = createHoldArrow(">")
        local holdValueButton = CreateFrame("Button", nil, widgets.releaseHoldStepper)
        holdValueButton:SetSize(40, 16)
        local holdValueText = createStyledFontString(holdValueButton, "ARTWORK", "GameFontHighlightSmall", 11)
        holdValueText:SetPoint("CENTER", holdValueButton, "CENTER", 0, 0)
        holdValueText:SetTextColor(0.86, 0.86, 0.90, 1)
        local holdValueEdit = CreateFrame("EditBox", nil, holdValueButton)
        holdValueEdit:SetAllPoints(holdValueButton)
        holdValueEdit:SetAutoFocus(false)
        holdValueEdit:SetJustifyH("CENTER")
        holdValueEdit:SetTextInsets(0, 0, 0, 0)
        holdValueEdit:SetTextColor(1, 1, 1, 1)
        holdValueEdit:SetHighlightColor(1, 1, 1, 0.25)
        applyGlobalFontToObject(holdValueEdit, 11)
        holdValueEdit:Hide()

        holdMinus:SetPoint("LEFT", widgets.releaseHoldStepper, "LEFT", 6, 0)
        holdValueButton:SetPoint("LEFT", holdMinus, "RIGHT", 4, 0)
        holdPlus:SetPoint("LEFT", holdValueButton, "RIGHT", 4, 0)

        local function normalizeHoldSeconds(value)
            local n = tonumber(value)
            if n == nil then
                local defaults = (PortalAuthority and PortalAuthority.defaults) or {}
                n = tonumber(defaults.releaseGateHoldSeconds) or 1.0
            end
            if n < HOLD_MIN then n = HOLD_MIN end
            if n > HOLD_MAX then n = HOLD_MAX end
            n = math.floor((n / HOLD_STEP) + 0.5) * HOLD_STEP
            n = math.floor((n * 100) + 0.5) / 100
            if n < HOLD_MIN then n = HOLD_MIN end
            if n > HOLD_MAX then n = HOLD_MAX end
            return n
        end

        local function formatHoldSeconds(value)
            return string.format("%.2f", normalizeHoldSeconds(value))
        end

        local function setHoldVisual(value)
            holdCurrentValue = normalizeHoldSeconds(value)
            holdValueText:SetText(formatHoldSeconds(holdCurrentValue))
            if holdEditing then
                holdValueEdit:SetText(formatHoldSeconds(holdCurrentValue))
            end
        end

        local function commitHoldValue(value)
            local clean = normalizeHoldSeconds(value)
            local old = normalizeHoldSeconds(PortalAuthorityDB and PortalAuthorityDB.releaseGateHoldSeconds)
            setHoldVisual(clean)
            if math.abs(clean - old) < 0.0001 then
                return false
            end
            if PortalAuthorityDB then
                PortalAuthorityDB.releaseGateHoldSeconds = clean
            end
            onApply()
            return true
        end

        local function endHoldEdit(commit)
            if not holdEditing then
                return
            end
            holdEditing = false
            if commit then
                local parsed = tonumber(trim(holdValueEdit:GetText() or ""))
                if parsed ~= nil then
                    commitHoldValue(parsed)
                end
            end
            holdValueEdit:Hide()
            holdValueText:Show()
            holdValueEdit:ClearFocus()
            setHoldVisual(holdCurrentValue)
        end

        local function beginHoldEdit()
            if not holdControlEnabled then
                return
            end
            holdEditing = true
            holdValueText:Hide()
            holdValueEdit:SetText(formatHoldSeconds(holdCurrentValue))
            holdValueEdit:Show()
            holdValueEdit:SetFocus()
            holdValueEdit:HighlightText()
        end

        local function setHoldEnabled(enabled)
            holdControlEnabled = enabled and true or false
            widgets.releaseHoldStepper:SetAlpha(holdControlEnabled and 1 or 0.55)
            holdMinus:SetEnabled(holdControlEnabled)
            holdPlus:SetEnabled(holdControlEnabled)
            holdValueButton:SetEnabled(holdControlEnabled)
            if not holdControlEnabled and holdEditing then
                endHoldEdit(false)
            end
        end

        holdMinus:SetScript("OnClick", function()
            if not holdControlEnabled then
                return
            end
            local mult = (IsShiftKeyDown and IsShiftKeyDown()) and HOLD_SHIFT_MULTIPLIER or 1
            commitHoldValue((holdCurrentValue or normalizeHoldSeconds(nil)) - (HOLD_STEP * mult))
        end)
        holdPlus:SetScript("OnClick", function()
            if not holdControlEnabled then
                return
            end
            local mult = (IsShiftKeyDown and IsShiftKeyDown()) and HOLD_SHIFT_MULTIPLIER or 1
            commitHoldValue((holdCurrentValue or normalizeHoldSeconds(nil)) + (HOLD_STEP * mult))
        end)
        holdValueButton:SetScript("OnClick", beginHoldEdit)
        holdValueEdit:SetScript("OnEnterPressed", function(edit)
            endHoldEdit(true)
            edit:ClearFocus()
        end)
        holdValueEdit:SetScript("OnEscapePressed", function(edit)
            endHoldEdit(false)
            edit:ClearFocus()
        end)
        holdValueEdit:SetScript("OnEditFocusLost", function()
            -- Explicit-action only: no commit on focus loss.
            endHoldEdit(false)
        end)

        widgets.releaseHoldStepper.SetEnabled = setHoldEnabled
        widgets.releaseHoldStepper.Refresh = function()
            setHoldVisual(normalizeHoldSeconds(PortalAuthorityDB and PortalAuthorityDB.releaseGateHoldSeconds))
        end
        widgets.releaseHoldStepper.SetVisualValue = setHoldVisual
        setHoldVisual(normalizeHoldSeconds(PortalAuthorityDB and PortalAuthorityDB.releaseGateHoldSeconds))

        local KU_UpdateKeystoneTooltipPreview
        local KU_PositionPreviewTooltip
        local KU_ReadPreviewBodyLeftLines
        local releaseHoldDesc = createStyledFontString(scrollChild, "ARTWORK", "GameFontHighlightSmall", 11)
        releaseHoldDesc:SetText(L["SETTINGS_KS_HOLD_DESC"])
        releaseHoldDesc:SetTextColor(0.72, 0.72, 0.72, 1)
        releaseHoldDesc:SetJustifyH("LEFT")
        local tooltipHeader = createStyledFontString(scrollChild, "ARTWORK", "GameFontNormalLarge", 14)
        tooltipHeader:SetText("|cffffd100" .. L["SETTINGS_KS_TOOLTIP_HEADER"] .. "|r")
        local tooltipSubheader = createStyledFontString(scrollChild, "ARTWORK", "GameFontHighlight", 12)
        tooltipSubheader:SetText(L["SETTINGS_KS_TOOLTIP_CUSTOMIZATION"])
        local KEYSTONE_UTILITY_LAYOUT = {
            SCROLL_WIDTH_FUDGE = 8,
            MIN_CONTENT_W = 560,
            HEADER_MIN_W = 220,
            LABEL_MIN_W = 150,
            LABEL_TEXT_PAD = 8,
            LABEL_TO_CONTROL_GAP = 12,
            CONTROL_MIN_W = 170,
            CONTROL_MAX_W = 220,
            CONTROL_WIDTH_RATIO = 0.34,
            DESC_MIN_W = 120,
            DESC_RIGHT_PAD = 10,
            STATUS_CHIP_MIN_W = 92,
            STATUS_CHIP_TEXT_PAD = 20,
            TOOLTIP_LABEL_MIN_W = 64,
            TOOLTIP_LABEL_MAX_W = 140,
            TOOLTIP_LABEL_TEXT_PAD = 8,
            TOOLTIP_LABEL_TO_CONTROL_GAP = 8,
            PAGE = {
                TOP_PAD = 20,
                HEADER_LEFT = 16,
                CONTENT_LEFT = 20,
                CONTENT_RIGHT = 20,
                TITLE_FLOOR = 16,
                TITLE_TO_SECTION_GAP = 8,
                BOTTOM_PAD = 40,
            },
            SECTION = {
                TITLE_FLOOR = 16,
                SUBHEADER_FLOOR = 12,
                SUBHEADER_GAP = 8,
                STACK_GAP = 16,
                DIVIDER_H = 1,
                DIVIDER_Y_OFFSET = 8,
                RELEASE_TO_TOOLTIP_GAP = 20,
                TOOLTIP_TITLE_TO_SUBHEADER_GAP = 6,
                TOOLTIP_SUBHEADER_TO_CONTENT_GAP = 8,
                TOOLTIP_BOTTOM_GAP = 14,
            },
            CARD = {
                PAD_X = 14,
                PAD_TOP = 12,
                PAD_BOTTOM = 12,
                ROW_FLOOR = 22,
                ROW_GAP = 10,
                DESC_GAP = 2,
                LABEL_FLOOR = 12,
                HELPER_FLOOR = 11,
                CONTROL_FLOOR = 22,
                CONTROL_TOP_NUDGE = 1,
            },
            STATUS = {
                STRIP_Y_NUDGE = 2,
                CHIP_H = 34,
                CHIP_GAP = 8,
            },
            TOOLTIP = {
                PANE_GAP = 16,
                STATUS_H = 16,
                ROW_GAP = 8,
                BASE_ROW_H = 30,
                ROW_H_COMPOUND_DROPPED = 68,
                ROW_H_SWATCH_DROPPED = 56,
                INLINE_BLOCK_GAP = 6,
                INLINE_REGION_GAP = 8,
                SUBLINE_MAIN_TO_LABEL_GAP = 2,
                SUBLINE_LABEL_TO_CONTROL_GAP = 2,
                INSPECTOR_PAD_X = 10,
                INSPECTOR_PAD_Y = 2,
                STATUS_TO_CONTENT_GAP = 2,
                MAIN_TOP_PAD = 2,
                SWATCH_GAP = 8,
                TOP_LABEL_Y_INSET = 4,
                SUBLINE_LABEL_X_INSET = 7,
                SUBLINE_LABEL_MIN_W = 72,
                SUBLINE_LABEL_RIGHT_PAD = 14,
                SUBLINE_ACCENT_X_INSET = 2,
                SUBLINE_ACCENT_Y_NUDGE = 1,
                SUBLINE_ACCENT_MIN_H = 12,
                SUBLINE_ACCENT_HEIGHT_PAD = 1,
                DROPPED_ROW_TOP_PAD = 2,
                DROPPED_ROW_BOTTOM_PAD = 4,
                CONTROL_FLOOR = 19,
                INLINE_LABEL_FLOOR = 10,
                TITLE_TOP_PAD = 8,
                PREVIEW_TITLE_FLOOR = 11,
                PREVIEW_TITLE_PAD_X = 10,
                PREVIEW_TITLE_CLEARANCE = 3,
                PREVIEW_FRAME_OFFSET_Y = 8,
                PREVIEW_BODY_TOP_GAP = 7,
                PREVIEW_BODY_PAD_X = 10,
                PREVIEW_BODY_BOTTOM_PAD = 10,
                STICKY_TOP_PAD = 0,
            },
            METRIC_WATCH_INTERVAL = 0.20,
        }
        local TOOLTIP_BUILDER_PREVIEW_MIN_W = 250
        local TOOLTIP_BUILDER_INSPECTOR_MIN_W = 250
        local TOOLTIP_BUILDER_PREVIEW_READABLE_MIN_W = 130
        local TOOLTIP_BUILDER_INSPECTOR_PICKER_W = 190
        local TOOLTIP_BUILDER_INLINE_TOGGLE_W = 88
        local TOOLTIP_BUILDER_INLINE_LABEL_W = 102
        local TOOLTIP_BUILDER_INSPECTOR_RIGHT_INSET = 30
        local TOOLTIP_BUILDER_MAIN_MIN_W = 240
        local TOOLTIP_BUILDER_MAIN_MAX_W = 360
        local TOOLTIP_BUILDER_PREVIEW_H = 260
        local TOOLTIP_BUILDER_CARD_BG_R, TOOLTIP_BUILDER_CARD_BG_G, TOOLTIP_BUILDER_CARD_BG_B, TOOLTIP_BUILDER_CARD_BG_A = 0.06, 0.07, 0.09, 0.90
        local TOOLTIP_BUILDER_CARD_BORDER_R, TOOLTIP_BUILDER_CARD_BORDER_G, TOOLTIP_BUILDER_CARD_BORDER_B, TOOLTIP_BUILDER_CARD_BORDER_A = 0.20, 0.23, 0.29, 0.90
        local TOOLTIP_BUILDER_MUTED_TEXT_R, TOOLTIP_BUILDER_MUTED_TEXT_G, TOOLTIP_BUILDER_MUTED_TEXT_B, TOOLTIP_BUILDER_MUTED_TEXT_A = 0.72, 0.74, 0.78, 0.94
        local TOOLTIP_BUILDER_HIGHLIGHT_BG_R, TOOLTIP_BUILDER_HIGHLIGHT_BG_G, TOOLTIP_BUILDER_HIGHLIGHT_BG_B = 0.24, 0.30, 0.38
        local TOOLTIP_BUILDER_HIGHLIGHT_ACCENT_R, TOOLTIP_BUILDER_HIGHLIGHT_ACCENT_G, TOOLTIP_BUILDER_HIGHLIGHT_ACCENT_B = 0.72, 0.79, 0.92

        local tooltipDungeonNameChoices = {
            { label = L["SETTINGS_KS_CHOICE_SHORT_NAME"], value = "SHORT" },
            { label = L["SETTINGS_KS_CHOICE_FULL_NAME"], value = "FULL" },
            { label = L["SETTINGS_KS_CHOICE_NICKNAME"], value = "NICKNAME" },
            { label = L["SETTINGS_KS_CHOICE_NICKNAME_FULL"], value = "NICKNAME_FULL" },
            { label = L["COMMON_DEFAULT"], value = "NO_CHANGES" },
        }
        local tooltipLevelChoices = {
            { label = "n", value = "N" },
            { label = "+n", value = "PLUS_N" },
            { label = "mn+", value = "M_N_PLUS" },
            { label = L["COMMON_HIDE"], value = "HIDE" },
            { label = L["COMMON_DEFAULT"], value = "NO_CHANGES" },
        }
        local tooltipAffixesChoices = {
            { label = L["SETTINGS_KS_CHOICE_NO_CHANGES"], value = "NO_CHANGES" },
            { label = L["SETTINGS_KS_CHOICE_RENAME_AFFIXES"], value = "RENAME_AFFIXES" },
            { label = L["COMMON_HIDE"], value = "HIDE" },
        }
        local tooltipModifiersSegmentChoices = {
            { label = L["COMMON_HIDE"], value = "HIDE", toggleState = "off" },
            { label = L["COMMON_DEFAULT"], value = "NO_CHANGES", toggleState = "on" },
            { label = L["SETTINGS_KS_CHOICE_AFFIXES"], value = "RENAME_AFFIXES", toggleState = "on" },
        }
        local tooltipHideShowChoices = {
            { label = L["COMMON_HIDE"], value = "HIDE", toggleState = "off" },
            { label = L["COMMON_SHOW"], value = "NO_CHANGES", toggleState = "on" },
        }
        local tooltipOffOnChoices = {
            { label = L["COMMON_OFF"], value = false, toggleState = "off" },
            { label = L["COMMON_ON"], value = true, toggleState = "on" },
        }
        local tooltipPrefixOffOnChoices = {
            -- Inverted mapping (UI intent):
            -- Off => remove "Keystone:" prefix
            -- On  => keep "Keystone:" prefix
            { label = L["COMMON_OFF"], value = true, toggleState = "off" },
            { label = L["COMMON_ON"], value = false, toggleState = "on" },
        }
        local tooltipLineConfigs = {
            {
                lineId = "DungeonName",
                label = L["SETTINGS_KS_DUNGEON_NAME"],
                type = "picker",
                dbKey = "keystoneTooltipDungeonNameMode",
                options = tooltipDungeonNameChoices,
                inline = {
                    label = L["SETTINGS_KS_KEYSTONE_PREFIX"],
                    dbKey = "keystoneTooltipRemoveKeystonePrefix",
                    choices = tooltipPrefixOffOnChoices,
                    layout = "subline",
                },
                affectsLayout = true,
            },
            {
                lineId = "Level",
                label = L["SETTINGS_KS_LEVEL"],
                type = "picker",
                dbKey = "keystoneTooltipLevelMode",
                options = tooltipLevelChoices,
                inline = {
                    label = L["SETTINGS_KS_APPEND_TO_NAME"],
                    dbKey = "keystoneTooltipLevelAddToName",
                    choices = tooltipOffOnChoices,
                    layout = "subline",
                },
                affectsLayout = true,
            },
            {
                lineId = "Resilient",
                label = L["SETTINGS_KS_RESILIENT_LEVEL"],
                type = "segmented",
                dbKey = "keystoneTooltipResilientMode",
                choices = tooltipHideShowChoices,
                affectsLayout = true,
            },
            {
                lineId = "Soulbound",
                label = L["SETTINGS_KS_SOULBOUND_BOP"],
                type = "segmented",
                dbKey = "keystoneTooltipSoulboundMode",
                choices = tooltipHideShowChoices,
                affectsLayout = true,
            },
            {
                lineId = "Unique",
                label = L["SETTINGS_KS_UNIQUE"],
                type = "segmented",
                dbKey = "keystoneTooltipUniqueMode",
                choices = tooltipHideShowChoices,
                affectsLayout = true,
            },
            {
                lineId = "Modifiers",
                label = L["SETTINGS_KS_DUNGEON_MODIFIERS"],
                type = "segmented",
                dbKey = "keystoneTooltipAffixesMode",
                choices = tooltipModifiersSegmentChoices,
                affectsLayout = true,
            },
            {
                lineId = "Duration",
                label = L["SETTINGS_KS_DURATION"],
                type = "segmented",
                dbKey = "keystoneTooltipDurationMode",
                choices = tooltipHideShowChoices,
                affectsLayout = true,
            },
            {
                lineId = "RPQuote",
                label = L["SETTINGS_KS_YELLOW_RP_QUOTE"],
                type = "segmented",
                dbKey = "keystoneTooltipRPQuoteMode",
                choices = tooltipHideShowChoices,
                affectsLayout = true,
            },
        }

        local tooltipBuilder = {}
        widgets.tooltipBuilder = tooltipBuilder
        tooltipBuilder.rows = {}
        tooltipBuilder.rowsById = {}
        tooltipBuilder.previewOverlays = {}
        tooltipBuilder.previewOverlaysByLineId = {}
        tooltipBuilder.mappingByLineId = {}
        tooltipBuilder.visibleInspectorLineIds = {}
        tooltipBuilder.visiblePreviewLineIds = {}
        tooltipBuilder.hoveredLineId = nil
        tooltipBuilder.selectedLineId = nil
        tooltipBuilder._lastCommit = nil

        local tooltipBuilderRoot = CreateFrame("Frame", nil, scrollChild)
        tooltipBuilder.root = tooltipBuilderRoot

        tooltipBuilder.inspectorPane = CreateFrame("Frame", nil, tooltipBuilderRoot, "BackdropTemplate")
        tooltipBuilder.inspectorPane:SetBackdrop({
            bgFile = "Interface\\Buttons\\WHITE8x8",
            edgeFile = "Interface\\Buttons\\WHITE8x8",
            edgeSize = 1,
            insets = { left = 0, right = 0, top = 0, bottom = 0 },
        })
        tooltipBuilder.inspectorPane:SetBackdropColor(TOOLTIP_BUILDER_CARD_BG_R, TOOLTIP_BUILDER_CARD_BG_G, TOOLTIP_BUILDER_CARD_BG_B, TOOLTIP_BUILDER_CARD_BG_A)
        tooltipBuilder.inspectorPane:SetBackdropBorderColor(TOOLTIP_BUILDER_CARD_BORDER_R, TOOLTIP_BUILDER_CARD_BORDER_G, TOOLTIP_BUILDER_CARD_BORDER_B, TOOLTIP_BUILDER_CARD_BORDER_A)
        if tooltipBuilder.inspectorPane.SetBackdrop then
            tooltipBuilder.inspectorPane:SetBackdrop(nil)
        end

        tooltipBuilder.statusSlot = CreateFrame("Frame", nil, tooltipBuilder.inspectorPane)
        tooltipBuilder.statusSlot:SetHeight(KEYSTONE_UTILITY_LAYOUT.TOOLTIP.STATUS_H)
        tooltipBuilder.statusText = createStyledFontString(tooltipBuilder.statusSlot, "ARTWORK", "GameFontHighlightSmall", 11)
        tooltipBuilder.statusText:SetPoint("TOPLEFT", tooltipBuilder.statusSlot, "TOPLEFT", 0, 0)
        tooltipBuilder.statusText:SetPoint("BOTTOMLEFT", tooltipBuilder.statusSlot, "BOTTOMLEFT", 0, 0)
        tooltipBuilder.statusText:SetJustifyH("LEFT")
        tooltipBuilder.statusText:SetTextColor(TOOLTIP_BUILDER_MUTED_TEXT_R, TOOLTIP_BUILDER_MUTED_TEXT_G, TOOLTIP_BUILDER_MUTED_TEXT_B, 0.88)
        tooltipBuilder.statusText:SetText("")

        tooltipBuilder.inspectorContent = CreateFrame("Frame", nil, tooltipBuilder.inspectorPane)
        tooltipBuilder.inspectorContent:SetSize(1, 1)
        tooltipBuilder.inspectorHeader = createStyledFontString(tooltipBuilder.inspectorContent, "ARTWORK", "GameFontHighlightSmall", 11)
        tooltipBuilder.inspectorHeader:SetText("")
        tooltipBuilder.inspectorHeader:SetTextColor(TOOLTIP_BUILDER_MUTED_TEXT_R, TOOLTIP_BUILDER_MUTED_TEXT_G, TOOLTIP_BUILDER_MUTED_TEXT_B, 0.95)
        tooltipBuilder.inspectorHeader:SetJustifyH("LEFT")
        tooltipBuilder.inspectorHeader:Hide()

        tooltipBuilder.previewPane = CreateFrame("Frame", nil, tooltipBuilderRoot, "BackdropTemplate")
        tooltipBuilder.previewPane:SetBackdrop({
            bgFile = "Interface\\Buttons\\WHITE8x8",
            edgeFile = "Interface\\Buttons\\WHITE8x8",
            edgeSize = 1,
            insets = { left = 0, right = 0, top = 0, bottom = 0 },
        })
        tooltipBuilder.previewPane:SetBackdropColor(TOOLTIP_BUILDER_CARD_BG_R, TOOLTIP_BUILDER_CARD_BG_G, TOOLTIP_BUILDER_CARD_BG_B, 0.92)
        tooltipBuilder.previewPane:SetBackdropBorderColor(TOOLTIP_BUILDER_CARD_BORDER_R, TOOLTIP_BUILDER_CARD_BORDER_G, TOOLTIP_BUILDER_CARD_BORDER_B, TOOLTIP_BUILDER_CARD_BORDER_A)
        if tooltipBuilder.previewPane.SetBackdrop then
            tooltipBuilder.previewPane:SetBackdrop(nil)
        end

        tooltipBuilder.previewTitle = createStyledFontString(tooltipBuilder.previewPane, "ARTWORK", "GameFontHighlightSmall", 11)
        tooltipBuilder.previewTitle:SetText("")
        tooltipBuilder.previewTitle:SetTextColor(TOOLTIP_BUILDER_MUTED_TEXT_R, TOOLTIP_BUILDER_MUTED_TEXT_G, TOOLTIP_BUILDER_MUTED_TEXT_B, 0.90)
        tooltipBuilder.previewTitle:Hide()

        widgets.keystoneTooltipPreviewAnchor = CreateFrame("Frame", nil, tooltipBuilder.previewPane, "BackdropTemplate")
        widgets.keystoneTooltipPreviewAnchor:EnableMouse(false)
        widgets.keystoneTooltipPreviewAnchor:SetSize(164, 220)

        widgets.keystoneTooltipPreviewTooltip = CreateFrame("GameTooltip", "PortalAuthority_KeystoneTooltipPreview", widgets.keystoneTooltipPreviewAnchor, "GameTooltipTemplate")
        widgets.keystoneTooltipPreviewTooltip:EnableMouse(false)
        widgets.keystoneTooltipPreviewTooltip:SetClampedToScreen(true)
        widgets.keystoneTooltipPreviewTooltip:SetOwner(widgets.keystoneTooltipPreviewAnchor, "ANCHOR_NONE")
        widgets.keystoneTooltipPreviewTooltip:ClearAllPoints()
        widgets.keystoneTooltipPreviewTooltip:SetPoint("TOPLEFT", widgets.keystoneTooltipPreviewAnchor, "TOPLEFT", 6, -6)

        tooltipBuilder.previewHitLayer = CreateFrame("Frame", nil, tooltipBuilder.previewPane)
        tooltipBuilder.previewHitLayer:SetFrameStrata("TOOLTIP")
        tooltipBuilder.previewHitLayer:SetFrameLevel((widgets.keystoneTooltipPreviewTooltip:GetFrameLevel() or 0) + 50)
        tooltipBuilder.previewHitLayer:EnableMouse(true)

        local function KU_ApplyExternalTooltipSkin(tt)
            if not tt then
                return
            end
            local elv = _G.ElvUI
            local E = nil
            if type(elv) == "table" then
                E = elv[1] or elv
            end
            if E and E.GetModule then
                local okTT, TT = pcall(E.GetModule, E, "Tooltip")
                if okTT and TT and TT.SetStyle then
                    pcall(TT.SetStyle, TT, tt)
                end
            end
        end

        local function refreshTooltipAffixesSwatch()
            local defaults = (PortalAuthority and PortalAuthority.defaults) or {}
            local fallback = defaults.keystoneTooltipAffixesColor or { r = 1, g = 0.82, b = 0, a = 1 }
            local c = PortalAuthorityDB and PortalAuthorityDB.keystoneTooltipAffixesColor or fallback
            local r = tonumber(c and c.r) or fallback.r
            local g = tonumber(c and c.g) or fallback.g
            local b = tonumber(c and c.b) or fallback.b
            local a = tonumber(c and c.a) or fallback.a
            for _, row in ipairs(tooltipBuilder.rows) do
                if row.colorSwatch and row.colorSwatch.SetBackdropColor then
                    row.colorSwatch:SetBackdropColor(r, g, b, a)
                end
            end
        end

        local function openKeystoneTooltipAffixesColorPicker(onChangedFn)
            if not (ColorPickerFrame and ColorPickerFrame.SetupColorPickerAndShow) then
                return
            end
            local defaults = (PortalAuthority and PortalAuthority.defaults) or {}
            local fallback = defaults.keystoneTooltipAffixesColor or { r = 1, g = 0.82, b = 0, a = 1 }
            local cur = PortalAuthorityDB and PortalAuthorityDB.keystoneTooltipAffixesColor or fallback
            local r = tonumber(cur and cur.r) or fallback.r
            local g = tonumber(cur and cur.g) or fallback.g
            local b = tonumber(cur and cur.b) or fallback.b
            local a = tonumber(cur and cur.a) or fallback.a
            ColorPickerFrame:SetupColorPickerAndShow({
                r = r,
                g = g,
                b = b,
                opacity = 1 - a,
                hasOpacity = true,
                swatchFunc = function()
                    local nr, ng, nb = ColorPickerFrame:GetColorRGB()
                    local na = 1 - (OpacitySliderFrame and OpacitySliderFrame:GetValue() or 0)
                    PortalAuthorityDB.keystoneTooltipAffixesColor = { r = nr, g = ng, b = nb, a = na }
                    if onChangedFn then onChangedFn() end
                end,
                opacityFunc = function()
                    local nr, ng, nb = ColorPickerFrame:GetColorRGB()
                    local na = 1 - (OpacitySliderFrame and OpacitySliderFrame:GetValue() or 0)
                    PortalAuthorityDB.keystoneTooltipAffixesColor = { r = nr, g = ng, b = nb, a = na }
                    if onChangedFn then onChangedFn() end
                end,
                cancelFunc = function(prev)
                    PortalAuthorityDB.keystoneTooltipAffixesColor = restoreColorPickerPrevious(prev, fallback)
                    if onChangedFn then onChangedFn() end
                end,
            })
        end

        local function KU_FindFirstKeystoneLinkInBags()
            local firstBag = BACKPACK_CONTAINER or 0
            local lastBag = NUM_TOTAL_EQUIPPED_BAG_SLOTS or 4
            for bag = firstBag, lastBag do
                local slots = 0
                if C_Container and C_Container.GetContainerNumSlots then
                    local okSlots, bagSlots = pcall(C_Container.GetContainerNumSlots, bag)
                    if okSlots then
                        slots = tonumber(bagSlots) or 0
                    end
                end
                for slot = 1, slots do
                    if C_Container and C_Container.GetContainerItemLink then
                        local okLink, link = pcall(C_Container.GetContainerItemLink, bag, slot)
                        if okLink and type(link) == "string" and string.find(link, "|Hkeystone:", 1, true) then
                            return link
                        end
                    end
                end
            end
            return nil
        end

        local function KU_BuildFallbackKeystoneContext()
            local mapID = 0
            local level = 10
            local affixIDs = {}
            local displayName = L["SETTINGS_KS_FALLBACK_SAMPLE_KEYSTONE"]

            if C_MythicPlus and C_MythicPlus.GetOwnedKeystoneMapID then
                local ok, ownedMapID = pcall(C_MythicPlus.GetOwnedKeystoneMapID)
                if ok then
                    mapID = tonumber(ownedMapID) or mapID
                end
            end
            if mapID <= 0 and C_MythicPlus and C_MythicPlus.GetOwnedKeystoneChallengeMapID then
                local ok, ownedChallengeMapID = pcall(C_MythicPlus.GetOwnedKeystoneChallengeMapID)
                if ok then
                    mapID = tonumber(ownedChallengeMapID) or mapID
                end
            end
            if mapID <= 0 and C_ChallengeMode and C_ChallengeMode.GetActiveChallengeMapID then
                local ok, activeMapID = pcall(C_ChallengeMode.GetActiveChallengeMapID)
                if ok then
                    mapID = tonumber(activeMapID) or mapID
                end
            end
            if mapID <= 0 and C_ChallengeMode and C_ChallengeMode.GetMapTable then
                local ok, mapTable = pcall(C_ChallengeMode.GetMapTable)
                if ok and type(mapTable) == "table" then
                    for _, v in ipairs(mapTable) do
                        local n = tonumber(v) or 0
                        if n > 0 then
                            mapID = n
                            break
                        end
                    end
                end
            end

            if C_MythicPlus and C_MythicPlus.GetOwnedKeystoneLevel then
                local ok, ownedLevel = pcall(C_MythicPlus.GetOwnedKeystoneLevel)
                if ok then
                    local n = tonumber(ownedLevel) or 0
                    if n > 0 then
                        level = n
                    end
                end
            end

            if C_MythicPlus and C_MythicPlus.GetCurrentAffixes then
                local ok, currentAffixes = pcall(C_MythicPlus.GetCurrentAffixes)
                if ok and type(currentAffixes) == "table" then
                    for _, a in ipairs(currentAffixes) do
                        local id = 0
                        if type(a) == "table" then
                            id = tonumber(a.id) or tonumber(a.affixID) or tonumber(a[1]) or 0
                        else
                            id = tonumber(a) or 0
                        end
                        if id > 0 then
                            affixIDs[#affixIDs + 1] = id
                            if #affixIDs >= 3 then
                                break
                            end
                        end
                    end
                end
            end
            if #affixIDs == 0 and C_ChallengeMode and C_ChallengeMode.GetAffixInfo then
                for id = 1, 200 do
                    local ok, name = pcall(C_ChallengeMode.GetAffixInfo, id)
                    if ok and type(name) == "string" and trim(name) ~= "" then
                        affixIDs[#affixIDs + 1] = id
                        if #affixIDs >= 3 then
                            break
                        end
                    end
                end
            end

            if mapID > 0 and C_ChallengeMode and C_ChallengeMode.GetMapUIInfo then
                local ok, name = pcall(C_ChallengeMode.GetMapUIInfo, mapID)
                if ok and type(name) == "string" and trim(name) ~= "" then
                    displayName = trim(name)
                end
            end

            return mapID, level, affixIDs, displayName
        end

        local function KU_BuildFallbackKeystoneHyperlink(mapID, level, affixIDs)
            local safeMapID = tonumber(mapID) or 0
            local safeLevel = tonumber(level) or 10
            if safeLevel <= 0 then
                safeLevel = 10
            end

            local affixParts = {}
            if type(affixIDs) == "table" then
                for i = 1, math.min(#affixIDs, 3) do
                    local n = tonumber(affixIDs[i]) or 0
                    if n > 0 then
                        affixParts[#affixParts + 1] = tostring(n)
                    end
                end
            end
            local affixSuffix = (#affixParts > 0) and (":" .. table.concat(affixParts, ":")) or ""
            return string.format("|cffa335ee|Hkeystone:180653:%d:%d%s|h[%s]|h|r", safeMapID, safeLevel, affixSuffix, L["SETTINGS_KS_STATUS_KEYSTONE"])
        end

        local function KU_SeedFallbackPreviewLines(previewTooltip, displayName, level, affixIDs)
            if not previewTooltip then
                return
            end
            previewTooltip:ClearLines()
            previewTooltip:AddLine(L["SETTINGS_KS_FALLBACK_MYTHIC_KEYSTONE"], 0.64, 0.21, 0.93)
            previewTooltip:AddLine(string.format(L["SETTINGS_KS_FALLBACK_KEYSTONE_FORMAT"], displayName or L["SETTINGS_KS_FALLBACK_SAMPLE_KEYSTONE"]), 1, 1, 1)
            previewTooltip:AddLine(string.format(L["SETTINGS_KS_FALLBACK_LEVEL_FORMAT"], math.floor(tonumber(level) or 10)), 1, 1, 1)
            previewTooltip:AddLine(L["SETTINGS_KS_FALLBACK_RESILIENT_LEVEL"], 1, 1, 1)
            previewTooltip:AddLine(L["SETTINGS_KS_FALLBACK_SOULBOUND"], 1, 1, 1)
            previewTooltip:AddLine(L["SETTINGS_KS_FALLBACK_UNIQUE"], 1, 1, 1)
            previewTooltip:AddLine(L["SETTINGS_KS_FALLBACK_DUNGEON_MODIFIERS"], 1, 1, 1)

            if type(affixIDs) == "table" then
                for i = 1, math.min(#affixIDs, 3) do
                    local affixID = tonumber(affixIDs[i]) or 0
                    if affixID > 0 then
                        local affixName = nil
                        if C_ChallengeMode and C_ChallengeMode.GetAffixInfo then
                            local ok, name = pcall(C_ChallengeMode.GetAffixInfo, affixID)
                            if ok and type(name) == "string" and trim(name) ~= "" then
                                affixName = trim(name)
                            end
                        end
                        previewTooltip:AddLine("- " .. (affixName or string.format(L["SETTINGS_KS_FALLBACK_AFFIX_FORMAT"], affixID)), 1, 1, 1)
                    end
                end
            end

            previewTooltip:AddLine(L["SETTINGS_KS_FALLBACK_DURATION"], 1, 1, 1)
            previewTooltip:AddLine(L["SETTINGS_KS_FALLBACK_RP_QUOTE"], 1, 0.82, 0)
        end

        local function KU_ApplyPreviewWordWrap(tooltip, previewAnchor)
            if not tooltip or not tooltip.GetName then
                return
            end
            local baseName = tooltip:GetName()
            if type(baseName) ~= "string" or baseName == "" then
                return
            end
            local anchorW = 0
            if previewAnchor and previewAnchor.GetWidth then
                anchorW = tonumber(previewAnchor:GetWidth()) or 0
            end
            if tooltipBuilder and tooltipBuilder.previewPane and tooltipBuilder.previewPane.GetWidth then
                local paneW = tonumber(tooltipBuilder.previewPane:GetWidth()) or 0
                if paneW > 0 then
                    anchorW = math.max(anchorW, paneW - 20)
                end
            end
            if anchorW <= 0 then
                anchorW = 280
            end
            local maxW = anchorW - 20
            if maxW < 240 then maxW = 240 end
            if maxW > 280 then maxW = 280 end

            if tooltip.SetWidth then
                pcall(tooltip.SetWidth, tooltip, maxW)
            end
            local textW = maxW - 20
            for i = 1, (tooltip.NumLines and tooltip:NumLines() or 0) do
                local left = _G[baseName .. "TextLeft" .. i]
                local right = _G[baseName .. "TextRight" .. i]
                if left then
                    if left.SetWidth then pcall(left.SetWidth, left, textW) end
                    if left.SetWordWrap then pcall(left.SetWordWrap, left, true) end
                    if left.SetNonSpaceWrap then pcall(left.SetNonSpaceWrap, left, true) end
                end
                if right then
                    if right.SetWidth then pcall(right.SetWidth, right, textW) end
                    if right.SetWordWrap then pcall(right.SetWordWrap, right, true) end
                    if right.SetNonSpaceWrap then pcall(right.SetNonSpaceWrap, right, true) end
                end
            end
        end

        local function KU_FitPreviewTooltipFrameToContent(tooltip)
            if not tooltip or not tooltip.GetName then
                return
            end
            local baseName = tooltip:GetName()
            if type(baseName) ~= "string" or baseName == "" then
                return
            end

            local minLeft, maxRight, minBottom, maxTop
            local sumLineH = 0
            for i = 1, (tooltip.NumLines and tooltip:NumLines() or 0) do
                local left = _G[baseName .. "TextLeft" .. i]
                local right = _G[baseName .. "TextRight" .. i]
                local leftShown = left and left.IsShown and left:IsShown() and trim(left:GetText() or "") ~= ""
                local rightShown = right and right.IsShown and right:IsShown() and trim(right:GetText() or "") ~= ""
                if leftShown then
                    local l, r, t, b = left:GetLeft(), left:GetRight(), left:GetTop(), left:GetBottom()
                    if l and r and t and b then
                        minLeft = minLeft and math.min(minLeft, l) or l
                        maxRight = maxRight and math.max(maxRight, r) or r
                        maxTop = maxTop and math.max(maxTop, t) or t
                        minBottom = minBottom and math.min(minBottom, b) or b
                    end
                end
                if rightShown then
                    local l, r, t, b = right:GetLeft(), right:GetRight(), right:GetTop(), right:GetBottom()
                    if l and r and t and b then
                        minLeft = minLeft and math.min(minLeft, l) or l
                        maxRight = maxRight and math.max(maxRight, r) or r
                        maxTop = maxTop and math.max(maxTop, t) or t
                        minBottom = minBottom and math.min(minBottom, b) or b
                    end
                end
                if leftShown or rightShown then
                    local leftH = (left and left.GetStringHeight and tonumber(left:GetStringHeight())) or 0
                    local rightH = (right and right.GetStringHeight and tonumber(right:GetStringHeight())) or 0
                    local lineH = math.max(leftH, rightH, 12)
                    sumLineH = sumLineH + lineH + 2
                end
            end

            local targetW, targetH
            if minLeft and maxRight and maxTop and minBottom then
                targetW = math.max(1, math.ceil((maxRight - minLeft) + 20))
                targetH = math.max(1, math.ceil((maxTop - minBottom) + 14))
            end
            if sumLineH > 0 then
                local byStringH = math.max(1, math.ceil(sumLineH + 14))
                if targetH then
                    targetH = math.max(targetH, byStringH)
                else
                    targetH = byStringH
                end
            end
            if targetW and tooltip.SetWidth then
                pcall(tooltip.SetWidth, tooltip, targetW)
            end
            if targetH and tooltip.SetHeight then
                pcall(tooltip.SetHeight, tooltip, targetH)
            end
        end

        local function KU_RequestPreviewSettle(tooltip, previewAnchor)
            if not tooltip then
                return
            end
            tooltip._paPreviewSettleAnchor = previewAnchor
            tooltip._paPreviewSettlePasses = 90
            local settleDriver = tooltipBuilder and tooltipBuilder.previewSettleDriver or nil
            if settleDriver then
                settleDriver._elapsed = 0
                settleDriver:Show()
            end
        end

        local function KU_RunPreviewSettleStep(tooltip)
            if not tooltip then
                return
            end
            local anchor = tooltip._paPreviewSettleAnchor or widgets.keystoneTooltipPreviewAnchor
            if not anchor then
                tooltip._paPreviewSettlePasses = 0
                return
            end
            KU_ApplyPreviewWordWrap(tooltip, anchor)
            tooltip:Show()
            KU_FitPreviewTooltipFrameToContent(tooltip)
            KU_PositionPreviewTooltip(tooltip, anchor)
            tooltip._paPreviewSettlePasses = (tonumber(tooltip._paPreviewSettlePasses) or 1) - 1
            if (tooltip._paPreviewSettlePasses or 0) < 0 then
                tooltip._paPreviewSettlePasses = 0
            end
        end

        if not tooltipBuilder.previewSettleDriver then
            local settleDriver = CreateFrame("Frame", nil, tooltipBuilder.previewPane)
            settleDriver:Hide()
            settleDriver:SetScript("OnUpdate", function(selfDriver, elapsed)
                selfDriver._elapsed = (tonumber(selfDriver._elapsed) or 0) + (tonumber(elapsed) or 0)
                if selfDriver._elapsed < 0.08 then
                    return
                end
                selfDriver._elapsed = 0
                if not panelRef or not panelRef.IsShown or not panelRef:IsShown() then
                    selfDriver:Hide()
                    return
                end
                local tt = widgets and widgets.keystoneTooltipPreviewTooltip or nil
                local anchor = widgets and widgets.keystoneTooltipPreviewAnchor or nil
                if tt and tt.IsShown and tt:IsShown() and anchor then
                    if (tonumber(tt._paPreviewSettlePasses) or 0) > 0 then
                        KU_RunPreviewSettleStep(tt)
                    else
                        KU_ApplyPreviewWordWrap(tt, anchor)
                        KU_FitPreviewTooltipFrameToContent(tt)
                        KU_PositionPreviewTooltip(tt, anchor)
                    end
                end
            end)
            tooltipBuilder.previewSettleDriver = settleDriver
            panelRef._kuTooltipPreviewSettleDriver = settleDriver
        end

        KU_UpdateKeystoneTooltipPreview = function()
            local previewAnchor = widgets.keystoneTooltipPreviewAnchor
            local previewTooltip = widgets.keystoneTooltipPreviewTooltip
            if not previewAnchor or not previewTooltip then
                return
            end
            KU_ApplyExternalTooltipSkin(previewTooltip)

            local link = KU_FindFirstKeystoneLinkInBags()
            previewTooltip:SetOwner(previewAnchor, "ANCHOR_NONE")
            previewTooltip:ClearAllPoints()
            previewTooltip:SetPoint("TOPLEFT", previewAnchor, "TOPLEFT", 6, -6)
            previewTooltip:ClearLines()

            if type(link) ~= "string" then
                local mapID, level, affixIDs, displayName = KU_BuildFallbackKeystoneContext()
                local fallbackLink = KU_BuildFallbackKeystoneHyperlink(mapID, level, affixIDs)
                local okSet = false
                if previewTooltip.SetHyperlink and type(fallbackLink) == "string" then
                    okSet = pcall(previewTooltip.SetHyperlink, previewTooltip, fallbackLink)
                end
                if not okSet then
                    KU_SeedFallbackPreviewLines(previewTooltip, displayName, level, affixIDs)
                end
                if PortalAuthority and PortalAuthority.KeystoneTooltip_OnItemTooltip then
                    PortalAuthority:KeystoneTooltip_OnItemTooltip(previewTooltip, { hyperlink = fallbackLink })
                end
                KU_ApplyPreviewWordWrap(previewTooltip, previewAnchor)
                previewTooltip:Show()
                KU_RequestPreviewSettle(previewTooltip, previewAnchor)
                KU_RunPreviewSettleStep(previewTooltip)
                return
            end

            previewTooltip:SetHyperlink(link)
            if PortalAuthority and PortalAuthority.KeystoneTooltip_OnItemTooltip then
                PortalAuthority:KeystoneTooltip_OnItemTooltip(previewTooltip, { hyperlink = link })
            end
            KU_ApplyPreviewWordWrap(previewTooltip, previewAnchor)
            previewTooltip:Show()
            KU_RequestPreviewSettle(previewTooltip, previewAnchor)
            KU_RunPreviewSettleStep(previewTooltip)
        end

        local function KU_Normalize(v)
            local ok, s = pcall(tostring, v)
            if not ok or s == nil then
                return ""
            end
            s = trim(tostring(s))
            if s == "" then
                return ""
            end
            return string.upper(s)
        end

        local KU_RefreshTooltipBuilderVisual = nil
        panelRef._kuHydrateKeystoneTooltipControls = function()
            if KU_RefreshTooltipBuilderVisual then
                KU_RefreshTooltipBuilderVisual()
            end
        end
        panelRef._kuHydrateKeystoneTooltipVisualOnly = panelRef._kuHydrateKeystoneTooltipControls
        panelRef._kuRefreshHoldForce = function()
            if widgets.releaseHoldStepper and widgets.releaseHoldStepper.Refresh then
                widgets.releaseHoldStepper:Refresh()
            end
        end
        panelRef._commitHoldIfDirty = nil

        KU_PositionPreviewTooltip = function(previewTooltip, previewAnchor)
            if not previewTooltip or not previewAnchor then
                return
            end
            local x = 6
            local y = -8
            previewTooltip:ClearAllPoints()
            previewTooltip:SetPoint("TOPLEFT", previewAnchor, "TOPLEFT", x, y)
        end

        if widgets.keystoneTooltipPreviewTooltip
            and widgets.keystoneTooltipPreviewTooltip.HasScript
            and widgets.keystoneTooltipPreviewTooltip:HasScript("OnTooltipSetItem")
        then
            widgets.keystoneTooltipPreviewTooltip:HookScript("OnTooltipSetItem", function(tt)
                local anchor = widgets.keystoneTooltipPreviewAnchor
                if not anchor then return end
                KU_RequestPreviewSettle(tt, anchor)
                KU_RunPreviewSettleStep(tt)
            end)
        end
        if widgets.keystoneTooltipPreviewTooltip
            and widgets.keystoneTooltipPreviewTooltip.HasScript
            and widgets.keystoneTooltipPreviewTooltip:HasScript("OnShow")
        then
            widgets.keystoneTooltipPreviewTooltip:HookScript("OnShow", function(tt)
                local anchor = widgets.keystoneTooltipPreviewAnchor
                if not anchor then return end
                if (tonumber(tt._paPreviewSettlePasses) or 0) <= 0 then
                    KU_RequestPreviewSettle(tt, anchor)
                end
            end)
        end
        if widgets.keystoneTooltipPreviewTooltip
            and widgets.keystoneTooltipPreviewTooltip.HasScript
            and widgets.keystoneTooltipPreviewTooltip:HasScript("OnUpdate")
        then
            widgets.keystoneTooltipPreviewTooltip:HookScript("OnUpdate", function(tt)
                if (tonumber(tt._paPreviewSettlePasses) or 0) > 0 then
                    KU_RunPreviewSettleStep(tt)
                end
            end)
        end
        if widgets.keystoneTooltipPreviewTooltip
            and widgets.keystoneTooltipPreviewTooltip.HasScript
            and widgets.keystoneTooltipPreviewTooltip:HasScript("OnHide")
        then
            widgets.keystoneTooltipPreviewTooltip:HookScript("OnHide", function(tt)
                tt._paPreviewSettlePasses = 0
            end)
        end

        local function KU_SetBuilderStatus(text)
            local value = trim(tostring(text or ""))
            tooltipBuilder.statusText:SetText(value)
        end

        local function KU_ClearBuilderStatus()
            KU_SetBuilderStatus("")
        end

        local function KU_ValuesEqual(a, b)
            if type(a) == "boolean" or type(b) == "boolean" then
                return PA_SafeBool(a) == PA_SafeBool(b)
            end
            return KU_Normalize(a) == KU_Normalize(b)
        end

        local function KU_ResolveVisualChoice(rawValue, choices)
            for _, choice in ipairs(choices or {}) do
                if KU_ValuesEqual(choice.value, rawValue) then
                    return choice.value, choice.label
                end
            end
            for _, choice in ipairs(choices or {}) do
                if KU_Normalize(choice.value) == "NO_CHANGES" then
                    return choice.value, choice.label
                end
            end
            local first = choices and choices[1]
            if first then
                return first.value, first.label
            end
            return nil, ""
        end

        local function KU_SetRowHighlight(row, hovered, selected)
            if not row then
                return
            end
            if selected then
                row.highlightBg:SetAlpha(0.12)
                row.highlightAccent:SetAlpha(0.34)
            elseif hovered then
                row.highlightBg:SetAlpha(0.07)
                row.highlightAccent:SetAlpha(0)
            else
                row.highlightBg:SetAlpha(0)
                row.highlightAccent:SetAlpha(0)
            end
        end

        local function KU_SetOverlayHighlight(overlay, hovered, selected)
            if not overlay then
                return
            end
            if selected then
                overlay._bg:SetAlpha(0.12)
                overlay._accent:SetAlpha(0.34)
            elseif hovered then
                overlay._bg:SetAlpha(0.07)
                overlay._accent:SetAlpha(0)
            else
                overlay._bg:SetAlpha(0)
                overlay._accent:SetAlpha(0)
            end
        end

        local function KU_RefreshLinkedVisuals()
            for _, row in ipairs(tooltipBuilder.rows) do
                KU_SetRowHighlight(row, tooltipBuilder.hoveredLineId == row.lineId, tooltipBuilder.selectedLineId == row.lineId)
            end
            for _, overlay in ipairs(tooltipBuilder.previewOverlays) do
                KU_SetOverlayHighlight(overlay, tooltipBuilder.hoveredLineId == overlay.lineId, tooltipBuilder.selectedLineId == overlay.lineId)
            end
        end

        local function KU_SetHoveredLine(lineId)
            local normalized = lineId
            if normalized and not tooltipBuilder.rowsById[normalized] then
                normalized = nil
            end
            if tooltipBuilder.hoveredLineId ~= normalized then
                tooltipBuilder.hoveredLineId = normalized
                KU_RefreshLinkedVisuals()
            end
        end

        local function KU_ClearHover()
            if tooltipBuilder.hoveredLineId ~= nil then
                tooltipBuilder.hoveredLineId = nil
                KU_RefreshLinkedVisuals()
            end
        end

        local function KU_SelectLine(lineId, fromPreviewClick)
            if lineId and tooltipBuilder.rowsById[lineId] then
                if tooltipBuilder.selectedLineId == lineId then
                    tooltipBuilder.selectedLineId = nil
                else
                    tooltipBuilder.selectedLineId = lineId
                end
                KU_ClearBuilderStatus()
            else
                tooltipBuilder.selectedLineId = nil
            end
            KU_RefreshLinkedVisuals()

            if fromPreviewClick and lineId and tooltipBuilder.rowsById[lineId] then
                -- Non-scrollable layout: no per-row viewport to adjust.
            end
        end

        tooltipBuilder.inspectorPane:EnableMouse(true)
        tooltipBuilder.inspectorPane:SetScript("OnMouseDown", function(_, mouseButton)
            if mouseButton == "LeftButton" then
                KU_SelectLine(nil, false)
            end
        end)
        tooltipBuilder.previewHitLayer:SetScript("OnMouseDown", function(_, mouseButton)
            if mouseButton == "LeftButton" then
                KU_SelectLine(nil, false)
            end
        end)

        local function KU_OnTooltipCommit(lineId, affectsLayout)
            tooltipBuilder._lastCommit = {
                lineId = lineId,
                affectsLayout = affectsLayout and true or false,
            }
            onApply()
        end

        local function KU_ForwardPanelMouseWheel(delta)
            if not scrollFrame then
                return
            end
            local onWheel = scrollFrame.GetScript and scrollFrame:GetScript("OnMouseWheel") or nil
            if type(onWheel) == "function" then
                onWheel(scrollFrame, delta)
            end
        end

        local function KU_CreatePremiumPickerButton(parent, getter, setter, optionsProvider, onCommit, controlOpts)
            controlOpts = type(controlOpts) == "table" and controlOpts or {}
            local cycleEnabled = controlOpts.enableCycle and true or false
            local wheelCycleEnabled = cycleEnabled and not (controlOpts.disableWheelCycle and true or false)
            local noSearch = controlOpts.noSearch and true or false
            local hideTitle = controlOpts.hideTitle and true or false
            local autoHeightToOptions = controlOpts.autoHeightToOptions and true or false
            local cycleGutterW = 18
            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 },
            })
            button:SetBackdropColor(0.10, 0.11, 0.14, 0.95)
            button:SetBackdropBorderColor(0.24, 0.27, 0.32, 1.0)
            button:SetHeight(22)
            button:SetWidth(TOOLTIP_BUILDER_INSPECTOR_PICKER_W)

            local text = createStyledFontString(button, "ARTWORK", "GameFontHighlightSmall", 11)
            local leftTextInset = cycleEnabled and (8 + cycleGutterW) or 8
            local rightTextInset = cycleEnabled and (8 + cycleGutterW) or 18
            text:SetPoint("LEFT", button, "LEFT", leftTextInset, 0)
            text:SetPoint("RIGHT", button, "RIGHT", -rightTextInset, 0)
            text:SetJustifyH(cycleEnabled and "CENTER" or "LEFT")
            text:SetTextColor(0.92, 0.92, 0.92, 1)

            local caret = nil
            local leftChevron = nil
            local rightChevron = nil
            if not cycleEnabled then
                caret = createStyledFontString(button, "ARTWORK", "GameFontHighlightSmall", 10)
                caret:SetPoint("RIGHT", button, "RIGHT", -7, 0)
                caret:SetText("v")
                caret:SetTextColor(0.76, 0.76, 0.78, 1)
            else
                leftChevron = createStyledFontString(button, "ARTWORK", "GameFontHighlightSmall", 10)
                leftChevron:SetPoint("LEFT", button, "LEFT", 8, 0)
                leftChevron:SetText("<")
                leftChevron:SetTextColor(0.62, 0.64, 0.69, 0.95)

                rightChevron = createStyledFontString(button, "ARTWORK", "GameFontHighlightSmall", 10)
                rightChevron:SetPoint("RIGHT", button, "RIGHT", -8, 0)
                rightChevron:SetText(">")
                rightChevron:SetTextColor(0.62, 0.64, 0.69, 0.95)
            end

            local picker = CreatePicker(UIParent, {}, function(value)
                setter(tostring(value or ""))
                if onCommit then
                    onCommit()
                end
            end, {
                title = L["SETTINGS_SELECT_TOOLTIP_OPTION"],
                searchHint = L["SETTINGS_SEARCH_OPTIONS"],
                width = 380,
                height = 330,
                showSecondary = false,
                showClearButton = false,
                preserveOrder = true,
                noSearch = noSearch,
                hideTitle = hideTitle,
                hideScrollBar = (noSearch and hideTitle),
                minHeight = autoHeightToOptions and 120 or 220,
            })

            local currentButtonLabel = ""
            local function getTextMaxWidth()
                local base = (button:GetWidth() or 0) - (leftTextInset + rightTextInset)
                return math.max(4, base)
            end
            local function setButtonLabel(labelText)
                currentButtonLabel = tostring(labelText or "")
                text:SetWordWrap(false)
                if text.SetMaxLines then
                    text:SetMaxLines(1)
                end
                local maxWidth = getTextMaxWidth()
                text:SetWidth(maxWidth)
                text:SetText(currentButtonLabel)
                if text:GetStringWidth() <= maxWidth then
                    return
                end
                local source = currentButtonLabel
                local cut = string.len(source)
                while cut > 0 do
                    local candidate = string.sub(source, 1, cut) .. "..."
                    text:SetText(candidate)
                    if text:GetStringWidth() <= maxWidth then
                        return
                    end
                    cut = cut - 1
                end
                text:SetText("...")
            end

            local function applyVisual(hovered)
                if hovered then
                    button:SetBackdropColor(0.16, 0.17, 0.20, 0.95)
                    button:SetBackdropBorderColor(0.30, 0.33, 0.38, 1.0)
                    if caret then
                        caret:SetTextColor(0.88, 0.88, 0.90, 1)
                    end
                    if leftChevron then
                        leftChevron:SetTextColor(0.84, 0.85, 0.89, 1.0)
                    end
                    if rightChevron then
                        rightChevron:SetTextColor(0.84, 0.85, 0.89, 1.0)
                    end
                else
                    button:SetBackdropColor(0.10, 0.11, 0.14, 0.95)
                    button:SetBackdropBorderColor(0.24, 0.27, 0.32, 1.0)
                    if caret then
                        caret:SetTextColor(0.76, 0.76, 0.78, 1)
                    end
                    if leftChevron then
                        leftChevron:SetTextColor(0.62, 0.64, 0.69, 0.95)
                    end
                    if rightChevron then
                        rightChevron:SetTextColor(0.62, 0.64, 0.69, 0.95)
                    end
                end
            end

            local function buildPickerOptions()
                local built = {}
                for _, option in ipairs(optionsProvider and optionsProvider() or {}) do
                    built[#built + 1] = {
                        value = tostring(option.value or ""),
                        label = tostring(option.label or option.value or ""),
                        buttonLabel = tostring(option.label or option.value or ""),
                        secondary = "",
                    }
                end
                return built
            end

            local function resolveSelectedValue(options)
                local selectedRaw = getter and getter() or nil
                local selectedValue = tostring(selectedRaw or "")
                local visualValue, visualLabel = KU_ResolveVisualChoice(selectedRaw, options)
                if visualValue ~= nil then
                    selectedValue = tostring(visualValue)
                end
                local selectedIndex = 1
                for i, option in ipairs(options or {}) do
                    if tostring(option.value or "") == selectedValue then
                        selectedIndex = i
                        break
                    end
                end
                return selectedValue, selectedIndex, visualLabel
            end

            local spec = {}
            spec.control = button
            local function applyAutoHeight(options)
                if not autoHeightToOptions or not picker then
                    return
                end
                local optionCount = math.max(1, #(options or {}))
                local rowH = math.max(20, tonumber(picker._rowHeight) or 26)
                local topInset
                if noSearch and hideTitle then
                    topInset = 14
                elseif noSearch then
                    topInset = 34
                else
                    topInset = 72
                end
                local bottomInset = 48
                local targetH = topInset + bottomInset + (optionCount * rowH)
                targetH = math.max(tonumber(picker._minHeight) or 120, targetH)
                picker:SetHeight(math.floor(targetH))
            end
            spec.SetWidth = function(_, width)
                button:SetWidth(math.max(0, math.floor(tonumber(width) or TOOLTIP_BUILDER_INSPECTOR_PICKER_W)))
                setButtonLabel(currentButtonLabel)
            end
            spec.ClosePicker = function()
                if picker and picker.Close and picker.IsShown and picker:IsShown() then
                    picker:Close()
                end
            end
            spec.Refresh = function()
                local options = buildPickerOptions()
                picker:SetOptions(options)
                applyAutoHeight(options)
                local selectedValue, _, selectedLabel = resolveSelectedValue(options)
                if selectedValue ~= nil then
                    picker:SetSelectedValue(tostring(selectedValue))
                end
                setButtonLabel(selectedLabel ~= "" and selectedLabel or L["COMMON_DEFAULT"])
            end

            local function cycleBy(delta)
                local options = buildPickerOptions()
                if #options <= 0 then
                    return
                end
                local _, selectedIndex = resolveSelectedValue(options)
                local newIndex = ((selectedIndex - 1 + delta) % #options) + 1
                local newValue = tostring(options[newIndex] and options[newIndex].value or "")
                setter(newValue)
                if onCommit then
                    onCommit()
                end
                spec.Refresh()
            end

            button:SetScript("OnEnter", function()
                applyVisual(true)
            end)
            button:SetScript("OnLeave", function()
                applyVisual(false)
            end)
            button:SetScript("OnClick", function(selfButton)
                if cycleEnabled then
                    local cursorX = GetCursorPosition()
                    local scale = selfButton:GetEffectiveScale() or (UIParent and UIParent:GetEffectiveScale()) or 1
                    if scale and scale > 0 then
                        cursorX = cursorX / scale
                    end
                    local left = selfButton:GetLeft() or 0
                    local width = selfButton:GetWidth() or 0
                    local localX = cursorX - left
                    if localX <= cycleGutterW then
                        cycleBy(-1)
                        return
                    elseif localX >= (width - cycleGutterW) then
                        cycleBy(1)
                        return
                    end
                end
                if cycleEnabled and picker and picker.IsShown and picker:IsShown() then
                    picker:Close()
                    return
                end
                spec.Refresh()
                picker:Open(selfButton)
            end)
            button:EnableMouseWheel(true)
            button:SetScript("OnMouseWheel", function(_, delta)
                if not wheelCycleEnabled then
                    KU_ForwardPanelMouseWheel(delta)
                    return
                end
                if delta > 0 then
                    cycleBy(-1)
                elseif delta < 0 then
                    cycleBy(1)
                end
            end)
            button:HookScript("OnSizeChanged", function()
                setButtonLabel(currentButtonLabel)
            end)

            spec.Refresh()
            return spec
        end

        local function KU_CreateSegmentedControl(parent, choices, getter, setter, onCommit, controlOpts)
            local internalValue = getter and getter() or nil
            local segmented = createPremiumSegmentedChoice(parent, "", nil, choices, function(value)
                internalValue = value
                setter(value)
                if onCommit then
                    onCommit()
                end
            end, {
                semantic = "toggle",
                controlHeight = controlOpts and controlOpts.controlHeight or nil,
                textSize = controlOpts and controlOpts.textSize or nil,
                textEllipsis = controlOpts and controlOpts.textEllipsis or nil,
                minWidth = controlOpts and controlOpts.minWidth or 0,
                segmentGap = controlOpts and controlOpts.segmentGap or nil,
                segmentMinWidth = controlOpts and controlOpts.segmentMinWidth or nil,
                getValue = function()
                    return internalValue
                end,
                setValue = function(value)
                    internalValue = value
                end,
            })
            if segmented.label then
                segmented.label:Hide()
            end
            local spec = {}
            spec.control = segmented.control
            spec.Layout = function(_, width)
                segmented:Layout(width)
            end
            spec.SetEnabled = function(_, enabled)
                segmented:SetEnabled(enabled)
            end
            spec.SetChoiceEnabled = function(_, value, enabled)
                segmented:SetChoiceEnabled(value, enabled)
            end
            spec.SetVisualSelectedValue = function(_, value)
                segmented:SetVisualSelectedValue(value)
            end
            spec.Refresh = function()
                local selectedValue = getter and getter() or nil
                local visualValue = KU_ResolveVisualChoice(selectedValue, choices)
                if visualValue ~= nil then
                    internalValue = visualValue
                    segmented:SetVisualSelectedValue(visualValue)
                end
            end
            spec.Refresh()
            return spec
        end

        local function KU_CreateInspectorRow(cfg)
            local row = {}
            row.lineId = cfg.lineId
            row.cfg = cfg
            row.container = CreateFrame("Button", nil, tooltipBuilder.inspectorContent)
            row.container:EnableMouse(true)
            row.container:SetHeight(KEYSTONE_UTILITY_LAYOUT.TOOLTIP.BASE_ROW_H)
            row.container:SetScript("OnEnter", function()
                KU_SetHoveredLine(row.lineId)
            end)
            row.container:SetScript("OnLeave", function()
                KU_SetHoveredLine(nil)
            end)
            row.container:SetScript("OnClick", function()
                KU_SelectLine(row.lineId, false)
            end)

            row.highlightBg = row.container:CreateTexture(nil, "BACKGROUND")
            row.highlightBg:SetAllPoints(row.container)
            row.highlightBg:SetTexture("Interface\\Buttons\\WHITE8x8")
            row.highlightBg:SetVertexColor(TOOLTIP_BUILDER_HIGHLIGHT_BG_R, TOOLTIP_BUILDER_HIGHLIGHT_BG_G, TOOLTIP_BUILDER_HIGHLIGHT_BG_B, 0.16)
            row.highlightBg:SetAlpha(0)
            row.highlightAccent = row.container:CreateTexture(nil, "BORDER")
            row.highlightAccent:SetPoint("TOPLEFT", row.container, "TOPLEFT", 0, 0)
            row.highlightAccent:SetPoint("BOTTOMLEFT", row.container, "BOTTOMLEFT", 0, 0)
            row.highlightAccent:SetWidth(1)
            row.highlightAccent:SetTexture("Interface\\Buttons\\WHITE8x8")
            row.highlightAccent:SetVertexColor(TOOLTIP_BUILDER_HIGHLIGHT_ACCENT_R, TOOLTIP_BUILDER_HIGHLIGHT_ACCENT_G, TOOLTIP_BUILDER_HIGHLIGHT_ACCENT_B, 0.62)
            row.highlightAccent:SetAlpha(0)

            row.label = createStyledFontString(row.container, "ARTWORK", "GameFontHighlight", 12)
            row.label:SetText(cfg.label)
            row.label:SetJustifyH("LEFT")
            row.label:SetWordWrap(false)
            if row.label.SetMaxLines then
                row.label:SetMaxLines(1)
            end

            if cfg.type == "picker" then
                row.main = KU_CreatePremiumPickerButton(
                    row.container,
                    function()
                        return KU_Normalize(PortalAuthorityDB and PortalAuthorityDB[cfg.dbKey])
                    end,
                    function(value)
                        if PortalAuthorityDB then
                            PortalAuthorityDB[cfg.dbKey] = tostring(value or "")
                        end
                    end,
                    function()
                        return cfg.options or {}
                    end,
                    function()
                        KU_OnTooltipCommit(cfg.lineId, cfg.affectsLayout)
                    end,
                    {
                        enableCycle = (cfg.lineId == "DungeonName" or cfg.lineId == "Level"),
                        disableWheelCycle = (cfg.lineId == "DungeonName" or cfg.lineId == "Level"),
                        noSearch = (cfg.lineId == "DungeonName" or cfg.lineId == "Level"),
                        hideTitle = (cfg.lineId == "DungeonName" or cfg.lineId == "Level"),
                        autoHeightToOptions = (cfg.lineId == "DungeonName" or cfg.lineId == "Level"),
                    }
                )
            else
                row.main = KU_CreateSegmentedControl(
                    row.container,
                    cfg.choices or tooltipHideShowChoices,
                    function()
                        return KU_Normalize(PortalAuthorityDB and PortalAuthorityDB[cfg.dbKey])
                    end,
                    function(value)
                        if PortalAuthorityDB then
                            PortalAuthorityDB[cfg.dbKey] = value
                        end
                    end,
                    function()
                        KU_OnTooltipCommit(cfg.lineId, cfg.affectsLayout)
                    end,
                    {
                        textSize = (cfg.lineId == "Modifiers") and 10 or nil,
                        textEllipsis = (cfg.lineId == "Modifiers"),
                        segmentGap = (cfg.lineId == "Modifiers") and 2 or nil,
                        segmentMinWidth = (cfg.lineId == "Modifiers") and 34 or nil,
                        minWidth = 0,
                    }
                )
            end

            if cfg.inline then
                row.inlineAccent = row.container:CreateTexture(nil, "ARTWORK")
                row.inlineAccent:SetTexture("Interface\\Buttons\\WHITE8x8")
                row.inlineAccent:SetVertexColor(0.82, 0.84, 0.88, 0.58)
                row.inlineAccent:SetSize(2, 12)
                row.inlineLabel = createStyledFontString(row.container, "ARTWORK", "GameFontHighlightSmall", 10)
                row.inlineLabel:SetText(cfg.inline.label)
                row.inlineLabel:SetJustifyH("LEFT")
                row.inlineLabel:SetWordWrap(false)
                row.inlineLabel:SetTextColor(TOOLTIP_BUILDER_MUTED_TEXT_R, TOOLTIP_BUILDER_MUTED_TEXT_G, TOOLTIP_BUILDER_MUTED_TEXT_B, 0.92)
                if row.inlineLabel.SetMaxLines then
                    row.inlineLabel:SetMaxLines(1)
                end
                row.inline = KU_CreateSegmentedControl(
                    row.container,
                    cfg.inline.choices,
                    function()
                        return PortalAuthorityDB and PortalAuthorityDB[cfg.inline.dbKey]
                    end,
                    function(value)
                        if PortalAuthorityDB then
                            PortalAuthorityDB[cfg.inline.dbKey] = PA_SafeBool(value)
                        end
                    end,
                    function()
                        KU_OnTooltipCommit(cfg.lineId, cfg.affectsLayout)
                    end,
                    {
                        controlHeight = 19,
                        textSize = 10,
                    }
                )
            end

            if cfg.hasColorSwatch then
                row.colorSwatch = CreateFrame("Button", nil, row.container, "BackdropTemplate")
                row.colorSwatch:SetBackdrop({
                    bgFile = "Interface\\Buttons\\WHITE8x8",
                    edgeFile = "Interface\\Buttons\\WHITE8x8",
                    edgeSize = 1,
                    insets = { left = 0, right = 0, top = 0, bottom = 0 },
                })
                row.colorSwatch:SetBackdropBorderColor(0.24, 0.27, 0.32, 1.0)
                row.colorSwatch:SetSize(22, 18)
                row.colorSwatch:SetScript("OnClick", function()
                    openKeystoneTooltipAffixesColorPicker(function()
                        refreshTooltipAffixesSwatch()
                        KU_OnTooltipCommit(cfg.lineId, cfg.affectsLayout)
                    end)
                end)
            end

            tooltipBuilder.rows[#tooltipBuilder.rows + 1] = row
            tooltipBuilder.rowsById[cfg.lineId] = row
            return row
        end

        for _, cfg in ipairs(tooltipLineConfigs) do
            KU_CreateInspectorRow(cfg)
        end

        panelRef._kuCloseTooltipBuilderPickers = function()
            if not tooltipBuilder or not tooltipBuilder.rows then
                return
            end
            for _, row in ipairs(tooltipBuilder.rows) do
                if row and row.main and row.main.ClosePicker then
                    row.main:ClosePicker()
                end
            end
        end

        local function KU_GetTooltipBuilderInspectorVisibilityState()
            local db = PortalAuthorityDB or {}
            local levelMode = KU_Normalize(db.keystoneTooltipLevelMode)
            local addToName = PA_SafeBool(db.keystoneTooltipLevelAddToName)
            local levelVisible = true
            if levelMode == "HIDE" then
                levelVisible = false
            elseif addToName and levelMode ~= "" and levelMode ~= "NO_CHANGES" then
                levelVisible = false
            end
            return {
                DungeonName = true,
                Level = levelVisible,
                Resilient = KU_Normalize(db.keystoneTooltipResilientMode) ~= "HIDE",
                Soulbound = KU_Normalize(db.keystoneTooltipSoulboundMode) ~= "HIDE",
                Unique = KU_Normalize(db.keystoneTooltipUniqueMode) ~= "HIDE",
                Modifiers = KU_Normalize(db.keystoneTooltipAffixesMode) ~= "HIDE",
                Duration = KU_Normalize(db.keystoneTooltipDurationMode) ~= "HIDE",
                RPQuote = KU_Normalize(db.keystoneTooltipRPQuoteMode) ~= "HIDE",
            }
        end

        local function KU_GetVisibleInspectorLineIds()
            local visible = KU_GetTooltipBuilderInspectorVisibilityState()
            local ids = {}
            for _, cfg in ipairs(tooltipLineConfigs) do
                if visible[cfg.lineId] then
                    ids[#ids + 1] = cfg.lineId
                end
            end
            return ids
        end

        local function KU_EnsurePreviewOverlay(index)
            if tooltipBuilder.previewOverlays[index] then
                return tooltipBuilder.previewOverlays[index]
            end
            local overlay = CreateFrame("Button", nil, tooltipBuilder.previewHitLayer)
            overlay:SetFrameStrata(tooltipBuilder.previewHitLayer:GetFrameStrata())
            overlay:SetFrameLevel((tooltipBuilder.previewHitLayer:GetFrameLevel() or 0) + 2)
            overlay:RegisterForClicks("LeftButtonUp")
            overlay:EnableMouse(true)
            overlay._bg = overlay:CreateTexture(nil, "BACKGROUND")
            overlay._bg:SetAllPoints(overlay)
            overlay._bg:SetTexture("Interface\\Buttons\\WHITE8x8")
            overlay._bg:SetVertexColor(TOOLTIP_BUILDER_HIGHLIGHT_BG_R, TOOLTIP_BUILDER_HIGHLIGHT_BG_G, TOOLTIP_BUILDER_HIGHLIGHT_BG_B, 0.16)
            overlay._bg:SetAlpha(0)
            overlay._accent = overlay:CreateTexture(nil, "BORDER")
            overlay._accent:SetPoint("TOPLEFT", overlay, "TOPLEFT", 0, 0)
            overlay._accent:SetPoint("BOTTOMLEFT", overlay, "BOTTOMLEFT", 0, 0)
            overlay._accent:SetWidth(1)
            overlay._accent:SetTexture("Interface\\Buttons\\WHITE8x8")
            overlay._accent:SetVertexColor(TOOLTIP_BUILDER_HIGHLIGHT_ACCENT_R, TOOLTIP_BUILDER_HIGHLIGHT_ACCENT_G, TOOLTIP_BUILDER_HIGHLIGHT_ACCENT_B, 0.62)
            overlay._accent:SetAlpha(0)
            overlay:SetScript("OnEnter", function(selfOverlay)
                KU_SetHoveredLine(selfOverlay.lineId)
            end)
            overlay:SetScript("OnLeave", function()
                KU_SetHoveredLine(nil)
            end)
            overlay:SetScript("OnClick", function(selfOverlay)
                if selfOverlay.lineId then
                    KU_SelectLine(selfOverlay.lineId, true)
                end
            end)
            tooltipBuilder.previewOverlays[index] = overlay
            return overlay
        end

        local function KU_HideUnusedPreviewOverlays(fromIndex)
            for i = fromIndex, #tooltipBuilder.previewOverlays do
                local overlay = tooltipBuilder.previewOverlays[i]
                if overlay then
                    overlay:Hide()
                    overlay.lineId = nil
                end
            end
        end

        KU_ReadPreviewBodyLeftLines = function(previewTooltip)
            local lines = {}
            if not previewTooltip or not previewTooltip.GetName then
                return lines
            end
            local baseName = previewTooltip:GetName()
            if type(baseName) ~= "string" or baseName == "" then
                return lines
            end
            local count = previewTooltip:NumLines() or 0
            for i = 1, count do
                local left = _G[baseName .. "TextLeft" .. i]
                if left and left.GetText and left.IsShown and left:IsShown() then
                    local text = trim(left:GetText() or "")
                    if text ~= "" then
                        lines[#lines + 1] = { fs = left, text = text }
                    end
                end
            end
            -- Keep real first lines (e.g. "Keystone: ..."). Only drop the synthetic
            -- fallback header line when the hyperlink path wasn't available.
            if #lines > 0 then
                local firstLower = string.lower(trim(tostring(lines[1].text or "")))
                if string.find(firstLower, "mythic keystone", 1, true) then
                    table.remove(lines, 1)
                end
            end
            return lines
        end

        local function KU_BuildPreviewRegions()
            tooltipBuilder.mappingByLineId = {}
            tooltipBuilder.previewOverlaysByLineId = {}
            tooltipBuilder.visibleInspectorLineIds = KU_GetVisibleInspectorLineIds()
            tooltipBuilder.visiblePreviewLineIds = {}

            local previewTooltip = widgets.keystoneTooltipPreviewTooltip
            local bodyLines = KU_ReadPreviewBodyLeftLines(previewTooltip)
            local total = #bodyLines
            local cursor = 1
            local regions = {}
            local visibility = KU_GetTooltipBuilderInspectorVisibilityState()

            local function addSingle(lineId, matcher)
                if not visibility[lineId] then
                    return
                end
                if cursor <= total then
                    if matcher then
                        local lineText = (bodyLines[cursor] and bodyLines[cursor].text) or ""
                        if not matcher(string.lower(trim(tostring(lineText or "")))) then
                            return
                        end
                    end
                    regions[#regions + 1] = { lineId = lineId, startIndex = cursor, endIndex = cursor }
                    cursor = cursor + 1
                end
            end

            addSingle("DungeonName")
            addSingle("Level")
            addSingle("Resilient", function(lowerText)
                return string.find(lowerText, "resilient", 1, true) ~= nil
            end)
            addSingle("Soulbound", function(lowerText)
                return string.find(lowerText, "soulbound", 1, true) ~= nil
                    or string.find(lowerText, "binds when picked up", 1, true) ~= nil
                    or string.find(lowerText, "binds when equipped", 1, true) ~= nil
            end)
            addSingle("Unique", function(lowerText)
                return string.find(lowerText, "unique", 1, true) == 1
            end)

            if visibility.Modifiers and cursor <= total then
                local trailing = 0
                if visibility.Duration then trailing = trailing + 1 end
                if visibility.RPQuote then trailing = trailing + 1 end
                local modifiersEnd = total - trailing
                if modifiersEnd < cursor then
                    modifiersEnd = cursor
                end
                if modifiersEnd > total then
                    modifiersEnd = total
                end
                regions[#regions + 1] = { lineId = "Modifiers", startIndex = cursor, endIndex = modifiersEnd }
                cursor = modifiersEnd + 1
            end

            addSingle("Duration", function(lowerText)
                return string.find(lowerText, "duration", 1, true) ~= nil
            end)
            addSingle("RPQuote")

            -- Keep inspector<->preview linking based on actual rendered regions so
            -- missing optional lines (e.g. fallback without Resilient) do not shift
            -- subsequent mappings.
            do
                local actualInspectorLineIds = {}
                for _, region in ipairs(regions) do
                    actualInspectorLineIds[#actualInspectorLineIds + 1] = region.lineId
                end
                tooltipBuilder.visibleInspectorLineIds = actualInspectorLineIds
            end

            local overlayIndex = 1
            local visiblePreviewRegions = {}
            for _, region in ipairs(regions) do
                local startLine = bodyLines[region.startIndex]
                local endLine = bodyLines[region.endIndex]
                if startLine and endLine and startLine.fs and endLine.fs then
                    local overlay = KU_EnsurePreviewOverlay(overlayIndex)
                    overlay:ClearAllPoints()
                    overlay:SetPoint("TOPLEFT", startLine.fs, "TOPLEFT", -4, 2)
                    overlay:SetPoint("BOTTOMRIGHT", endLine.fs, "BOTTOMRIGHT", 4, -2)
                    overlay.lineId = region.lineId
                    overlay:Show()
                    tooltipBuilder.previewOverlaysByLineId[region.lineId] = overlay
                    tooltipBuilder.visiblePreviewLineIds[#tooltipBuilder.visiblePreviewLineIds + 1] = region.lineId
                    visiblePreviewRegions[#visiblePreviewRegions + 1] = { lineId = region.lineId, overlay = overlay }
                    overlayIndex = overlayIndex + 1
                end
            end
            KU_HideUnusedPreviewOverlays(overlayIndex)

            local ambiguous = false
            if #tooltipBuilder.visibleInspectorLineIds ~= #tooltipBuilder.visiblePreviewLineIds then
                ambiguous = true
            else
                for _, lineId in ipairs(tooltipBuilder.visibleInspectorLineIds) do
                    if not tooltipBuilder.previewOverlaysByLineId[lineId] then
                        ambiguous = true
                        break
                    end
                end
            end

            if not ambiguous then
                for _, lineId in ipairs(tooltipBuilder.visibleInspectorLineIds) do
                    tooltipBuilder.mappingByLineId[lineId] = tooltipBuilder.previewOverlaysByLineId[lineId]
                end
            else
                tooltipBuilder.mappingByLineId = {}
                local maxZip = math.min(#tooltipBuilder.visibleInspectorLineIds, #visiblePreviewRegions)
                for i = 1, maxZip do
                    local lineId = tooltipBuilder.visibleInspectorLineIds[i]
                    local overlay = visiblePreviewRegions[i] and visiblePreviewRegions[i].overlay or nil
                    if lineId and overlay and overlay:IsShown() then
                        overlay.lineId = lineId
                        tooltipBuilder.mappingByLineId[lineId] = overlay
                    end
                end
            end
        end

        local function KU_RebuildTooltipPreviewLinks(commitInfo)
            local oldHovered = tooltipBuilder.hoveredLineId
            local oldSelected = tooltipBuilder.selectedLineId
            if KU_UpdateKeystoneTooltipPreview then
                KU_UpdateKeystoneTooltipPreview()
            end
            KU_BuildPreviewRegions()

            if oldSelected and not tooltipBuilder.mappingByLineId[oldSelected] then
                tooltipBuilder.selectedLineId = nil
                if commitInfo and commitInfo.affectsLayout then
                    KU_SetBuilderStatus(L["SETTINGS_KS_LINE_HIDDEN"])
                end
            elseif commitInfo then
                KU_ClearBuilderStatus()
            else
                tooltipBuilder.selectedLineId = oldSelected
            end

            if oldHovered and tooltipBuilder.rowsById[oldHovered] then
                tooltipBuilder.hoveredLineId = oldHovered
            else
                tooltipBuilder.hoveredLineId = nil
            end

            KU_RefreshLinkedVisuals()
        end

        KU_RefreshTooltipBuilderVisual = function()
            if not PortalAuthorityDB then
                ensureDatabase()
                if not PortalAuthorityDB then
                    return
                end
            end
            for _, row in ipairs(tooltipBuilder.rows) do
                if row.main and row.main.Refresh then
                    row.main:Refresh()
                end
                if row.inline and row.inline.Refresh then
                    row.inline:Refresh()
                end
            end
            do
                local levelRow = tooltipBuilder.rowsById and tooltipBuilder.rowsById.Level or nil
                if levelRow and levelRow.inline then
                    local levelMode = KU_Normalize(PortalAuthorityDB and PortalAuthorityDB.keystoneTooltipLevelMode)
                    local forceInlineOff = (levelMode == "HIDE" or levelMode == "NO_CHANGES")
                    local allowInline = not forceInlineOff
                    if levelRow.inline.SetEnabled then
                        levelRow.inline:SetEnabled(allowInline)
                    end
                    if levelRow.inlineLabel then
                        levelRow.inlineLabel:SetAlpha(allowInline and 0.95 or 0.52)
                    end
                    if levelRow.inlineAccent then
                        levelRow.inlineAccent:SetAlpha(allowInline and 0.55 or 0.30)
                    end
                end
            end
            do
                local modifiersRow = tooltipBuilder.rowsById and tooltipBuilder.rowsById.Modifiers or nil
                local mode = KU_Normalize(PortalAuthorityDB and PortalAuthorityDB.keystoneTooltipAffixesMode)
                if modifiersRow and modifiersRow.colorSwatch then
                    modifiersRow.colorSwatch:SetAlpha((mode == "HIDE") and 0.50 or 1.00)
                end
            end
            refreshTooltipAffixesSwatch()
            local commitInfo = tooltipBuilder._lastCommit
            tooltipBuilder._lastCommit = nil
            KU_RebuildTooltipPreviewLinks(commitInfo)
        end

        panelRef._kuHydrateKeystoneTooltipControls = KU_RefreshTooltipBuilderVisual
        panelRef._kuHydrateKeystoneTooltipVisualOnly = KU_RefreshTooltipBuilderVisual

        local assistantRows = {
            {
                id = "keystoneHelperEnabled",
                spec = widgets.keystoneHelperEnabled,
                label = widgets.keystoneHelperEnabled and widgets.keystoneHelperEnabled.label or nil,
                control = widgets.keystoneHelperEnabled and widgets.keystoneHelperEnabled.control or nil,
                desc = helperDesc,
            },
            {
                id = "keystoneAutoSlotEnabled",
                spec = widgets.keystoneAutoSlotEnabled,
                label = widgets.keystoneAutoSlotEnabled and widgets.keystoneAutoSlotEnabled.label or nil,
                control = widgets.keystoneAutoSlotEnabled and widgets.keystoneAutoSlotEnabled.control or nil,
                desc = autoSlotDesc,
            },
            {
                id = "keystoneAutoStartEnabled",
                spec = widgets.keystoneAutoStartEnabled,
                label = widgets.keystoneAutoStartEnabled and widgets.keystoneAutoStartEnabled.label or nil,
                control = widgets.keystoneAutoStartEnabled and widgets.keystoneAutoStartEnabled.control or nil,
                desc = autoStartDesc,
            },
        }
        local releaseRows = {
            {
                id = "releaseGateEnabled",
                spec = widgets.releaseGateEnabled,
                label = widgets.releaseGateEnabled and widgets.releaseGateEnabled.label or nil,
                control = widgets.releaseGateEnabled and widgets.releaseGateEnabled.control or nil,
                desc = releaseEnabledDesc,
            },
            {
                id = "releaseGateModifier",
                spec = widgets.releaseGateModifier,
                label = widgets.releaseGateModifier and widgets.releaseGateModifier.label or nil,
                control = widgets.releaseGateModifier and widgets.releaseGateModifier.control or nil,
                desc = nil,
            },
            {
                id = "releaseHold",
                label = holdLabel,
                control = widgets.releaseHoldStepper,
                desc = releaseHoldDesc,
                controlWidth = 84,
                noLayout = true,
            },
        }
        for _, row in ipairs(assistantRows) do
            local searchTarget = row and (row.spec or row) or nil
            if searchTarget and frameIsAlive(row.desc) then
                settingsSearchRuntime.attachExtraSearchRefs(searchTarget, { row.desc })
            end
        end
        for _, row in ipairs(releaseRows) do
            local searchTarget = row and (row.spec or row) or nil
            if searchTarget and frameIsAlive(row.desc) then
                settingsSearchRuntime.attachExtraSearchRefs(searchTarget, { row.desc })
            end
        end
        local statusChips = {
            widgets.statusKeystone,
            widgets.statusLeader,
            widgets.statusAutomation,
        }
        local function KU_RoundMetric(value)
            local n = tonumber(value) or 0
            return math.floor(n + 0.5)
        end

        local function KU_GetRowLabel(row)
            if not row then
                return nil
            end
            return row.label or (row.spec and row.spec.label) or nil
        end

        local function KU_GetRowControl(row)
            if not row then
                return nil
            end
            return row.control or (row.spec and row.spec.control) or nil
        end

        local function KU_MeasureFontStringWidth(fs)
            if not (fs and fs.GetStringWidth) then
                return 0
            end
            return math.ceil(tonumber(fs:GetStringWidth()) or 0)
        end

        local function KU_MeasureFontStringHeight(fs, floor)
            local measured = 0
            if fs and fs.GetStringHeight then
                measured = math.ceil(tonumber(fs:GetStringHeight()) or 0)
            end
            return math.max(tonumber(floor) or 0, measured)
        end

        local function KU_MeasureControlHeight(widget, floor)
            local measured = 0
            if widget and widget.GetHeight then
                measured = math.ceil(tonumber(widget:GetHeight()) or 0)
            end
            return math.max(tonumber(floor) or 0, measured)
        end

        local function KU_AppendMetric(parts, key, value)
            parts[#parts + 1] = tostring(key or "") .. "=" .. tostring(KU_RoundMetric(value))
        end

        local function KU_AppendFontMetrics(parts, prefix, fs)
            KU_AppendMetric(parts, tostring(prefix or "") .. "W", KU_MeasureFontStringWidth(fs))
            KU_AppendMetric(parts, tostring(prefix or "") .. "H", KU_MeasureFontStringHeight(fs, 0))
        end

        local function KU_ComputeContentWidth()
            return math.max((scrollFrame:GetWidth() or 0) - KEYSTONE_UTILITY_LAYOUT.SCROLL_WIDTH_FUDGE, KEYSTONE_UTILITY_LAYOUT.MIN_CONTENT_W)
        end

        local function KU_ComputeSectionColumns(cardW, rows)
            local T = KEYSTONE_UTILITY_LAYOUT
            local C = T.CARD
            local innerW = math.max(1, cardW - (C.PAD_X * 2))
            local labelMetricW = T.LABEL_MIN_W
            for _, row in ipairs(rows or {}) do
                labelMetricW = math.max(labelMetricW, KU_MeasureFontStringWidth(KU_GetRowLabel(row)))
            end
            local preferredControlW = math.max(T.CONTROL_MIN_W, math.min(T.CONTROL_MAX_W, math.floor(innerW * T.CONTROL_WIDTH_RATIO)))
            local controlW = math.max(T.CONTROL_MIN_W, math.min(preferredControlW, innerW - T.LABEL_MIN_W - T.LABEL_TO_CONTROL_GAP))
            local controlX = C.PAD_X + innerW - controlW
            local maxLabelAvailW = math.max(T.LABEL_MIN_W, controlX - C.PAD_X - T.LABEL_TO_CONTROL_GAP)
            local labelW = math.max(T.LABEL_MIN_W, math.min(labelMetricW + T.LABEL_TEXT_PAD, maxLabelAvailW))
            local descW = math.max(T.DESC_MIN_W, controlX - C.PAD_X - T.DESC_RIGHT_PAD)
            return {
                labelX = C.PAD_X,
                labelW = labelW,
                controlX = controlX,
                controlW = controlW,
                descX = C.PAD_X,
                descW = descW,
                rowTopY = -C.PAD_TOP,
                rowGap = C.ROW_GAP,
                descGap = C.DESC_GAP,
            }
        end

        local function KU_LayoutRows(parent, rows, columns)
            local T = KEYSTONE_UTILITY_LAYOUT
            local C = T.CARD
            local rowTopY = columns and columns.rowTopY or 0
            for _, row in ipairs(rows or {}) do
                local label = KU_GetRowLabel(row)
                local control = KU_GetRowControl(row)
                local desc = row and row.desc or nil
                local controlW = row and row.controlWidth or columns.controlW
                local controlYOffset = row and row.controlYOffset or C.CONTROL_TOP_NUDGE
                if label then
                    label:ClearAllPoints()
                    label:SetPoint("TOPLEFT", parent, "TOPLEFT", columns.labelX, rowTopY)
                    label:SetWidth(columns.labelW)
                    if label.SetJustifyH then
                        label:SetJustifyH("LEFT")
                    end
                end
                if control then
                    if row and row.spec and row.spec.Layout and not row.noLayout then
                        row.spec:Layout(controlW)
                    elseif control.SetWidth and controlW then
                        control:SetWidth(controlW)
                    end
                    control:ClearAllPoints()
                    control:SetPoint("TOPLEFT", parent, "TOPLEFT", columns.controlX, rowTopY + controlYOffset)
                end
                local labelH = KU_MeasureFontStringHeight(label, C.LABEL_FLOOR)
                local controlH = KU_MeasureControlHeight(control, C.CONTROL_FLOOR)
                local rowBaseH = math.max(C.ROW_FLOOR, labelH, controlH)
                local rowBottomY = rowTopY - rowBaseH
                if desc then
                    desc:ClearAllPoints()
                    desc:SetPoint("TOPLEFT", parent, "TOPLEFT", columns.descX, rowBottomY - columns.descGap)
                    desc:SetWidth(columns.descW)
                    if desc.SetJustifyH then
                        desc:SetJustifyH("LEFT")
                    end
                    local descH = KU_MeasureFontStringHeight(desc, C.HELPER_FLOOR)
                    rowBottomY = rowBottomY - columns.descGap - descH
                end
                rowTopY = rowBottomY - columns.rowGap
            end
            return rowTopY
        end

        local function KU_ComputeTooltipGeometry(contentSpan)
            local T = KEYSTONE_UTILITY_LAYOUT
            local TT = T.TOOLTIP
            local geometry = {
                sideBySide = true,
                rootLeft = 0,
                rootW = math.max(0, contentSpan),
            }
            local thresholdW = TOOLTIP_BUILDER_PREVIEW_MIN_W + TOOLTIP_BUILDER_INSPECTOR_MIN_W + TT.PANE_GAP
            if contentSpan >= thresholdW then
                geometry.inspectorW = math.max(TOOLTIP_BUILDER_INSPECTOR_MIN_W, math.floor(contentSpan * 0.60))
                geometry.previewW = contentSpan - geometry.inspectorW - TT.PANE_GAP
                if geometry.previewW < TOOLTIP_BUILDER_PREVIEW_MIN_W then
                    geometry.inspectorW = contentSpan - TOOLTIP_BUILDER_PREVIEW_MIN_W - TT.PANE_GAP
                    geometry.previewW = TOOLTIP_BUILDER_PREVIEW_MIN_W
                end
            else
                local splitSpan = math.max(0, contentSpan - TT.PANE_GAP)
                geometry.inspectorW = math.floor(splitSpan * 0.60)
                geometry.previewW = splitSpan - geometry.inspectorW
                if geometry.previewW < TOOLTIP_BUILDER_PREVIEW_READABLE_MIN_W then
                    geometry.previewW = math.min(splitSpan, TOOLTIP_BUILDER_PREVIEW_READABLE_MIN_W)
                    geometry.inspectorW = math.max(0, splitSpan - geometry.previewW)
                end
            end
            geometry.previewW = math.max(0, geometry.previewW or 0)
            geometry.inspectorW = math.max(0, geometry.inspectorW or 0)
            geometry.inspectorContentW = math.max(1, geometry.inspectorW - (TT.INSPECTOR_PAD_X * 2))
            local labelMetricW = 0
            for _, row in ipairs(tooltipBuilder.rows or {}) do
                labelMetricW = math.max(labelMetricW, KU_MeasureFontStringWidth(row and row.label or nil))
            end
            geometry.labelColX = 0
            geometry.labelW = math.max(T.TOOLTIP_LABEL_MIN_W, math.min(T.TOOLTIP_LABEL_MAX_W, labelMetricW + T.TOOLTIP_LABEL_TEXT_PAD))
            geometry.controlColX = geometry.labelW + T.TOOLTIP_LABEL_TO_CONTROL_GAP
            geometry.rightInset = TOOLTIP_BUILDER_INSPECTOR_RIGHT_INSET
            local availW = geometry.inspectorContentW - (geometry.controlColX + geometry.rightInset)
            availW = math.max(0, availW)
            if availW >= TOOLTIP_BUILDER_MAIN_MIN_W then
                geometry.mainControlW = math.max(TOOLTIP_BUILDER_MAIN_MIN_W, math.min(availW, TOOLTIP_BUILDER_MAIN_MAX_W))
            else
                geometry.mainControlW = availW
            end
            geometry.mainControlW = math.max(0, math.min(geometry.mainControlW, availW))
            geometry.inlineRegionX = geometry.controlColX + geometry.mainControlW + TT.INLINE_REGION_GAP
            geometry.availableInlineW = geometry.inspectorContentW - geometry.rightInset - geometry.inlineRegionX
            geometry.inlineBlockW = TOOLTIP_BUILDER_INLINE_LABEL_W + TT.INLINE_BLOCK_GAP + TOOLTIP_BUILDER_INLINE_TOGGLE_W
            geometry.previewTitleH = KU_MeasureFontStringHeight(tooltipBuilder.previewTitle, TT.PREVIEW_TITLE_FLOOR)
            if geometry.sideBySide then
                local alignedBorderTopOffset = TT.INSPECTOR_PAD_Y
                    + TT.STATUS_H
                    + TT.STATUS_TO_CONTENT_GAP
                    + TT.MAIN_TOP_PAD
                    - TT.STICKY_TOP_PAD
                local minimumTitleClearance = geometry.previewTitleH + TT.PREVIEW_TITLE_CLEARANCE
                local borderTopOffset = math.max(alignedBorderTopOffset, minimumTitleClearance)
                geometry.previewAnchorTopInset = math.max(0, borderTopOffset - TT.PREVIEW_FRAME_OFFSET_Y)
            else
                geometry.previewAnchorTopInset = TT.TITLE_TOP_PAD + geometry.previewTitleH + TT.PREVIEW_BODY_TOP_GAP
            end
            return geometry
        end

        local function KU_HasSizedLayoutSurface()
            local readyFrame = self._sizingFrame or self
            if not readyFrame then
                return false
            end
            local width = tonumber(readyFrame:GetWidth()) or 0
            local height = tonumber(readyFrame:GetHeight()) or 0
            return width > 1 and height > 1
        end

        local function KU_BuildMetricSignature()
            local parts = {}
            KU_AppendMetric(parts, "viewportW", scrollFrame and scrollFrame:GetWidth() or 0)
            KU_AppendFontMetrics(parts, "Header", header)
            KU_AppendFontMetrics(parts, "AssistantHeader", helperHeader)
            KU_AppendFontMetrics(parts, "ReleaseHeader", releaseHeader)
            KU_AppendFontMetrics(parts, "TooltipSectionHeader", tooltipHeader)
            KU_AppendFontMetrics(parts, "TooltipSubheader", tooltipSubheader)
            for _, row in ipairs(assistantRows) do
                KU_AppendFontMetrics(parts, "Assistant" .. tostring(row.id or ""), KU_GetRowLabel(row))
                if row.desc then
                    KU_AppendFontMetrics(parts, "AssistantDesc" .. tostring(row.id or ""), row.desc)
                end
            end
            for _, row in ipairs(releaseRows) do
                KU_AppendFontMetrics(parts, "Release" .. tostring(row.id or ""), KU_GetRowLabel(row))
                if row.desc then
                    KU_AppendFontMetrics(parts, "ReleaseDesc" .. tostring(row.id or ""), row.desc)
                end
            end
            for index, chip in ipairs(statusChips) do
                KU_AppendFontMetrics(parts, "StatusTitle" .. tostring(index), chip and chip.title or nil)
                KU_AppendFontMetrics(parts, "StatusValue" .. tostring(index), chip and chip.value or nil)
            end
            KU_AppendFontMetrics(parts, "TooltipBuilderHeader", tooltipBuilder.inspectorHeader)
            KU_AppendFontMetrics(parts, "TooltipPreviewTitle", tooltipBuilder.previewTitle)
            for _, row in ipairs(tooltipBuilder.rows or {}) do
                KU_AppendFontMetrics(parts, "TooltipRow" .. tostring(row.lineId or ""), row and row.label or nil)
                if row and row.inlineLabel then
                    KU_AppendFontMetrics(parts, "TooltipInline" .. tostring(row.lineId or ""), row.inlineLabel)
                end
            end
            return table.concat(parts, "|")
        end

        local function invalidateLayout(reason)
            self._kuLayoutDirty = true
            self._kuLayoutDirtyReason = tostring(reason or self._kuLayoutDirtyReason or "layout-dirty")
        end

        local function ensureLayoutCurrent(reason)
            if not self._layout then
                return false
            end
            if not KU_HasSizedLayoutSurface() then
                invalidateLayout(reason or "unsized")
                return false
            end
            local currentSignature = KU_BuildMetricSignature()
            local needsLayout = self._kuLayoutDirty or (self._kuMetricSignatureCache ~= currentSignature)
            if not needsLayout then
                return true
            end
            self._layout(reason or "layout")
            if not KU_HasSizedLayoutSurface() then
                invalidateLayout(reason or "unsized")
                return false
            end
            self._kuMetricSignatureCache = KU_BuildMetricSignature()
            self._kuLayoutDirty = false
            self._kuLayoutDirtyReason = nil
            return true
        end

        local function KU_ReadLeaderOrAssistState()
            local isLeader = (UnitIsGroupLeader and UnitIsGroupLeader("player")) and true or false
            local isAssist = (UnitIsGroupAssistant and UnitIsGroupAssistant("player")) and true or false
            return isLeader or isAssist
        end

        local function KU_ReadKeystoneLevelFromLink(link)
            if type(link) ~= "string" then
                return 0
            end
            local itemString = link:match("|H(keystone:[^|]+)|")
            if type(itemString) ~= "string" then
                return 0
            end
            local _, _, mapIDText, levelText = strsplit(":", itemString)
            local mapID = tonumber(mapIDText) or 0
            local level = tonumber(levelText) or 0
            if mapID > 0 and level > 0 then
                return math.floor(level)
            end
            return 0
        end

        local function KU_ReadOwnedKeystoneLevel()
            if C_MythicPlus and C_MythicPlus.GetOwnedKeystoneLevel then
                local okLevel, ownedLevel = pcall(C_MythicPlus.GetOwnedKeystoneLevel)
                if okLevel then
                    local n = tonumber(ownedLevel) or 0
                    if n > 0 then
                        return math.floor(n)
                    end
                end
            end
            return 0
        end

        local function KU_RefreshStatusStrip()
            if not (widgets.statusKeystone and widgets.statusLeader and widgets.statusAutomation) then
                return
            end
            local keystoneLink = KU_FindFirstKeystoneLinkInBags and KU_FindFirstKeystoneLinkInBags() or nil
            local hasKeystoneInBags = type(keystoneLink) == "string" and keystoneLink ~= ""
            local keystoneLevel = 0
            if hasKeystoneInBags then
                keystoneLevel = KU_ReadKeystoneLevelFromLink(keystoneLink)
                if keystoneLevel <= 0 then
                    keystoneLevel = KU_ReadOwnedKeystoneLevel()
                end
            end
            local leaderOrAssist = KU_ReadLeaderOrAssistState()
            local autoSlotEnabled = PA_SafeBool(PortalAuthorityDB and PortalAuthorityDB.keystoneAutoSlotEnabled)
            local autoStartEnabled = PA_SafeBool(PortalAuthorityDB and PortalAuthorityDB.keystoneAutoStartEnabled)

            local automationText = L["SETTINGS_KS_STATUS_AUTO_OFF"]
            local automationTone = "warn"
            if autoSlotEnabled and autoStartEnabled then
                automationText = L["SETTINGS_KS_STATUS_AUTO_SLOT_START"]
                automationTone = "good"
            elseif autoSlotEnabled then
                automationText = L["SETTINGS_KS_STATUS_AUTO_SLOT"]
                automationTone = "good"
            elseif autoStartEnabled then
                automationText = L["SETTINGS_KS_STATUS_AUTO_START"]
                automationTone = "good"
            end

            local keystoneText = L["SETTINGS_KS_STATUS_MISSING"]
            local keystoneTone = "warn"
            if hasKeystoneInBags then
                local levelText = (keystoneLevel > 0) and tostring(keystoneLevel) or "?"
                keystoneText = string.format(L["SETTINGS_KS_STATUS_IN_BAGS_FORMAT"], levelText)
                keystoneTone = "good"
            end

            widgets.statusKeystone:SetState(keystoneText, keystoneTone)
            widgets.statusLeader:SetState(leaderOrAssist and L["COMMON_YES"] or L["COMMON_NO"], leaderOrAssist and "good" or "warn")
            widgets.statusAutomation:SetState(automationText, automationTone)
        end

        local function refreshVisuals()
            if not PortalAuthorityDB then
                ensureDatabase()
                if not PortalAuthorityDB then
                    return
                end
            end

            if widgets.keystoneHelperEnabled and widgets.keystoneHelperEnabled.Refresh then
                widgets.keystoneHelperEnabled:Refresh()
            end
            if widgets.keystoneAutoSlotEnabled and widgets.keystoneAutoSlotEnabled.Refresh then
                widgets.keystoneAutoSlotEnabled:Refresh()
            end
            if widgets.keystoneAutoStartEnabled and widgets.keystoneAutoStartEnabled.Refresh then
                widgets.keystoneAutoStartEnabled:Refresh()
            end
            if widgets.releaseGateEnabled and widgets.releaseGateEnabled.Refresh then
                widgets.releaseGateEnabled:Refresh()
            end
            if widgets.releaseGateModifier and widgets.releaseGateModifier.Refresh then
                widgets.releaseGateModifier:Refresh()
            end
            if widgets.releaseHoldStepper and widgets.releaseHoldStepper.Refresh then
                widgets.releaseHoldStepper:Refresh()
            end

            local releaseEnabled = PA_SafeBool(PortalAuthorityDB and PortalAuthorityDB.releaseGateEnabled)
            if widgets.releaseGateModifier and widgets.releaseGateModifier.SetEnabled then
                widgets.releaseGateModifier:SetEnabled(releaseEnabled)
            end
            holdLabel:SetTextColor(releaseEnabled and 1 or 0.6, releaseEnabled and 1 or 0.6, releaseEnabled and 1 or 0.6, 1)
            releaseHoldDesc:SetTextColor(releaseEnabled and 0.72 or 0.58, releaseEnabled and 0.72 or 0.58, releaseEnabled and 0.72 or 0.58, 1)
            if widgets.releaseHoldStepper and widgets.releaseHoldStepper.SetEnabled then
                widgets.releaseHoldStepper:SetEnabled(releaseEnabled)
            end

            KU_RefreshStatusStrip()

            if panelRef and panelRef._kuHydrateKeystoneTooltipVisualOnly then
                panelRef._kuHydrateKeystoneTooltipVisualOnly()
            end
        end

        local function refresh()
            refreshVisuals()
        end

        local function fullRefresh(reason)
            local needsBootstrap = not self._kuBootstrapComplete
            if needsBootstrap then
                refreshVisuals()
                local didLayout = ensureLayoutCurrent("bootstrap")
                refreshVisuals()
                if didLayout then
                    self._kuBootstrapComplete = true
                end
                return
            end
            ensureLayoutCurrent(reason or "full-refresh")
            refreshVisuals()
        end

        local function layout()
            local T = KEYSTONE_UTILITY_LAYOUT
            local P = T.PAGE
            local S = T.SECTION
            local C = T.CARD
            local ST = T.STATUS
            local TT = T.TOOLTIP
            local contentW = KU_ComputeContentWidth()
            local useHostedChrome = isPanelUsingCustomSettingsWindowHost(panelRef)
            scrollChild:SetWidth(contentW)

            local contentLeft = P.CONTENT_LEFT
            local contentRight = contentW - P.CONTENT_RIGHT
            local contentSpan = math.max(0, contentRight - contentLeft)
            local headerSpan = math.max(0, contentRight - P.HEADER_LEFT)
            local y = -P.TOP_PAD
            if useHostedChrome then
                y = y - SETTINGS_WINDOW_HOSTED_TOP_RHYTHM_NUDGE
            end

            if useHostedChrome then
                setSettingsWindowChromeVisible(header, false, scrollChild)
                setSettingsWindowChromeVisible(widgets.sectionDescriptor, false, scrollChild)
            else
                setSettingsWindowChromeVisible(header, true)
                setSettingsWindowChromeVisible(widgets.sectionDescriptor, true, scrollChild)
                header:ClearAllPoints()
                header:SetPoint("TOPLEFT", scrollChild, "TOPLEFT", P.HEADER_LEFT, y)
                header:SetWidth(math.max(T.HEADER_MIN_W, headerSpan))
                if header.SetJustifyH then
                    header:SetJustifyH("LEFT")
                end
                local headerH = KU_MeasureFontStringHeight(header, P.TITLE_FLOOR)
                y = y - headerH - P.TITLE_TO_SECTION_GAP
                y = layoutSettingsSectionDescriptor(
                    widgets.sectionDescriptor,
                    scrollChild,
                    P.HEADER_LEFT,
                    y,
                    math.max(T.HEADER_MIN_W, headerSpan)
                )
            end

            helperHeader:ClearAllPoints()
            helperHeader:SetPoint("TOPLEFT", scrollChild, "TOPLEFT", P.CONTENT_LEFT, y)
            helperHeader:SetWidth(math.max(T.HEADER_MIN_W, contentSpan))
            if helperHeader.SetJustifyH then
                helperHeader:SetJustifyH("LEFT")
            end
            local assistantHeaderH = KU_MeasureFontStringHeight(helperHeader, S.SUBHEADER_FLOOR)
            y = y - assistantHeaderH - S.SUBHEADER_GAP

            widgets.assistantCard:ClearAllPoints()
            widgets.assistantCard:SetPoint("TOPLEFT", scrollChild, "TOPLEFT", contentLeft, y)
            widgets.assistantCard:SetWidth(contentSpan)
            local assistantColumns = KU_ComputeSectionColumns(contentSpan, assistantRows)
            local assistantBottomY = KU_LayoutRows(widgets.assistantCard, assistantRows, assistantColumns)
            local assistantRowsBottomY = assistantBottomY + assistantColumns.rowGap

            local statusStripW = math.max(0, contentSpan - (C.PAD_X * 2))
            local chipGap = ST.CHIP_GAP
            local equalChipW = math.max(T.STATUS_CHIP_MIN_W, math.floor((statusStripW - (chipGap * 2)) / 3))
            local chipTextW = T.STATUS_CHIP_MIN_W
            for _, chip in ipairs(statusChips) do
                chipTextW = math.max(
                    chipTextW,
                    KU_MeasureFontStringWidth(chip and chip.title or nil) + T.STATUS_CHIP_TEXT_PAD,
                    KU_MeasureFontStringWidth(chip and chip.value or nil) + T.STATUS_CHIP_TEXT_PAD
                )
            end
            local chipW = math.max(T.STATUS_CHIP_MIN_W, chipTextW, equalChipW)
            if (chipW * 3) + (chipGap * 2) > statusStripW then
                chipW = math.max(T.STATUS_CHIP_MIN_W, math.floor((statusStripW - (chipGap * 2)) / 3))
            end
            local statusTopY = assistantBottomY + ST.STRIP_Y_NUDGE
            widgets.statusStrip:ClearAllPoints()
            widgets.statusStrip:SetPoint("TOPLEFT", widgets.assistantCard, "TOPLEFT", C.PAD_X, statusTopY)
            widgets.statusStrip:SetSize(math.max(0, (chipW * 3) + (chipGap * 2)), ST.CHIP_H)
            for index, chip in ipairs(statusChips) do
                local chipX = (index - 1) * (chipW + chipGap)
                chip:ClearAllPoints()
                chip:SetPoint("TOPLEFT", widgets.statusStrip, "TOPLEFT", chipX, 0)
                chip:SetSize(chipW, ST.CHIP_H)
            end

            local assistantCardBottomY = math.min(assistantRowsBottomY, statusTopY - ST.CHIP_H)
            local assistantCardH = math.abs(assistantCardBottomY) + C.PAD_BOTTOM
            widgets.assistantCard:SetHeight(assistantCardH)
            y = y - assistantCardH - S.STACK_GAP

            widgets.topSectionDivider:ClearAllPoints()
            widgets.topSectionDivider:SetPoint("TOPLEFT", scrollChild, "TOPLEFT", contentLeft, y + S.DIVIDER_Y_OFFSET)
            widgets.topSectionDivider:SetPoint("TOPRIGHT", scrollChild, "TOPLEFT", contentRight, y + S.DIVIDER_Y_OFFSET)
            widgets.topSectionDivider:SetHeight(S.DIVIDER_H)
            widgets.topSectionDivider:Show()

            releaseHeader:ClearAllPoints()
            releaseHeader:SetPoint("TOPLEFT", scrollChild, "TOPLEFT", P.CONTENT_LEFT, y)
            releaseHeader:SetWidth(math.max(T.HEADER_MIN_W, contentSpan))
            if releaseHeader.SetJustifyH then
                releaseHeader:SetJustifyH("LEFT")
            end
            local releaseHeaderH = KU_MeasureFontStringHeight(releaseHeader, S.SUBHEADER_FLOOR)
            y = y - releaseHeaderH - S.SUBHEADER_GAP

            widgets.releaseCard:ClearAllPoints()
            widgets.releaseCard:SetPoint("TOPLEFT", scrollChild, "TOPLEFT", contentLeft, y)
            widgets.releaseCard:SetWidth(contentSpan)
            local releaseColumns = KU_ComputeSectionColumns(contentSpan, releaseRows)
            local releaseBottomY = KU_LayoutRows(widgets.releaseCard, releaseRows, releaseColumns)
            local releaseRowsBottomY = releaseBottomY + releaseColumns.rowGap
            local releaseCardH = math.abs(releaseRowsBottomY) + C.PAD_BOTTOM
            widgets.releaseCard:SetHeight(releaseCardH)
            y = y - releaseCardH - S.RELEASE_TO_TOOLTIP_GAP

            tooltipHeader:ClearAllPoints()
            tooltipHeader:SetPoint("TOPLEFT", scrollChild, "TOPLEFT", P.CONTENT_LEFT, y)
            tooltipHeader:SetWidth(math.max(T.HEADER_MIN_W, contentSpan))
            if tooltipHeader.SetJustifyH then
                tooltipHeader:SetJustifyH("LEFT")
            end
            local tooltipHeaderH = KU_MeasureFontStringHeight(tooltipHeader, S.TITLE_FLOOR)
            y = y - tooltipHeaderH - S.TOOLTIP_TITLE_TO_SUBHEADER_GAP

            tooltipSubheader:ClearAllPoints()
            tooltipSubheader:SetPoint("TOPLEFT", scrollChild, "TOPLEFT", P.CONTENT_LEFT, y)
            tooltipSubheader:SetWidth(math.max(T.HEADER_MIN_W, contentSpan))
            if tooltipSubheader.SetJustifyH then
                tooltipSubheader:SetJustifyH("LEFT")
            end
            local tooltipSubheaderH = KU_MeasureFontStringHeight(tooltipSubheader, S.SUBHEADER_FLOOR)
            y = y - tooltipSubheaderH - S.TOOLTIP_SUBHEADER_TO_CONTENT_GAP

            local tooltipGeo = KU_ComputeTooltipGeometry(contentSpan)
            local inspectorContentW = tooltipGeo.inspectorContentW
            local availableInlineW = tooltipGeo.availableInlineW
            local inlineBlockW = tooltipGeo.inlineBlockW
            local inspectorPaneH = 0

            tooltipBuilder.root:ClearAllPoints()
            tooltipBuilder.root:SetPoint("TOPLEFT", scrollChild, "TOPLEFT", contentLeft, y)
            tooltipBuilder.root:SetWidth(tooltipGeo.rootW)

            tooltipBuilder.inspectorPane:ClearAllPoints()
            tooltipBuilder.inspectorPane:SetPoint("TOPLEFT", tooltipBuilder.root, "TOPLEFT", 0, 0)
            tooltipBuilder.inspectorPane:SetWidth(tooltipGeo.inspectorW)

            tooltipBuilder.statusSlot:ClearAllPoints()
            tooltipBuilder.statusSlot:SetPoint("TOPLEFT", tooltipBuilder.inspectorPane, "TOPLEFT", TT.INSPECTOR_PAD_X, -TT.INSPECTOR_PAD_Y)
            tooltipBuilder.statusSlot:SetPoint("TOPRIGHT", tooltipBuilder.inspectorPane, "TOPRIGHT", -TT.INSPECTOR_PAD_X, -TT.INSPECTOR_PAD_Y)
            tooltipBuilder.statusSlot:SetHeight(TT.STATUS_H)

            tooltipBuilder.inspectorContent:ClearAllPoints()
            tooltipBuilder.inspectorContent:SetPoint("TOPLEFT", tooltipBuilder.statusSlot, "BOTTOMLEFT", 0, -TT.STATUS_TO_CONTENT_GAP)
            tooltipBuilder.inspectorContent:SetPoint("TOPRIGHT", tooltipBuilder.statusSlot, "BOTTOMRIGHT", 0, -TT.STATUS_TO_CONTENT_GAP)

            tooltipBuilder.inspectorHeader:ClearAllPoints()
            tooltipBuilder.inspectorHeader:SetPoint("TOPLEFT", tooltipBuilder.root, "TOPLEFT", TT.INSPECTOR_PAD_X, -TT.TITLE_TOP_PAD)
            tooltipBuilder.inspectorHeader:SetWidth(math.max(1, tooltipGeo.inspectorW - (TT.INSPECTOR_PAD_X * 2)))
            if tooltipBuilder.inspectorHeader.SetJustifyH then
                tooltipBuilder.inspectorHeader:SetJustifyH("LEFT")
            end

            local rowY = 0

            for _, row in ipairs(tooltipBuilder.rows) do
                local rowW = inspectorContentW
                local rowContentYNudge = 0
                local inlineDrop = false
                if row.inline then
                    inlineDrop = availableInlineW < inlineBlockW
                    if row.cfg and row.cfg.inline and row.cfg.inline.layout == "subline" then
                        inlineDrop = true
                    end
                end
                local rowH = inlineDrop and TT.ROW_H_COMPOUND_DROPPED or TT.BASE_ROW_H
                local topAnchoredMain = inlineDrop
                local mainControlH = KU_MeasureControlHeight(row.main and row.main.control or nil, TT.CONTROL_FLOOR)
                local inlineLabelH = 0
                local inlineControlH = 0
                if inlineDrop and row.inline and row.inline.control and row.inlineLabel then
                    inlineLabelH = KU_MeasureFontStringHeight(row.inlineLabel, TT.INLINE_LABEL_FLOOR)
                    inlineControlH = KU_MeasureControlHeight(row.inline.control, TT.CONTROL_FLOOR)
                    rowH = math.max(
                        TT.BASE_ROW_H,
                        TT.DROPPED_ROW_TOP_PAD + mainControlH + TT.SUBLINE_MAIN_TO_LABEL_GAP + inlineLabelH + TT.SUBLINE_LABEL_TO_CONTROL_GAP + inlineControlH + TT.DROPPED_ROW_BOTTOM_PAD
                    )
                end
                local swatchDropped = false
                if row.colorSwatch then
                    local swatchW = tonumber(row.colorSwatch:GetWidth()) or 22
                    local swatchRight = tooltipGeo.controlColX + tooltipGeo.mainControlW + TT.SWATCH_GAP + swatchW
                    if swatchRight > (rowW - 2) then
                        swatchDropped = true
                        rowH = math.max(rowH, TT.ROW_H_SWATCH_DROPPED)
                    end
                end
                row.container:ClearAllPoints()
                row.container:SetPoint("TOPLEFT", tooltipBuilder.inspectorContent, "TOPLEFT", 0, rowY)
                row.container:SetWidth(rowW)
                row.container:SetHeight(rowH)

                row.label:ClearAllPoints()
                if topAnchoredMain then
                    row.label:SetPoint("TOPLEFT", row.container, "TOPLEFT", tooltipGeo.labelColX, -TT.TOP_LABEL_Y_INSET)
                else
                    row.label:SetPoint("LEFT", row.container, "LEFT", tooltipGeo.labelColX, rowContentYNudge)
                end
                row.label:SetWidth(math.max(T.TOOLTIP_LABEL_MIN_W, tooltipGeo.labelW))

                if row.main and row.main.control then
                    row.main.control:ClearAllPoints()
                    if topAnchoredMain then
                        row.main.control:SetPoint("TOPLEFT", row.container, "TOPLEFT", tooltipGeo.controlColX, -TT.MAIN_TOP_PAD)
                    else
                        row.main.control:SetPoint("LEFT", row.container, "LEFT", tooltipGeo.controlColX, rowContentYNudge)
                    end
                    if row.main.SetWidth then
                        row.main:SetWidth(tooltipGeo.mainControlW)
                    elseif row.main.Layout then
                        row.main:Layout(tooltipGeo.mainControlW)
                    end
                end

                if row.inline and row.inline.control and row.inlineLabel then
                    if inlineDrop then
                        if row.inlineAccent then
                            row.inlineAccent:Show()
                        end
                        local droppedLabelY = -(TT.MAIN_TOP_PAD + mainControlH + TT.SUBLINE_MAIN_TO_LABEL_GAP)
                        local inlineControlY = droppedLabelY - inlineLabelH - TT.SUBLINE_LABEL_TO_CONTROL_GAP
                        row.inlineLabel:ClearAllPoints()
                        row.inlineLabel:SetPoint("TOPLEFT", row.container, "TOPLEFT", tooltipGeo.controlColX + TT.SUBLINE_LABEL_X_INSET, droppedLabelY)
                        row.inlineLabel:SetWidth(math.max(TT.SUBLINE_LABEL_MIN_W, rowW - tooltipGeo.controlColX - TT.SUBLINE_LABEL_RIGHT_PAD))
                        if row.inlineAccent then
                            row.inlineAccent:ClearAllPoints()
                            row.inlineAccent:SetPoint("TOPLEFT", row.container, "TOPLEFT", tooltipGeo.controlColX + TT.SUBLINE_ACCENT_X_INSET, droppedLabelY - TT.SUBLINE_ACCENT_Y_NUDGE)
                            row.inlineAccent:SetHeight(math.max(TT.SUBLINE_ACCENT_MIN_H, inlineLabelH + TT.SUBLINE_ACCENT_HEIGHT_PAD))
                        end
                        row.inline.control:ClearAllPoints()
                        row.inline.control:SetPoint("TOPLEFT", row.container, "TOPLEFT", tooltipGeo.controlColX + TT.SUBLINE_LABEL_X_INSET, inlineControlY)
                    else
                        if row.inlineAccent then
                            row.inlineAccent:Hide()
                        end
                        row.inlineLabel:ClearAllPoints()
                        row.inlineLabel:SetPoint("LEFT", row.container, "LEFT", tooltipGeo.inlineRegionX, 0)
                        row.inlineLabel:SetWidth(TOOLTIP_BUILDER_INLINE_LABEL_W)
                        row.inline.control:ClearAllPoints()
                        row.inline.control:SetPoint(
                            "LEFT",
                            row.container,
                            "LEFT",
                            tooltipGeo.inlineRegionX + TOOLTIP_BUILDER_INLINE_LABEL_W + TT.INLINE_BLOCK_GAP,
                            0
                        )
                    end
                    row.inline:Layout(TOOLTIP_BUILDER_INLINE_TOGGLE_W)
                end

                if row.colorSwatch then
                    row.colorSwatch:ClearAllPoints()
                    if swatchDropped then
                        row.colorSwatch:SetPoint("TOPLEFT", row.container, "TOPLEFT", tooltipGeo.controlColX, -(TT.BASE_ROW_H + TT.DROPPED_ROW_BOTTOM_PAD))
                    else
                        row.colorSwatch:SetPoint(
                            "LEFT",
                            row.container,
                            "LEFT",
                            tooltipGeo.controlColX + tooltipGeo.mainControlW + TT.SWATCH_GAP,
                            0
                        )
                    end
                end

                rowY = rowY - rowH - TT.ROW_GAP
            end

            local usedInspectorH = math.max(0, math.abs(rowY) + TT.INSPECTOR_PAD_Y)
            tooltipBuilder.inspectorContent:SetHeight(usedInspectorH)
            inspectorPaneH = TT.STATUS_H + TT.INSPECTOR_PAD_Y + TT.STATUS_TO_CONTENT_GAP + usedInspectorH + TT.INSPECTOR_PAD_Y
            if inspectorPaneH < TOOLTIP_BUILDER_PREVIEW_H then
                inspectorPaneH = TOOLTIP_BUILDER_PREVIEW_H
            end
            tooltipBuilder.inspectorPane:SetHeight(inspectorPaneH)

            if tooltipGeo.sideBySide then
                tooltipBuilder.previewPane:ClearAllPoints()
                tooltipBuilder.previewPane:SetSize(tooltipGeo.previewW, TOOLTIP_BUILDER_PREVIEW_H)
                tooltipBuilder.previewPane:SetPoint("TOPLEFT", tooltipBuilder.root, "TOPLEFT", tooltipGeo.inspectorW + TT.PANE_GAP, -TT.STICKY_TOP_PAD)
                tooltipBuilder.root:SetHeight(math.max(inspectorPaneH, TOOLTIP_BUILDER_PREVIEW_H))
            else
                tooltipBuilder.previewPane:ClearAllPoints()
                tooltipBuilder.previewPane:SetPoint("TOPLEFT", tooltipBuilder.root, "TOPLEFT", 0, -(inspectorPaneH + TT.PANE_GAP))
                tooltipBuilder.previewPane:SetSize(tooltipGeo.previewW, TOOLTIP_BUILDER_PREVIEW_H)
                tooltipBuilder.root:SetHeight(inspectorPaneH + TT.PANE_GAP + TOOLTIP_BUILDER_PREVIEW_H)
            end

            tooltipBuilder.previewTitle:ClearAllPoints()
            if tooltipGeo.sideBySide then
                tooltipBuilder.previewTitle:SetPoint("TOPLEFT", tooltipBuilder.root, "TOPLEFT", tooltipGeo.inspectorW + TT.PANE_GAP + TT.PREVIEW_TITLE_PAD_X, -TT.TITLE_TOP_PAD)
            else
                tooltipBuilder.previewTitle:SetPoint("TOPLEFT", tooltipBuilder.previewPane, "TOPLEFT", TT.PREVIEW_TITLE_PAD_X, -TT.TITLE_TOP_PAD)
            end

            widgets.keystoneTooltipPreviewAnchor:ClearAllPoints()
            widgets.keystoneTooltipPreviewAnchor:SetPoint("TOPLEFT", tooltipBuilder.previewPane, "TOPLEFT", TT.PREVIEW_BODY_PAD_X, -tooltipGeo.previewAnchorTopInset)
            widgets.keystoneTooltipPreviewAnchor:SetPoint("BOTTOMRIGHT", tooltipBuilder.previewPane, "BOTTOMRIGHT", -TT.PREVIEW_BODY_PAD_X, TT.PREVIEW_BODY_BOTTOM_PAD)

            tooltipBuilder.previewHitLayer:ClearAllPoints()
            tooltipBuilder.previewHitLayer:SetPoint("TOPLEFT", widgets.keystoneTooltipPreviewAnchor, "TOPLEFT", 0, 0)
            tooltipBuilder.previewHitLayer:SetPoint("BOTTOMRIGHT", widgets.keystoneTooltipPreviewAnchor, "BOTTOMRIGHT", 0, 0)

            do
                local firstRow = tooltipBuilder.rows and tooltipBuilder.rows[1] or nil
                local firstRowTop = firstRow and firstRow.container and firstRow.container.GetTop and firstRow.container:GetTop() or nil
                if tooltipGeo.sideBySide and firstRowTop and firstRowTop > 0 then
                    tooltipBuilder._desiredPreviewBodyTopAbs = firstRowTop
                else
                    tooltipBuilder._desiredPreviewBodyTopAbs = nil
                end
            end

            y = y - tooltipBuilder.root:GetHeight() - S.TOOLTIP_BOTTOM_GAP

            scrollChild:SetHeight(math.max(scrollFrame:GetHeight(), math.abs(y) + P.BOTTOM_PAD))
            updateScrollBehavior(scrollFrame, scrollChild)
        end

        self._layout = layout
        self._refreshVisuals = refreshVisuals
        self._refresh = refresh
        self._fullRefresh = fullRefresh
        self._invalidateLayout = invalidateLayout
        self._kuBuildMetricSignature = KU_BuildMetricSignature
        invalidateLayout("initial-build")

        if not self._kuTooltipPreviewEventFrame then
            local eventFrame = CreateFrame("Frame")
            eventFrame:SetScript("OnEvent", function(frameEvent)
                local owner = frameEvent._owner
                if not owner or not owner.IsShown or not owner:IsShown() then
                    return
                end
                if owner._refresh then
                    owner._refresh()
                end
            end)
            self._kuTooltipPreviewEventFrame = eventFrame
        end
        self._kuTooltipPreviewEventFrame._owner = self

        if not self._kuMetricWatcher then
            local metricWatcher = CreateFrame("Frame", nil, self)
            metricWatcher:Hide()
            metricWatcher:SetScript("OnUpdate", function(frameWatcher, elapsed)
                local owner = frameWatcher._owner
                if not owner or not owner.IsShown or not owner:IsShown() then
                    frameWatcher:Hide()
                    return
                end
                frameWatcher._elapsed = (tonumber(frameWatcher._elapsed) or 0) + (tonumber(elapsed) or 0)
                if frameWatcher._elapsed < KEYSTONE_UTILITY_LAYOUT.METRIC_WATCH_INTERVAL then
                    return
                end
                frameWatcher._elapsed = 0
                if not (owner._kuBuildMetricSignature and owner._invalidateLayout and owner._fullRefresh) then
                    return
                end
                if not KU_HasSizedLayoutSurface() then
                    owner._invalidateLayout("metric-unsized")
                    return
                end
                local currentSignature = owner._kuBuildMetricSignature()
                if currentSignature ~= owner._kuMetricSignatureCache then
                    owner._invalidateLayout("metric-signature")
                    owner._fullRefresh("metric-signature")
                end
            end)
            metricWatcher:SetScript("OnHide", function(frameWatcher)
                frameWatcher._elapsed = 0
            end)
            self._kuMetricWatcher = metricWatcher
        end
        self._kuMetricWatcher._owner = self

        registerRefreshCallback(function()
            if self._refresh then
                self._refresh()
            end
        end, self)
        scrollFrame:SetScript("OnSizeChanged", function()
            invalidateLayout("size-changed")
            local useHostedFirstOpen = isPanelUsingCustomSettingsWindowHost(self)
            if useHostedFirstOpen and handleSettingsFirstOpenSizeReady(self, "size_changed") then
                return
            end
            if useHostedFirstOpen and shouldSuppressSettingsFirstOpenExternalRefresh(self) then
                return
            end
            if not (self and self.IsShown and self:IsShown()) then
                return
            end
            if self._fullRefresh then
                self._fullRefresh("size-changed")
            end
        end)

        self._settingsFirstOpenKey = "keystone"
        self._settingsFirstOpenSizeTarget = scrollFrame
        self._settingsFirstOpenRender = function(panel)
            ensureKeystonePanelAnchored(panel)
            ensureDatabase()
            if not (panel and panel._initialized and panel._layout and panel._refresh and panel._fullRefresh) then
                if panel and panel.EnsureBuilt then
                    panel:EnsureBuilt()
                end
            end
            if panel and PortalAuthorityDB and panel._initialized and panel._layout and panel._refresh and panel._fullRefresh and keystoneHasSizedViewport(panel) then
                renderKeystoneWhenReady(panel)
                return
            end
            if panel and panel._fullRefresh then
                panel._fullRefresh("bootstrap")
            end
            startKeystoneRenderBootstrap(panel)
        end
        self._settingsFirstOpenIsReady = function(panel)
            return isPanelUsingCustomSettingsWindowHost(panel)
                and panel ~= nil
                and panel._initialized == true
                and type(panel._layout) == "function"
                and type(panel._refresh) == "function"
                and type(panel._fullRefresh) == "function"
                and keystoneHasSizedViewport(panel)
                and panel._kuRenderBootstrapActive ~= true
                and panel._kuScrollChild ~= nil
                and panel._kuScrollChild.IsShown
                and panel._kuScrollChild:IsShown()
        end
        self._initialized = true
        settingsSearchRuntime.endDescriptorCapture(self)
    end

    ensureKeystonePanelAnchored = function(self)
        local p = self:GetParent()
        if not p then
            return false
        end
        if self._paAnchorParent ~= p or not self._paAnchored then
            self:ClearAllPoints()
            self:SetAllPoints(p)
            self._paAnchorParent = p
        end
        self._paAnchored = true
        return true
    end

    renderKeystoneWhenReady = function(self)
        if not self or not self.IsShown or not self:IsShown() then
            return
        end
        if not (self._initialized and self._layout and self._refresh and self._fullRefresh) then
            return
        end
        if not PortalAuthorityDB then
            return
        end
        ensureKeystonePanelAnchored(self)
        if self._sizingFrame and self._sizingFrame.Show then
            self._sizingFrame:Show()
            if self._sizingFrame.SetVerticalScroll then
                self._sizingFrame:SetVerticalScroll(0)
            end
        end
        if self._kuScrollChild and self._kuScrollChild.Show then
            self._kuScrollChild:Show()
        end
        if self._fullRefresh then
            self._fullRefresh("render-ready")
        end
    end

    keystoneHasSizedViewport = function(self)
        local readyFrame = (self and self._sizingFrame) or self
        if not readyFrame then
            return false
        end
        local w = tonumber(readyFrame:GetWidth()) or 0
        local h = tonumber(readyFrame:GetHeight()) or 0
        return (w > 1 and h > 1)
    end

    startKeystoneRenderBootstrap = function(self)
        if not self then
            return
        end
        local watcher = self._kuRenderBootstrapWatcher
        if not watcher then
            watcher = CreateFrame("Frame", nil, self)
            watcher:Hide()
            watcher:SetScript("OnUpdate", function(frameWatcher, elapsed)
                local owner = frameWatcher._owner
                if not owner or not owner.IsShown or not owner:IsShown() then
                    frameWatcher:Hide()
                    return
                end
                frameWatcher._elapsed = (tonumber(frameWatcher._elapsed) or 0) + (tonumber(elapsed) or 0)
                ensureDatabase()
                if not (owner._initialized and owner._layout and owner._refresh and owner._fullRefresh) then
                    owner:EnsureBuilt()
                end
                ensureKeystonePanelAnchored(owner)
                if PortalAuthorityDB and owner._initialized and owner._layout and owner._refresh and owner._fullRefresh and keystoneHasSizedViewport(owner) then
                    renderKeystoneWhenReady(owner)
                    frameWatcher:Hide()
                    return
                end
                -- Intentionally no hard timeout: keep retrying while this panel stays shown,
                -- so first-open can recover without requiring a section switch.
            end)
            watcher:SetScript("OnHide", function(frameWatcher)
                frameWatcher._elapsed = 0
                if frameWatcher._owner then
                    frameWatcher._owner._kuRenderBootstrapActive = false
                end
            end)
            self._kuRenderBootstrapWatcher = watcher
        end
        watcher._owner = self
        watcher._elapsed = 0
        if not self._kuRenderBootstrapActive then
            self._kuRenderBootstrapActive = true
            watcher:Show()
        end
    end

    panel:SetScript("OnShow", function(self)
        ensureKeystonePanelAnchored(self)
        ensureDatabase()
        self:EnsureBuilt()
        if self._kuTooltipPreviewEventFrame then
            self._kuTooltipPreviewEventFrame._owner = self
            self._kuTooltipPreviewEventFrame:RegisterEvent("GET_ITEM_INFO_RECEIVED")
            self._kuTooltipPreviewEventFrame:RegisterEvent("BAG_UPDATE_DELAYED")
            self._kuTooltipPreviewEventFrame:RegisterEvent("CHALLENGE_MODE_MAPS_UPDATE")
            self._kuTooltipPreviewEventFrame:RegisterEvent("PLAYER_ENTERING_WORLD")
        end
        if self._kuMetricWatcher then
            self._kuMetricWatcher._owner = self
            self._kuMetricWatcher._elapsed = 0
            self._kuMetricWatcher:Show()
        end

        if isPanelUsingCustomSettingsWindowHost(self) and self._paFirstOpenState == "pending" then
            resetSettingsFirstOpenPanelState(self)
        end
        if isPanelUsingCustomSettingsWindowHost(self) and handleSettingsFirstOpenPanelShow(self) then
            return
        end

        if PortalAuthorityDB and self._initialized and self._layout and self._refresh and self._fullRefresh and keystoneHasSizedViewport(self) then
            renderKeystoneWhenReady(self)
        else
            if self._fullRefresh then
                self._fullRefresh("bootstrap")
            end
            startKeystoneRenderBootstrap(self)
        end

        if C_Timer and C_Timer.After then
            C_Timer.After(0, function()
                if not self or not self:IsShown() then return end
                ensureDatabase()
                if not (self._initialized and self._layout and self._refresh and self._fullRefresh) then
                    self:EnsureBuilt()
                end
                if PortalAuthorityDB and self._initialized and self._layout and self._refresh and self._fullRefresh and keystoneHasSizedViewport(self) then
                    renderKeystoneWhenReady(self)
                else
                    if self._fullRefresh then
                        self._fullRefresh("bootstrap")
                    end
                    startKeystoneRenderBootstrap(self)
                end
            end)
        end
    end)
    panel:HookScript("OnHide", function(self)
        if isPanelUsingCustomSettingsWindowHost(self) or shouldSuppressSettingsFirstOpenExternalRefresh(self) then
            handleSettingsFirstOpenPanelHide(self)
        end
        if self and self._kuRenderBootstrapWatcher then
            self._kuRenderBootstrapWatcher:Hide()
        end
        if self and self._kuMetricWatcher then
            self._kuMetricWatcher:Hide()
        end
        if self and self._kuTooltipPreviewEventFrame then
            self._kuTooltipPreviewEventFrame:UnregisterAllEvents()
        end
        if self and self._kuCloseTooltipBuilderPickers then
            self._kuCloseTooltipBuilderPickers()
        end
    end)

    return panel
end
OptionsInternal.createKeystoneUtilityPanel = createKeystoneUtilityPanel
