GuildHelper = GuildHelper or {}

local addon = GuildHelper
local frame = CreateFrame("Frame")
local GUILD_ROSTER_UPDATE_DEBOUNCE_SECONDS = 0.35
local GUILD_ROSTER_UPDATE_MIN_INTERVAL_SECONDS = 1.0
local MYTHIC_AFFIX_REFRESH_DEBOUNCE_SECONDS = 0.5
local MYTHIC_AFFIX_REFRESH_MIN_INTERVAL_SECONDS = 30
local MYTHIC_BACKGROUND_REFRESH_INTERVAL_SECONDS = 2.0
local pendingGuildRosterUpdateGeneration = 0
local lastGuildRosterProcessAt = 0
local pendingMythicAffixRefreshGeneration = 0
local mythicAffixRefreshScheduled = false
local mythicAffixEventRegistered = false
local mythicAffixReregisterScheduled = false
local lastMythicAffixRefreshAt = 0
local mythicBackgroundRefreshElapsed = 0

local function beginPerfScope(scopeName)
    if addon.BeginPerfScope then
        return addon:BeginPerfScope(scopeName)
    end

    return nil
end

local function endPerfScope(scopeName, startedAt)
    if startedAt ~= nil and addon.EndPerfScope then
        addon:EndPerfScope(scopeName, startedAt)
    end
end

local function getEventClockSeconds()
    if type(GetTime) == "function" then
        return tonumber(GetTime()) or 0
    end

    return tonumber(time()) or 0
end

local function canProcessEssentialLiveEvent()
    return addon.initialized
        and addon.Store
        and addon.Store.IsReady
        and addon.Store:IsReady()
        and not (addon.IsSuspended and addon:IsSuspended())
end

local function canProcessNonEssentialLiveEvent()
    return canProcessEssentialLiveEvent()
        and not (addon.IsInstanceFeatureSuspended and addon:IsInstanceFeatureSuspended())
end

local function processGuildRosterUpdate()
    local perfScopeName = "core:process-guild-roster-update"
    local perfStartedAt = beginPerfScope(perfScopeName)

    if not canProcessNonEssentialLiveEvent() then
        endPerfScope(perfScopeName, perfStartedAt)
        return
    end

    lastGuildRosterProcessAt = getEventClockSeconds()

    addon.GratsUService:HandleGuildRosterUpdate()
    addon.RosterService:CaptureGuildRoster()

    if addon.Reconciler and addon.Reconciler.ScheduleLocalStatusCacheWarm then
        addon.Reconciler:ScheduleLocalStatusCacheWarm(0.05)
    end

    if addon.MaintenanceService and addon.MaintenanceService.MarkRosterScanDirty then
        addon.MaintenanceService:MarkRosterScanDirty()
    else
        addon.MaintenanceService:ScanRoster()
    end

    addon.MaintenanceService:HandleRecruiterRosterUpdate()

    if addon:IsFeatureEnabled("groups") then
        addon.GroupsService:HandleGuildRosterUpdate()
    end

    if addon.MainFrame and addon.MainFrame.MarkBackgroundRefreshPending then
        addon.MainFrame:MarkBackgroundRefreshPending()
    end

    endPerfScope(perfScopeName, perfStartedAt)
end

local function scheduleGuildRosterUpdateProcessing()
    pendingGuildRosterUpdateGeneration = pendingGuildRosterUpdateGeneration + 1
    local expectedGeneration = pendingGuildRosterUpdateGeneration
    local delaySeconds = GUILD_ROSTER_UPDATE_DEBOUNCE_SECONDS
    local now = getEventClockSeconds()

    if lastGuildRosterProcessAt > 0 then
        delaySeconds = math.max(delaySeconds, (lastGuildRosterProcessAt + GUILD_ROSTER_UPDATE_MIN_INTERVAL_SECONDS) - now)
    end

    if not (C_Timer and C_Timer.After) then
        processGuildRosterUpdate()
        return
    end

    C_Timer.After(math.max(0, delaySeconds), function()
        if expectedGeneration ~= pendingGuildRosterUpdateGeneration then
            return
        end

        processGuildRosterUpdate()
    end)
end

