-- Portal Authority — core/diagnostics.lua
-- Perf/CPU diagnostic infrastructure, host visibility snapshots, and diag dump builders.
--
-- Depends on: PortalAuthority; PortalAuthority.CoreInternal helpers
-- Exposes:    Perf*, CpuDiag*, GetSettingsPanelWalkOrder, GetSettingsPanelRegistry, StartDiagDump
-- DB keys:    PortalAuthorityDiagDump*
-- Events:     none
-- Search key: none

local ADDON_NAME = ...

PortalAuthority = PortalAuthority or {}
PortalAuthority.CoreInternal = PortalAuthority.CoreInternal or {}
local CoreInternal = PortalAuthority.CoreInternal

local PA_IsUiSurfaceGateEnabled = CoreInternal.PA_IsUiSurfaceGateEnabled
local PA_IsStaticBaselineGateEnabled = CoreInternal.PA_IsStaticBaselineGateEnabled
local PA_IsSettingsBaselineGateEnabled = CoreInternal.PA_IsSettingsBaselineGateEnabled
local PA_IsSettingsEagerBuildGateEnabled = CoreInternal.PA_IsSettingsEagerBuildGateEnabled
local PA_IsSettingsDirectBuildGateEnabled = CoreInternal.PA_IsSettingsDirectBuildGateEnabled
local PA_IsSettingsWindowHostEnabled = CoreInternal.PA_IsSettingsWindowHostEnabled
local PA_IsSettingsWindowDevGateEnabled = CoreInternal.PA_IsSettingsWindowDevGateEnabled
local PA_IsSettingsWindowPublicGateEnabled = CoreInternal.PA_IsSettingsWindowPublicGateEnabled
local PA_IsOnboardingD1DevGateEnabled = CoreInternal.PA_IsOnboardingD1DevGateEnabled
local PA_IsOnboardingD3DevGateEnabled = CoreInternal.PA_IsOnboardingD3DevGateEnabled
local PA_IsOnboardingD4DevGateEnabled = CoreInternal.PA_IsOnboardingD4DevGateEnabled
local PA_IsOnboardingD3PublicGateEnabled = CoreInternal.PA_IsOnboardingD3PublicGateEnabled
local PA_IsOnboardingD4PublicGateEnabled = CoreInternal.PA_IsOnboardingD4PublicGateEnabled
local PA_IsOnboardingQualifyingUpgradePublicGateEnabled = CoreInternal.PA_IsOnboardingQualifyingUpgradePublicGateEnabled
local PA_IsOnboardingD3Enabled = CoreInternal.PA_IsOnboardingD3Enabled
local PA_IsOnboardingD4Enabled = CoreInternal.PA_IsOnboardingD4Enabled
local trim = CoreInternal.trim
local clampNumber = CoreInternal.clampNumber
local PA_Clamp = CoreInternal.PA_Clamp
local PA_ToNumber = CoreInternal.PA_ToNumber
local PA_SafeBool = CoreInternal.PA_SafeBool
local PA_CompareSemver = CoreInternal.PA_CompareSemver
local PA_IsSemverStringValid = CoreInternal.PA_IsSemverStringValid
local PA_GetCurrentAddonVersionState = CoreInternal.PA_GetCurrentAddonVersionState
local VALID_OUTLINES = CoreInternal.VALID_OUTLINES
local VALID_SOUND_CHANNELS = CoreInternal.VALID_SOUND_CHANNELS
local BUILTIN_FONT_FALLBACK = CoreInternal.BUILTIN_FONT_FALLBACK
local PLAYER_LOGIN_MESSAGE = CoreInternal.PLAYER_LOGIN_MESSAGE
local DOCK_ENABLE_DEFAULTS_VERSION = CoreInternal.DOCK_ENABLE_DEFAULTS_VERSION
local PA_PrintPortalAuthorityMessage = CoreInternal.PA_PrintPortalAuthorityMessage
local PA_MaybeShowMPlusNotice = CoreInternal.PA_MaybeShowMPlusNotice
local ResetMPlusNoticeShown = CoreInternal.ResetMPlusNoticeShown
local PA_IsSecretValue = CoreInternal.PA_IsSecretValue
local PA_NormalizeSafeString = CoreInternal.PA_NormalizeSafeString
local PA_SafeStringsEqual = CoreInternal.PA_SafeStringsEqual
local PA_SafeUnitGUID = CoreInternal.PA_SafeUnitGUID

local PA_PERF_SCOPE_ORDER = {
    dock_onupdate = 1,
    dock_drag_motion = 2,
    dock_save_position = 3,
    timers_evaluate_visibility = 4,
    timers_tick = 5,
    interrupt_evaluate_visibility = 6,
    interrupt_update_display = 7,
    deathalerts_apply_settings = 8,
    deathalerts_unlocked_preview = 9,
    options_refresh_all = 10,
    profiles_refresh = 11,
    profiles_layout = 12,
    interrupt_periodic_inspect = 13,
    movehint_ticker = 14,
    modules_event_dispatch = 15,
    modules_event_unit_aura = 16,
    modules_event_unit_power_update = 17,
    modules_event_chat_msg_addon = 18,
    modules_event_other = 19,
    modules_event_init = 20,
    modules_event_evaluate_visibility = 21,
    modules_event_on_event = 22,
    core_event_dispatch = 23,
    core_event_chat = 24,
    core_event_group_roster_update = 25,
    core_event_unit_spellcast = 26,
    core_event_other = 27,
    onboarding_ticker = 28,
    keystone_buttons_poll = 29,
    release_gate_popup_onupdate = 30,
    dock_button_cooldown_onupdate = 31,
    dock_event_dispatch = 32,
    dock_event_spell_update_cooldown = 33,
    dock_event_spells_changed = 34,
    dock_event_zone = 35,
    dock_event_player_entering_world = 36,
    dock_event_other = 37,
    callback_class_unit_event = 38,
    callback_class_delayed_timer = 39,
    callback_class_ui_hook = 40,
    dock_rebuild = 41,
    dock_update_button_states = 42,
    dock_update_button_state = 43,
    dock_refresh_cooldown_ordering = 44,
    dock_label_settle_rebuild = 45,
    dock_refresh_visibility = 46,
    dock_frame_onshow = 47,
    dock_frame_onhide = 48,
    keystone_event_dispatch = 49,
    death_alerts_preview_tick = 50,
    death_alerts_drag_tick = 51,
}

local PA_PERF_STATE_ORDER = {
    closed = 1,
    settings = 2,
    unlock_global = 3,
    settings_unlock_global = 4,
    ["unlock_surface:dock"] = 5,
    ["settings_unlock_surface:dock"] = 6,
    ["unlock_surface:timers"] = 7,
    ["settings_unlock_surface:timers"] = 8,
    ["unlock_surface:interrupt"] = 9,
    ["settings_unlock_surface:interrupt"] = 10,
    ["unlock_surface:deathalerts"] = 11,
    ["settings_unlock_surface:deathalerts"] = 12,
}

local function PA_PerfGetRecordBucket(stats, stateLabel, scopeName)
    local stateStats = stats[stateLabel]
    if not stateStats then
        stateStats = {}
        stats[stateLabel] = stateStats
    end

    local bucket = stateStats[scopeName]
    if not bucket then
        bucket = {
            calls = 0,
            totalMs = 0,
            maxMs = 0,
        }
        stateStats[scopeName] = bucket
    end

    return bucket
end

local function PA_PerfStateRank(label)
    local direct = PA_PERF_STATE_ORDER[label]
    if direct then
        return direct
    end
    if type(label) ~= "string" then
        return 5000
    end
    if string.find(label, "^unlock_surface:") then
        return 1000
    end
    if string.find(label, "^settings_unlock_surface:") then
        return 1100
    end
    return 5000
end

local function PA_PerfScopeRank(scopeName)
    return PA_PERF_SCOPE_ORDER[scopeName] or 5000
end

function PortalAuthority:PerfIsEnabled()
    return self and self._perf and self._perf.enabled == true
end

function PortalAuthority:PerfReset()
    self._perf = self._perf or {}
    self._perf.stats = {}
    if debugprofilestart then
        pcall(debugprofilestart)
    end
end