local function processScheduledMythicAffixRefresh(expectedGeneration)
    local perfScopeName = "mythics:process-affix-update"
    local perfStartedAt = beginPerfScope(perfScopeName)

    if expectedGeneration ~= pendingMythicAffixRefreshGeneration then
        endPerfScope(perfScopeName, perfStartedAt)
        return
    end

    mythicAffixRefreshScheduled = false

    if not (addon.initialized and canProcessEssentialLiveEvent() and addon:IsFeatureEnabled("mythics") and addon.MythicPlusService and addon.MythicPlusService.RefreshCurrentCharacter) then
        endPerfScope(perfScopeName, perfStartedAt)
        return
    end

    local now = getEventClockSeconds()

    if lastMythicAffixRefreshAt > 0 and (now - lastMythicAffixRefreshAt) < MYTHIC_AFFIX_REFRESH_MIN_INTERVAL_SECONDS then
        local remainingDelay = math.max(MYTHIC_AFFIX_REFRESH_DEBOUNCE_SECONDS, (lastMythicAffixRefreshAt + MYTHIC_AFFIX_REFRESH_MIN_INTERVAL_SECONDS) - now)
        pendingMythicAffixRefreshGeneration = pendingMythicAffixRefreshGeneration + 1
        local nextGeneration = pendingMythicAffixRefreshGeneration
        mythicAffixRefreshScheduled = true

        if C_Timer and C_Timer.After then
            C_Timer.After(remainingDelay, function()
                processScheduledMythicAffixRefresh(nextGeneration)
            end)
        else
            mythicAffixRefreshScheduled = false
        end

        endPerfScope(perfScopeName, perfStartedAt)
        return
    end

    lastMythicAffixRefreshAt = now

    local changed = addon.MythicPlusService:RefreshCurrentCharacter(true)

    if changed and addon.Reconciler and addon.Reconciler.BroadcastGroupStatus then
        local suppressNonEssentialInInstance = addon.IsInstanceFeatureSuspended and addon:IsInstanceFeatureSuspended()

        if not suppressNonEssentialInInstance then
            addon.Reconciler:BroadcastGroupStatus()
        end
    end

    if changed and addon.MainFrame and addon.MainFrame.MarkBackgroundRefreshPending then
        addon.MainFrame:MarkBackgroundRefreshPending()
    end

    endPerfScope(perfScopeName, perfStartedAt)
end

local function registerMythicAffixUpdateEvent()
    if mythicAffixEventRegistered then
        return
    end

    frame:RegisterEvent("MYTHIC_PLUS_CURRENT_AFFIX_UPDATE")
    mythicAffixEventRegistered = true
end

local function unregisterMythicAffixUpdateEvent()
    if not mythicAffixEventRegistered then
        return
    end

    frame:UnregisterEvent("MYTHIC_PLUS_CURRENT_AFFIX_UPDATE")
    mythicAffixEventRegistered = false
end

local function scheduleMythicAffixEventReregister(delaySeconds)
    if mythicAffixEventRegistered or mythicAffixReregisterScheduled then
        return
    end

    mythicAffixReregisterScheduled = true

    local function reregister()
        mythicAffixReregisterScheduled = false
        registerMythicAffixUpdateEvent()
    end

    if C_Timer and C_Timer.After then
        C_Timer.After(math.max(MYTHIC_AFFIX_REFRESH_MIN_INTERVAL_SECONDS, tonumber(delaySeconds) or 0), reregister)
    else
        reregister()
    end
end

local function scheduleMythicAffixRefresh()
    if mythicAffixRefreshScheduled then
        return
    end

    pendingMythicAffixRefreshGeneration = pendingMythicAffixRefreshGeneration + 1
    local expectedGeneration = pendingMythicAffixRefreshGeneration
    mythicAffixRefreshScheduled = true
    unregisterMythicAffixUpdateEvent()
    scheduleMythicAffixEventReregister(MYTHIC_AFFIX_REFRESH_MIN_INTERVAL_SECONDS)

    if C_Timer and C_Timer.After then
        C_Timer.After(MYTHIC_AFFIX_REFRESH_DEBOUNCE_SECONDS, function()
            processScheduledMythicAffixRefresh(expectedGeneration)
        end)
    else
        processScheduledMythicAffixRefresh(expectedGeneration)
    end
end

frame:RegisterEvent("ADDON_LOADED")
frame:RegisterEvent("PLAYER_LOGIN")
frame:RegisterEvent("PLAYER_ENTERING_WORLD")
frame:RegisterEvent("ZONE_CHANGED_NEW_AREA")
frame:RegisterEvent("GUILD_ROSTER_UPDATE")
frame:RegisterEvent("GUILD_NEWS_UPDATE")
frame:RegisterEvent("CHAT_MSG_GUILD_ACHIEVEMENT")
frame:RegisterEvent("CHAT_MSG_LOOT")
frame:RegisterEvent("CHAT_MSG_SYSTEM")
frame:RegisterEvent("UI_ERROR_MESSAGE")
frame:RegisterEvent("CHAT_MSG_ADDON")
frame:RegisterEvent("ADDON_ACTION_BLOCKED")
frame:RegisterEvent("ADDON_ACTION_FORBIDDEN")
frame:RegisterEvent("GROUP_ROSTER_UPDATE")
frame:RegisterEvent("PLAYER_EQUIPMENT_CHANGED")
frame:RegisterEvent("BAG_UPDATE_DELAYED")
frame:RegisterEvent("ITEM_LOCK_CHANGED")
frame:RegisterEvent("CHALLENGE_MODE_START")
frame:RegisterEvent("CHALLENGE_MODE_COMPLETED")
frame:RegisterEvent("CHALLENGE_MODE_MAPS_UPDATE")
frame:RegisterEvent("CHALLENGE_MODE_KEYSTONE_RECEPTABLE_OPEN")
registerMythicAffixUpdateEvent()
frame:RegisterEvent("PLAYER_REGEN_DISABLED")
frame:RegisterEvent("PLAYER_REGEN_ENABLED")
frame:RegisterEvent("TRADE_SHOW")
frame:RegisterEvent("TRADE_CLOSED")
frame:RegisterEvent("TRADE_ACCEPT_UPDATE")
frame:RegisterEvent("TRADE_PLAYER_ITEM_CHANGED")
frame:RegisterEvent("TRADE_TARGET_ITEM_CHANGED")
frame:RegisterEvent("WEEKLY_REWARDS_UPDATE")
frame:RegisterEvent("WHO_LIST_UPDATE")

frame:SetScript("OnUpdate", function(_, elapsedSeconds)
    mythicBackgroundRefreshElapsed = mythicBackgroundRefreshElapsed + math.max(0, tonumber(elapsedSeconds) or 0)

    if mythicBackgroundRefreshElapsed < MYTHIC_BACKGROUND_REFRESH_INTERVAL_SECONDS then
        return
    end

    mythicBackgroundRefreshElapsed = 0

    if not canProcessEssentialLiveEvent() or not addon:IsFeatureEnabled("mythics") then
        return
    end

    if not (addon.MythicPlusService and addon.MythicPlusService.AutoRefreshLiveData) then
        return
    end

    if addon.MythicPlusService.IsChallengeModeActive and addon.MythicPlusService:IsChallengeModeActive() then
        return
    end

    local changed = addon.MythicPlusService:AutoRefreshLiveData() and true or false

    if changed then
        local suppressNonEssentialInInstance = addon.IsInstanceFeatureSuspended and addon:IsInstanceFeatureSuspended()

        if not suppressNonEssentialInInstance and addon.Reconciler and addon.Reconciler.BroadcastGroupStatus then
            addon.Reconciler:BroadcastGroupStatus()
        end

        if addon.MainFrame and addon.MainFrame.MarkBackgroundRefreshPending then
            addon.MainFrame:MarkBackgroundRefreshPending()
        end
    end
end)