function PortalAuthority:PerfGetUnlockedSurfaceNames()
    local db = PortalAuthorityDB or self.defaults or {}
    local surfaces = {}

    if db.dockLocked == false then
        surfaces[#surfaces + 1] = "dock"
    end
    if db.deathAlertLocked == false then
        surfaces[#surfaces + 1] = "deathalerts"
    end

    local modulesDb = db.modules or {}
    local timersDb = modulesDb.timers or {}
    if timersDb.locked == false then
        surfaces[#surfaces + 1] = "timers"
    end

    local interruptDb = modulesDb.interruptTracker or {}
    if interruptDb.locked == false then
        surfaces[#surfaces + 1] = "interrupt"
    end

    table.sort(surfaces)
    return surfaces
end

function PortalAuthority:PerfIsSettingsVisible()
    return self:IsAnySettingsHostVisible()
end

function PortalAuthority:PerfGetStateLabel(explicitState)
    if type(explicitState) == "string" and explicitState ~= "" then
        return explicitState
    end

    local prefix = self:PerfIsSettingsVisible() and "settings_" or ""
    local surfaces = self:PerfGetUnlockedSurfaceNames()
    local count = #surfaces

    if count <= 0 then
        if prefix ~= "" then
            return "settings"
        end
        return "closed"
    end

    if count >= 4 then
        return prefix .. "unlock_global"
    end

    return prefix .. "unlock_surface:" .. table.concat(surfaces, "+")
end

function PortalAuthority:PerfBegin(scopeName, explicitState)
    if not self:PerfIsEnabled() or type(scopeName) ~= "string" or scopeName == "" or not debugprofilestop then
        return nil, nil
    end
    return debugprofilestop(), self:PerfGetStateLabel(explicitState)
end

function PortalAuthority:PerfEnd(scopeName, startedAt, stateLabel)
    if not self:PerfIsEnabled() or startedAt == nil or type(scopeName) ~= "string" or scopeName == "" or not debugprofilestop then
        return
    end

    local elapsedMs = debugprofilestop() - startedAt
    if elapsedMs < 0 then
        elapsedMs = 0
    end

    local perf = self._perf or {}
    perf.stats = perf.stats or {}
    self._perf = perf

    stateLabel = self:PerfGetStateLabel(stateLabel)
    local bucket = PA_PerfGetRecordBucket(perf.stats, stateLabel, scopeName)
    bucket.calls = bucket.calls + 1
    bucket.totalMs = bucket.totalMs + elapsedMs
    if elapsedMs > bucket.maxMs then
        bucket.maxMs = elapsedMs
    end
end

local function PA_CpuDiagNormalizeVisibilityMode(mode)
    local normalized = tostring(mode or "NORMAL"):upper()
    if normalized == "HIDE" then
        return "HIDE"
    end
    return "NORMAL"
end

local function PA_CpuDiagBoolText(value)
    return value and "true" or "false"
end

local PA_CPUDIAG_CORE_DISPATCH_EVENTS = {
    "ADDON_LOADED",
    "PLAYER_LOGIN",
    "PLAYER_LOGOUT",
    "PLAYER_DEAD",
    "UNIT_SPELLCAST_START",
    "UNIT_SPELLCAST_SUCCEEDED",
    "CHALLENGE_MODE_START",
    "CHAT_MSG_WHISPER",
    "CHAT_MSG_BN_WHISPER",
    "CHAT_MSG_INSTANCE_CHAT",
    "CHAT_MSG_INSTANCE_CHAT_LEADER",
    "CHAT_MSG_RAID",
    "CHAT_MSG_RAID_LEADER",
    "CHAT_MSG_PARTY",
    "CHAT_MSG_PARTY_LEADER",
    "UNIT_DIED",
    "GROUP_ROSTER_UPDATE",
    "PLAYER_REGEN_DISABLED",
    "PLAYER_REGEN_ENABLED",
}

local PA_CPUDIAG_MODULES_DISPATCH_EVENTS = {
    "PLAYER_ENTERING_WORLD",
    "ZONE_CHANGED_NEW_AREA",
    "GROUP_ROSTER_UPDATE",
    "CHALLENGE_MODE_START",
    "CHALLENGE_MODE_COMPLETED",
    "ENCOUNTER_START",
    "ENCOUNTER_END",
    "UNIT_SPELLCAST_SUCCEEDED",
    "CHAT_MSG_ADDON",
    "CHAT_MSG_ADDON_LOGGED",
    "UNIT_AURA",
    "UNIT_POWER_UPDATE",
    "PLAYER_DEAD",
    "PLAYER_ALIVE",
    "PLAYER_UNGHOST",
    "PLAYER_ROLES_ASSIGNED",
    "PLAYER_SPECIALIZATION_CHANGED",
    "UNIT_PET",
    "INSPECT_READY",
    "SPELLS_CHANGED",
    "ROLE_CHANGED_INFORM",
    "UNIT_DIED",
}

local PA_CPUDIAG_DOCK_DISPATCH_EVENTS = {
    "PLAYER_UPDATE_RESTING",
    "ZONE_CHANGED",
    "ZONE_CHANGED_INDOORS",
    "ZONE_CHANGED_NEW_AREA",
    "PLAYER_REGEN_ENABLED",
    "PLAYER_REGEN_DISABLED",
    "SPELL_UPDATE_COOLDOWN",
    "SPELLS_CHANGED",
    "PLAYER_ENTERING_WORLD",
    "ADDON_LOADED",
}

local PA_CPUDIAG_KEYSTONE_DISPATCH_EVENTS = {
    "CHALLENGE_MODE_KEYSTONE_RECEPTABLE_OPEN",
    "START_TIMER",
}

local PA_CPUDIAG_UNIT_CALLBACK_EVENTS = {
    "UNIT_SPELLCAST_SUCCEEDED",
    "UNIT_SPELLCAST_INTERRUPTED",
    "NAME_PLATE_UNIT_ADDED",
    "NAME_PLATE_UNIT_REMOVED",
}

local PA_CPUDIAG_DELAYED_TIMER_KEYS = {
    "interrupt_inspect_delay",
    "interrupt_inspect_step",
    "interrupt_init_hello",
    "interrupt_pew_queue",
    "interrupt_pew_hello",
    "interrupt_unitpet_retry_1",
    "interrupt_unitpet_retry_2",
    "interrupt_unitpet_retry_3",
    "interrupt_warlock_retry_1",
    "interrupt_warlock_retry_2",
    "onboarding_postshow_layout",
    "onboarding_retry",
    "keystone_buttons_refresh",
    "keystone_slot_retry",
    "keystone_autostart_arm_clear",
    "keystone_autostart_fallback",
    "keystone_autostart_startkey",
}

local PA_CPUDIAG_UI_HOOK_KEYS = {
    "dock_gizmo_frame_onshow",
    "dock_gizmo_frame_onhide",
    "dock_showuipanel",
    "dock_hideuipanel",
    "keystone_frame_onshow",
    "keystone_frame_onhide",
    "keystone_slot_onclick",
    "keystone_slot_onreceivedrag",
    "keystone_slot_onmouseup",
    "keystone_tooltip_postcall",
    "keystone_tooltip_gametooltip",
    "keystone_tooltip_itemref",
    "keystone_setitemref_after",
}

local PA_CPUDIAG_TRIGGER_KEYS = {
    "enter_world",
    "zone_new_area",
    "zone_local",
    "group_roster",
    "combat_enter",
    "combat_leave",
    "resting_update",
    "addon_chat",
    "spec_change",
    "challenge_start",
    "challenge_complete",
    "settings_open",
    "settings_closed",
}

local PA_CPUDIAG_TRIGGER_RECENT_CAPACITY = 12
local PA_CPUDIAG_LARGE_HEAP_DELTA_KB = 64
local PA_CPUDIAG_IDLE_WITNESS_CAPACITY = 256
local PA_CPUDIAG_IDLE_WITNESS_INTERVAL_SECONDS = 2.0
local PA_CPUDIAG_IDLE_WITNESS_HEARTBEAT_SECONDS = 60

local PA_CPUDIAG_IDLE_WITNESS_ENV_FIELDS = {
    "settings",
    "resting",
    "instance",
    "combat",
}

local PA_CPUDIAG_IDLE_WITNESS_UNLOCK_FIELDS = {
    "dockUnlocked",
    "timersUnlocked",
    "interruptUnlocked",
    "deathUnlocked",
}

local PA_CPUDIAG_IDLE_WITNESS_RUNTIME_FIELDS = {
    "dockShown",
    "dockOnUpdateArmed",
    "moveHintTicker",
    "onboardingTicker",
    "deathShown",
    "deathPreviewTicker",
    "deathDragTicker",
    "timersShown",
    "timersTicker",
    "interruptShown",
    "interruptTicker",
    "interruptInspectTicker",
    "keystoneHelperShown",
    "keystonePollArmed",
}

local PA_CPUDIAG_IDLE_WITNESS_DOCK_SURFACE_FIELDS = {
    "cooldownActive",
    "cooldownOnUpdate",
    "cooldownTextShown",
    "iconMove",
    "labelMove",
    "labelSettle",
    "labelAnimActive",
    "settleRunning",
}

local PA_CPUDIAG_IDLE_WITNESS_DELTA_SPECS = {
    { entryKey = "coreDispatchDelta", snapshotKey = "coreDispatchTotal" },
    { entryKey = "modulesDispatchDelta", snapshotKey = "modulesDispatchTotal" },
    { entryKey = "dockDispatchDelta", snapshotKey = "dockDispatchTotal" },
    { entryKey = "keystoneDispatchDelta", snapshotKey = "keystoneDispatchTotal" },
    { entryKey = "unitCallbacksDelta", snapshotKey = "unitCallbacksTotal" },
    { entryKey = "uiHooksDelta", snapshotKey = "uiHooksTotal" },
    { entryKey = "delayedTimersDelta", snapshotKey = "delayedTimersTotal" },
    { entryKey = "dockOnUpdateDelta", snapshotKey = "dockOnUpdateTotal" },
    { entryKey = "dockButtonCooldownDelta", snapshotKey = "dockButtonCooldownTotal" },
    { entryKey = "moveHintTickDelta", snapshotKey = "moveHintTickTotal" },
    { entryKey = "onboardingTickDelta", snapshotKey = "onboardingTickTotal" },
    { entryKey = "deathPreviewTickDelta", snapshotKey = "deathPreviewTickTotal" },
    { entryKey = "deathDragTickDelta", snapshotKey = "deathDragTickTotal" },
    { entryKey = "timersEvaluateDelta", snapshotKey = "timersEvaluateTotal" },
    { entryKey = "interruptEvaluateDelta", snapshotKey = "interruptEvaluateTotal" },
    { entryKey = "interruptUpdateDelta", snapshotKey = "interruptUpdateTotal" },
    { entryKey = "interruptInspectDelta", snapshotKey = "interruptInspectTotal" },
    { entryKey = "moduleChatDelta", snapshotKey = "moduleChatTotal" },
    { entryKey = "coreGroupRosterDelta", snapshotKey = "coreGroupRosterTotal" },
    { entryKey = "coreChatDelta", snapshotKey = "coreChatTotal" },
    { entryKey = "coreSpellcastDelta", snapshotKey = "coreSpellcastTotal" },
}

local function PA_CpuDiagNewFixedCounter(keys)
    local counter = { total = 0 }
    for i = 1, #keys do
        counter[keys[i]] = 0
    end
    return counter
end

local function PA_CpuDiagResetFixedCounter(counter, keys)
    counter.total = 0
    for i = 1, #keys do
        counter[keys[i]] = 0
    end
end

local function PA_CpuDiagNewRingBuffer(capacity)
    return {
        entries = {},
        size = 0,
        nextIndex = 1,
        capacity = tonumber(capacity) or PA_CPUDIAG_TRIGGER_RECENT_CAPACITY,
    }
end

local function PA_CpuDiagResetRingBuffer(buffer)
    if type(buffer) ~= "table" then
        return
    end
    buffer.entries = {}
    buffer.size = 0
    buffer.nextIndex = 1
    buffer.capacity = tonumber(buffer.capacity) or PA_CPUDIAG_TRIGGER_RECENT_CAPACITY
end

local function PA_CpuDiagPushRingBuffer(buffer, entry)
    if type(buffer) ~= "table" then
        return
    end

    local capacity = tonumber(buffer.capacity) or PA_CPUDIAG_TRIGGER_RECENT_CAPACITY
    buffer.capacity = capacity
    local nextIndex = tonumber(buffer.nextIndex) or 1
    if nextIndex < 1 or nextIndex > capacity then
        nextIndex = 1
    end

    buffer.entries[nextIndex] = entry
    nextIndex = nextIndex + 1
    if nextIndex > capacity then
        nextIndex = 1
    end
    buffer.nextIndex = nextIndex
    buffer.size = math.min(capacity, (tonumber(buffer.size) or 0) + 1)
end

local function PA_CpuDiagGetRingBufferEntriesNewestFirst(buffer)
    local entries = {}
    if type(buffer) ~= "table" then
        return entries
    end

    local size = tonumber(buffer.size) or 0
    local capacity = tonumber(buffer.capacity) or PA_CPUDIAG_TRIGGER_RECENT_CAPACITY
    if size <= 0 or type(buffer.entries) ~= "table" then
        return entries
    end

    local index = (tonumber(buffer.nextIndex) or 1) - 1
    if index < 1 then
        index = capacity
    end

    for _ = 1, math.min(size, capacity) do
        local entry = buffer.entries[index]
        if entry ~= nil then
            entries[#entries + 1] = entry
        end
        index = index - 1
        if index < 1 then
            index = capacity
        end
    end

    return entries
end

local function PA_CpuDiagGetRingBufferNewestEntry(buffer)
    if type(buffer) ~= "table" then
        return nil
    end
    if (tonumber(buffer.size) or 0) <= 0 or type(buffer.entries) ~= "table" then
        return nil
    end

    local capacity = tonumber(buffer.capacity) or PA_CPUDIAG_TRIGGER_RECENT_CAPACITY
    local index = (tonumber(buffer.nextIndex) or 1) - 1
    if index < 1 then
        index = capacity
    end
    return buffer.entries[index]
end

local function PA_CpuDiagSafeTime()
    if type(time) == "function" then
        local ok, value = pcall(time)
        if ok then
            return tonumber(value) or 0
        end
    end
    return 0
end

local function PA_CpuDiagGetCharacterStore()
    if type(PortalAuthorityCharacterDB) ~= "table" then
        PortalAuthorityCharacterDB = {}
    end
    return PortalAuthorityCharacterDB
end

local function PA_CpuDiagGetIdleWitnessStoreReadOnly()
    if PA_IsStaticBaselineGateEnabled() then
        return nil
    end
    local charStore = type(PortalAuthorityCharacterDB) == "table" and PortalAuthorityCharacterDB or nil
    local store = charStore and charStore.diagWitnessV1 or nil
    if type(store) ~= "table" or type(store.entries) ~= "table" then
        return nil
    end
    return store
end

local function PA_CpuDiagEnsureIdleWitnessStore()
    if PA_IsStaticBaselineGateEnabled() then
        return nil
    end
    local charStore = PA_CpuDiagGetCharacterStore()
    local store = type(charStore.diagWitnessV1) == "table" and charStore.diagWitnessV1 or nil
    if type(store) ~= "table" then
        store = {}
        charStore.diagWitnessV1 = store
    end

    store.version = 1
    store.capacity = tonumber(store.capacity) or PA_CPUDIAG_IDLE_WITNESS_CAPACITY
    if store.capacity < 1 then
        store.capacity = PA_CPUDIAG_IDLE_WITNESS_CAPACITY
    end
    store.size = math.max(0, math.min(store.capacity, tonumber(store.size) or 0))
    store.head = math.max(0, tonumber(store.head) or 0)
    if store.head > store.capacity then
        store.head = 0
    end
    store.sessionId = math.max(0, tonumber(store.sessionId) or 0)
    store.sessionStartedAt = tonumber(store.sessionStartedAt) or 0
    store.sessionStartedUptime = tonumber(store.sessionStartedUptime) or 0
    store.lastHeartbeatAt = tonumber(store.lastHeartbeatAt) or 0
    if type(store.entries) ~= "table" then
        store.entries = {}
    end
    if type(store.sessionMeta) ~= "table" then
        store.sessionMeta = {}
    end
    return store
end

local function PA_CpuDiagGetIdleWitnessSessionMeta(store, sessionId)
    if type(store) ~= "table" or type(store.sessionMeta) ~= "table" then
        return nil
    end
    sessionId = tonumber(sessionId) or 0
    if sessionId <= 0 then
        return nil
    end
    local meta = store.sessionMeta[sessionId]
    if type(meta) ~= "table" then
        return nil
    end
    return meta
end

local function PA_CpuDiagSetIdleWitnessSessionMeta(store, sessionId, meta)
    if type(store) ~= "table" or type(meta) ~= "table" then
        return
    end
    sessionId = tonumber(sessionId) or 0
    if sessionId <= 0 then
        return
    end
    if type(store.sessionMeta) ~= "table" then
        store.sessionMeta = {}
    end
    local existing = type(store.sessionMeta[sessionId]) == "table" and store.sessionMeta[sessionId] or {}
    if meta.uiSurfaceGate ~= nil then
        existing.uiSurfaceGate = meta.uiSurfaceGate == true
    end
    if meta.settingsBaselineGate ~= nil then
        existing.settingsBaselineGate = meta.settingsBaselineGate == true
    end
    if meta.settingsEagerBuildGate ~= nil then
        existing.settingsEagerBuildGate = meta.settingsEagerBuildGate == true
    end
    if meta.settingsDirectBuildGate ~= nil then
        existing.settingsDirectBuildGate = meta.settingsDirectBuildGate == true
    end
    store.sessionMeta[sessionId] = existing
end

local function PA_CpuDiagIdleWitnessPushEntry(store, entry)
    if type(store) ~= "table" or type(entry) ~= "table" then
        return
    end

    local capacity = tonumber(store.capacity) or PA_CPUDIAG_IDLE_WITNESS_CAPACITY
    if capacity < 1 then
        capacity = PA_CPUDIAG_IDLE_WITNESS_CAPACITY
        store.capacity = capacity
    end

    local head = tonumber(store.head) or 0
    head = head + 1
    if head > capacity or head < 1 then
        head = 1
    end

    store.entries[head] = entry
    store.head = head
    store.size = math.min(capacity, math.max(0, tonumber(store.size) or 0) + 1)
end

local function PA_CpuDiagIdleWitnessGetEntriesNewestFirst(store)
    local entries = {}
    if type(store) ~= "table" or type(store.entries) ~= "table" then
        return entries
    end

    local size = tonumber(store.size) or 0
    local capacity = tonumber(store.capacity) or PA_CPUDIAG_IDLE_WITNESS_CAPACITY
    local head = tonumber(store.head) or 0
    if head > capacity then
        head = 0
    end
    if size <= 0 or head <= 0 then
        return entries
    end

    local index = head
    for _ = 1, math.min(size, capacity) do
        local entry = store.entries[index]
        if entry ~= nil then
            entries[#entries + 1] = entry
        end
        index = index - 1
        if index < 1 then
            index = capacity
        end
    end

    return entries
end

local function PA_CpuDiagIdleWitnessGetLatestEntryForSession(store, sessionId)
    if type(sessionId) ~= "number" or sessionId <= 0 then
        return nil
    end

    local entries = PA_CpuDiagIdleWitnessGetEntriesNewestFirst(store)
    for i = 1, #entries do
        local entry = entries[i]
        if tonumber(entry and entry.sessionId) == sessionId then
            return entry
        end
    end
    return nil
end

local function PA_CpuDiagAddUniqueReason(reasons, token)
    if type(reasons) ~= "table" or type(token) ~= "string" or token == "" then
        return
    end
    for i = 1, #reasons do
        if reasons[i] == token then
            return
        end
    end
    reasons[#reasons + 1] = token
end

local function PA_CpuDiagSnapshotFieldChanged(previous, current, fields)
    for i = 1, #fields do
        local key = fields[i]
        if previous[key] ~= current[key] then
            return true
        end
    end
    return false
end

local function PA_CpuDiagPositiveDelta(currentValue, previousValue)
    local currentNumber = tonumber(currentValue) or 0
    local previousNumber = tonumber(previousValue) or 0
    if currentNumber <= previousNumber then
        return 0
    end
    return currentNumber - previousNumber
end

local function PA_CpuDiagReadLuaHeapKB()
    if type(collectgarbage) == "function" then
        local ok, value = pcall(collectgarbage, "count")
        if ok then
            return tonumber(value)
        end
    end
    if type(gcinfo) == "function" then
        local ok, value = pcall(gcinfo)
        if ok then
            return tonumber(value)
        end
    end
    return nil
end

local function PA_CpuDiagFormatKB(value)
    if type(value) ~= "number" then
        return "unknown"
    end
    return string.format("%.1f", value)
end

local function PA_CpuDiagFormatSignedKB(value)
    if type(value) ~= "number" then
        return "unknown"
    end
    return string.format("%+.1f", value)
end

local function PA_CpuDiagFormatPct(value)
    if type(value) ~= "number" then
        return "unknown"
    end
    return string.format("%.1f", value)
end

local function PA_CpuDiagGetAddOnCount()
    if type(GetNumAddOns) == "function" then
        local ok, value = pcall(GetNumAddOns)
        if ok then
            return tonumber(value)
        end
    end
    if C_AddOns and type(C_AddOns.GetNumAddOns) == "function" then
        local ok, value = pcall(C_AddOns.GetNumAddOns)
        if ok then
            return tonumber(value)
        end
    end
    return nil
end

local function PA_CpuDiagGetAddOnIdentity(index)
    if type(GetAddOnInfo) == "function" then
        local ok, name, title = pcall(GetAddOnInfo, index)
        if ok and type(name) == "string" and name ~= "" then
            if type(title) ~= "string" or title == "" then
                title = name
            end
            return name, title
        end
    end
    if C_AddOns and type(C_AddOns.GetAddOnInfo) == "function" then
        local ok, info = pcall(C_AddOns.GetAddOnInfo, index)
        if ok and type(info) == "table" then
            local name = info.name or info.Name
            local title = info.title or info.Title or info.displayName or info.DisplayName
            if type(name) == "string" and name ~= "" then
                if type(title) ~= "string" or title == "" then
                    title = name
                end
                return name, title
            end
        end
    end
    return nil, nil
end

local function PA_CpuDiagGetAddOnMemoryUsage(index, key)
    if type(GetAddOnMemoryUsage) == "function" then
        local ok, value = pcall(GetAddOnMemoryUsage, index)
        if ok and tonumber(value) ~= nil then
            return tonumber(value)
        end
        if type(key) == "string" and key ~= "" then
            ok, value = pcall(GetAddOnMemoryUsage, key)
            if ok and tonumber(value) ~= nil then
                return tonumber(value)
            end
        end
    end
    if C_AddOns and type(C_AddOns.GetAddOnMemoryUsage) == "function" then
        local ok, value = pcall(C_AddOns.GetAddOnMemoryUsage, index)
        if ok and tonumber(value) ~= nil then
            return tonumber(value)
        end
        if type(key) == "string" and key ~= "" then
            ok, value = pcall(C_AddOns.GetAddOnMemoryUsage, key)
            if ok and tonumber(value) ~= nil then
                return tonumber(value)
            end
        end
    end
    return nil
end

local function PA_CpuDiagReadAddonMemorySnapshot()
    if type(UpdateAddOnMemoryUsage) ~= "function" then
        return nil
    end

    local addOnCount = PA_CpuDiagGetAddOnCount()
    if type(addOnCount) ~= "number" or addOnCount < 0 then
        return nil
    end

    local okUpdate = pcall(UpdateAddOnMemoryUsage)
    if not okUpdate then
        return nil
    end

    local entries = {}
    local entriesByKey = {}
    local totalKB = 0

    for index = 1, addOnCount do
        local key, displayName = PA_CpuDiagGetAddOnIdentity(index)
        if type(key) ~= "string" or key == "" then
            return nil
        end

        local currentKB = PA_CpuDiagGetAddOnMemoryUsage(index, key)
        if type(currentKB) ~= "number" then
            return nil
        end

        local entry = {
            key = key,
            displayName = displayName or key,
            currentKB = currentKB,
        }
        entries[#entries + 1] = entry
        entriesByKey[key] = entry
        totalKB = totalKB + currentKB
    end

    return {
        entries = entries,
        entriesByKey = entriesByKey,
        totalKB = totalKB,
    }
end

local function PA_CpuDiagSeedAddonMemoryBaseline(state, snapshot)
    local baseline = state.addonMemory or {}
    baseline.seeded = false
    baseline.byKey = {}
    baseline.totalKB = nil
    baseline.paKB = nil

    if type(snapshot) ~= "table" or type(snapshot.entries) ~= "table" then
        state.addonMemory = baseline
        return false
    end

    baseline.seeded = true
    baseline.totalKB = tonumber(snapshot.totalKB)
    for i = 1, #snapshot.entries do
        local entry = snapshot.entries[i]
        if entry and type(entry.key) == "string" and entry.key ~= "" then
            baseline.byKey[entry.key] = tonumber(entry.currentKB) or 0
        end
    end
    baseline.paKB = baseline.byKey[ADDON_NAME]
    state.addonMemory = baseline
    return true
end

function PortalAuthority:CpuDiagEnsureState()
    if self._cpuDiag then
        return self._cpuDiag
    end

    local baselineLuaKB = PA_CpuDiagReadLuaHeapKB()
    self._cpuDiag = {
        startedAt = GetTime() or 0,
        suspendCounting = false,
        timers = {
            visibilityMode = "NORMAL",
            naturalVisible = nil,
            effectiveVisible = nil,
            frameShown = nil,
            evaluateVisibilityCalls = 0,
            tickCalls = 0,
        },
        interrupt = {
            visibilityMode = "NORMAL",
            naturalVisible = nil,
            effectiveVisible = nil,
            frameShown = nil,
            evaluateVisibilityCalls = 0,
            updateDisplayCalls = 0,
            periodicInspectCalls = 0,
        },
        moduleEvents = {
            unitAura = 0,
            unitPowerUpdate = 0,
            chatMsgAddon = 0,
            other = 0,
        },
        coreEvents = {
            chat = 0,
            groupRoster = 0,
            spellcast = 0,
            other = 0,
        },
        coreDispatch = PA_CpuDiagNewFixedCounter(PA_CPUDIAG_CORE_DISPATCH_EVENTS),
        modulesDispatch = PA_CpuDiagNewFixedCounter(PA_CPUDIAG_MODULES_DISPATCH_EVENTS),
        dockDispatch = PA_CpuDiagNewFixedCounter(PA_CPUDIAG_DOCK_DISPATCH_EVENTS),
        keystoneDispatch = PA_CpuDiagNewFixedCounter(PA_CPUDIAG_KEYSTONE_DISPATCH_EVENTS),
        unitCallbacks = PA_CpuDiagNewFixedCounter(PA_CPUDIAG_UNIT_CALLBACK_EVENTS),
        delayedTimers = PA_CpuDiagNewFixedCounter(PA_CPUDIAG_DELAYED_TIMER_KEYS),
        uiHooks = PA_CpuDiagNewFixedCounter(PA_CPUDIAG_UI_HOOK_KEYS),
        triggerCounts = PA_CpuDiagNewFixedCounter(PA_CPUDIAG_TRIGGER_KEYS),
        triggerRecent = PA_CpuDiagNewRingBuffer(PA_CPUDIAG_TRIGGER_RECENT_CAPACITY),
        memory = {
            startLuaKB = baselineLuaKB,
            lastTrackedLuaKB = baselineLuaKB,
            trackedMinKB = baselineLuaKB,
            trackedMaxKB = baselineLuaKB,
            trackedSamples = 0,
            largeRiseEvents = 0,
            gcSuspectDrops = 0,
            largestRiseKB = 0,
            largestDropKB = 0,
        },
        addonMemory = {
            seeded = false,
            byKey = {},
            totalKB = nil,
            paKB = nil,
        },
        dockRuntime = {
            onUpdateTickCalls = 0,
            buttonCooldownTickCalls = 0,
        },
        keystone = {
            pollCalls = 0,
        },
        moveHint = {
            tickCalls = 0,
        },
        onboarding = {
            tickCalls = 0,
        },
        deathAlerts = {
            previewTickCalls = 0,
            dragTickCalls = 0,
        },
        releaseGate = {
            onUpdateCalls = 0,
        },
    }
    return self._cpuDiag
end

function PortalAuthority:CpuDiagRecordDispatcherEvent(dispatcherName, eventName)
    local state = self:CpuDiagEnsureState()
    if state.suspendCounting then
        return
    end

    local counter = nil
    if dispatcherName == "core" then
        counter = state.coreDispatch
    elseif dispatcherName == "modules" then
        counter = state.modulesDispatch
    elseif dispatcherName == "dock" then
        counter = state.dockDispatch
    elseif dispatcherName == "keystone" then
        counter = state.keystoneDispatch
    end

    if not counter then
        return
    end

    counter.total = (tonumber(counter.total) or 0) + 1
    if type(eventName) == "string" and counter[eventName] ~= nil then
        counter[eventName] = (tonumber(counter[eventName]) or 0) + 1
    end
end

function PortalAuthority:CpuDiagRecordUnitCallback(eventName)
    local state = self:CpuDiagEnsureState()
    if state.suspendCounting then
        return
    end

    local counter = state.unitCallbacks
    counter.total = (tonumber(counter.total) or 0) + 1
    if type(eventName) == "string" and counter[eventName] ~= nil then
        counter[eventName] = (tonumber(counter[eventName]) or 0) + 1
    end
end

function PortalAuthority:CpuDiagSuspendCounting(callback)
    local state = self:CpuDiagEnsureState()
    local prior = state.suspendCounting and true or false
    state.suspendCounting = true
    local ok, resultA, resultB, resultC = pcall(callback)
    state.suspendCounting = prior
    if not ok then
        error(resultA)
    end
    return resultA, resultB, resultC
end

function PortalAuthority:CpuDiagGetEntry(target)
    local state = self:CpuDiagEnsureState()
    if target == "timers" then
        return state.timers
    end
    if target == "interrupt" then
        return state.interrupt
    end
    return nil
end

function PortalAuthority:GetCpuDiagVisibilityMode(target)
    local entry = self:CpuDiagGetEntry(target)
    if not entry then
        return "NORMAL"
    end
    entry.visibilityMode = PA_CpuDiagNormalizeVisibilityMode(entry.visibilityMode)
    return entry.visibilityMode
end

function PortalAuthority:CpuDiagResolveVisibility(target, naturalVisible)
    local effectiveVisible = not not naturalVisible
    if effectiveVisible and self:GetCpuDiagVisibilityMode(target) == "HIDE" then
        effectiveVisible = false
    end
    return effectiveVisible
end

function PortalAuthority:CpuDiagRecordLiveVisibility(target, frame, naturalVisible, effectiveVisible)
    local entry = self:CpuDiagGetEntry(target)
    if not entry then
        return
    end

    entry.naturalVisible = not not naturalVisible
    entry.effectiveVisible = not not effectiveVisible
    if frame and frame.IsShown then
        entry.frameShown = frame:IsShown() and true or false
    else
        entry.frameShown = false
    end
end

function PortalAuthority:CpuDiagIsNaturallyVisible(target)
    local entry = self:CpuDiagGetEntry(target)
    return entry and entry.naturalVisible == true or false
end

function PortalAuthority:CpuDiagApplyVisibility(target, frame, naturalVisible)
    local effectiveVisible = self:CpuDiagResolveVisibility(target, naturalVisible)
    if frame then
        if effectiveVisible then
            frame:Show()
        else
            frame:Hide()
        end
    end
    self:CpuDiagRecordLiveVisibility(target, frame, naturalVisible, effectiveVisible)
    return effectiveVisible
end

function PortalAuthority:CpuDiagCount(scopeName, detailKey)
    local state = self:CpuDiagEnsureState()
    if state.suspendCounting then
        return
    end

    if scopeName == "timers_evaluate_visibility" then
        state.timers.evaluateVisibilityCalls = state.timers.evaluateVisibilityCalls + 1
        return
    end
    if scopeName == "timers_tick" then
        state.timers.tickCalls = state.timers.tickCalls + 1
        return
    end
    if scopeName == "interrupt_evaluate_visibility" then
        state.interrupt.evaluateVisibilityCalls = state.interrupt.evaluateVisibilityCalls + 1
        return
    end
    if scopeName == "interrupt_update_display" then
        state.interrupt.updateDisplayCalls = state.interrupt.updateDisplayCalls + 1
        return
    end
    if scopeName == "interrupt_periodic_inspect" then
        state.interrupt.periodicInspectCalls = state.interrupt.periodicInspectCalls + 1
        return
    end
    if scopeName == "movehint_ticker" then
        state.moveHint.tickCalls = state.moveHint.tickCalls + 1
        return
    end
    if scopeName == "onboarding_ticker" then
        state.onboarding.tickCalls = state.onboarding.tickCalls + 1
        return
    end
    if scopeName == "keystone_buttons_poll" then
        state.keystone.pollCalls = state.keystone.pollCalls + 1
        return
    end
    if scopeName == "dock_onupdate" then
        state.dockRuntime.onUpdateTickCalls = (tonumber(state.dockRuntime.onUpdateTickCalls) or 0) + 1
        return
    end
    if scopeName == "dock_button_cooldown_onupdate" then
        state.dockRuntime.buttonCooldownTickCalls = (tonumber(state.dockRuntime.buttonCooldownTickCalls) or 0) + 1
        return
    end
    if scopeName == "callback_class_ui_hook" then
        if type(detailKey) == "string" and state.uiHooks[detailKey] ~= nil then
            state.uiHooks.total = (tonumber(state.uiHooks.total) or 0) + 1
            state.uiHooks[detailKey] = (tonumber(state.uiHooks[detailKey]) or 0) + 1
        end
        return
    end
    if scopeName == "callback_class_delayed_timer" then
        state.delayedTimers.total = (tonumber(state.delayedTimers.total) or 0) + 1
        if type(detailKey) == "string" and state.delayedTimers[detailKey] ~= nil then
            state.delayedTimers[detailKey] = (tonumber(state.delayedTimers[detailKey]) or 0) + 1
        end
        return
    end
    if scopeName == "release_gate_popup_onupdate" then
        state.releaseGate.onUpdateCalls = state.releaseGate.onUpdateCalls + 1
        return
    end
    if scopeName == "death_alerts_preview_tick" then
        state.deathAlerts.previewTickCalls = state.deathAlerts.previewTickCalls + 1
        return
    end
    if scopeName == "death_alerts_drag_tick" then
        state.deathAlerts.dragTickCalls = state.deathAlerts.dragTickCalls + 1
    end
end

function PortalAuthority:CpuDiagRecordModuleEvent(eventScope)
    local state = self:CpuDiagEnsureState()
    if state.suspendCounting then
        return
    end

    if eventScope == "modules_event_unit_aura" then
        state.moduleEvents.unitAura = state.moduleEvents.unitAura + 1
        return
    end
    if eventScope == "modules_event_unit_power_update" then
        state.moduleEvents.unitPowerUpdate = state.moduleEvents.unitPowerUpdate + 1
        return
    end
    if eventScope == "modules_event_chat_msg_addon" then
        state.moduleEvents.chatMsgAddon = state.moduleEvents.chatMsgAddon + 1
        return
    end
    state.moduleEvents.other = state.moduleEvents.other + 1
end

function PortalAuthority:CpuDiagRecordCoreEvent(eventScope)
    local state = self:CpuDiagEnsureState()
    if state.suspendCounting then
        return
    end

    if eventScope == "core_event_chat" then
        state.coreEvents.chat = state.coreEvents.chat + 1
        return
    end
    if eventScope == "core_event_group_roster_update" then
        state.coreEvents.groupRoster = state.coreEvents.groupRoster + 1
        return
    end
    if eventScope == "core_event_unit_spellcast" then
        state.coreEvents.spellcast = state.coreEvents.spellcast + 1
        return
    end
    state.coreEvents.other = state.coreEvents.other + 1
end

function PortalAuthority:CpuDiagGetSettingsPanelFrame()
    return _G and (_G.SettingsPanel or _G.InterfaceOptionsFrame) or nil
end

function PortalAuthority:GetExistingSettingsWindowFrame()
    local frame = self and (self.settingsWindow or self._settingsWindow or self.SettingsWindow) or nil
    if frame and frame.IsObjectType and frame:IsObjectType("Frame") then
        return frame
    end

    frame = _G and _G.PortalAuthoritySettingsWindow or nil
    if frame and frame.IsObjectType and frame:IsObjectType("Frame") then
        return frame
    end

    return nil
end

function PortalAuthority:GetSettingsHostVisibilityState()
    local sawHost = false

    local customFrame = self:GetExistingSettingsWindowFrame()
    if customFrame and customFrame.IsShown then
        sawHost = true
        if customFrame:IsShown() then
            return true
        end
    end

    local settingsPanel = self:CpuDiagGetSettingsPanelFrame()
    if settingsPanel and settingsPanel.IsShown then
        sawHost = true
        if settingsPanel:IsShown() then
            return true
        end
    end

    if sawHost then
        return false
    end
    return nil
end

function PortalAuthority:IsAnySettingsHostVisible()
    return self:GetSettingsHostVisibilityState() == true
end

function PortalAuthority:BuildCpuDiagEnvSnapshot()
    local settingsVisible = self:GetSettingsHostVisibilityState()

    local lockState = "unknown"
    local db = PortalAuthorityDB
    if type(db) == "table"
        and db.dockLocked ~= nil
        and db.deathAlertLocked ~= nil
        and type(db.modules) == "table"
        and type(db.modules.timers) == "table"
        and db.modules.timers.locked ~= nil
        and type(db.modules.interruptTracker) == "table"
        and db.modules.interruptTracker.locked ~= nil
    then
        local unlockedSurfaces = self:PerfGetUnlockedSurfaceNames()
        if #unlockedSurfaces <= 0 then
            lockState = "closed"
        elseif #unlockedSurfaces >= 4 then
            lockState = "unlock_global"
        else
            lockState = "unlock_surface:" .. table.concat(unlockedSurfaces, "+")
        end
    end

    local resting = nil
    if type(IsResting) == "function" then
        resting = IsResting() and true or false
    end

    local inInstance = nil
    if type(IsInInstance) == "function" then
        local ok, value = pcall(IsInInstance)
        if ok then
            inInstance = value and true or false
        end
    end

    local inCombat = nil
    if type(InCombatLockdown) == "function" then
        inCombat = InCombatLockdown() and true or false
    end

    return {
        settingsVisible = settingsVisible,
        lockState = lockState,
        resting = resting,
        inInstance = inInstance,
        inCombat = inCombat,
    }
end

function PortalAuthority:BuildCpuDiagMemorySnapshot()
    local state = self:CpuDiagEnsureState()
    local memory = state.memory or {}
    local currentLuaKB = PA_CpuDiagReadLuaHeapKB()
    local deltaFromStartKB = nil
    if type(currentLuaKB) == "number" and type(memory.startLuaKB) == "number" then
        deltaFromStartKB = currentLuaKB - memory.startLuaKB
    end

    return {
        currentLuaKB = currentLuaKB,
        startLuaKB = memory.startLuaKB,
        deltaFromStartKB = deltaFromStartKB,
        trackedMinKB = memory.trackedMinKB,
        trackedMaxKB = memory.trackedMaxKB,
        trackedSamples = tonumber(memory.trackedSamples) or 0,
        largeRiseEvents = tonumber(memory.largeRiseEvents) or 0,
        gcSuspectDrops = tonumber(memory.gcSuspectDrops) or 0,
        largestRiseKB = tonumber(memory.largestRiseKB) or 0,
        largestDropKB = tonumber(memory.largestDropKB) or 0,
    }
end

function PortalAuthority:BuildCpuDiagAddonMemorySnapshot()
    local state = self:CpuDiagEnsureState()
    local baseline = state.addonMemory or {}
    if baseline.seeded ~= true then
        return {
            available = false,
            entries = {},
        }
    end

    local current = PA_CpuDiagReadAddonMemorySnapshot()
    if type(current) ~= "table"
        or type(current.entries) ~= "table"
        or type(current.entriesByKey) ~= "table"
        or type(current.totalKB) ~= "number"
    then
        return {
            available = false,
            entries = {},
        }
    end

    local baselineByKey = type(baseline.byKey) == "table" and baseline.byKey or {}
    local entries = {}
    local paEntry = nil

    for i = 1, #current.entries do
        local entry = current.entries[i]
        local key = entry and entry.key or nil
        local currentKB = entry and tonumber(entry.currentKB) or nil
        if type(key) ~= "string" or key == "" or type(currentKB) ~= "number" then
            return {
                available = false,
                entries = {},
            }
        end

        local baselineKB = tonumber(baselineByKey[key])
        local isNew = baselineKB == nil
        if baselineKB == nil then
            baselineKB = 0
        end

        local displayName = entry.displayName
        if type(displayName) ~= "string" or displayName == "" then
            displayName = key
        end

        local summaryEntry = {
            key = key,
            displayName = displayName,
            currentKB = currentKB,
            deltaKB = currentKB - baselineKB,
            newSinceReset = isNew,
        }
        entries[#entries + 1] = summaryEntry
        if key == ADDON_NAME then
            paEntry = summaryEntry
        end
    end

    table.sort(entries, function(left, right)
        local leftAbs = math.abs(tonumber(left.deltaKB) or 0)
        local rightAbs = math.abs(tonumber(right.deltaKB) or 0)
        if leftAbs ~= rightAbs then
            return leftAbs > rightAbs
        end

        local leftCurrent = tonumber(left.currentKB) or 0
        local rightCurrent = tonumber(right.currentKB) or 0
        if leftCurrent ~= rightCurrent then
            return leftCurrent > rightCurrent
        end

        local leftName = tostring(left.displayName or left.key or "")
        local rightName = tostring(right.displayName or right.key or "")
        return leftName < rightName
    end)

    local paRankByDelta = nil
    if paEntry then
        for i = 1, #entries do
            if entries[i].key == paEntry.key then
                paRankByDelta = i
                break
            end
        end
    end

    local totalAddonKB = tonumber(current.totalKB)
    local totalAddonDeltaKB = nil
    if type(totalAddonKB) == "number" and type(baseline.totalKB) == "number" then
        totalAddonDeltaKB = totalAddonKB - baseline.totalKB
    end

    local paKB = paEntry and tonumber(paEntry.currentKB) or nil
    local paDeltaKB = paEntry and tonumber(paEntry.deltaKB) or nil
    local paSharePct = nil
    if type(paKB) == "number" and type(totalAddonKB) == "number" and totalAddonKB > 0 then
        paSharePct = (paKB / totalAddonKB) * 100
    end

    return {
        available = true,
        entries = entries,
        paKB = paKB,
        paDeltaKB = paDeltaKB,
        totalAddonKB = totalAddonKB,
        totalAddonDeltaKB = totalAddonDeltaKB,
        paSharePct = paSharePct,
        paRankByDelta = paRankByDelta,
        newSinceReset = paEntry and paEntry.newSinceReset or nil,
    }
end

function PortalAuthority:CpuDiagCaptureTriggerSnapshot(triggerKey)
    local state = self:CpuDiagEnsureState()
    local now = GetTime() or 0
    local env = self:BuildCpuDiagEnvSnapshot()
    local luaKB = PA_CpuDiagReadLuaHeapKB()
    local lastTrackedLuaKB = state.memory and state.memory.lastTrackedLuaKB or nil
    local deltaKB = nil
    if type(luaKB) == "number" and type(lastTrackedLuaKB) == "number" then
        deltaKB = luaKB - lastTrackedLuaKB
    end

    return {
        elapsed = math.max(0, now - (state.startedAt or 0)),
        key = triggerKey,
        luaKB = luaKB,
        deltaKB = deltaKB,
        settings = env.settingsVisible,
        resting = env.resting,
        instance = env.inInstance,
        combat = env.inCombat,
    }
end

function PortalAuthority:CpuDiagRecordTrigger(triggerKey)
    local state = self:CpuDiagEnsureState()
    if state.suspendCounting then
        return
    end
    if type(triggerKey) ~= "string" or state.triggerCounts[triggerKey] == nil then
        return
    end

    local memory = state.memory or {}
    local snapshot = self:CpuDiagCaptureTriggerSnapshot(triggerKey)
    local luaKB = snapshot.luaKB
    local deltaKB = snapshot.deltaKB

    state.triggerCounts.total = (tonumber(state.triggerCounts.total) or 0) + 1
    state.triggerCounts[triggerKey] = (tonumber(state.triggerCounts[triggerKey]) or 0) + 1

    if type(luaKB) == "number" then
        memory.trackedSamples = (tonumber(memory.trackedSamples) or 0) + 1
        if memory.trackedMinKB == nil or luaKB < memory.trackedMinKB then
            memory.trackedMinKB = luaKB
        end
        if memory.trackedMaxKB == nil or luaKB > memory.trackedMaxKB then
            memory.trackedMaxKB = luaKB
        end
        if type(deltaKB) == "number" then
            if deltaKB >= PA_CPUDIAG_LARGE_HEAP_DELTA_KB then
                memory.largeRiseEvents = (tonumber(memory.largeRiseEvents) or 0) + 1
            end
            if deltaKB <= -PA_CPUDIAG_LARGE_HEAP_DELTA_KB then
                memory.gcSuspectDrops = (tonumber(memory.gcSuspectDrops) or 0) + 1
            end
            if deltaKB > (tonumber(memory.largestRiseKB) or 0) then
                memory.largestRiseKB = deltaKB
            end
            if deltaKB < (tonumber(memory.largestDropKB) or 0) then
                memory.largestDropKB = deltaKB
            end
        end
        memory.lastTrackedLuaKB = luaKB
    end

    PA_CpuDiagPushRingBuffer(state.triggerRecent, snapshot)
end

function PortalAuthority:CpuDiagEnsureSettingsHooks()
    if PA_IsSettingsBaselineGateEnabled() then
        return false
    end
    if self._cpuDiagSettingsHooksInstalled then
        return true
    end

    local settingsPanel = self:CpuDiagGetSettingsPanelFrame()
    if not settingsPanel or not settingsPanel.HookScript then
        return false
    end

    settingsPanel:HookScript("OnShow", function()
        if PortalAuthority and PortalAuthority.CpuDiagRecordTrigger then
            PortalAuthority:CpuDiagRecordTrigger("settings_open")
        end
    end)
    settingsPanel:HookScript("OnHide", function()
        if PortalAuthority and PortalAuthority.CpuDiagRecordTrigger then
            PortalAuthority:CpuDiagRecordTrigger("settings_closed")
        end
    end)
    self._cpuDiagSettingsHooksInstalled = true
    return true
end
function PortalAuthority:CpuDiagRefreshSubsystem(target)
    local modulesApi = self.Modules
    local registry = modulesApi and modulesApi.registry or nil
    if not registry then
        return
    end

    local module = nil
    if target == "timers" then
        module = registry.timers
    elseif target == "interrupt" then
        module = registry.interruptTracker
    end

    if module and module.EvaluateVisibility then
        pcall(module.EvaluateVisibility, module, "cpudiag-visibility-change")
    end
end

function PortalAuthority:CpuDiagRefreshAllSubsystems()
    self:CpuDiagRefreshSubsystem("timers")
    self:CpuDiagRefreshSubsystem("interrupt")
end

function PortalAuthority:SetCpuDiagVisibilityMode(target, mode)
    local entry = self:CpuDiagGetEntry(target)
    if not entry then
        return false
    end

    local normalized = PA_CpuDiagNormalizeVisibilityMode(mode)
    if entry.visibilityMode == normalized then
        return true
    end

    entry.visibilityMode = normalized
    self:CpuDiagSuspendCounting(function()
        self:CpuDiagRefreshSubsystem(target)
    end)
    return true
end

function PortalAuthority:ResetCpuDiag()
    if PA_IsStaticBaselineGateEnabled() then
        return false
    end
    local state = self:CpuDiagEnsureState()
    state.startedAt = GetTime() or 0
    state.timers.naturalVisible = nil
    state.timers.effectiveVisible = nil
    state.timers.frameShown = nil
    state.timers.evaluateVisibilityCalls = 0
    state.timers.tickCalls = 0
    state.interrupt.naturalVisible = nil
    state.interrupt.effectiveVisible = nil
    state.interrupt.frameShown = nil
    state.interrupt.evaluateVisibilityCalls = 0
    state.interrupt.updateDisplayCalls = 0
    state.interrupt.periodicInspectCalls = 0
    state.moduleEvents.unitAura = 0
    state.moduleEvents.unitPowerUpdate = 0
    state.moduleEvents.chatMsgAddon = 0
    state.moduleEvents.other = 0
    state.coreEvents.chat = 0
    state.coreEvents.groupRoster = 0
    state.coreEvents.spellcast = 0
    state.coreEvents.other = 0
    PA_CpuDiagResetFixedCounter(state.coreDispatch, PA_CPUDIAG_CORE_DISPATCH_EVENTS)
    PA_CpuDiagResetFixedCounter(state.modulesDispatch, PA_CPUDIAG_MODULES_DISPATCH_EVENTS)
    PA_CpuDiagResetFixedCounter(state.dockDispatch, PA_CPUDIAG_DOCK_DISPATCH_EVENTS)
    PA_CpuDiagResetFixedCounter(state.keystoneDispatch, PA_CPUDIAG_KEYSTONE_DISPATCH_EVENTS)
    PA_CpuDiagResetFixedCounter(state.unitCallbacks, PA_CPUDIAG_UNIT_CALLBACK_EVENTS)
    PA_CpuDiagResetFixedCounter(state.delayedTimers, PA_CPUDIAG_DELAYED_TIMER_KEYS)
    PA_CpuDiagResetFixedCounter(state.uiHooks, PA_CPUDIAG_UI_HOOK_KEYS)
    PA_CpuDiagResetFixedCounter(state.triggerCounts, PA_CPUDIAG_TRIGGER_KEYS)
    PA_CpuDiagResetRingBuffer(state.triggerRecent)
    local baselineLuaKB = PA_CpuDiagReadLuaHeapKB()
    state.memory.startLuaKB = baselineLuaKB
    state.memory.lastTrackedLuaKB = baselineLuaKB
    state.memory.trackedMinKB = baselineLuaKB
    state.memory.trackedMaxKB = baselineLuaKB
    state.memory.trackedSamples = 0
    state.memory.largeRiseEvents = 0
    state.memory.gcSuspectDrops = 0
    state.memory.largestRiseKB = 0
    state.memory.largestDropKB = 0
    PA_CpuDiagSeedAddonMemoryBaseline(state, PA_CpuDiagReadAddonMemorySnapshot())
    state.dockRuntime.onUpdateTickCalls = 0
    state.dockRuntime.buttonCooldownTickCalls = 0
    state.keystone.pollCalls = 0
    state.moveHint.tickCalls = 0
    state.onboarding.tickCalls = 0
    state.deathAlerts.previewTickCalls = 0
    state.deathAlerts.dragTickCalls = 0
    state.releaseGate.onUpdateCalls = 0

    self:CpuDiagAppendIdleWitnessEntry({ "cpudiag_reset" }, nil)
    self:CpuDiagScheduleIdleWitnessStart()
    return true
end

function PortalAuthority:BuildCpuDiagTimersSnapshot()
    local state = self:CpuDiagEnsureState()
    local entry = state.timers
    local modulesApi = self.Modules
    local module = modulesApi and modulesApi.registry and modulesApi.registry.timers or nil
    local frame = module and (module.frame or module.mainFrame) or nil
    local testMode = modulesApi and modulesApi.timersTestMode == true or false
    local unlocked = module and module.unlocked == true or false

    if not unlocked and module and module.GetDB then
        local okDb, db = pcall(module.GetDB, module)
        if okDb and type(db) == "table" then
            unlocked = db.locked == false
        end
    end

    local naturalVisible = entry.naturalVisible
    if naturalVisible == nil then
        local liveVisible = false
        if module and module.ShouldShowLive then
            local okLive, live = pcall(module.ShouldShowLive, module)
            liveVisible = okLive and live and true or false
        end
        naturalVisible = liveVisible or testMode or unlocked
    end

    local effectiveVisible = entry.effectiveVisible
    if effectiveVisible == nil then
        effectiveVisible = self:CpuDiagResolveVisibility("timers", naturalVisible)
    end

    local frameShown = frame and frame.IsShown and frame:IsShown() and true or false

    return {
        overrideMode = self:GetCpuDiagVisibilityMode("timers"),
        naturalVisible = naturalVisible and true or false,
        effectiveVisible = effectiveVisible and true or false,
        frameShown = frameShown,
        unlocked = unlocked,
        testMode = testMode,
        tickerActive = module and module.ticker ~= nil or false,
        evaluateVisibilityCalls = entry.evaluateVisibilityCalls or 0,
        tickCalls = entry.tickCalls or 0,
    }
end

function PortalAuthority:BuildCpuDiagInterruptSnapshot()
    local state = self:CpuDiagEnsureState()
    local entry = state.interrupt
    local modulesApi = self.Modules
    local module = modulesApi and modulesApi.registry and modulesApi.registry.interruptTracker or nil
    local frame = module and module.frame or nil
    local unlocked = module and module.unlocked == true or false

    if not unlocked and module and module.GetDB then
        local okDb, db = pcall(module.GetDB, module)
        if okDb and type(db) == "table" then
            unlocked = db.locked == false
        end
    end

    local isPreview = unlocked
    if module and module.IsPreviewMode then
        local okPreview, preview = pcall(module.IsPreviewMode, module)
        if okPreview then
            isPreview = preview and true or false
        end
    end

    local naturalVisible = entry.naturalVisible
    if naturalVisible == nil then
        local liveVisible = false
        if module and module.IsSupportedLiveContext then
            local okLive, live = pcall(module.IsSupportedLiveContext, module)
            liveVisible = okLive and live and true or false
        end
        naturalVisible = liveVisible or isPreview
    end

    local effectiveVisible = entry.effectiveVisible
    if effectiveVisible == nil then
        effectiveVisible = self:CpuDiagResolveVisibility("interrupt", naturalVisible)
    end

    local frameShown = frame and frame.IsShown and frame:IsShown() and true or false

    return {
        overrideMode = self:GetCpuDiagVisibilityMode("interrupt"),
        naturalVisible = naturalVisible and true or false,
        effectiveVisible = effectiveVisible and true or false,
        frameShown = frameShown,
        unlocked = unlocked,
        previewMode = isPreview and true or false,
        tickerActive = module and module.ticker ~= nil or false,
        periodicInspectActive = module and module.inspectTicker ~= nil or false,
        evaluateVisibilityCalls = entry.evaluateVisibilityCalls or 0,
        updateDisplayCalls = entry.updateDisplayCalls or 0,
        periodicInspectCalls = entry.periodicInspectCalls or 0,
    }
end

function PortalAuthority:BuildCpuDiagKeystoneSnapshot()
    local state = self:CpuDiagEnsureState()
    local keystone = self.KeystoneUtility or nil
    local container = keystone and keystone.container or nil
    local keystoneFrame = _G.ChallengesKeystoneFrame
    local pollArmed = false
    if container and container.GetScript then
        pollArmed = container:GetScript("OnUpdate") ~= nil
    end

    return {
        enabled = PA_SafeBool(PortalAuthorityDB and PortalAuthorityDB.keystoneHelperEnabled),
        frameShown = keystoneFrame and keystoneFrame.IsShown and keystoneFrame:IsShown() and true or false,
        helperShown = container and container.IsShown and container:IsShown() and true or false,
        pollArmed = pollArmed,
        pollCalls = state.keystone.pollCalls or 0,
    }
end

function PortalAuthority:BuildCpuDiagMoveHintSnapshot()
    local state = self:CpuDiagEnsureState()
    return {
        tickerActive = self._moveHintTicker ~= nil,
        tickCalls = state.moveHint.tickCalls or 0,
    }
end

function PortalAuthority:BuildCpuDiagOnboardingSnapshot()
    local runtime = self._onboardingD4
    return {
        active = runtime and runtime.active == true or false,
        tickerActive = false,
        tickCalls = 0,
    }
end

function PortalAuthority:BuildCpuDiagDeathAlertsSnapshot()
    local state = self:CpuDiagEnsureState()
    local deathAlerts = self.DeathAlerts or nil
    local deathFrame = deathAlerts and deathAlerts.frame or nil
    return {
        frameShown = deathFrame and deathFrame.IsShown and deathFrame:IsShown() and true or false,
        testMode = deathAlerts and deathAlerts._testMode == true or false,
        previewTickerActive = deathAlerts and deathAlerts.previewTicker ~= nil or false,
        previewTickCalls = state.deathAlerts.previewTickCalls or 0,
        dragTickerActive = deathAlerts and deathAlerts.dragTicker ~= nil or false,
        dragTickCalls = state.deathAlerts.dragTickCalls or 0,
    }
end

function PortalAuthority:BuildCpuDiagReleaseGateSnapshot()
    local state = self:CpuDiagEnsureState()
    local popupShown = false
    for i = 1, 4 do
        local popup = _G["StaticPopup" .. i]
        if popup and popup.IsShown and popup:IsShown() and popup.which == "DEATH" then
            popupShown = true
            break
        end
    end

    return {
        enabled = PA_SafeBool(PortalAuthorityDB and PortalAuthorityDB.releaseGateEnabled),
        popupShown = popupShown,
        onUpdateCalls = state.releaseGate.onUpdateCalls or 0,
    }
end

function PortalAuthority:BuildCpuDiagSettingsFirstOpenSnapshot()
    local host = self._settingsFirstOpenHostDebug
    local panelEntries = self._settingsFirstOpenDebugPanels
    local snapshot = {
        host = {
            selectedKey = host and tostring(host.selectedKey or "none") or "none",
            selectedGeneration = tonumber(host and host.selectedGeneration) or 0,
            selectionToken = tonumber(host and host.selectionToken) or 0,
        },
        panels = {},
    }

    if type(panelEntries) ~= "table" then
        return snapshot
    end

    for i = 1, #panelEntries do
        local entry = panelEntries[i]
        local panel = entry and entry.panel or nil
        local sizeTarget = panel and (panel._settingsFirstOpenSizeTarget or panel._sizingFrame or panel) or nil
        local readyValue = nil
        if panel and type(panel._settingsFirstOpenIsReady) == "function" then
            local ok, value = pcall(panel._settingsFirstOpenIsReady, panel)
            if ok then
                readyValue = value == true
            else
                readyValue = "error"
            end
        end

        snapshot.panels[#snapshot.panels + 1] = {
            key = tostring(entry and entry.key or "?"),
            name = tostring(entry and entry.name or "?"),
            initialized = panel and panel._initialized == true or false,
            shown = panel and panel.IsShown and panel:IsShown() and true or false,
            state = panel and tostring(panel._paFirstOpenState or "idle") or "missing",
            generation = tonumber(panel and panel._paFirstOpenGeneration) or 0,
            sizeReady = sizeTarget and sizeTarget.GetWidth and sizeTarget.GetHeight
                and ((tonumber(sizeTarget:GetWidth()) or 0) > 1 and (tonumber(sizeTarget:GetHeight()) or 0) > 1)
                or false,
            sizeW = tonumber(sizeTarget and sizeTarget.GetWidth and sizeTarget:GetWidth()) or 0,
            sizeH = tonumber(sizeTarget and sizeTarget.GetHeight and sizeTarget:GetHeight()) or 0,
            ready = readyValue,
            selected = host and host.selectedPanel == panel or false,
        }
    end

    return snapshot
end

function PortalAuthority:BuildCpuDiagCoreEventSnapshot()
    local state = self:CpuDiagEnsureState()
    return {
        chat = state.coreEvents.chat or 0,
        groupRoster = state.coreEvents.groupRoster or 0,
        spellcast = state.coreEvents.spellcast or 0,
        other = state.coreEvents.other or 0,
    }
end

function PortalAuthority:BuildCpuDiagDockSurfaceSnapshot()
    local snapshot = {
        shown = false,
        visibilityDriver = false,
        entries = 0,
        activeButtons = 0,
        cooldownActive = 0,
        cooldownOnUpdate = 0,
        cooldownTextShown = 0,
        labelShown = 0,
        iconMove = 0,
        labelMove = 0,
        labelSettle = 0,
        labelAnimActive = 0,
        settleRunning = false,
    }

    local dockFrame = self and self.dockFrame or nil
    if not dockFrame then
        return snapshot
    end

    snapshot.shown = dockFrame.IsShown and dockFrame:IsShown() and true or false
    snapshot.visibilityDriver = self.dockVisibilityDriverActive == true
    snapshot.entries = tonumber(self.dockEntriesCount) or 0
    snapshot.labelAnimActive = tonumber(self._paDockLabelAnimActiveCount) or 0
    snapshot.settleRunning = self._paDockLabelSettleRunning == true

    local buttons = nil
    if type(self.dockActiveButtons) == "table" and #self.dockActiveButtons > 0 then
        buttons = self.dockActiveButtons
    elseif type(self.dockButtons) == "table" and #self.dockButtons > 0 then
        buttons = self.dockButtons
    end
    if type(buttons) ~= "table" or #buttons <= 0 then
        return snapshot
    end

    local now = GetTime() or 0
    for i = 1, #buttons do
        local btn = buttons[i]
        if btn then
            local liveButton = btn.entry ~= nil or btn.slotIndex ~= nil
            if (not liveButton) and btn.IsShown and btn:IsShown() then
                liveButton = true
            end
            if liveButton then
                snapshot.activeButtons = snapshot.activeButtons + 1

                if (tonumber(btn.cooldownEndTime) or 0) > now then
                    snapshot.cooldownActive = snapshot.cooldownActive + 1
                end
                if btn.GetScript and btn:GetScript("OnUpdate") ~= nil then
                    snapshot.cooldownOnUpdate = snapshot.cooldownOnUpdate + 1
                end

                local cooldownText = btn.cooldownText
                if cooldownText and cooldownText.IsShown and cooldownText:IsShown() then
                    snapshot.cooldownTextShown = snapshot.cooldownTextShown + 1
                end

                local labelArea = btn.labelArea
                if labelArea and labelArea.IsShown and labelArea:IsShown() then
                    snapshot.labelShown = snapshot.labelShown + 1
                end

                local moveAG = btn._moveAG
                if moveAG and moveAG.IsPlaying and moveAG:IsPlaying() then
                    snapshot.iconMove = snapshot.iconMove + 1
                end

                local labelMoveAG = labelArea and labelArea._paLabelMoveAG or nil
                if labelMoveAG and labelMoveAG.IsPlaying and labelMoveAG:IsPlaying() then
                    snapshot.labelMove = snapshot.labelMove + 1
                end

                local labelSettleAG = labelArea and labelArea._paLabelSettleAG or nil
                if labelSettleAG and labelSettleAG.IsPlaying and labelSettleAG:IsPlaying() then
                    snapshot.labelSettle = snapshot.labelSettle + 1
                end
            end
        end
    end

    return snapshot
end

function PortalAuthority:CpuDiagEnsureIdleWitnessSession()
    if PA_IsStaticBaselineGateEnabled() then
        self._idleWitnessRuntime = nil
        return nil
    end
    local runtime = self._idleWitnessRuntime
    if type(runtime) == "table" and runtime.started == true and type(runtime.sessionId) == "number" and runtime.sessionId > 0 then
        return runtime
    end

    if self.InitializeProfiles and not self._profilesInitialized then
        self:InitializeProfiles()
    end

    local store = PA_CpuDiagEnsureIdleWitnessStore()
    if type(store) ~= "table" then
        return nil
    end
    local sessionId = math.max(0, tonumber(store.sessionId) or 0) + 1
    local sessionStartedAt = PA_CpuDiagSafeTime()
    local sessionStartedUptime = GetTime() or 0

    store.sessionId = sessionId
    store.sessionStartedAt = sessionStartedAt
    store.sessionStartedUptime = sessionStartedUptime
    store.lastHeartbeatAt = 0
    local sessionMeta = {}
    if PA_IsUiSurfaceGateEnabled() then
        sessionMeta.uiSurfaceGate = true
    end
    if PA_IsSettingsBaselineGateEnabled() then
        sessionMeta.settingsBaselineGate = true
    end
    if PA_IsSettingsEagerBuildGateEnabled() then
        sessionMeta.settingsEagerBuildGate = true
    end
    if PA_IsSettingsDirectBuildGateEnabled() then
        sessionMeta.settingsDirectBuildGate = true
    end
    if next(sessionMeta) ~= nil then
        PA_CpuDiagSetIdleWitnessSessionMeta(store, sessionId, sessionMeta)
    end

    runtime = {
        started = true,
        sessionId = sessionId,
        sessionStartedAt = sessionStartedAt,
        sessionStartedUptime = sessionStartedUptime,
        previousSnapshot = nil,
    }
    self._idleWitnessRuntime = runtime

    local snapshot = self:BuildIdleWitnessSnapshot()
    if type(snapshot) == "table" then
        runtime.previousSnapshot = snapshot
    end
    return runtime
end

function PortalAuthority:CpuDiagStopIdleWitnessTicker()
    if self._idleWitnessTicker and self._idleWitnessTicker.Cancel then
        self._idleWitnessTicker:Cancel()
    end
    self._idleWitnessTicker = nil
    self._idleWitnessStartScheduled = false
end

function PortalAuthority:BuildIdleWitnessSnapshot()
    local runtime = self._idleWitnessRuntime
    if type(runtime) ~= "table" or runtime.started ~= true or type(runtime.sessionId) ~= "number" or runtime.sessionId <= 0 then
        return nil
    end

    local state = self:CpuDiagEnsureState()
    local nowUptime = GetTime() or 0
    local sessionUptime = math.max(0, nowUptime - (tonumber(runtime.sessionStartedUptime) or nowUptime))
    local db = PortalAuthorityDB
    local modulesApi = self.Modules
    local timersModule = modulesApi and modulesApi.registry and modulesApi.registry.timers or nil
    local interruptModule = modulesApi and modulesApi.registry and modulesApi.registry.interruptTracker or nil
    local latestTrigger = PA_CpuDiagGetRingBufferNewestEntry(state.triggerRecent)
    local currentDiagElapsed = math.max(0, (GetTime() or 0) - (state.startedAt or 0))

    local settingsVisible = self:GetSettingsHostVisibilityState()

    local resting = false
    if type(IsResting) == "function" then
        resting = IsResting() and true or false
    end

    local inInstance = false
    if type(IsInInstance) == "function" then
        local ok, value = pcall(IsInInstance)
        if ok then
            inInstance = value and true or false
        end
    end

    local inCombat = false
    if type(InCombatLockdown) == "function" then
        inCombat = InCombatLockdown() and true or false
    end

    local dockUnlocked = db and db.dockLocked == false or false
    local timersUnlocked = false
    if type(db) == "table" and type(db.modules) == "table" and type(db.modules.timers) == "table" then
        timersUnlocked = db.modules.timers.locked == false
    elseif timersModule and timersModule.unlocked == true then
        timersUnlocked = true
    end

    local interruptUnlocked = false
    if type(db) == "table" and type(db.modules) == "table" and type(db.modules.interruptTracker) == "table" then
        interruptUnlocked = db.modules.interruptTracker.locked == false
    elseif interruptModule and interruptModule.unlocked == true then
        interruptUnlocked = true
    end

    local deathUnlocked = db and db.deathAlertLocked == false or false

    local dockShown = self.dockFrame and self.dockFrame.IsShown and self.dockFrame:IsShown() and true or false
    local dockOnUpdateArmed = self.dockFrame and self.dockFrame.GetScript and self.dockFrame:GetScript("OnUpdate") ~= nil or false
    local moveHintTicker = self._moveHintTicker ~= nil
    local onboardingTicker = false
    local deathAlerts = self.DeathAlerts or nil
    local deathShown = deathAlerts and deathAlerts.frame and deathAlerts.frame.IsShown and deathAlerts.frame:IsShown() and true or false
    local deathPreviewTicker = deathAlerts and deathAlerts.previewTicker ~= nil or false
    local deathDragTicker = deathAlerts and deathAlerts.dragTicker ~= nil or false
    local timersFrame = timersModule and (timersModule.frame or timersModule.mainFrame) or nil
    local timersShown = timersFrame and timersFrame.IsShown and timersFrame:IsShown() and true or false
    local timersTicker = timersModule and timersModule.ticker ~= nil or false
    local interruptFrame = interruptModule and interruptModule.frame or nil
    local interruptShown = interruptFrame and interruptFrame.IsShown and interruptFrame:IsShown() and true or false
    local interruptTicker = interruptModule and interruptModule.ticker ~= nil or false
    local interruptInspectTicker = interruptModule and interruptModule.inspectTicker ~= nil or false
    local keystoneContainer = self.KeystoneUtility and self.KeystoneUtility.container or nil
    local keystoneHelperShown = keystoneContainer and keystoneContainer.IsShown and keystoneContainer:IsShown() and true or false
    local keystonePollArmed = keystoneContainer and keystoneContainer.GetScript and keystoneContainer:GetScript("OnUpdate") ~= nil or false
    local dockSurface = self:BuildCpuDiagDockSurfaceSnapshot()

    local idleGate = settingsVisible == false
        and inCombat == false
        and dockUnlocked == false
        and timersUnlocked == false
        and interruptUnlocked == false
        and deathUnlocked == false

    local unexpectedRuntime = idleGate and (
        moveHintTicker
        or onboardingTicker
        or deathShown
        or deathPreviewTicker
        or deathDragTicker
        or dockOnUpdateArmed
        or timersTicker
        or interruptTicker
        or interruptInspectTicker
    ) or false

    local triggerKey = nil
    local triggerAge = nil
    local triggerSignature = nil
    if type(latestTrigger) == "table" then
        triggerKey = type(latestTrigger.key) == "string" and latestTrigger.key or nil
        if type(triggerKey) == "string" and triggerKey ~= "" then
            local triggerElapsed = tonumber(latestTrigger.elapsed) or 0
            triggerAge = math.max(0, currentDiagElapsed - triggerElapsed)
            triggerSignature = string.format("%s@%.3f", triggerKey, triggerElapsed)
        end
    end

    return {
        sessionId = runtime.sessionId,
        t = PA_CpuDiagSafeTime(),
        u = sessionUptime,
        settings = settingsVisible,
        resting = resting,
        instance = inInstance,
        combat = inCombat,
        dockUnlocked = dockUnlocked,
        timersUnlocked = timersUnlocked,
        interruptUnlocked = interruptUnlocked,
        deathUnlocked = deathUnlocked,
        dockShown = dockShown,
        dockOnUpdateArmed = dockOnUpdateArmed,
        moveHintTicker = moveHintTicker,
        onboardingTicker = onboardingTicker,
        deathShown = deathShown,
        deathPreviewTicker = deathPreviewTicker,
        deathDragTicker = deathDragTicker,
        timersShown = timersShown,
        timersTicker = timersTicker,
        interruptShown = interruptShown,
        interruptTicker = interruptTicker,
        interruptInspectTicker = interruptInspectTicker,
        keystoneHelperShown = keystoneHelperShown,
        keystonePollArmed = keystonePollArmed,
        cooldownActive = tonumber(dockSurface.cooldownActive) or 0,
        cooldownOnUpdate = tonumber(dockSurface.cooldownOnUpdate) or 0,
        cooldownTextShown = tonumber(dockSurface.cooldownTextShown) or 0,
        iconMove = tonumber(dockSurface.iconMove) or 0,
        labelMove = tonumber(dockSurface.labelMove) or 0,
        labelSettle = tonumber(dockSurface.labelSettle) or 0,
        labelAnimActive = tonumber(dockSurface.labelAnimActive) or 0,
        settleRunning = dockSurface.settleRunning == true,
        idleGate = idleGate,
        unexpectedRuntime = unexpectedRuntime,
        triggerKey = triggerKey,
        triggerAge = triggerAge,
        triggerSignature = triggerSignature,
        coreDispatchTotal = tonumber(state.coreDispatch.total) or 0,
        modulesDispatchTotal = tonumber(state.modulesDispatch.total) or 0,
        dockDispatchTotal = tonumber(state.dockDispatch.total) or 0,
        keystoneDispatchTotal = tonumber(state.keystoneDispatch.total) or 0,
        unitCallbacksTotal = tonumber(state.unitCallbacks.total) or 0,
        uiHooksTotal = tonumber(state.uiHooks.total) or 0,
        delayedTimersTotal = tonumber(state.delayedTimers.total) or 0,
        dockOnUpdateTotal = tonumber(state.dockRuntime.onUpdateTickCalls) or 0,
        dockButtonCooldownTotal = tonumber(state.dockRuntime.buttonCooldownTickCalls) or 0,
        moveHintTickTotal = tonumber(state.moveHint.tickCalls) or 0,
        onboardingTickTotal = 0,
        deathPreviewTickTotal = tonumber(state.deathAlerts.previewTickCalls) or 0,
        deathDragTickTotal = tonumber(state.deathAlerts.dragTickCalls) or 0,
        timersEvaluateTotal = tonumber(state.timers.evaluateVisibilityCalls) or 0,
        interruptEvaluateTotal = tonumber(state.interrupt.evaluateVisibilityCalls) or 0,
        interruptUpdateTotal = tonumber(state.interrupt.updateDisplayCalls) or 0,
        interruptInspectTotal = tonumber(state.interrupt.periodicInspectCalls) or 0,
        moduleChatTotal = tonumber(state.moduleEvents.chatMsgAddon) or 0,
        coreGroupRosterTotal = tonumber(state.coreEvents.groupRoster) or 0,
        coreChatTotal = tonumber(state.coreEvents.chat) or 0,
        coreSpellcastTotal = tonumber(state.coreEvents.spellcast) or 0,
    }
end

function PortalAuthority:BuildIdleWitnessDeltaFields(previousSnapshot, currentSnapshot)
    local deltas = {}
    local hasDelta = false
    if type(previousSnapshot) ~= "table" or type(currentSnapshot) ~= "table" then
        return deltas, hasDelta
    end

    for i = 1, #PA_CPUDIAG_IDLE_WITNESS_DELTA_SPECS do
        local spec = PA_CPUDIAG_IDLE_WITNESS_DELTA_SPECS[i]
        local delta = PA_CpuDiagPositiveDelta(currentSnapshot[spec.snapshotKey], previousSnapshot[spec.snapshotKey])
        if delta > 0 then
            deltas[spec.entryKey] = delta
            hasDelta = true
        end
    end

    return deltas, hasDelta
end

function PortalAuthority:BuildIdleWitnessEntry(currentSnapshot, previousSnapshot, reasonTokens, manualLabel)
    if type(currentSnapshot) ~= "table" then
        return nil
    end

    local entry = {
        sessionId = tonumber(currentSnapshot.sessionId) or 0,
        t = tonumber(currentSnapshot.t) or 0,
        u = tonumber(currentSnapshot.u) or 0,
        idleGate = currentSnapshot.idleGate == true,
        unexpectedRuntime = currentSnapshot.unexpectedRuntime == true,
        reason = {},
        settings = currentSnapshot.settings == true,
        resting = currentSnapshot.resting == true,
        instance = currentSnapshot.instance == true,
        combat = currentSnapshot.combat == true,
        dockUnlocked = currentSnapshot.dockUnlocked == true,
        timersUnlocked = currentSnapshot.timersUnlocked == true,
        interruptUnlocked = currentSnapshot.interruptUnlocked == true,
        deathUnlocked = currentSnapshot.deathUnlocked == true,
        dockShown = currentSnapshot.dockShown == true,
        dockOnUpdateArmed = currentSnapshot.dockOnUpdateArmed == true,
        moveHintTicker = currentSnapshot.moveHintTicker == true,
        onboardingTicker = currentSnapshot.onboardingTicker == true,
        deathShown = currentSnapshot.deathShown == true,
        deathPreviewTicker = currentSnapshot.deathPreviewTicker == true,
        deathDragTicker = currentSnapshot.deathDragTicker == true,
        timersShown = currentSnapshot.timersShown == true,
        timersTicker = currentSnapshot.timersTicker == true,
        interruptShown = currentSnapshot.interruptShown == true,
        interruptTicker = currentSnapshot.interruptTicker == true,
        interruptInspectTicker = currentSnapshot.interruptInspectTicker == true,
        keystoneHelperShown = currentSnapshot.keystoneHelperShown == true,
        keystonePollArmed = currentSnapshot.keystonePollArmed == true,
        cooldownActive = tonumber(currentSnapshot.cooldownActive) or 0,
        cooldownOnUpdate = tonumber(currentSnapshot.cooldownOnUpdate) or 0,
        cooldownTextShown = tonumber(currentSnapshot.cooldownTextShown) or 0,
        iconMove = tonumber(currentSnapshot.iconMove) or 0,
        labelMove = tonumber(currentSnapshot.labelMove) or 0,
        labelSettle = tonumber(currentSnapshot.labelSettle) or 0,
        labelAnimActive = tonumber(currentSnapshot.labelAnimActive) or 0,
        settleRunning = currentSnapshot.settleRunning == true,
    }

    if type(manualLabel) == "string" and manualLabel ~= "" then
        entry.manualLabel = manualLabel
    end

    if type(reasonTokens) == "table" then
        for i = 1, #reasonTokens do
            local token = reasonTokens[i]
            if type(token) == "string" and token ~= "" then
                entry.reason[#entry.reason + 1] = token
            end
        end
    end

    local deltaFields = {}
    local hasDelta = false
    if type(previousSnapshot) == "table" then
        deltaFields, hasDelta = self:BuildIdleWitnessDeltaFields(previousSnapshot, currentSnapshot)
    end
    if hasDelta then
        for key, value in pairs(deltaFields) do
            entry[key] = value
        end
    end

    if type(previousSnapshot) == "table" and currentSnapshot.triggerSignature ~= previousSnapshot.triggerSignature and type(currentSnapshot.triggerKey) == "string" and currentSnapshot.triggerKey ~= "" then
        entry.triggerKey = currentSnapshot.triggerKey
        entry.triggerAge = tonumber(currentSnapshot.triggerAge) or 0
    end

    return entry
end

function PortalAuthority:CpuDiagAppendIdleWitnessEntry(reasonTokens, manualLabel)
    if PA_IsStaticBaselineGateEnabled() then
        return false
    end
    local runtime = self:CpuDiagEnsureIdleWitnessSession()
    if type(runtime) ~= "table" or runtime.started ~= true then
        return false
    end

    local currentSnapshot = self:BuildIdleWitnessSnapshot()
    if type(currentSnapshot) ~= "table" then
        return false
    end

    local entry = self:BuildIdleWitnessEntry(currentSnapshot, runtime.previousSnapshot, reasonTokens, manualLabel)
    if type(entry) ~= "table" or (tonumber(entry.sessionId) or 0) <= 0 then
        return false
    end

    local store = PA_CpuDiagEnsureIdleWitnessStore()
    if type(store) ~= "table" then
        return false
    end
    PA_CpuDiagIdleWitnessPushEntry(store, entry)
    for i = 1, #(entry.reason or {}) do
        if entry.reason[i] == "heartbeat" then
            store.lastHeartbeatAt = tonumber(entry.t) or 0
            break
        end
    end
    runtime.previousSnapshot = currentSnapshot
    return true
end

function PortalAuthority:CpuDiagTickIdleWitness()
    if PA_IsStaticBaselineGateEnabled() then
        return false
    end
    local runtime = self._idleWitnessRuntime
    if type(runtime) ~= "table" or runtime.started ~= true then
        return false
    end

    local currentSnapshot = self:BuildIdleWitnessSnapshot()
    if type(currentSnapshot) ~= "table" then
        return false
    end

    local previousSnapshot = runtime.previousSnapshot
    if type(previousSnapshot) ~= "table" then
        runtime.previousSnapshot = currentSnapshot
        return false
    end

    local reasons = {}
    if PA_CpuDiagSnapshotFieldChanged(previousSnapshot, currentSnapshot, PA_CPUDIAG_IDLE_WITNESS_ENV_FIELDS) then
        PA_CpuDiagAddUniqueReason(reasons, "env")
    end
    if PA_CpuDiagSnapshotFieldChanged(previousSnapshot, currentSnapshot, PA_CPUDIAG_IDLE_WITNESS_UNLOCK_FIELDS) then
        PA_CpuDiagAddUniqueReason(reasons, "unlock")
    end
    if PA_CpuDiagSnapshotFieldChanged(previousSnapshot, currentSnapshot, PA_CPUDIAG_IDLE_WITNESS_RUNTIME_FIELDS) then
        PA_CpuDiagAddUniqueReason(reasons, "runtime")
    end
    if PA_CpuDiagSnapshotFieldChanged(previousSnapshot, currentSnapshot, PA_CPUDIAG_IDLE_WITNESS_DOCK_SURFACE_FIELDS) then
        PA_CpuDiagAddUniqueReason(reasons, "dock_surface")
    end
    if previousSnapshot.idleGate ~= currentSnapshot.idleGate then
        PA_CpuDiagAddUniqueReason(reasons, "idle_gate")
    end
    if previousSnapshot.unexpectedRuntime ~= currentSnapshot.unexpectedRuntime then
        PA_CpuDiagAddUniqueReason(reasons, "unexpected_runtime")
    end
    if currentSnapshot.triggerSignature ~= previousSnapshot.triggerSignature and type(currentSnapshot.triggerKey) == "string" and currentSnapshot.triggerKey ~= "" then
        PA_CpuDiagAddUniqueReason(reasons, "trigger")
    end

    local _, hasDelta = self:BuildIdleWitnessDeltaFields(previousSnapshot, currentSnapshot)
    if hasDelta then
        PA_CpuDiagAddUniqueReason(reasons, "delta")
    end

    local store = PA_CpuDiagEnsureIdleWitnessStore()
    if type(store) ~= "table" then
        runtime.previousSnapshot = currentSnapshot
        return false
    end
    local lastEntry = PA_CpuDiagIdleWitnessGetLatestEntryForSession(store, runtime.sessionId)
    local lastAppendedAt = lastEntry and tonumber(lastEntry.t) or nil
    if lastAppendedAt == nil then
        lastAppendedAt = tonumber(runtime.sessionStartedAt) or 0
    end
    if ((tonumber(currentSnapshot.t) or 0) - (tonumber(lastAppendedAt) or 0)) >= PA_CPUDIAG_IDLE_WITNESS_HEARTBEAT_SECONDS then
        PA_CpuDiagAddUniqueReason(reasons, "heartbeat")
    end

    if #reasons <= 0 then
        runtime.previousSnapshot = currentSnapshot
        return false
    end

    local entry = self:BuildIdleWitnessEntry(currentSnapshot, previousSnapshot, reasons, nil)
    if type(entry) ~= "table" or (tonumber(entry.sessionId) or 0) <= 0 then
        runtime.previousSnapshot = currentSnapshot
        return false
    end

    PA_CpuDiagIdleWitnessPushEntry(store, entry)
    for i = 1, #reasons do
        if reasons[i] == "heartbeat" then
            store.lastHeartbeatAt = tonumber(entry.t) or 0
            break
        end
    end
    runtime.previousSnapshot = currentSnapshot
    return true
end

function PortalAuthority:CpuDiagRunIdleWitnessTick()
    if PA_IsStaticBaselineGateEnabled() then
        return false
    end
    local perfStart, perfState = self:PerfBegin("idle_witness_tick")
    local ok, result = pcall(function()
        return self:CpuDiagTickIdleWitness()
    end)
    self:PerfEnd("idle_witness_tick", perfStart, perfState)
    if not ok then
        return false
    end
    return result and true or false
end

function PortalAuthority:CpuDiagEnsureIdleWitnessStarted()
    if PA_IsStaticBaselineGateEnabled() then
        self:CpuDiagStopIdleWitnessTicker()
        return false
    end
    local runtime = self:CpuDiagEnsureIdleWitnessSession()
    if type(runtime) ~= "table" or runtime.started ~= true then
        return false
    end
    if self._idleWitnessTicker ~= nil then
        return true
    end
    if not (C_Timer and C_Timer.NewTicker) then
        return false
    end

    self._idleWitnessTicker = C_Timer.NewTicker(PA_CPUDIAG_IDLE_WITNESS_INTERVAL_SECONDS, function()
        if PortalAuthority and PortalAuthority.CpuDiagRunIdleWitnessTick then
            PortalAuthority:CpuDiagRunIdleWitnessTick()
        end
    end)
    return true
end

function PortalAuthority:CpuDiagScheduleIdleWitnessStart()
    if PA_IsStaticBaselineGateEnabled() then
        self:CpuDiagStopIdleWitnessTicker()
        self._idleWitnessRuntime = nil
        return false
    end
    self:CpuDiagEnsureIdleWitnessSession()
    if self._idleWitnessTicker ~= nil or self._idleWitnessStartScheduled == true then
        return true
    end

    if not (C_Timer and C_Timer.After) then
        return self:CpuDiagEnsureIdleWitnessStarted()
    end

    self._idleWitnessStartScheduled = true
    C_Timer.After(0, function()
        if PortalAuthority and PortalAuthority.CpuDiagEnsureIdleWitnessStarted then
            PortalAuthority._idleWitnessStartScheduled = false
            PortalAuthority:CpuDiagEnsureIdleWitnessStarted()
        end
    end)
    return true
end

function PortalAuthority:BuildCpuDiagIdleWitnessSummary()
    if PA_IsStaticBaselineGateEnabled() then
        return {
            enabled = false,
            disabled = true,
            sessionId = "disabled",
            size = 0,
            capacity = PA_CPUDIAG_IDLE_WITNESS_CAPACITY,
            lastT = "disabled",
            lastU = "disabled",
            uiSurfaceGate = false,
        }
    end

    local store = PA_CpuDiagGetIdleWitnessStoreReadOnly()
    if type(store) ~= "table" then
        return {
            enabled = false,
            disabled = false,
            sessionId = "unknown",
            size = 0,
            capacity = PA_CPUDIAG_IDLE_WITNESS_CAPACITY,
            lastT = "none",
            lastU = "none",
            uiSurfaceGate = false,
            settingsBaselineGate = false,
            settingsEagerBuildGate = false,
            settingsDirectBuildGate = false,
        }
    end

    local sessionId = tonumber(store.sessionId)
    local sessionMeta = PA_CpuDiagGetIdleWitnessSessionMeta(store, sessionId)
    local lastEntry = PA_CpuDiagIdleWitnessGetLatestEntryForSession(store, sessionId)
    local lastT = "none"
    local lastU = "none"
    if type(lastEntry) == "table" then
        lastT = tostring(tonumber(lastEntry.t) or 0)
        lastU = string.format("%.1f", tonumber(lastEntry.u) or 0)
    end

    return {
        enabled = sessionId ~= nil and sessionId > 0,
        disabled = false,
        sessionId = sessionId and tostring(sessionId) or "unknown",
        size = math.max(0, tonumber(store.size) or 0),
        capacity = math.max(1, tonumber(store.capacity) or PA_CPUDIAG_IDLE_WITNESS_CAPACITY),
        lastT = lastT,
        lastU = lastU,
        uiSurfaceGate = sessionMeta and sessionMeta.uiSurfaceGate == true or false,
        settingsBaselineGate = sessionMeta and sessionMeta.settingsBaselineGate == true or false,
        settingsEagerBuildGate = sessionMeta and sessionMeta.settingsEagerBuildGate == true or false,
        settingsDirectBuildGate = sessionMeta and sessionMeta.settingsDirectBuildGate == true or false,
    }
end

local function PA_CpuDiagSnapshotFixedCounter(counter, order)
    local snapshot = {
        total = tonumber(counter and counter.total) or 0,
    }
    for i = 1, #order do
        local key = order[i]
        snapshot[key] = tonumber(counter and counter[key]) or 0
    end
    return snapshot
end

local function PA_CpuDiagSnapshotRecentEntries(entries)
    local snapshot = {}
    for i = 1, #entries do
        local entry = entries[i]
        snapshot[#snapshot + 1] = {
            elapsed = tonumber(entry and entry.elapsed) or 0,
            key = tostring(entry and entry.key or "?"),
            luaKB = entry and entry.luaKB or nil,
            deltaKB = entry and entry.deltaKB or nil,
            settings = entry and entry.settings or nil,
            resting = entry and entry.resting or nil,
            instance = entry and entry.instance or nil,
            combat = entry and entry.combat or nil,
        }
    end
    return snapshot
end

function PortalAuthority:BuildCpuDiagStatusSnapshot()
    local state = self:CpuDiagEnsureState()
    local env = self:BuildCpuDiagEnvSnapshot()
    local memory = self:BuildCpuDiagMemorySnapshot()
    local addonMemory = self:BuildCpuDiagAddonMemorySnapshot()
    local timers = self:BuildCpuDiagTimersSnapshot()
    local interrupt = self:BuildCpuDiagInterruptSnapshot()
    local coreEvents = self:BuildCpuDiagCoreEventSnapshot()
    local keystone = self:BuildCpuDiagKeystoneSnapshot()
    local moveHint = self:BuildCpuDiagMoveHintSnapshot()
    local onboarding = self:BuildCpuDiagOnboardingSnapshot()
    local deathAlerts = self:BuildCpuDiagDeathAlertsSnapshot()
    local releaseGate = self:BuildCpuDiagReleaseGateSnapshot()
    local settingsFirstOpen = self:BuildCpuDiagSettingsFirstOpenSnapshot()
    local dockSurface = self:BuildCpuDiagDockSurfaceSnapshot()
    local idleWitness = self:BuildCpuDiagIdleWitnessSummary()
    local settingsBaselineGate = PA_IsSettingsBaselineGateEnabled()
    local settingsEagerBuildGate = PA_IsSettingsEagerBuildGateEnabled()
    local settingsDirectBuildGate = PA_IsSettingsDirectBuildGateEnabled()
    local keystoneBootstrapState = self:GetSettingsKeystoneBootstrapState()
    local settingsBootstrapActive = self:GetSettingsBootstrapActive()
    local elapsed = math.max(0, (GetTime() or 0) - (state.startedAt or 0))
    local dockOnUpdateArmed = "unknown"
    if self.dockFrame and self.dockFrame.GetScript then
        dockOnUpdateArmed = self.dockFrame:GetScript("OnUpdate") ~= nil
    end
    return {
        elapsed = elapsed,
        env = env,
        memory = memory,
        addonMemory = addonMemory,
        timers = timers,
        interrupt = interrupt,
        coreEvents = coreEvents,
        keystone = keystone,
        moveHint = moveHint,
        onboarding = onboarding,
        deathAlerts = deathAlerts,
        releaseGate = releaseGate,
        settingsFirstOpen = settingsFirstOpen,
        dockSurface = dockSurface,
        idleWitness = idleWitness,
        staticBaselineGate = PA_IsStaticBaselineGateEnabled(),
        settingsBaselineGate = settingsBaselineGate,
        settingsEagerBuildGate = settingsEagerBuildGate,
        settingsDirectBuildGate = settingsDirectBuildGate,
        keystoneBootstrapState = keystoneBootstrapState,
        settingsBootstrapActive = settingsBootstrapActive,
        moduleEvents = {
            unitAura = tonumber(state.moduleEvents.unitAura) or 0,
            unitPowerUpdate = tonumber(state.moduleEvents.unitPowerUpdate) or 0,
            chatMsgAddon = tonumber(state.moduleEvents.chatMsgAddon) or 0,
            other = tonumber(state.moduleEvents.other) or 0,
        },
        coreDispatch = PA_CpuDiagSnapshotFixedCounter(state.coreDispatch, PA_CPUDIAG_CORE_DISPATCH_EVENTS),
        modulesDispatch = PA_CpuDiagSnapshotFixedCounter(state.modulesDispatch, PA_CPUDIAG_MODULES_DISPATCH_EVENTS),
        dockDispatch = PA_CpuDiagSnapshotFixedCounter(state.dockDispatch, PA_CPUDIAG_DOCK_DISPATCH_EVENTS),
        keystoneDispatch = PA_CpuDiagSnapshotFixedCounter(state.keystoneDispatch, PA_CPUDIAG_KEYSTONE_DISPATCH_EVENTS),
        unitCallbacks = PA_CpuDiagSnapshotFixedCounter(state.unitCallbacks, PA_CPUDIAG_UNIT_CALLBACK_EVENTS),
        delayedTimers = PA_CpuDiagSnapshotFixedCounter(state.delayedTimers, PA_CPUDIAG_DELAYED_TIMER_KEYS),
        uiHooks = PA_CpuDiagSnapshotFixedCounter(state.uiHooks, PA_CPUDIAG_UI_HOOK_KEYS),
        triggerCounts = PA_CpuDiagSnapshotFixedCounter(state.triggerCounts, PA_CPUDIAG_TRIGGER_KEYS),
        triggerRecent = PA_CpuDiagSnapshotRecentEntries(PA_CpuDiagGetRingBufferEntriesNewestFirst(state.triggerRecent)),
        dockOnUpdateArmed = dockOnUpdateArmed,
        dockRuntime = {
            onUpdateTickCalls = tonumber(state.dockRuntime and state.dockRuntime.onUpdateTickCalls) or 0,
            buttonCooldownTickCalls = tonumber(state.dockRuntime and state.dockRuntime.buttonCooldownTickCalls) or 0,
        },
        uiSurfaceGate = PA_IsUiSurfaceGateEnabled() or idleWitness.uiSurfaceGate == true,
    }
end

function PortalAuthority:RenderCpuDiagStatusLines(snapshot)
    local env = snapshot and snapshot.env or {}
    local memory = snapshot and snapshot.memory or {}
    local addonMemory = snapshot and snapshot.addonMemory or {}
    local timers = snapshot and snapshot.timers or {}
    local interrupt = snapshot and snapshot.interrupt or {}
    local coreEvents = snapshot and snapshot.coreEvents or {}
    local keystone = snapshot and snapshot.keystone or {}
    local moveHint = snapshot and snapshot.moveHint or {}
    local onboarding = snapshot and snapshot.onboarding or {}
    local deathAlerts = snapshot and snapshot.deathAlerts or {}
    local releaseGate = snapshot and snapshot.releaseGate or {}
    local settingsFirstOpen = snapshot and snapshot.settingsFirstOpen or {}
    local dockSurface = snapshot and snapshot.dockSurface or {}
    local idleWitness = snapshot and snapshot.idleWitness or {}
    local staticBaselineGate = snapshot and snapshot.staticBaselineGate == true or false
    local settingsBaselineGate = snapshot and snapshot.settingsBaselineGate == true or false
    local settingsEagerBuildGate = snapshot and snapshot.settingsEagerBuildGate == true or false
    local settingsDirectBuildGate = snapshot and snapshot.settingsDirectBuildGate == true or false
    local keystoneBootstrapState = snapshot and snapshot.keystoneBootstrapState or "unknown"
    local settingsBootstrapActive = snapshot and snapshot.settingsBootstrapActive or "unknown"
    local elapsed = tonumber(snapshot and snapshot.elapsed) or 0
    local moduleEvents = snapshot and snapshot.moduleEvents or {}
    local coreDispatch = snapshot and snapshot.coreDispatch or {}
    local modulesDispatch = snapshot and snapshot.modulesDispatch or {}
    local dockDispatch = snapshot and snapshot.dockDispatch or {}
    local keystoneDispatch = snapshot and snapshot.keystoneDispatch or {}
    local unitCallbacks = snapshot and snapshot.unitCallbacks or {}
    local delayedTimers = snapshot and snapshot.delayedTimers or {}
    local uiHooks = snapshot and snapshot.uiHooks or {}
    local triggerCounts = snapshot and snapshot.triggerCounts or {}
    local triggerRecent = snapshot and snapshot.triggerRecent or {}
    local dockOnUpdateArmed = snapshot and snapshot.dockOnUpdateArmed or "unknown"
    local dockRuntime = snapshot and snapshot.dockRuntime or {}
    local function boolOrUnknownText(value)
        if value == nil or value == "unknown" then
            return "unknown"
        end
        return PA_CpuDiagBoolText(value)
    end
    local function settingsFirstOpenFlagText(value)
        if value == nil then
            return "n/a"
        end
        if value == "error" then
            return "error"
        end
        return PA_CpuDiagBoolText(value)
    end
    local function summarizeFixedCounter(counter, order)
        local total = tonumber(counter.total) or 0
        if total <= 0 then
            return "none"
        end
        local entries = {}
        for i = 1, #order do
            local key = order[i]
            local count = tonumber(counter[key]) or 0
            if count > 0 then
                entries[#entries + 1] = {
                    key = key,
                    count = count,
                    index = i,
                }
            end
        end
        table.sort(entries, function(left, right)
            if left.count ~= right.count then
                return left.count > right.count
            end
            return left.index < right.index
        end)
        local limit = math.min(6, #entries)
        local parts = {}
        for i = 1, limit do
            parts[#parts + 1] = string.format("%s=%d", tostring(entries[i].key), tonumber(entries[i].count) or 0)
        end
        if #entries > limit then
            parts[#parts + 1] = string.format("+%d more", #entries - limit)
        end
        return table.concat(parts, " ")
    end
    local function triggerFlagText(value)
        if value == nil then
            return "?"
        end
        return PA_CpuDiagBoolText(value)
    end
    local function summarizeRecentTriggers(entries)
        if #entries <= 0 then
            return "none"
        end
        local limit = math.min(6, #entries)
        local parts = {}
        for i = 1, limit do
            local entry = entries[i]
            parts[#parts + 1] = string.format(
                "%.1fs:%s[k=%s d=%s s=%s r=%s i=%s c=%s]",
                tonumber(entry.elapsed) or 0,
                tostring(entry.key or "?"),
                PA_CpuDiagFormatKB(entry.luaKB),
                PA_CpuDiagFormatKB(entry.deltaKB),
                triggerFlagText(entry.settings),
                triggerFlagText(entry.resting),
                triggerFlagText(entry.instance),
                triggerFlagText(entry.combat)
            )
        end
        if #entries > limit then
            parts[#parts + 1] = string.format("+%d more", #entries - limit)
        end
        return table.concat(parts, " ")
    end
    local function summarizeAddonMemoryTopDelta(snapshot)
        if type(snapshot) ~= "table" or snapshot.available ~= true then
            return "unknown"
        end
        if type(snapshot.entries) ~= "table" or #snapshot.entries <= 0 then
            return "none"
        end

        local limit = math.min(4, #snapshot.entries)
        local parts = {}
        for i = 1, limit do
            local entry = snapshot.entries[i]
            local label = tostring(entry.displayName or entry.key or "?")
            local suffix = entry.newSinceReset and "(new)" or ""
            parts[#parts + 1] = string.format(
                "%s=%sKB%s",
                label,
                PA_CpuDiagFormatSignedKB(entry.deltaKB),
                suffix
            )
        end
        if #snapshot.entries > limit then
            parts[#parts + 1] = string.format("+%d more", #snapshot.entries - limit)
        end
        return table.concat(parts, " ")
    end
    local addonMemoryRankText = "unknown"
    if type(addonMemory) == "table" and addonMemory.available == true and type(addonMemory.paRankByDelta) == "number" then
        addonMemoryRankText = tostring(addonMemory.paRankByDelta)
    end
    local lines = {
        string.format("|cffffd100Portal Authority CpuDiag:|r elapsed=%.1fs", elapsed),
        string.format(
            "|cffffd100Portal Authority CpuDiag:|r env settings=%s lock=%s resting=%s instance=%s combat=%s",
            boolOrUnknownText(env.settingsVisible),
            tostring(env.lockState or "unknown"),
            boolOrUnknownText(env.resting),
            boolOrUnknownText(env.inInstance),
            boolOrUnknownText(env.inCombat)
        ),
        string.format(
            "|cffffd100Portal Authority CpuDiag:|r timers override=%s natural=%s effective=%s shown=%s unlocked=%s test=%s ticker=%s eval=%d tick=%d",
            tostring(timers.overrideMode or "NORMAL"),
            PA_CpuDiagBoolText(timers.naturalVisible),
            PA_CpuDiagBoolText(timers.effectiveVisible),
            PA_CpuDiagBoolText(timers.frameShown),
            PA_CpuDiagBoolText(timers.unlocked),
            PA_CpuDiagBoolText(timers.testMode),
            PA_CpuDiagBoolText(timers.tickerActive),
            tonumber(timers.evaluateVisibilityCalls) or 0,
            tonumber(timers.tickCalls) or 0
        ),
        string.format(
            "|cffffd100Portal Authority CpuDiag:|r interrupt override=%s natural=%s effective=%s shown=%s unlocked=%s preview=%s ticker=%s inspect=%s eval=%d update=%d periodicInspect=%d",
            tostring(interrupt.overrideMode or "NORMAL"),
            PA_CpuDiagBoolText(interrupt.naturalVisible),
            PA_CpuDiagBoolText(interrupt.effectiveVisible),
            PA_CpuDiagBoolText(interrupt.frameShown),
            PA_CpuDiagBoolText(interrupt.unlocked),
            PA_CpuDiagBoolText(interrupt.previewMode),
            PA_CpuDiagBoolText(interrupt.tickerActive),
            PA_CpuDiagBoolText(interrupt.periodicInspectActive),
            tonumber(interrupt.evaluateVisibilityCalls) or 0,
            tonumber(interrupt.updateDisplayCalls) or 0,
            tonumber(interrupt.periodicInspectCalls) or 0
        ),
        string.format(
            "|cffffd100Portal Authority CpuDiag:|r coreDispatch total=%d %s",
            tonumber(coreDispatch.total) or 0,
            summarizeFixedCounter(coreDispatch, PA_CPUDIAG_CORE_DISPATCH_EVENTS)
        ),
        string.format(
            "|cffffd100Portal Authority CpuDiag:|r modulesDispatch total=%d %s",
            tonumber(modulesDispatch.total) or 0,
            summarizeFixedCounter(modulesDispatch, PA_CPUDIAG_MODULES_DISPATCH_EVENTS)
        ),
        string.format(
            "|cffffd100Portal Authority CpuDiag:|r dockDispatch total=%d %s",
            tonumber(dockDispatch.total) or 0,
            summarizeFixedCounter(dockDispatch, PA_CPUDIAG_DOCK_DISPATCH_EVENTS)
        ),
        string.format(
            "|cffffd100Portal Authority CpuDiag:|r keystoneDispatch total=%d %s",
            tonumber(keystoneDispatch.total) or 0,
            summarizeFixedCounter(keystoneDispatch, PA_CPUDIAG_KEYSTONE_DISPATCH_EVENTS)
        ),
        string.format(
            "|cffffd100Portal Authority CpuDiag:|r unitCallbacks total=%d %s",
            tonumber(unitCallbacks.total) or 0,
            summarizeFixedCounter(unitCallbacks, PA_CPUDIAG_UNIT_CALLBACK_EVENTS)
        ),
        string.format(
            "|cffffd100Portal Authority CpuDiag:|r uiHooks total=%d %s",
            tonumber(uiHooks.total) or 0,
            summarizeFixedCounter(uiHooks, PA_CPUDIAG_UI_HOOK_KEYS)
        ),
        string.format(
            "|cffffd100Portal Authority CpuDiag:|r dockRuntime onUpdateArmed=%s onUpdateTick=%d buttonCooldownTick=%d",
            boolOrUnknownText(dockOnUpdateArmed),
            tonumber(dockRuntime.onUpdateTickCalls) or 0,
            tonumber(dockRuntime.buttonCooldownTickCalls) or 0
        ),
        string.format(
            "|cffffd100Portal Authority CpuDiag:|r dockSurface shown=%s visibilityDriver=%s entries=%d activeButtons=%d cooldownActive=%d cooldownOnUpdate=%d cooldownTextShown=%d labelShown=%d iconMove=%d labelMove=%d labelSettle=%d labelAnimActive=%d settleRunning=%s",
            PA_CpuDiagBoolText(dockSurface.shown),
            PA_CpuDiagBoolText(dockSurface.visibilityDriver),
            tonumber(dockSurface.entries) or 0,
            tonumber(dockSurface.activeButtons) or 0,
            tonumber(dockSurface.cooldownActive) or 0,
            tonumber(dockSurface.cooldownOnUpdate) or 0,
            tonumber(dockSurface.cooldownTextShown) or 0,
            tonumber(dockSurface.labelShown) or 0,
            tonumber(dockSurface.iconMove) or 0,
            tonumber(dockSurface.labelMove) or 0,
            tonumber(dockSurface.labelSettle) or 0,
            tonumber(dockSurface.labelAnimActive) or 0,
            PA_CpuDiagBoolText(dockSurface.settleRunning)
        ),
        string.format(
            "|cffffd100Portal Authority CpuDiag:|r delayedTimers total=%d %s",
            tonumber(delayedTimers.total) or 0,
            summarizeFixedCounter(delayedTimers, PA_CPUDIAG_DELAYED_TIMER_KEYS)
        ),
        string.format(
            "|cffffd100Portal Authority CpuDiag:|r memory currentLuaKB=%s startLuaKB=%s deltaFromStartKB=%s trackedMinKB=%s trackedMaxKB=%s trackedSamples=%d largeRiseEvents=%d gcSuspectDrops=%d largestRiseKB=%s largestDropKB=%s",
            PA_CpuDiagFormatKB(memory.currentLuaKB),
            PA_CpuDiagFormatKB(memory.startLuaKB),
            PA_CpuDiagFormatKB(memory.deltaFromStartKB),
            PA_CpuDiagFormatKB(memory.trackedMinKB),
            PA_CpuDiagFormatKB(memory.trackedMaxKB),
            tonumber(memory.trackedSamples) or 0,
            tonumber(memory.largeRiseEvents) or 0,
            tonumber(memory.gcSuspectDrops) or 0,
            PA_CpuDiagFormatKB(memory.largestRiseKB),
            PA_CpuDiagFormatKB(memory.largestDropKB)
        ),
        addonMemory.available == true and string.format(
            "|cffffd100Portal Authority CpuDiag:|r addonMemory paKB=%s paDeltaKB=%s totalAddonKB=%s totalAddonDeltaKB=%s paSharePct=%s paRankByDelta=%s newSinceReset=%s",
            PA_CpuDiagFormatKB(addonMemory.paKB),
            PA_CpuDiagFormatSignedKB(addonMemory.paDeltaKB),
            PA_CpuDiagFormatKB(addonMemory.totalAddonKB),
            PA_CpuDiagFormatSignedKB(addonMemory.totalAddonDeltaKB),
            PA_CpuDiagFormatPct(addonMemory.paSharePct),
            addonMemoryRankText,
            boolOrUnknownText(addonMemory.newSinceReset)
        ) or "|cffffd100Portal Authority CpuDiag:|r addonMemory unknown",
        string.format(
            "|cffffd100Portal Authority CpuDiag:|r addonMemoryTopDelta %s",
            summarizeAddonMemoryTopDelta(addonMemory)
        ),
        string.format(
            "|cffffd100Portal Authority CpuDiag:|r triggerCounts total=%d %s",
            tonumber(triggerCounts.total) or 0,
            summarizeFixedCounter(triggerCounts, PA_CPUDIAG_TRIGGER_KEYS)
        ),
        string.format(
            "|cffffd100Portal Authority CpuDiag:|r triggerRecent %s",
            summarizeRecentTriggers(triggerRecent)
        ),
        staticBaselineGate and string.format(
            "|cffffd100Portal Authority CpuDiag:|r idleWitness enabled=%s disabled=true sessionId=%s size=%d capacity=%d lastT=%s lastU=%s",
            PA_CpuDiagBoolText(false),
            tostring(idleWitness.sessionId or "disabled"),
            tonumber(idleWitness.size) or 0,
            tonumber(idleWitness.capacity) or PA_CPUDIAG_IDLE_WITNESS_CAPACITY,
            tostring(idleWitness.lastT or "disabled"),
            tostring(idleWitness.lastU or "disabled")
        ) or string.format(
            "|cffffd100Portal Authority CpuDiag:|r idleWitness enabled=%s sessionId=%s size=%d capacity=%d lastT=%s lastU=%s",
            PA_CpuDiagBoolText(idleWitness.enabled),
            tostring(idleWitness.sessionId or "unknown"),
            tonumber(idleWitness.size) or 0,
            tonumber(idleWitness.capacity) or PA_CPUDIAG_IDLE_WITNESS_CAPACITY,
            tostring(idleWitness.lastT or "none"),
            tostring(idleWitness.lastU or "none")
        ),
        string.format(
            "|cffffd100Portal Authority CpuDiag:|r moduleEvents unitAura=%d unitPower=%d chat=%d other=%d",
            tonumber(moduleEvents.unitAura) or 0,
            tonumber(moduleEvents.unitPowerUpdate) or 0,
            tonumber(moduleEvents.chatMsgAddon) or 0,
            tonumber(moduleEvents.other) or 0
        ),
        string.format(
            "|cffffd100Portal Authority CpuDiag:|r coreEvents chat=%d groupRoster=%d spellcast=%d other=%d",
            tonumber(coreEvents.chat) or 0,
            tonumber(coreEvents.groupRoster) or 0,
            tonumber(coreEvents.spellcast) or 0,
            tonumber(coreEvents.other) or 0
        ),
        string.format(
            "|cffffd100Portal Authority CpuDiag:|r keystone enabled=%s frameShown=%s helperShown=%s pollArmed=%s poll=%d",
            PA_CpuDiagBoolText(keystone.enabled),
            PA_CpuDiagBoolText(keystone.frameShown),
            PA_CpuDiagBoolText(keystone.helperShown),
            PA_CpuDiagBoolText(keystone.pollArmed),
            tonumber(keystone.pollCalls) or 0
        ),
        string.format(
            "|cffffd100Portal Authority CpuDiag:|r settingsBootstrap active=%s",
            tostring(settingsBootstrapActive)
        ),
        string.format(
            "|cffffd100Portal Authority CpuDiag:|r moveHint ticker=%s tick=%d guidedSetupActive=%s",
            PA_CpuDiagBoolText(moveHint.tickerActive),
            tonumber(moveHint.tickCalls) or 0,
            PA_CpuDiagBoolText(onboarding.active)
        ),
        string.format(
            "|cffffd100Portal Authority CpuDiag:|r deathAlerts shown=%s test=%s previewTicker=%s previewTick=%d dragTicker=%s dragTick=%d",
            PA_CpuDiagBoolText(deathAlerts.frameShown),
            PA_CpuDiagBoolText(deathAlerts.testMode),
            PA_CpuDiagBoolText(deathAlerts.previewTickerActive),
            tonumber(deathAlerts.previewTickCalls) or 0,
            PA_CpuDiagBoolText(deathAlerts.dragTickerActive),
            tonumber(deathAlerts.dragTickCalls) or 0
        ),
        string.format(
            "|cffffd100Portal Authority CpuDiag:|r releaseGate enabled=%s popupShown=%s onUpdate=%d",
            PA_CpuDiagBoolText(releaseGate.enabled),
            PA_CpuDiagBoolText(releaseGate.popupShown),
            tonumber(releaseGate.onUpdateCalls) or 0
        ),
    }

    local firstOpenHost = settingsFirstOpen and settingsFirstOpen.host or {}
    lines[#lines + 1] = string.format(
        "|cffffd100Portal Authority CpuDiag:|r settingsFirstOpenHost selected=%s gen=%d token=%d",
        tostring(firstOpenHost.selectedKey or "none"),
        tonumber(firstOpenHost.selectedGeneration) or 0,
        tonumber(firstOpenHost.selectionToken) or 0
    )
    for i = 1, math.min(type(settingsFirstOpen and settingsFirstOpen.panels) == "table" and #settingsFirstOpen.panels or 0, 8) do
        local panelInfo = settingsFirstOpen.panels[i]
        lines[#lines + 1] = string.format(
            "|cffffd100Portal Authority CpuDiag:|r settingsPanel key=%s init=%s shown=%s selected=%s state=%s gen=%d ready=%s size=%s %dx%d",
            tostring(panelInfo.key or "?"),
            PA_CpuDiagBoolText(panelInfo.initialized),
            PA_CpuDiagBoolText(panelInfo.shown),
            PA_CpuDiagBoolText(panelInfo.selected),
            tostring(panelInfo.state or "missing"),
            tonumber(panelInfo.generation) or 0,
            settingsFirstOpenFlagText(panelInfo.ready),
            PA_CpuDiagBoolText(panelInfo.sizeReady),
            tonumber(panelInfo.sizeW) or 0,
            tonumber(panelInfo.sizeH) or 0
        )
    end

    if settingsBaselineGate then
        table.insert(lines, 2, "|cffffd100Portal Authority CpuDiag:|r settingsBaselineGate=true")
        table.insert(lines, 3, string.format(
            "|cffffd100Portal Authority CpuDiag:|r idleWitness=%s",
            idleWitness.enabled and "enabled" or "disabled"
        ))
    end

    if settingsEagerBuildGate then
        table.insert(lines, 2, "|cffffd100Portal Authority CpuDiag:|r settingsEagerBuildGate=true")
        table.insert(lines, 3, string.format(
            "|cffffd100Portal Authority CpuDiag:|r idleWitness=%s",
            idleWitness.enabled and "enabled" or "disabled"
        ))
    end

    if settingsDirectBuildGate then
        table.insert(lines, 2, "|cffffd100Portal Authority CpuDiag:|r settingsDirectBuildGate=true")
        table.insert(lines, 3, string.format(
            "|cffffd100Portal Authority CpuDiag:|r idleWitness=%s",
            idleWitness.enabled and "enabled" or "disabled"
        ))
        table.insert(lines, 4, string.format(
            "|cffffd100Portal Authority CpuDiag:|r keystoneBootstrap=%s",
            tostring(keystoneBootstrapState)
        ))
    end

    if snapshot and snapshot.uiSurfaceGate == true then
        table.insert(lines, 2, "|cffffd100Portal Authority CpuDiag:|r uiSurfaceGate=true")
    end

    return lines
end

function PortalAuthority:GetCpuDiagStatusLines()
    return self:RenderCpuDiagStatusLines(self:BuildCpuDiagStatusSnapshot())
end

function PortalAuthority:BuildPerfSnapshot()
    local perf = self._perf or {}
    local stats = perf.stats or {}
    local snapshot = {
        enabled = self:PerfIsEnabled(),
        states = {},
    }
    local stateLabels = {}

    for stateLabel, stateStats in pairs(stats) do
        if type(stateStats) == "table" then
            local hasEntries = false
            for _, entry in pairs(stateStats) do
                if type(entry) == "table" and (tonumber(entry.calls) or 0) > 0 then
                    hasEntries = true
                    break
                end
            end
            if hasEntries then
                stateLabels[#stateLabels + 1] = stateLabel
            end
        end
    end

    table.sort(stateLabels, function(left, right)
        local leftRank = PA_PerfStateRank(left)
        local rightRank = PA_PerfStateRank(right)
        if leftRank ~= rightRank then
            return leftRank < rightRank
        end
        return tostring(left) < tostring(right)
    end)

    for _, stateLabel in ipairs(stateLabels) do
        local stateStats = stats[stateLabel]
        local scopes = {}
        local stateTotalMs = 0

        for scopeName, entry in pairs(stateStats) do
            if type(entry) == "table" and (tonumber(entry.calls) or 0) > 0 then
                scopes[#scopes + 1] = scopeName
                stateTotalMs = stateTotalMs + (tonumber(entry.totalMs) or 0)
            end
        end

        table.sort(scopes, function(left, right)
            local leftEntry = stateStats[left] or {}
            local rightEntry = stateStats[right] or {}
            local leftTotal = tonumber(leftEntry.totalMs) or 0
            local rightTotal = tonumber(rightEntry.totalMs) or 0
            if leftTotal ~= rightTotal then
                return leftTotal > rightTotal
            end
            local leftRank = PA_PerfScopeRank(left)
            local rightRank = PA_PerfScopeRank(right)
            if leftRank ~= rightRank then
                return leftRank < rightRank
            end
            return tostring(left) < tostring(right)
        end)

        local stateSnapshot = {
            label = stateLabel,
            totalMs = stateTotalMs,
            scopes = {},
        }
        for _, scopeName in ipairs(scopes) do
            local entry = stateStats[scopeName] or {}
            local calls = tonumber(entry.calls) or 0
            local totalMs = tonumber(entry.totalMs) or 0
            local maxMs = tonumber(entry.maxMs) or 0
            local avgMs = 0
            if calls > 0 then
                avgMs = totalMs / calls
            end
            stateSnapshot.scopes[#stateSnapshot.scopes + 1] = {
                name = scopeName,
                calls = calls,
                totalMs = totalMs,
                avgMs = avgMs,
                maxMs = maxMs,
            }
        end
        snapshot.states[#snapshot.states + 1] = stateSnapshot
    end

    return snapshot
end

function PortalAuthority:RenderPerfSnapshotLines(snapshot)
    local lines = {}
    local states = snapshot and snapshot.states or nil
    if type(states) ~= "table" or #states <= 0 then
        lines[#lines + 1] = "|cffffd100Portal Authority Perf:|r no recorded samples."
        return lines
    end

    lines[#lines + 1] = string.format(
        "|cffffd100Portal Authority Perf:|r dump (%s).",
        snapshot and snapshot.enabled and "enabled" or "disabled"
    )

    for i = 1, #states do
        local stateSnapshot = states[i]
        lines[#lines + 1] = string.format(
            "|cffffd100Portal Authority Perf:|r state=%s total=%.3fms",
            tostring(stateSnapshot and stateSnapshot.label or "?"),
            tonumber(stateSnapshot and stateSnapshot.totalMs) or 0
        )
        local scopes = stateSnapshot and stateSnapshot.scopes or nil
        for j = 1, math.max(0, type(scopes) == "table" and #scopes or 0) do
            local scopeSnapshot = scopes[j]
            lines[#lines + 1] = string.format(
                "|cffffd100Portal Authority Perf:|r   %s calls=%d total=%.3fms avg=%.3fms max=%.3fms",
                tostring(scopeSnapshot and scopeSnapshot.name or "?"),
                tonumber(scopeSnapshot and scopeSnapshot.calls) or 0,
                tonumber(scopeSnapshot and scopeSnapshot.totalMs) or 0,
                tonumber(scopeSnapshot and scopeSnapshot.avgMs) or 0,
                tonumber(scopeSnapshot and scopeSnapshot.maxMs) or 0
            )
        end
    end

    return lines
end

function PortalAuthority:PerfDump()
    for _, line in ipairs(self:RenderPerfSnapshotLines(self:BuildPerfSnapshot()) or {}) do
        print(line)
    end
end
local function PA_PrintDiagnosticMessage(message)
    print("|cffffd100PA Diagnostic:|r " .. tostring(message or ""))
end

local function PA_DiagJoinNotes(notes)
    if type(notes) ~= "table" or #notes <= 0 then
        return ""
    end
    return table.concat(notes, "; ")
end

local function PA_DiagRecursiveFrameCount(rootFrame)
    if not rootFrame then
        return nil
    end
    local seen = {}
    local function count(frame)
        if not frame or seen[frame] then
            return 0
        end
        seen[frame] = true
        local total = 1
        for i = 1, select("#", frame:GetChildren()) do
            total = total + count(select(i, frame:GetChildren()))
        end
        return total
    end
    return count(rootFrame)
end

local function PA_DiagFindSettingsPanelInfo(snapshot, panelKey)
    local panels = snapshot and snapshot.panels or nil
    if type(panels) ~= "table" then
        return nil
    end
    for i = 1, #panels do
        local entry = panels[i]
        if entry and entry.key == panelKey then
            return entry
        end
    end
    return nil
end

local function PA_DiagNormalizePanelKey(panelKey)
    if type(panelKey) ~= "string" then
        return nil
    end
    panelKey = trim(panelKey):lower()
    for i = 1, #PA_DIAG_WALK_ORDER do
        if PA_DIAG_WALK_ORDER[i] == panelKey then
            return panelKey
        end
    end
    return nil
end

local function PA_DiagBuildCharacterLabel()
    local name = UnitName and UnitName("player") or nil
    local realm = GetRealmName and GetRealmName() or nil
    name = trim(tostring(name or "Unknown"))
    realm = trim(tostring(realm or "Unknown"))
    if realm == "" then
        return name
    end
    return string.format("%s-%s", name, realm)
end

local function PA_DiagBuildWowBuildSnapshot()
    local version, build, buildDate, tocVersion = GetBuildInfo()
    return {
        version = version,
        build = build,
        buildDate = buildDate,
        tocVersion = tocVersion,
    }
end

local function PA_DiagBuildSpecSnapshot()
    local specIndex = GetSpecialization and GetSpecialization() or nil
    local specID, specName = nil, nil
    if type(specIndex) == "number" and GetSpecializationInfo then
        specID, specName = GetSpecializationInfo(specIndex)
    end
    return {
        index = specIndex,
        id = specID,
        name = specName,
    }
end

local function PA_DiagBuildClassSnapshot()
    local localized, english = nil, nil
    if UnitClass then
        localized, english = UnitClass("player")
    end
    return {
        localized = localized,
        english = english,
    }
end

function PortalAuthority:GetSettingsPanelWalkOrder()
    if type(self.settingsPanelWalkOrder) == "table" and #self.settingsPanelWalkOrder > 0 then
        local copy = {}
        for i = 1, #self.settingsPanelWalkOrder do
            copy[#copy + 1] = tostring(self.settingsPanelWalkOrder[i])
        end
        return copy
    end
    local copy = {}
    for i = 1, #PA_DIAG_WALK_ORDER do
        copy[#copy + 1] = PA_DIAG_WALK_ORDER[i]
    end
    return copy
end

function PortalAuthority:GetSettingsPanelRegistry()
    if type(self.settingsPanelRegistry) == "table" then
        return self.settingsPanelRegistry
    end

    local registry = {}
    local panels = self._settingsFirstOpenDebugPanels
    if type(panels) == "table" then
        for i = 1, #panels do
            local entry = panels[i]
            local key = entry and entry.key or nil
            if type(key) == "string" and key ~= "" then
                registry[key] = {
                    key = key,
                    name = entry.name,
                    panel = entry.panel,
                }
            end
        end
    end

    if registry.root then
        registry.root.categoryID = self.rootCategoryID
    end
    local rootFallbackCategoryID = self.defaultCategoryID or self.rootCategoryID
    if registry.announcements then
        registry.announcements.categoryID = rootFallbackCategoryID
    end
    if registry.dock then
        registry.dock.categoryID = rootFallbackCategoryID
    end
    if registry.timers then
        registry.timers.categoryID = rootFallbackCategoryID
    end
    if registry.interrupt then
        registry.interrupt.categoryID = rootFallbackCategoryID
    end
    if registry.combat then
        registry.combat.categoryID = rootFallbackCategoryID
    end
    if registry.keystone then
        registry.keystone.categoryID = rootFallbackCategoryID
    end
    if registry.profiles then
        registry.profiles.categoryID = rootFallbackCategoryID
    end

    return registry
end

function PortalAuthority:GetDiagHostSurfaceName()
    if self:IsSettingsWindowHostEnabled() then
        return "custom-settings-window"
    end
    return "blizzard-settings"
end

function PortalAuthority:IsDiagDumpCombatBlocked()
    local inCombatLockdown = (InCombatLockdown and InCombatLockdown()) or false
    local isPlayerInCombat = self.IsPlayerInCombat and self:IsPlayerInCombat() or false
    return inCombatLockdown or isPlayerInCombat
end

function PortalAuthority:GetDiagCombatState()
    return {
        inCombatLockdown = (InCombatLockdown and InCombatLockdown()) or false,
        isPlayerInCombat = self.IsPlayerInCombat and self:IsPlayerInCombat() or false,
    }
end

function PortalAuthority:GetDiagCodeRevision()
    if type(self.GetCodeRevision) == "function" then
        local ok, value = pcall(self.GetCodeRevision, self)
        if ok and value ~= nil then
            return value
        end
    end
    if self.codeRevision ~= nil then
        return self.codeRevision
    end
    return nil
end

function PortalAuthority:GetDiagCustomSettingsWindowFrame()
    return self:GetExistingSettingsWindowFrame()
end

function PortalAuthority:IsDiagRelevantSettingsHostVisible()
    return self:IsAnySettingsHostVisible()
end

function PortalAuthority:CloseDiagRelevantSettingsHost()
    local closed = false
    if type(self.CloseSettingsWindow) == "function" then
        local ok, didClose = pcall(self.CloseSettingsWindow, self)
        if ok and didClose then
            closed = true
        end
    end
    local customFrame = self:GetDiagCustomSettingsWindowFrame()
    if customFrame and customFrame.IsShown and customFrame:IsShown() and customFrame.Hide then
        customFrame:Hide()
        closed = true
    end

    if Settings and type(Settings.CloseSettings) == "function" then
        local ok = pcall(Settings.CloseSettings)
        if ok then
            closed = true
        end
    end
    if Settings and type(Settings.Close) == "function" then
        local ok = pcall(Settings.Close)
        if ok then
            closed = true
        end
    end
    if self.HideSettingsPanelForOnboardingD4 then
        self:HideSettingsPanelForOnboardingD4()
        closed = true
    end
    local settingsPanel = self:CpuDiagGetSettingsPanelFrame()
    if settingsPanel and settingsPanel.Hide then
        settingsPanel:Hide()
        closed = true
    end
    return closed
end

function PortalAuthority:OpenDiagHostedSettingsPanel(panelKey)
    panelKey = PA_DiagNormalizePanelKey(panelKey)
    if not panelKey then
        return false, "Diagnostic settings target is unavailable."
    end

    if self:IsSettingsWindowHostEnabled() then
        if panelKey == "root" then
            if type(self.OpenSettingsWindow) == "function" then
                local ok, result = pcall(self.OpenSettingsWindow, self, "root", { source = "diagdump" })
                if ok and result ~= false then
                    return true
                end
                local runtime = self._settingsWindowRuntime
                return false, tostring((runtime and runtime.lastError) or "Settings host is unavailable.")
            end
            return false, "Settings host is unavailable."
        end
        if type(self.OpenSettingsWindowToSection) == "function" then
            local ok, result = pcall(self.OpenSettingsWindowToSection, self, panelKey)
            if ok and result ~= false then
                return true
            end
            local runtime = self._settingsWindowRuntime
            return false, tostring((runtime and runtime.lastError) or "Settings host is unavailable.")
        end
        return false, "Settings host is unavailable."
    end

    local registry = self:GetSettingsPanelRegistry()
    local entry = registry and registry[panelKey] or nil
    local categoryID = entry and entry.categoryID or nil
    if panelKey == "announcements" and type(categoryID) ~= "number" then
        categoryID = self.defaultCategoryID
    elseif panelKey == "root" and type(categoryID) ~= "number" then
        categoryID = self.rootCategoryID
    end
    return self:OpenSettings(categoryID)
end

function PortalAuthority:GetDiagActiveHostRootFrame()
    if self:IsSettingsWindowHostEnabled() then
        return self:GetDiagCustomSettingsWindowFrame()
    end
    return self:CpuDiagGetSettingsPanelFrame()
end

function PortalAuthority:MeasureHostedSettingsPanel(panelKey)
    panelKey = PA_DiagNormalizePanelKey(panelKey)
    local registry = self:GetSettingsPanelRegistry()
    local entry = registry and registry[panelKey] or nil
    local panel = entry and entry.panel or nil
    local measurement = {
        key = panelKey,
        hasScrollChild = false,
        scrollWidth = nil,
        scrollChildTop = nil,
        firstElement = nil,
        notes = "",
    }
    if not panel then
        measurement.notes = "panel missing"
        return measurement
    end
    if not panel.IsShown or not panel:IsShown() then
        measurement.notes = "panel hidden"
        return measurement
    end

    local sizeTarget = panel._settingsFirstOpenSizeTarget or panel._sizingFrame or panel
    local scrollChild = sizeTarget and sizeTarget.GetScrollChild and sizeTarget:GetScrollChild() or nil
    if not scrollChild then
        measurement.notes = "no scrollChild"
        return measurement
    end

    measurement.hasScrollChild = true
    measurement.scrollWidth = tonumber(sizeTarget and sizeTarget.GetWidth and sizeTarget:GetWidth()) or nil
    measurement.scrollChildTop = tonumber(scrollChild.GetTop and scrollChild:GetTop()) or nil

    local scrollChildTop = measurement.scrollChildTop
    if type(scrollChildTop) ~= "number" then
        measurement.notes = "scrollChild top unavailable"
        return measurement
    end

    local viewportTop = tonumber(sizeTarget and sizeTarget.GetTop and sizeTarget:GetTop()) or scrollChildTop
    local viewportBottom = tonumber(sizeTarget and sizeTarget.GetBottom and sizeTarget:GetBottom()) or nil
    if type(viewportBottom) ~= "number" then
        local viewportHeight = tonumber(sizeTarget and sizeTarget.GetHeight and sizeTarget:GetHeight()) or 0
        viewportBottom = viewportTop - viewportHeight
    end
    if viewportTop < viewportBottom then
        viewportTop, viewportBottom = viewportBottom, viewportTop
    end

    local function stripColorCodes(text)
        if type(text) ~= "string" then
            return nil
        end
        local cleaned = text:gsub("|c%x%x%x%x%x%x%x%x", ""):gsub("|r", "")
        cleaned = cleaned:match("^%s*(.-)%s*$") or ""
        if cleaned == "" then
            return nil
        end
        return cleaned
    end

    local function getObjectIdentity(obj)
        local objectType = obj and obj.GetObjectType and obj:GetObjectType() or "?"
        local text = stripColorCodes(obj and obj.GetText and obj:GetText() or nil)
        local name = obj and obj.GetName and obj:GetName() or nil
        if type(name) == "string" then
            name = name:match("^%s*(.-)%s*$") or ""
            if name == "" then
                name = nil
            end
        else
            name = nil
        end
        local label = text or name or "<unnamed>"
        return objectType, label, (text ~= nil or name ~= nil)
    end

    local function intersectsClip(obj, clipTop, clipBottom)
        if not obj or (obj.IsShown and not obj:IsShown()) or not obj.GetTop or not obj.GetBottom then
            return nil
        end
        local top = obj:GetTop()
        local bottom = obj:GetBottom()
        if not top or not bottom then
            return nil
        end
        if bottom > clipTop or top < clipBottom then
            return nil
        end
        local visibleTop = math.min(top, clipTop)
        local visibleBottom = math.max(bottom, clipBottom)
        if (visibleTop - visibleBottom) < 2 then
            return nil
        end
        return top, bottom, visibleTop, visibleBottom
    end

    local function betterDirectCandidate(candidate, incumbent)
        if not incumbent then
            return true
        end
        if candidate.visibleTop > incumbent.visibleTop + 0.5 then
            return true
        end
        if math.abs(candidate.visibleTop - incumbent.visibleTop) > 0.5 then
            return false
        end
        if candidate.priority ~= incumbent.priority then
            return candidate.priority > incumbent.priority
        end
        if math.abs(candidate.left - incumbent.left) > 0.5 then
            return candidate.left < incumbent.left
        end
        return candidate.order < incumbent.order
    end

    local directBest = nil
    local directOrder = 0
    local function considerDirect(obj)
        local top, bottom, visibleTop = intersectsClip(obj, viewportTop, viewportBottom)
        if not top then
            return
        end
        directOrder = directOrder + 1
        local objectType = obj.GetObjectType and obj:GetObjectType() or ""
        local priority = (objectType == "FontString" and 5)
            or ((objectType == "Button" or objectType == "CheckButton" or objectType == "EditBox" or objectType == "Slider" or objectType == "Frame") and 4)
            or (objectType == "Texture" and 1)
            or 0
        if priority <= 0 then
            return
        end
        local candidate = {
            obj = obj,
            top = top,
            bottom = bottom,
            visibleTop = visibleTop,
            left = tonumber(obj.GetLeft and obj:GetLeft()) or 0,
            priority = priority,
            order = directOrder,
        }
        if betterDirectCandidate(candidate, directBest) then
            directBest = candidate
        end
    end

    for i = 1, select("#", scrollChild:GetRegions()) do
        considerDirect(select(i, scrollChild:GetRegions()))
    end
    for i = 1, select("#", scrollChild:GetChildren()) do
        considerDirect(select(i, scrollChild:GetChildren()))
    end

    if not directBest then
        measurement.notes = "no candidate element"
        return measurement
    end

    local clipTop = math.min(viewportTop, directBest.top)
    local clipBottom = math.max(viewportBottom, directBest.bottom)
    local visitOrder = 0
    local meaningfulBest = nil
    local fallbackBest = nil

    local function candidatePriority(objectType, meaningful)
        if meaningful then
            if objectType == "FontString" then
                return 6
            end
            if objectType == "Button" or objectType == "CheckButton" or objectType == "EditBox" or objectType == "Slider" then
                return 5
            end
            if objectType == "Frame" then
                return 4
            end
            if objectType == "Texture" then
                return 1
            end
            return 0
        end
        if objectType == "Frame" or objectType == "Button" or objectType == "CheckButton" or objectType == "EditBox" or objectType == "Slider" then
            return 3
        end
        if objectType == "Texture" then
            return 1
        end
        return 0
    end

    local function betterRecursiveCandidate(candidate, incumbent)
        if not incumbent then
            return true
        end
        if candidate.visibleTop > incumbent.visibleTop + 0.5 then
            return true
        end
        if math.abs(candidate.visibleTop - incumbent.visibleTop) > 0.5 then
            return false
        end
        if candidate.priority ~= incumbent.priority then
            return candidate.priority > incumbent.priority
        end
        if candidate.depth ~= incumbent.depth then
            return candidate.depth < incumbent.depth
        end
        if math.abs(candidate.left - incumbent.left) > 0.5 then
            return candidate.left < incumbent.left
        end
        local candidateKey = tostring(candidate.label or "") .. ":" .. tostring(candidate.type or "")
        local incumbentKey = tostring(incumbent.label or "") .. ":" .. tostring(incumbent.type or "")
        if candidateKey ~= incumbentKey then
            return candidateKey < incumbentKey
        end
        return candidate.order < incumbent.order
    end

    local function considerRecursive(obj, depth)
        local top, bottom, visibleTop = intersectsClip(obj, clipTop, clipBottom)
        if not top then
            return
        end
        visitOrder = visitOrder + 1
        local objectType, label, meaningful = getObjectIdentity(obj)
        local priority = candidatePriority(objectType, meaningful)
        if priority <= 0 then
            return
        end
        local candidate = {
            obj = obj,
            type = objectType,
            label = label,
            meaningful = meaningful,
            top = top,
            bottom = bottom,
            visibleTop = visibleTop,
            left = tonumber(obj.GetLeft and obj:GetLeft()) or 0,
            priority = priority,
            depth = depth or 0,
            order = visitOrder,
        }
        if meaningful then
            if betterRecursiveCandidate(candidate, meaningfulBest) then
                meaningfulBest = candidate
            end
            return
        end
        if betterRecursiveCandidate(candidate, fallbackBest) then
            fallbackBest = candidate
        end
    end

    local function visitVisibleTree(obj, depth)
        considerRecursive(obj, depth)
        if not obj or not obj.GetObjectType then
            return
        end
        local objectType = obj:GetObjectType()
        if objectType == "FontString" or objectType == "Texture" then
            return
        end
        if obj.GetRegions then
            for i = 1, select("#", obj:GetRegions()) do
                visitVisibleTree(select(i, obj:GetRegions()), (depth or 0) + 1)
            end
        end
        if obj.GetChildren then
            for i = 1, select("#", obj:GetChildren()) do
                visitVisibleTree(select(i, obj:GetChildren()), (depth or 0) + 1)
            end
        end
    end

    visitVisibleTree(directBest.obj, 0)

    local best = meaningfulBest or fallbackBest
    if not best then
        measurement.notes = "no candidate element"
        return measurement
    end

    measurement.firstElement = {
        type = best.type,
        label = best.label,
        offsetY = scrollChildTop - (best.top or scrollChildTop),
    }
    if not best.meaningful and best.label == "<unnamed>" then
        measurement.notes = "unnamed fallback candidate"
    end
    return measurement
end

function PortalAuthority:IsDiagPanelMeasurementReady(panelKey)
    panelKey = PA_DiagNormalizePanelKey(panelKey)
    local snapshot = self:BuildCpuDiagSettingsFirstOpenSnapshot()
    local panelInfo = PA_DiagFindSettingsPanelInfo(snapshot, panelKey)
    if not panelInfo then
        return false, "panel untracked"
    end
    if panelInfo.shown ~= true then
        return false, "panel hidden"
    end
    if panelInfo.ready == true then
        return true, nil
    end
    if panelInfo.sizeReady == true then
        return true, nil
    end
    return false, "panel not ready"
end

function PortalAuthority:BuildDiagPreWalkInitStates(cpuDiagSnapshot)
    local allowedKeys = {
        root = true,
        announcements = true,
        dock = true,
        timers = true,
        interrupt = true,
        combat = true,
        keystone = true,
        profiles = true,
    }
    local states = {
        root = nil,
        announcements = nil,
        dock = nil,
        timers = nil,
        interrupt = nil,
        combat = nil,
        keystone = nil,
        profiles = nil,
    }
    local settingsFirstOpen = cpuDiagSnapshot and cpuDiagSnapshot.settingsFirstOpen or nil
    local panels = settingsFirstOpen and settingsFirstOpen.panels or nil
    if type(panels) ~= "table" then
        return states
    end
    for i = 1, #panels do
        local panelInfo = panels[i]
        if panelInfo and type(panelInfo.key) == "string" and allowedKeys[panelInfo.key] then
            states[panelInfo.key] = panelInfo.initialized == true
        end
    end
    return states
end

function PortalAuthority:BuildDiagDumpPayload(phase)
    local nowTimestamp = nil
    if type(date) == "function" then
        local ok, value = pcall(date, "%Y-%m-%dT%H:%M:%S")
        if ok then
            nowTimestamp = value
        end
    end
    local cpuDiagSnapshot = self:BuildCpuDiagStatusSnapshot()
    local perfSnapshot = self:BuildPerfSnapshot()
    return {
        phase = tostring(phase or ""),
        timestamp = nowTimestamp,
        addonVersion = PA_GetAddonVersionString(),
        wowBuild = PA_DiagBuildWowBuildSnapshot(),
        character = PA_DiagBuildCharacterLabel(),
        class = PA_DiagBuildClassSnapshot(),
        spec = PA_DiagBuildSpecSnapshot(),
        diagGate = self:IsDiagDumpEnabled(),
        settingsWindowDevGate = self:IsSettingsWindowDevGateEnabled(),
        settingsWindowPublicGate = self:IsSettingsWindowPublicGateEnabled(),
        hostSurface = self:GetDiagHostSurfaceName(),
        walkDriver = self:GetDiagHostSurfaceName(),
        walkStartTarget = "root",
        walkOrder = self:GetSettingsPanelWalkOrder(),
        codeRevision = self:GetDiagCodeRevision(),
        interrupted = false,
        interruptReason = nil,
        completedPanels = {},
        skippedPanels = {},
        perfSnapshot = perfSnapshot,
        perfSnapshotRendered = table.concat(self:RenderPerfSnapshotLines(perfSnapshot) or {}, "\n"),
        preWalkCpuDiagSnapshot = cpuDiagSnapshot,
        preWalkInitStates = self:BuildDiagPreWalkInitStates(cpuDiagSnapshot),
        combatState = self:GetDiagCombatState(),
        hostFrameCount = nil,
        settingsPanelFrameCount = nil,
        panels = {},
    }
end

function PortalAuthority:FinalizeDiagDump(runtime, interrupted, interruptReason)
    if type(runtime) ~= "table" or runtime.finalized == true then
        return
    end
    runtime.finalized = true
    if type(runtime.token) == "number" then
        self._diagDumpToken = runtime.token
    end

    local payload = runtime.payload or {}
    payload.interrupted = interrupted == true
    payload.interruptReason = interruptReason
    payload.completedPanels = runtime.completedPanels or {}

    local skippedPanels = {}
    local completedLookup = {}
    for i = 1, #(payload.completedPanels or {}) do
        completedLookup[payload.completedPanels[i]] = true
    end
    for i = 1, #(runtime.walkOrder or {}) do
        local key = runtime.walkOrder[i]
        if not completedLookup[key] then
            skippedPanels[#skippedPanels + 1] = key
        end
    end
    payload.skippedPanels = skippedPanels

    local hostRoot = self:GetDiagActiveHostRootFrame()
    payload.hostFrameCount = PA_DiagRecursiveFrameCount(hostRoot)
    if payload.hostSurface == "blizzard-settings" then
        payload.settingsPanelFrameCount = PA_DiagRecursiveFrameCount(self:CpuDiagGetSettingsPanelFrame())
    else
        payload.settingsPanelFrameCount = nil
    end
    payload.combatState = self:GetDiagCombatState()

    PortalAuthorityDiagDump = payload
    self:CloseDiagRelevantSettingsHost()
    self._diagDumpRuntime = nil

    if interrupted == true and interruptReason == "combat-started" then
        PA_PrintDiagnosticMessage("capture interrupted by combat. Partial data saved.")
        return
    end
    if interrupted == true then
        PA_PrintDiagnosticMessage("capture interrupted. Partial data saved.")
        return
    end
    PA_PrintDiagnosticMessage("capture complete. Reload to flush SavedVariables.")
end

function PortalAuthority:AdvanceDiagDump(runtime, panelIndex, attempt)
    if type(runtime) ~= "table" or runtime.finalized == true then
        return
    end
    if runtime.token ~= self._diagDumpToken then
        return
    end
    if self:IsDiagDumpCombatBlocked() then
        self:FinalizeDiagDump(runtime, true, "combat-started")
        return
    end

    local walkOrder = runtime.walkOrder or PA_DIAG_WALK_ORDER
    local key = walkOrder[panelIndex]
    if key == nil then
        self:FinalizeDiagDump(runtime, false, nil)
        return
    end

    local normalizedAttempt = math.max(1, tonumber(attempt) or 1)
    if normalizedAttempt == 1 then
        local preSnapshot = self:BuildCpuDiagSettingsFirstOpenSnapshot()
        local preInfo = PA_DiagFindSettingsPanelInfo(preSnapshot, key)
        runtime.payload.panels[key] = runtime.payload.panels[key] or {
            preShowInit = preInfo and preInfo.initialized or nil,
            postShowInit = nil,
            hasScrollChild = nil,
            scrollWidth = nil,
            scrollChildTop = nil,
            firstElement = nil,
            notes = "",
        }
        local opened, openErr = self:OpenDiagHostedSettingsPanel(key)
        if not opened then
            runtime.payload.panels[key].notes = tostring(openErr or "open failed")
            runtime.completedPanels[#runtime.completedPanels + 1] = key
            if C_Timer and C_Timer.After then
                C_Timer.After(0, function()
                    if runtime.token == self._diagDumpToken and runtime.finalized ~= true then
                        self:AdvanceDiagDump(runtime, panelIndex + 1, 1)
                    end
                end)
            else
                self:AdvanceDiagDump(runtime, panelIndex + 1, 1)
            end
            return
        end
    end

    local ready, readyReason = self:IsDiagPanelMeasurementReady(key)
    if not ready and normalizedAttempt < PA_DIAG_PANEL_MAX_ATTEMPTS then
        if C_Timer and C_Timer.After then
            C_Timer.After(PA_DIAG_PANEL_RETRY_DELAY, function()
                if runtime.token == self._diagDumpToken and runtime.finalized ~= true then
                    self:AdvanceDiagDump(runtime, panelIndex, normalizedAttempt + 1)
                end
            end)
        else
            self:AdvanceDiagDump(runtime, panelIndex, normalizedAttempt + 1)
        end
        return
    end

    local measurement = self:MeasureHostedSettingsPanel(key)
    local postSnapshot = self:BuildCpuDiagSettingsFirstOpenSnapshot()
    local postInfo = PA_DiagFindSettingsPanelInfo(postSnapshot, key)
    local panelPayload = runtime.payload.panels[key] or {}
    panelPayload.postShowInit = postInfo and postInfo.initialized or nil
    panelPayload.hasScrollChild = measurement.hasScrollChild
    panelPayload.scrollWidth = measurement.scrollWidth
    panelPayload.scrollChildTop = measurement.scrollChildTop
    panelPayload.firstElement = measurement.firstElement

    local notes = {}
    if not ready and readyReason then
        notes[#notes + 1] = tostring(readyReason)
    end
    if measurement.notes and measurement.notes ~= "" then
        notes[#notes + 1] = tostring(measurement.notes)
    end
    panelPayload.notes = PA_DiagJoinNotes(notes)
    runtime.payload.panels[key] = panelPayload
    runtime.completedPanels[#runtime.completedPanels + 1] = key

    if C_Timer and C_Timer.After then
        C_Timer.After(PA_DIAG_PANEL_SETTLE_DELAY, function()
            if runtime.token == self._diagDumpToken and runtime.finalized ~= true then
                self:AdvanceDiagDump(runtime, panelIndex + 1, 1)
            end
        end)
    else
        self:AdvanceDiagDump(runtime, panelIndex + 1, 1)
    end
end

function PortalAuthority:StartDiagDump(phase)
    local normalizedPhase = trim(tostring(phase or ""))
    if normalizedPhase == "" then
        PA_PrintDiagnosticMessage("usage: /pa diagdump <phase>")
        return false
    end
    if not self:IsDiagDumpEnabled() then
        PA_PrintDiagnosticMessage("unavailable in this build.")
        return false
    end
    if self._diagDumpRuntime and self._diagDumpRuntime.finalized ~= true then
        PA_PrintDiagnosticMessage("capture already in progress.")
        return false
    end
    if self:IsDiagDumpCombatBlocked() then
        PA_PrintDiagnosticMessage("capture unavailable during combat.")
        return false
    end
    if self:IsDiagRelevantSettingsHostVisible() then
        self:CloseDiagRelevantSettingsHost()
        if self:IsDiagRelevantSettingsHostVisible() then
            PA_PrintDiagnosticMessage("close settings before running diagdump.")
            return false
        end
    end

    self._diagDumpToken = (tonumber(self._diagDumpToken) or 0) + 1
    local runtime = {
        token = self._diagDumpToken,
        finalized = false,
        walkOrder = self:GetSettingsPanelWalkOrder(),
        completedPanels = {},
        payload = self:BuildDiagDumpPayload(normalizedPhase),
    }
    self._diagDumpRuntime = runtime

    if C_Timer and C_Timer.After then
        C_Timer.After(0, function()
            if runtime.token == self._diagDumpToken and runtime.finalized ~= true then
                self:AdvanceDiagDump(runtime, 1, 1)
            end
        end)
    else
        self:AdvanceDiagDump(runtime, 1, 1)
    end
    return true
end

PortalAuthority.KeystoneUtility = PortalAuthority.KeystoneUtility or {}
local PA_KeystoneIsSlotted
local PA_SafeNumber