frame:SetScript("OnEvent", function(_, event, ...)
    local eventPerfScopeName = "event:" .. tostring(event or "unknown")
    local eventPerfStartedAt = beginPerfScope(eventPerfScopeName)

    if event == "ADDON_LOADED" then
        local addonName = ...

        if addonName == "GuildHelper" or addonName == "GH3" then
            addon:SetLoadedAddonName(addonName)
            addon:Initialize()
        end
    elseif event == "MYTHIC_PLUS_CURRENT_AFFIX_UPDATE" then
        scheduleMythicAffixRefresh()
    elseif event == "PLAYER_REGEN_DISABLED" then
        if addon.initialized then
            addon:EnterCombatSuspend()
        end
    elseif event == "PLAYER_LOGIN" then
        if canProcessEssentialLiveEvent() then
            if addon.RefreshInstanceFeatureSuspension then
                addon:RefreshInstanceFeatureSuspension()
            end

            local suppressNonEssentialInInstance = addon.IsInstanceFeatureSuspended and addon:IsInstanceFeatureSuspended()

            addon.Store:EnsureHomeGuild()

            if not suppressNonEssentialInInstance then
                addon.RosterService:CaptureGuildRoster()

                if addon.RosterService and addon.RosterService.RefreshGuildJoinDatesFromNews then
                    addon.RosterService:RefreshGuildJoinDatesFromNews(true)
                end

                if addon.MaintenanceService and addon.MaintenanceService.MarkRosterScanDirty then
                    addon.MaintenanceService:MarkRosterScanDirty()
                else
                    addon.MaintenanceService:ScanRoster()
                end

                addon.MaintenanceService:HandleRecruiterRosterUpdate()
                addon.GratsUService:HandlePlayerLogin()
                addon.ToonCelebrationService:HandlePlayerLogin()
                if addon:IsFeatureEnabled("groups") then
                    addon.GroupsService:HandlePlayerLogin()
                end
            end

            if addon:IsFeatureEnabled("bis") and addon.BISService and addon.BISService.EnsureCurrentInventoryScan then
                addon.BISService:EnsureCurrentInventoryScan({ force = true })
            end

            if not suppressNonEssentialInInstance and not addon.Reconciler:IsManualOnlySync() then
                addon.Reconciler:RequestGuildStatus()
            end

            if addon.MainFrame and addon.MainFrame.MarkBackgroundRefreshPending then
                addon.MainFrame:MarkBackgroundRefreshPending()
            end
        end
    elseif event == "PLAYER_ENTERING_WORLD" or event == "ZONE_CHANGED_NEW_AREA" then
        if addon.initialized and addon.RefreshInstanceFeatureSuspension then
            addon:RefreshInstanceFeatureSuspension()
        end

        if addon.initialized and addon:IsFeatureEnabled("mythics") and addon.MythicPlusService and addon.MythicPlusService.HandleWorldStateChanged then
            addon.MythicPlusService:HandleWorldStateChanged(event)
        end
    elseif event == "GUILD_ROSTER_UPDATE" then
        if canProcessNonEssentialLiveEvent() then
            scheduleGuildRosterUpdateProcessing()
        end
    elseif event == "GUILD_NEWS_UPDATE" then
        if canProcessNonEssentialLiveEvent() then
            if addon.RosterService and addon.RosterService.HandleGuildNewsUpdate then
                local changed = addon.RosterService:HandleGuildNewsUpdate()

                if changed and addon.MainFrame and addon.MainFrame.MarkBackgroundRefreshPending then
                    addon.MainFrame:MarkBackgroundRefreshPending()
                end
            end
        end
    elseif event == "CHAT_MSG_GUILD_ACHIEVEMENT" then
        if canProcessNonEssentialLiveEvent() then
            addon.GratsUService:HandleGuildAchievement(...)
        end
    elseif event == "CHAT_MSG_LOOT" then
        if canProcessEssentialLiveEvent() then
            if addon:IsFeatureEnabled("mythics") and addon.MythicPlusService and addon.MythicPlusService.HandleLootMessage then
                addon.MythicPlusService:HandleLootMessage(...)
            end

            if addon:IsFeatureEnabled("bis") and addon.BISService and addon.BISService.HandleLootMessage then
                addon.BISService:HandleLootMessage(...)
            end
        end
    elseif event == "CHAT_MSG_SYSTEM" then
        if canProcessEssentialLiveEvent() then
            if addon:IsFeatureEnabled("mythics") and addon.MythicPlusService and addon.MythicPlusService.HandleSystemMessage then
                local mythicsHandled = addon.MythicPlusService:HandleSystemMessage(...)

                if mythicsHandled and addon.MainFrame and addon.MainFrame.MarkBackgroundRefreshPending then
                    addon.MainFrame:MarkBackgroundRefreshPending()
                end
            end
        end

        if canProcessNonEssentialLiveEvent() then
            if addon.MaintenanceService and addon.MaintenanceService.HandleRecruiterSystemMessage then
                local handled = addon.MaintenanceService:HandleRecruiterSystemMessage(...)

                if handled and addon.MainFrame and addon.MainFrame.MarkBackgroundRefreshPending then
                    addon.MainFrame:MarkBackgroundRefreshPending()
                end
            end
        end
    elseif event == "ADDON_ACTION_BLOCKED" or event == "ADDON_ACTION_FORBIDDEN" then
        if canProcessNonEssentialLiveEvent() then
            if addon.MaintenanceService and addon.MaintenanceService.HandleRecruiterBlockedAction then
                local blockingAddon, blockedFunction = ...
                local handled = addon.MaintenanceService:HandleRecruiterBlockedAction(blockingAddon, blockedFunction, event == "ADDON_ACTION_FORBIDDEN")

                if handled and addon.MainFrame and addon.MainFrame.MarkBackgroundRefreshPending then
                    addon.MainFrame:MarkBackgroundRefreshPending()
                end
            end
        end
    elseif event == "UI_ERROR_MESSAGE" then
        if canProcessNonEssentialLiveEvent() then
            if addon.MaintenanceService and addon.MaintenanceService.HandleRecruiterSystemMessage then
                local _, messageText = ...
                local handled = addon.MaintenanceService:HandleRecruiterSystemMessage(messageText)

                if handled and addon.MainFrame and addon.MainFrame.MarkBackgroundRefreshPending then
                    addon.MainFrame:MarkBackgroundRefreshPending()
                end
            end
        end
    elseif event == "WEEKLY_REWARDS_UPDATE" then
        if canProcessEssentialLiveEvent() then
            if addon:IsFeatureEnabled("bis") and addon.BISService and addon.BISService.HandleWeeklyRewardsUpdate then
                addon.BISService:HandleWeeklyRewardsUpdate()
            end
        end
    elseif event == "WHO_LIST_UPDATE" then
        if canProcessNonEssentialLiveEvent() then
            if addon.MaintenanceService and addon.MaintenanceService.HandleWhoListUpdate then
                local handled = addon.MaintenanceService:HandleWhoListUpdate()

                if handled and addon.MainFrame and addon.MainFrame.MarkBackgroundRefreshPending then
                    addon.MainFrame:MarkBackgroundRefreshPending()
                end
            end
        end
    elseif event == "TRADE_SHOW" then
        if canProcessEssentialLiveEvent() then
            if addon:IsFeatureEnabled("bis") and addon.BISService and addon.BISService.HandleTradeShow then
                addon.BISService:HandleTradeShow()
            end
        end
    elseif event == "TRADE_ACCEPT_UPDATE" then
        if canProcessEssentialLiveEvent() then
            if addon:IsFeatureEnabled("bis") and addon.BISService and addon.BISService.HandleTradeAcceptUpdate then
                addon.BISService:HandleTradeAcceptUpdate(...)
            end
        end
    elseif event == "TRADE_PLAYER_ITEM_CHANGED" or event == "TRADE_TARGET_ITEM_CHANGED" then
        if canProcessEssentialLiveEvent() then
            if addon:IsFeatureEnabled("bis") and addon.BISService and addon.BISService.HandleTradeItemsChanged then
                addon.BISService:HandleTradeItemsChanged()
            end
        end
    elseif event == "TRADE_CLOSED" then
        if canProcessEssentialLiveEvent() then
            if addon:IsFeatureEnabled("bis") and addon.BISService and addon.BISService.HandleTradeClosed then
                addon.BISService:HandleTradeClosed()
            end
        end
    elseif event == "GROUP_ROSTER_UPDATE" then
        if canProcessEssentialLiveEvent() then
            local suppressNonEssentialInInstance = addon.IsInstanceFeatureSuspended and addon:IsInstanceFeatureSuspended()

            if not suppressNonEssentialInInstance and addon:IsFeatureEnabled("raidbingo") then
                addon.RaidBingoService:HandleGroupUpdate()
            end
            if addon:IsFeatureEnabled("mythics") and addon.MythicPlusService and addon.MythicPlusService.RequestOpenRaidPartyKeystoneData then
                addon.MythicPlusService:RequestOpenRaidPartyKeystoneData()
            end
            if not suppressNonEssentialInInstance and addon.Reconciler and addon.Reconciler.BroadcastGroupStatus then
                addon.Reconciler:BroadcastGroupStatus()
            end
            local bisGroupUpdateHandled = addon:IsFeatureEnabled("bis") and addon.BISService and addon.BISService.HandleGroupRosterUpdate and addon.BISService:HandleGroupRosterUpdate() or false
            if not suppressNonEssentialInInstance and addon.Reconciler and addon.Reconciler.HandleGroupRosterUpdate then
                addon.Reconciler:HandleGroupRosterUpdate()
            end

            if addon.NewUIBIS and addon.NewUIBIS.IsDropReviewDialogShown and addon.NewUIBIS:IsDropReviewDialogShown() and addon.NewUIBIS.ShowDropReviewDialog and bisGroupUpdateHandled then
                addon.NewUIBIS:ShowDropReviewDialog()
            elseif not suppressNonEssentialInInstance and addon.MainFrame and addon.MainFrame.IsRaidBingoViewActive and addon.MainFrame:IsRaidBingoViewActive() then
                addon.MainFrame:RefreshCurrentView(true)
            elseif addon.MainFrame and addon.MainFrame.MarkBackgroundRefreshPending then
                addon.MainFrame:MarkBackgroundRefreshPending()
            end
        end
    elseif event == "PLAYER_EQUIPMENT_CHANGED" or event == "BAG_UPDATE_DELAYED" or event == "ITEM_LOCK_CHANGED" or event == "CHALLENGE_MODE_MAPS_UPDATE" then
        if canProcessEssentialLiveEvent() then
            local suppressNonEssentialInInstance = addon.IsInstanceFeatureSuspended and addon:IsInstanceFeatureSuspended()
            local challengeModeActive = addon.MythicPlusService
                and addon.MythicPlusService.IsChallengeModeActive
                and addon.MythicPlusService:IsChallengeModeActive()
                or false

            local mythicsChanged = false

            if (event == "BAG_UPDATE_DELAYED" or event == "ITEM_LOCK_CHANGED" or event == "CHALLENGE_MODE_MAPS_UPDATE") and addon:IsFeatureEnabled("mythics") and addon.MythicPlusService then
                if (event == "ITEM_LOCK_CHANGED" or event == "CHALLENGE_MODE_MAPS_UPDATE") and addon.MythicPlusService.HandleOwnedKeystoneStateChanged then
                    mythicsChanged = addon.MythicPlusService:HandleOwnedKeystoneStateChanged(event) and true or false
                elseif event == "BAG_UPDATE_DELAYED" and addon.MythicPlusService.HandleOwnedKeystoneStateChanged then
                    mythicsChanged = addon.MythicPlusService:HandleOwnedKeystoneStateChanged(event) and true or false
                elseif addon.MythicPlusService.HandleBagUpdateDelayed then
                    mythicsChanged = addon.MythicPlusService:HandleBagUpdateDelayed() and true or false
                elseif not challengeModeActive and addon.MythicPlusService.RefreshCurrentCharacter then
                    mythicsChanged = addon.MythicPlusService:RefreshCurrentCharacter() and true or false
                end

                if mythicsChanged and not suppressNonEssentialInInstance and addon.Reconciler and addon.Reconciler.BroadcastGroupStatus then
                    addon.Reconciler:BroadcastGroupStatus()
                end
            end

            local bisInventoryChanged = false

            if addon:IsFeatureEnabled("bis") and addon.BISService then
                if event == "BAG_UPDATE_DELAYED" and challengeModeActive and addon.BISService.MarkInventoryScanDirty then
                    addon.BISService:MarkInventoryScanDirty()
                elseif addon.BISService.HandleInventoryChanged then
                    bisInventoryChanged = addon.BISService:HandleInventoryChanged() and true or false
                end
            end

            local suppressPassiveRefresh = event == "BAG_UPDATE_DELAYED"
                and challengeModeActive
                and not mythicsChanged
                and not bisInventoryChanged

            if addon:IsFeatureEnabled("bis") and addon.MainFrame and addon.Router and addon.Router.GetCurrentView and addon.Router:GetCurrentView() == "bis" and bisInventoryChanged then
                addon.MainFrame:RefreshCurrentView(true)
            elseif mythicsChanged and addon:IsFeatureEnabled("mythics") and addon.MainFrame and addon.Router and addon.Router.GetCurrentView and addon.Router:GetCurrentView() == "mythics" then
                if addon.MainFrame.MarkBackgroundRefreshPending then
                    addon.MainFrame:MarkBackgroundRefreshPending()
                else
                    addon.MainFrame:RefreshCurrentView(false)
                end
            elseif not suppressPassiveRefresh and addon.MainFrame and addon.MainFrame.MarkBackgroundRefreshPending then
                addon.MainFrame:MarkBackgroundRefreshPending()
            end
        end
    elseif event == "CHALLENGE_MODE_START" then
        if canProcessEssentialLiveEvent() then
            local mythicsChanged = addon:IsFeatureEnabled("mythics")
                and addon.MythicPlusService
                and addon.MythicPlusService.HandleChallengeModeStarted
                and addon.MythicPlusService:HandleChallengeModeStarted(event)
                or false

            if mythicsChanged and addon.MainFrame and addon.MainFrame.MarkBackgroundRefreshPending then
                addon.MainFrame:MarkBackgroundRefreshPending()
            end
        end
    elseif event == "CHALLENGE_MODE_KEYSTONE_RECEPTABLE_OPEN" then
        if canProcessEssentialLiveEvent() then
            local mythicsChanged = addon:IsFeatureEnabled("mythics")
                and addon.MythicPlusService
                and addon.MythicPlusService.HandleKeystoneReceptacleOpen
                and addon.MythicPlusService:HandleKeystoneReceptacleOpen()
                or false

            if mythicsChanged and addon:IsFeatureEnabled("mythics") and addon.MainFrame and addon.Router and addon.Router.GetCurrentView and addon.Router:GetCurrentView() == "mythics" then
                addon.MainFrame:RefreshCurrentView(true)
            elseif addon.MainFrame and addon.MainFrame.MarkBackgroundRefreshPending then
                addon.MainFrame:MarkBackgroundRefreshPending()
            end
        end
    elseif event == "CHALLENGE_MODE_COMPLETED" then
        if canProcessEssentialLiveEvent() then
            local suppressNonEssentialInInstance = addon.IsInstanceFeatureSuspended and addon:IsInstanceFeatureSuspended()

            local mythicsChanged = addon:IsFeatureEnabled("mythics")
                and addon.MythicPlusService
                and addon.MythicPlusService.HandleChallengeModeCompleted
                and addon.MythicPlusService:HandleChallengeModeCompleted()
                or false

            local function refreshMythicsCompletionState()
                if not canProcessEssentialLiveEvent() or not addon:IsFeatureEnabled("mythics") then
                    return
                end

                local followupChanged = addon.MythicPlusService
                    and addon.MythicPlusService.RefreshCurrentCharacter
                    and addon.MythicPlusService:RefreshCurrentCharacter(true)
                    or false

                if followupChanged and not suppressNonEssentialInInstance and addon.Reconciler and addon.Reconciler.BroadcastGroupStatus then
                    addon.Reconciler:BroadcastGroupStatus()
                end

                if addon.MainFrame and addon.Router and addon.Router.GetCurrentView and addon.Router:GetCurrentView() == "mythics" then
                    addon.MainFrame:RefreshCurrentView(true)
                elseif addon.MainFrame and addon.MainFrame.MarkBackgroundRefreshPending then
                    addon.MainFrame:MarkBackgroundRefreshPending()
                end
            end

            if mythicsChanged and not suppressNonEssentialInInstance and addon.Reconciler and addon.Reconciler.BroadcastGroupStatus then
                addon.Reconciler:BroadcastGroupStatus()
            end

            refreshMythicsCompletionState()

            if C_Timer and C_Timer.After then
                C_Timer.After(1.5, refreshMythicsCompletionState)
            end
        end
    elseif event == "PLAYER_REGEN_ENABLED" then
        if addon.initialized then
            addon:ExitCombatSuspend()
        end

        if addon.initialized and addon.MainFrame then
            if addon.MainFrame.pendingInitializeAfterCombat then
                addon.MainFrame.pendingInitializeAfterCombat = false
                addon.MainFrame:Initialize()
            end

            if addon.NewUIBIS and addon.NewUIBIS._pendingDropReviewAfterCombat then
                addon.NewUIBIS._pendingDropReviewAfterCombat = false

                if addon.BISService and addon.BISService.ListActiveDropReviewRows and #addon.BISService:ListActiveDropReviewRows() > 0 and addon.NewUIBIS.ShowDropReviewDialog then
                    addon.NewUIBIS:ShowDropReviewDialog()
                end
            end

            if addon.MainFrame.pendingShowAfterCombat then
                addon.MainFrame.pendingShowAfterCombat = false
                addon.MainFrame:ShowForCurrentView()
            elseif addon.MainFrame.pendingRefreshAfterCombat then
                addon.MainFrame.pendingRefreshAfterCombat = false

                if addon.MainFrame.IsRaidBingoViewActive and addon.MainFrame:IsRaidBingoViewActive() then
                    addon.MainFrame:RefreshCurrentView(true)
                elseif addon.MainFrame.MarkBackgroundRefreshPending then
                    addon.MainFrame:MarkBackgroundRefreshPending()
                end
            end

            if addon.MainFrame.HandleDeferredProtectedUiAfterCombat then
                addon.MainFrame:HandleDeferredProtectedUiAfterCombat()
            end
        end
    elseif event == "CHAT_MSG_ADDON" then
        if canProcessEssentialLiveEvent() then
            local suppressNonEssentialInInstance = addon.IsInstanceFeatureSuspended and addon:IsInstanceFeatureSuspended()
            local prefix, message, channel, sender = ...

            local gratsHandled = false
            local raidBingoHandled = false
            local bisHandled = false
            local mythicsHandled = false
            local recruiterHandled = false
            local gratsPrefix = addon.GratsUService and addon.GratsUService.GetPrefix and addon.GratsUService:GetPrefix() or nil
            local raidBingoPrefix = addon.RaidBingoService and addon.RaidBingoService.GetPrefix and addon.RaidBingoService:GetPrefix() or nil
            local bisPrefix = addon.BISService and addon.BISService.GetPrefix and addon.BISService:GetPrefix() or nil
            local recruiterPrefix = addon.MaintenanceService and addon.MaintenanceService.GetRecruiterSyncPrefix and addon.MaintenanceService:GetRecruiterSyncPrefix() or nil
            local syncState = addon.Store and addon.Store.GetSync and addon.Store:GetSync() or nil
            local syncPrefix = type(syncState) == "table" and syncState.prefix or nil

            if not suppressNonEssentialInInstance and prefix == gratsPrefix then
                local gratsPerfStartedAt = beginPerfScope("addonmsg:gratsu")
                gratsHandled = addon.GratsUService:HandleIncoming(prefix, message, channel, sender) or false
                endPerfScope("addonmsg:gratsu", gratsPerfStartedAt)
            end

            if not suppressNonEssentialInInstance and prefix == raidBingoPrefix and addon:IsFeatureEnabled("raidbingo") then
                local raidBingoPerfStartedAt = beginPerfScope("addonmsg:raidbingo")
                raidBingoHandled = addon.RaidBingoService:HandleIncoming(prefix, message, channel, sender) or false
                endPerfScope("addonmsg:raidbingo", raidBingoPerfStartedAt)
            end

            if prefix == bisPrefix and addon:IsFeatureEnabled("bis") and addon.BISService and addon.BISService.HandleIncoming then
                local bisPerfStartedAt = beginPerfScope("addonmsg:bis")
                bisHandled = addon.BISService:HandleIncoming(prefix, message, channel, sender) or false
                endPerfScope("addonmsg:bis", bisPerfStartedAt)
            end

            if (prefix == "LibKS" or prefix == "LRS") and addon:IsFeatureEnabled("mythics") and addon.MythicPlusService and addon.MythicPlusService.HandleOpenRaidKeystoneMessage then
                local mythicsPerfStartedAt = beginPerfScope("addonmsg:mythics")
                mythicsHandled = addon.MythicPlusService:HandleOpenRaidKeystoneMessage(prefix, message, channel, sender) or false
                endPerfScope("addonmsg:mythics", mythicsPerfStartedAt)
            end

            if not suppressNonEssentialInInstance and prefix == recruiterPrefix and addon.MaintenanceService and addon.MaintenanceService.HandleIncoming then
                local recruiterPerfStartedAt = beginPerfScope("addonmsg:recruiter")
                recruiterHandled = addon.MaintenanceService:HandleIncoming(prefix, message, channel, sender) or false
                endPerfScope("addonmsg:recruiter", recruiterPerfStartedAt)
            end

            if not suppressNonEssentialInInstance and prefix == syncPrefix then
                local transportPerfStartedAt = beginPerfScope("addonmsg:transport")
                addon.Transport:HandleIncoming(prefix, message, channel, sender)
                endPerfScope("addonmsg:transport", transportPerfStartedAt)
            end

            if addon.MainFrame then
                if raidBingoHandled and addon.MainFrame.IsRaidBingoViewActive and addon.MainFrame:IsRaidBingoViewActive() then
                    addon.MainFrame:RefreshCurrentView(true)
                elseif mythicsHandled and addon.Router and addon.Router.GetCurrentView and addon.Router:GetCurrentView() == "mythics" and addon.MainFrame.MarkBackgroundRefreshPending then
                    addon.MainFrame:MarkBackgroundRefreshPending()
                elseif recruiterHandled and addon.Router and addon.Router.GetCurrentView and addon.Router:GetCurrentView() == "maintenance" then
                    addon.MainFrame:RefreshCurrentView(true)
                elseif addon.MainFrame.MarkBackgroundRefreshPending then
                    if raidBingoHandled and addon.Router and addon.Router.GetCurrentView and addon.Router:GetCurrentView() == "raidbingo" then
                        addon.MainFrame:MarkBackgroundRefreshPending()
                    elseif gratsHandled and addon.Router and addon.Router.GetCurrentView and addon.Router:GetCurrentView() == "gratsu" then
                        addon.MainFrame:MarkBackgroundRefreshPending()
                    elseif bisHandled and addon.Router and addon.Router.GetCurrentView and addon.Router:GetCurrentView() == "bis" then
                        addon.MainFrame:MarkBackgroundRefreshPending()
                    elseif recruiterHandled and addon.Router and addon.Router.GetCurrentView and addon.Router:GetCurrentView() == "maintenance" then
                        addon.MainFrame:MarkBackgroundRefreshPending()
                    end
                end
            end
        end
    end

    endPerfScope(eventPerfScopeName, eventPerfStartedAt)
end)
