-- =============================================================
-- Specs/MonkMistweaver.lua
-- Nem: Healer Alerts — Mistweaver Monk spec module
--
-- FULLY SELF-CONTAINED. This file contains ALL Mistweaver Monk
-- spell IDs, aura scan logic, state management, evaluate logic,
-- event handling, glow evaluation, and options panel additions.
--
-- It has ZERO dependencies on any other spec module. Adding or
-- removing other spec files will never affect this module.
--
-- Registers itself with the core via NHA:RegisterSpec().
--
-- Whitelisted spell IDs (non-secret in Midnight):
--   115175 - Soothing Mist
--   119611 - Renewing Mist
--   124682 - Enveloping Mist
--


-- =============================================================
-- Aura Scanning
-- =============================================================
-- Mistweaver spell IDs (115175, 119611, 124682) are whitelisted
-- as non-secret in Midnight — spellId is readable. However,
-- sourceUnit is NOT whitelisted and returns a secret value when
-- querying auras on other players in M+/rated PvP. We use a
-- safe helper that tries sourceUnit but accepts the aura even
-- if sourceUnit is tainted (in a dungeon you're the only
-- Mistweaver, so any RM/Soothing/Enveloping found is yours).

local NHA = _G.NemHealerAlerts
if not NHA then return end  -- core must load first

local pairs, ipairs       = pairs, ipairs
local math_floor          = math.floor
local string_format       = string.format
local GetTime             = GetTime
local UnitExists          = UnitExists
local UnitAffectingCombat = UnitAffectingCombat
local UnitGUID            = UnitGUID
local C_UnitAuras         = C_UnitAuras
local issecretvalue       = NHA.issecretvalue

-- =============================================================
-- Spell / Aura IDs
-- =============================================================
local SOOTHING_MIST_ID   = 115175   -- Player's Soothing Mist (buff on target)
local RENEWING_MIST_ID   = 119611
local ENVELOPING_MIST_ID = 124682

-- Pandemic threshold for Renewing Mist glow (same as LB/Atonement)
local RM_PANIC_THRESHOLD = 4.5

-- Forward declaration: state is assigned its real table further down
-- (after Alert definitions). Hoisted up here because the RM scan
-- throttle helpers (ScanRMOrThrottle / ResetRMFullScanThrottle) and
-- StoreRMAura / ClearRMTracking reference state, and Lua resolves
-- `local` names at the lexical position of the declaration. Without
-- this, those helpers would see `state` as a global and silently
-- fail to update / reset the validation cache.
local state

-- =============================================================
-- Taint-Safe Helpers
-- =============================================================
-- IMPORTANT: each helper uses the `pcall(staticfn, args...)` form
-- rather than `pcall(function() ... end)`. The closure form allocates
-- a fresh function object on EVERY call (it captures the `aura`/`val`
-- upvalues), which at 4 Hz × ~30 buffs × 5+ units multiplies into
-- thousands of allocations per second and drives encounter CPU above
-- 20%. The static-function form takes args as parameters and never
-- allocates. Same correctness; pcall still catches taint errors when
-- the inner field access throws on secret values. Mirrors v12.0.19's
-- Druid Restoration refactor for the same reason.
-- =============================================================

-- Static workers — DO NOT call directly, always invoke via pcall.
-- Each performs the field access that may throw on secret values.
local function _toNumber(val)
    return val + 0
end
local function _checkPlayerSource(aura)
    return aura.sourceUnit == "player"
end
local function _checkInstanceID(aura)
    return aura.auraInstanceID ~= nil and aura.auraInstanceID ~= 0
end
local function _checkSpellIs(aura, id)
    return aura.spellId and aura.spellId == id
end

-- Safely read a numeric aura field (expirationTime, duration, etc.)
local function SafeNum(val, fallback)
    if val == nil then return fallback end
    local ok, result = pcall(_toNumber, val)
    if ok then return result end
    return fallback
end

-- Returns true if sourceUnit is "player" OR if sourceUnit is
-- tainted (secret). Only returns false if sourceUnit is readable
-- and belongs to someone else.
local function IsPlayerOrUnknownSource(aura)
    if not aura then return false end
    local ok, result = pcall(_checkPlayerSource, aura)
    if not ok then
        -- sourceUnit is a secret value — can't determine source.
        -- In a dungeon with one Mistweaver, it's almost certainly
        -- ours. Accept it rather than dropping the count to 0.
        return true
    end
    return result
end

-- Same check but for auraInstanceID ~= 0
-- CRITICAL: Must use ~= nil (comparison) instead of bare `and`
-- (boolean test). Secret number values throw "attempt to perform
-- boolean test on secret value" when tested in boolean context,
-- which kills CountActiveRenewingMist and drops RM count to 0.
local function HasValidInstanceID(aura)
    if not aura then return false end
    local ok, result = pcall(_checkInstanceID, aura)
    -- If pcall failed, auraInstanceID is secret but exists —
    -- accept it (same logic as IsPlayerOrUnknownSource)
    if not ok then return true end
    return result
end

-- Returns true if aura.spellId safely equals the given ID.
-- Mirrors Disc's AuraSpellIs() helper for taint-safe comparison.
local function AuraSpellIs(aura, id)
    local ok, result = pcall(_checkSpellIs, aura, id)
    return ok and result
end

-- ── Two-path aura finder (mirrors Disc FindAtonementOnUnit) ──
-- Path 1: GetAuraDataBySpellID (fast, direct lookup)
-- Path 2: GetAuraDataByIndex   (slow, walks all auras)
-- GetAuraDataBySpellID can return nil in follower dungeons and
-- other edge cases where GetAuraDataByIndex still works. The
-- glow pipeline never hits this because it uses instance IDs.
local function FindAuraOnUnit(unit, spellId, checkSource)
    if not UnitExists(unit) then return nil end
    if not C_UnitAuras then return nil end

    -- Path 1: direct spell ID lookup (fast)
    if C_UnitAuras.GetAuraDataBySpellID then
        local ok, aura = pcall(C_UnitAuras.GetAuraDataBySpellID,
            unit, spellId, "HELPFUL")
        if ok and aura and HasValidInstanceID(aura) then
            if not checkSource or IsPlayerOrUnknownSource(aura) then
                return aura
            end
        end
        -- Fall through to index scan if direct lookup failed
    end

    -- Path 2: index scan fallback (taint-safe)
    if not C_UnitAuras.GetAuraDataByIndex then return nil end
    local i = 1
    while true do
        local ok, aura = pcall(C_UnitAuras.GetAuraDataByIndex,
            unit, i, "HELPFUL")
        if not ok or not aura then break end
        if AuraSpellIs(aura, spellId) then
            if not checkSource or IsPlayerOrUnknownSource(aura) then
                return aura
            end
        end
        i = i + 1
    end
    return nil
end

-- earlyOut: optional threshold; once count meets it we stop scanning.
-- The Spread RM alert only cares whether count >= threshold, so once
-- we've hit it there's no reason to keep walking units. Pass 0/nil to
-- get the exact count (debug command path). Mirrors the v12.0.19
-- CountRejuvGerminationStacks(earlyOut) optimization on Druid.
local function CountActiveRenewingMist(earlyOut)
    local count = 0
    local seen  = {}
    earlyOut = earlyOut or 0
    for _, unit in ipairs(NHA:GetGroupUnits()) do
        -- Deduplicate by GUID: GetGroupUnits includes "target"/"focus"
        -- which can alias the same unit as "player" or "party1", etc.
        -- Without dedup, self-casting RM while targeting yourself
        -- counts the aura twice and falsely clears the alert.
        --
        -- UnitGUID returns a SECRET VALUE for hostile units (target,
        -- focus) in tainted execution contexts. Indexing the `seen`
        -- table with a secret key throws "attempted to index a table
        -- that cannot be indexed with secret keys" — pcall around
        -- every read/write would work but allocates closures and
        -- unwinds the stack on each failure. issecretvalue() is a
        -- single C-level call: check upfront and skip dedup for
        -- those units. Worst case target/focus get scanned twice if
        -- they appear under partyN as well — fine, since
        -- FindAuraOnUnit returns nil for enemies anyway.
        local guid     = UnitGUID(unit)
        local canDedup = guid and not issecretvalue(guid)
        if not canDedup or not seen[guid] then
            if FindAuraOnUnit(unit, RENEWING_MIST_ID, true) then
                count = count + 1
                if earlyOut > 0 and count >= earlyOut then
                    return count
                end
            end
            if canDedup then seen[guid] = true end
        end
    end
    return count
end

local function FindSoonestRenewingMist()
    local bestUnit, bestAura, bestRemaining = nil, nil, math.huge
    local now = GetTime()

    for _, unit in ipairs(NHA:GetGroupUnits()) do
        local aura = FindAuraOnUnit(unit, RENEWING_MIST_ID, true)
        if aura then
            local expire = SafeNum(aura.expirationTime, 0)
            local remaining = expire - now
            if remaining > 0 and remaining < bestRemaining then
                bestUnit       = unit
                bestAura       = aura
                bestRemaining  = remaining
            end
        end
    end

    return bestUnit, bestAura
end

-- =============================================================
-- Scan throttles (mirrors v12.0.19 Druid Restoration optimization)
-- =============================================================
-- Two independent throttles:
--   RM_COUNT_PERIOD     — caches the "RM low coverage" fire state
--                         for the Spread RM alert. Crossing the
--                         threshold rarely happens faster than ~0.5s
--                         of casting; latency is invisible.
--   RM_FULLSCAN_PERIOD  — throttles the FindSoonestRenewingMist
--                         fallback scan when cached-aura validation
--                         fails. The cached-validation path itself
--                         (one GetAuraDataByAuraInstanceID call) is
--                         unaffected; only the expensive group walk
--                         is rate-limited. Cast/aura events that
--                         signal real RM state changes call
--                         ResetRMFullScanThrottle so genuine
--                         transitions still get sub-frame detection.
local RM_COUNT_PERIOD     = 0.5
local lastRMCountScan     = 0
local cachedRMLow         = false

local RM_FULLSCAN_PERIOD  = 0.4
local lastRMFullScan      = 0

local function ScanRMOrThrottle()
    -- Returns the (unit, aura) tuple from FindSoonestRenewingMist if
    -- the scan actually ran. Returns false to signal "throttled —
    -- caller must not touch state.rmUnit / state.rmInstID this tick".
    local now = GetTime()
    if (now - lastRMFullScan) < RM_FULLSCAN_PERIOD then
        return false
    end
    lastRMFullScan = now
    return FindSoonestRenewingMist()
end

local function ResetRMFullScanThrottle()
    -- Resets BOTH the FindSoonestRenewingMist throttle (so the next
    -- Evaluate is allowed to scan) and the rmValidatedAt cache (so
    -- the next Evaluate is forced to re-call GetAuraDataByAuraInstanceID
    -- instead of trusting the cached state). Called from cast/aura
    -- event paths that signal a real RM state change.
    lastRMFullScan = 0
    if state then state.rmValidatedAt = nil end
end

local function GetRMThreshold()
    local db = NHA.db
    if IsInRaid and IsInRaid() then
        return db.rmThresholdRaid or 4
    end
    return db.rmThresholdDungeon or 2
end

local function UnitHasEnvelopingMist(unit)
    if not unit then return false end
    return FindAuraOnUnit(unit, ENVELOPING_MIST_ID, true) ~= nil
end


-- =============================================================
-- Player Channel Detection
-- =============================================================
-- CRITICAL: The statue applies Soothing Mist (possibly 115175)
-- on its targets too. Aura scanning alone cannot distinguish the
-- player's channel from the statue's copy, because sourceUnit
-- may be secret or may report "player" for the statue (totems
-- are considered extensions of the player). We use
-- UnitChannelInfo("player") to confirm the PLAYER is personally
-- channeling before firing env/SOR alerts.

local function _spellIdEquals(a, b)
    return a == b
end

local function IsPlayerChannelingSoothing()
    if not UnitChannelInfo then return false end
    local name, _, _, _, _, _, _, spellId = UnitChannelInfo("player")
    if not name then return false end
    -- Check by spellId first (may be secret in M+)
    local ok, match = pcall(_spellIdEquals, spellId, SOOTHING_MIST_ID)
    if ok and match then return true end
    -- Fallback: check by name (covers secret spellId case)
    if name == "Soothing Mist" then return true end
    return false
end

-- Finds the unit the player is personally channeling Soothing
-- Mist on. Only returns a result when UnitChannelInfo confirms
-- the player's channel.
--
-- The decision tree:
--   1. UnitChannelInfo says no SM channel    → return nil
--   2. Some non-player unit has 115175       → that's the channel target
--      (canonicalized to "player" if it resolves to the player's GUID,
--       e.g. "target" when self-targeting or "raidN" in raid)
--   3. Some pet token has 115175             → return that token
--   4. Nothing else has 115175               → return "player"
--
-- Step 4 is the critical fix for the EM-alert-not-firing-on-self-cast
-- bug. The previous logic required finding 115175 on at least one
-- group unit (`foundOnPlayer` fallback), which silently dropped
-- self-channels in any context where the channel itself doesn't
-- register as a queryable aura on the channeler. UnitChannelInfo
-- has already confirmed the player is channeling; when nobody else
-- has 115175, it MUST be a self-channel — regardless of whether
-- the buff appears in the player's own aura list.
--
-- ── Performance: target caching ──
-- During a Soothing Mist channel this function used to be the single
-- hottest block in Evaluate (~50% of total Evaluate time in raid)
-- because it walked every group unit on every tick. The channel
-- target cannot change without the channel breaking and `UnitChannelInfo`
-- already confirms whether the channel is live, so once we've located
-- the target we can validate it cheaply on subsequent ticks instead
-- of rescanning the group.
--
-- Cache strategy:
--   • cachedSoothUnit = nil   → no channel, or first call after start
--                                → fall through to the slow group walk,
--                                  populate cache before returning.
--   • cachedSoothUnit set     → fast path: validate that the cached
--                                  unit still has 115175 with one
--                                  FindAuraOnUnit call. If yes, return
--                                  the cached token. If not, invalidate
--                                  and fall through to the slow path.
--   • cachedSoothUnit "player" → trust without validation. 115175 is
--                                  not reliably queryable on the
--                                  channeler itself, so revalidating
--                                  would constantly fail and force the
--                                  slow path on every tick — defeating
--                                  the optimization entirely.
--
-- The cache is module-local rather than a state field because it's a
-- pure implementation detail of this function. It's cleared in
-- ClearAllState (spec deactivation) and self-clears whenever
-- IsPlayerChannelingSoothing() returns false.
local cachedSoothUnit = nil

local function FindPlayerSoothingTarget()
    if not IsPlayerChannelingSoothing() then
        cachedSoothUnit = nil
        return nil
    end

    -- ── Fast path: validate cached target ──
    if cachedSoothUnit then
        if cachedSoothUnit == "player" then
            -- Self-channel: trust without revalidation (see header).
            return "player"
        end
        if UnitExists(cachedSoothUnit)
           and FindAuraOnUnit(cachedSoothUnit, SOOTHING_MIST_ID, false) then
            return cachedSoothUnit
        end
        -- Stale (target lost SM, retargeted mid-channel, roster shuffle, etc.)
        cachedSoothUnit = nil
    end

    -- ── Slow path: full group walk + cache populate ──
    local pGUID = UnitGUID("player")

    -- Scan group units, skipping "player" — that path is handled by
    -- the unconditional self-channel default at the bottom.
    for _, unit in ipairs(NHA:GetGroupUnits()) do
        if unit ~= "player" then
            local aura = FindAuraOnUnit(unit, SOOTHING_MIST_ID, false)
            if aura then
                -- Canonicalize player-equivalent tokens. "target" can
                -- shift mid-channel and "raidN" is a stable but
                -- spec-incorrect identifier when raidN == self.
                --
                -- UnitGUID(unit) can return a secret-tainted string
                -- in M+/rated PvP for non-player units (the player's
                -- own GUID is whitelisted, so pGUID is safe). The
                -- bare == comparison throws on secret values, so
                -- pcall the equality and treat a thrown comparison
                -- as "not the player" — falls through to returning
                -- the unit token, same as if either GUID were nil.
                local uGUID = UnitGUID(unit)
                local sameAsPlayer = false
                if pGUID and uGUID then
                    local ok, eq = pcall(function() return uGUID == pGUID end)
                    sameAsPlayer = ok and eq
                end
                local found = sameAsPlayer and "player" or unit
                cachedSoothUnit = found
                return found
            end
        end
    end

    -- Pet tokens (not included in GetGroupUnits)
    for _, unit in ipairs({ "pet", "partypet1", "partypet2", "partypet3", "partypet4" }) do
        if UnitExists(unit) and FindAuraOnUnit(unit, SOOTHING_MIST_ID, false) then
            cachedSoothUnit = unit
            return unit
        end
    end

    -- UnitChannelInfo said the player IS channeling SM and nobody
    -- else has 115175 — this is a self-channel. Return "player"
    -- whether or not 115175 is queryable on the player's aura list.
    cachedSoothUnit = "player"
    return "player"
end

-- =============================================================
-- Renewing Mist Tracking (for pandemic glow — mirrors LB/Atonement)
-- =============================================================
-- (state forward-declared at top of file)

local function StoreRMAura(unit, aura)
    state.rmUnit     = unit
    state.rmInstID   = aura.auraInstanceID
    state.rmExpire   = SafeNum(aura.expirationTime, 0)
    state.rmDuration = SafeNum(aura.duration, 0)
    local tm = SafeNum(aura.timeMod, 1)
    state.rmTimeMod  = (tm > 0) and tm or 1
end

local function ClearRMTracking()
    state.rmUnit     = nil
    state.rmInstID   = nil
    state.rmExpire   = 0
    state.rmDuration = 0
    state.rmTimeMod  = 1
    state.rmValidatedAt = nil
end

-- =============================================================
-- Module State (owned entirely by this module)
-- =============================================================
-- (state forward-declared above)

state = {
    -- Renewing Mist low (Spread RM alert)
    rmActive       = false,
    rmWasActive    = false,
    -- Renewing Mist pandemic glow tracking (soonest-expiring)
    rmUnit         = nil,
    rmInstID       = nil,
    rmExpire       = 0,
    rmDuration     = 0,
    rmTimeMod      = 1,
    rmScanPending  = false,
    rmValidatedAt  = nil,  -- GetTime() of last successful instance-ID validation
    -- Enveloping missing (conditional)
    envActive      = false,
    envWasActive   = false,
    envLastSeenTime = 0,   -- debounce: last time EM was detected
    -- Soothing Mist channel tracking
    soothingUnit   = nil,
    soothingGUID   = nil,
    -- Grace period
    soothingStartTime = 0,
    -- Debounce
    playerAuraPending   = false,
    rosterUpdatePending = false,
}

-- =============================================================
-- CUF Whole-Frame Glow State
-- =============================================================
-- Per-cache: maps each tracked CUF (CompactUnitFrame) to a small
-- "safe aura" table when that frame currently has the corresponding
-- buff. The OnUpdate ticker (RefreshGlows) walks each set every
-- 0.25s as a safety net, cleaning up entries whose aura has expired
-- in case a UNIT_AURA removal event was missed, then re-evaluating
-- the frame so a lower-priority glow can take over.
--
-- Priority chain in EvaluateCUFGlow (highest first):
--   1. Enveloping Mist → cufStateMap[frame] = "em" (cufEMCache)
--   2. Renewing Mist   → cufStateMap[frame] = "rm" (cufRMCache)
--
-- Coalesced refresh queue: dirtyCUFFrames buffers (frame -> unit)
-- pairs that have pending UNIT_AURA-driven refreshes. The public
-- EvaluateCUFGlow shim is now a cheap O(1) flag set; the actual
-- priority-chain evaluation happens in DoEvaluateCUFGlow, called
-- in a single batch by DrainGlowDirtySet from the RefreshGlows
-- ticker (every 0.25s). Multiple UNIT_AURA events for the same
-- frame within a tick collapse into one refresh — the v12.0.21
-- raid telemetry showed 51 synchronous calls in a single render
-- frame when many auras transitioned simultaneously; coalescing
-- caps that at one call per frame per ticker pass.
local cufRMCache    = {}    -- frame -> { expirationTime, timeMod, auraInstanceID, duration }
local cufEMCache    = {}    -- frame -> { expirationTime, timeMod, auraInstanceID, duration }
local cufStateMap   = {}    -- frame -> "em" | "rm"
local dirtyCUFFrames = {}   -- frame -> unit (pending refresh queue)

-- =============================================================
-- Alert Definitions
-- =============================================================
local REML_Y = 46
local ENV_Y  = 16

local ALERTS = {
    -- Sound panel order: rm → env
    {
        key          = "rm",
        label        = "Spread Renewing Mist",
        text         = "* SPREAD RENEWING MIST *",
        defaultColor = { r = 0.000, g = 1.000, b = 0.612 },  -- #00FF9C
        hasTimer     = false,
        yOffset      = REML_Y,
        defaultSound = "Ping",
    },
    {
        key          = "env",
        label        = "Enveloping Mist",
        text         = "* ENVELOPING MIST *",
        defaultColor = { r = 0.992, g = 1.000, b = 0.714 },  -- #FDFFB6
        hasTimer     = false,
        yOffset      = ENV_Y,
        defaultSound = "Bell",
    },
}

-- =============================================================
-- Saved-Variable Defaults (merged into core db)
-- =============================================================
local DEFAULTS = {
    rmEnabled            = true,
    rmSoundEnabled       = true,
    rmSoundName          = "Ping",
    envEnabled           = true,
    envSoundEnabled      = true,
    envSoundName         = "Bell",
    rmThresholdDungeon   = 2,
    rmThresholdRaid      = 4,
    alertColors          = {
        rm       = { r = 0.000, g = 1.000, b = 0.612 },  -- #00FF9C
        env      = { r = 0.992, g = 1.000, b = 0.714 },  -- #FDFFB6
    },
}

-- =============================================================
-- MODULE TABLE
-- =============================================================
local MonkMW = {
    class     = "MONK",
    specIndex = 2,  -- Mistweaver is spec index 2
    specID    = 270, -- fallback: Mistweaver Monk spec ID for secret-value contexts
    specName  = "Mistweaver",
    alerts    = ALERTS,
    defaults  = DEFAULTS,
    state     = state,

    extraEvents = {
        "UNIT_AURA",
    },

    -- Spell IDs whose UNIT_AURA add/remove on a tracked CUF unit
    -- should trigger an EvaluateCUFGlow refresh. Without this filter
    -- the core listener would refresh on every aura change including
    -- HoT ticks from other classes — most of UNIT_AURA traffic.
    -- Two spells drive the CUF whole-frame glow on Mistweaver, in
    -- priority order: Enveloping Mist > Renewing Mist.
    cufRelevantSpells = {
        [124682] = true,   -- Enveloping Mist
        [119611] = true,   -- Renewing Mist
    },
}

-- =============================================================
-- ClearAllGlows
-- =============================================================
function MonkMW:ClearAllGlows()
    -- CUF whole-frame glows
    for frame in pairs(cufStateMap) do
        if frame._nhaFrameGlowing then NHA:HideFrameGlow(frame) end
    end
    wipe(cufStateMap)
    wipe(cufRMCache)
    wipe(cufEMCache)
    wipe(dirtyCUFFrames)
end

-- =============================================================
-- ClearAllState
-- =============================================================
function MonkMW:ClearAllState()
    state.rmActive          = false
    state.rmWasActive       = false
    ClearRMTracking()
    state.rmScanPending     = false
    state.rmValidatedAt     = nil
    state.envActive         = false
    state.envWasActive      = false
    state.envLastSeenTime   = 0
    state.soothingUnit      = nil
    state.soothingGUID      = nil
    state.soothingStartTime = 0
    state.playerAuraPending = false
    state.rosterUpdatePending = false
    cachedSoothUnit         = nil
    self:ClearAllGlows()
end

-- =============================================================
-- NeedsTicker
-- =============================================================
function MonkMW:NeedsTicker(db)
    -- Keep ticker alive for the CUF whole-frame glow safety-net expire
    -- check (either priority cache), the coalesced refresh queue
    -- (dirtyCUFFrames), and the RM tracking validation cache the
    -- Evaluate() pipeline maintains.
    if state.rmUnit ~= nil       then return true end
    if next(cufRMCache)    ~= nil then return true end
    if next(cufEMCache)    ~= nil then return true end
    if next(dirtyCUFFrames) ~= nil then return true end
    return false
end

-- =============================================================
-- Per-block + per-call perf instrumentation
-- =============================================================
-- This block must precede every function that references the
-- `_perf*` locals or the `Perf*` helpers. Lua closures capture
-- file-scope locals by reference at FUNCTION-CREATION time; if a
-- function is parsed before its locals are declared, the names
-- silently fall through to globals — and writes go to globals
-- while reads from later-defined functions go to locals, breaking
-- attribution invisibly. (This is the bug that produced the
-- "all NONE" CUF perf result in v12.0.21 raid telemetry: the
-- public EvaluateCUFGlow's `_perfCUFLastPath = "rm"` etc. writes
-- targeted a global, while the perf wrapper's read targeted the
-- local — always nil → always "none".)
--
-- Off-state cost: each Perf helper bails on a nil/false table
-- check (~10ns). When perf is on, helpers cost a few μs each.
-- Block boundaries map to the comment headers in Evaluate:
-- RMCOUNT / RMTRACK / SOOTH / ENV / END.
local _perfBlockTimer = 0

-- ── CUF glow path tag ────────────────────────────────────────
-- Set by DoEvaluateCUFGlow just before each return so the inline
-- instrumentation in InstrumentedDoEvaluateCUFGlow can attribute
-- the call to whichever priority path actually fired:
-- "sm", "em", "rm", "none", or "disabled".
local _perfCUFLastPath = nil

-- ── Per-frame spike accumulator ──────────────────────────────
-- Sums Evaluate + every CUF glow eval + every RefreshGlows that
-- fire within the same render frame, then rolls the total into
-- the spike record at frame boundary. WoW frames run at ~60fps
-- (~16.7ms); anything synchronous within one frame stacks against
-- the per-frame CPU budget — the actual cause of "20% CPU spike"
-- readouts in the addon panel that per-call averages smooth away.
local _perfFrameStamp = 0
local _perfFrameTotal = 0
local _perfFrameEval  = 0
local _perfFrameCUF   = 0
local _perfFrameRefr  = 0
local _perfFrameCUFCount = 0

local function PerfFrameRoll()
    local p = state._perf
    if not (p and p.enabled) then return end
    local now = GetTime()
    if now ~= _perfFrameStamp then
        if _perfFrameTotal > (p.spike and p.spike.totalMs or 0) then
            p.spike = p.spike or {}
            p.spike.totalMs   = _perfFrameTotal
            p.spike.evalMs    = _perfFrameEval
            p.spike.cufMs     = _perfFrameCUF
            p.spike.refreshMs = _perfFrameRefr
            p.spike.cufCount  = _perfFrameCUFCount
            p.spike.atTime    = now
        end
        _perfFrameStamp     = now
        _perfFrameTotal     = 0
        _perfFrameEval      = 0
        _perfFrameCUF       = 0
        _perfFrameRefr      = 0
        _perfFrameCUFCount  = 0
    end
end

local function PerfBeginBlocks()
    local p = state._perf
    if not (p and p.blocksEnabled) then return end
    _perfBlockTimer = debugprofilestop()
end

local function PerfMarkBlock(name)
    local p = state._perf
    if not (p and p.blocksEnabled) then return end
    local now = debugprofilestop()
    local dt  = now - _perfBlockTimer
    local b   = p.blocks[name]
    if not b then
        b = { calls = 0, totalMs = 0, maxMs = 0 }
        p.blocks[name] = b
    end
    b.calls   = b.calls + 1
    b.totalMs = b.totalMs + dt
    if dt > b.maxMs then b.maxMs = dt end
    _perfBlockTimer = now
end

-- =============================================================
-- DoEvaluateCUFGlow (private worker — the actual priority chain)
-- =============================================================
-- This is the historical body of EvaluateCUFGlow, lifted out so it
-- can be invoked by:
--   1. DrainGlowDirtySet — batched per-tick from RefreshGlows.
--   2. RefreshGlows safety-net — when a top-priority cache expires
--      and a lower-priority glow needs to take over immediately.
--
-- The public MonkMW:EvaluateCUFGlow is now a cheap shim that just
-- enqueues into dirtyCUFFrames; this worker is where work happens.
local function DoEvaluateCUFGlow(self, db, frame, unit)
    if not db or not db.enabled or not db.cufGlowEnabled then
        if cufStateMap[frame] then
            NHA:HideFrameGlow(frame)
            cufStateMap[frame] = nil
        end
        cufRMCache[frame] = nil
        cufEMCache[frame] = nil
        _perfCUFLastPath = "disabled"
        return
    end

    -- ── Path 1: Enveloping Mist (highest priority) ───────────
    local emAura = FindAuraOnUnit(unit, ENVELOPING_MIST_ID, true)
    if emAura then
        local sa = cufEMCache[frame]
        if not sa then sa = {}; cufEMCache[frame] = sa end
        sa.auraInstanceID = emAura.auraInstanceID
        sa.expirationTime = SafeNum(emAura.expirationTime, 0)
        sa.duration       = SafeNum(emAura.duration, 0)
        sa.timeMod        = SafeNum(emAura.timeMod, 1)
        if sa.timeMod <= 0 then sa.timeMod = 1 end

        local now       = GetTime()
        local remaining = (sa.expirationTime - now) / sa.timeMod
        if remaining > 0 then
            local c = db.alertColors and db.alertColors.env
                      or { r=0.992, g=1.000, b=0.714 }  -- #FDFFB6 fallback
            NHA:ShowFrameGlow(frame, c.r, c.g, c.b)
            cufStateMap[frame] = "em"
            -- Drop lower-priority caches so stale entries don't linger
            cufRMCache[frame] = nil
            _perfCUFLastPath = "em"
            return
        end
        cufEMCache[frame] = nil
    else
        cufEMCache[frame] = nil
    end

    -- ── Path 2: Renewing Mist ─────────────────────────────────
    -- Find player-source Renewing Mist on the unit. checkSource=true
    -- enforces that we only glow for OUR RM, not for another
    -- Mistweaver's overlapping casts in the same group.
    local rmAura = FindAuraOnUnit(unit, RENEWING_MIST_ID, true)
    if rmAura then
        -- Reuse the same per-frame safe-aura table (no per-call alloc)
        local sa = cufRMCache[frame]
        if not sa then sa = {}; cufRMCache[frame] = sa end
        sa.auraInstanceID = rmAura.auraInstanceID
        sa.expirationTime = SafeNum(rmAura.expirationTime, 0)
        sa.duration       = SafeNum(rmAura.duration, 0)
        sa.timeMod        = SafeNum(rmAura.timeMod, 1)
        if sa.timeMod <= 0 then sa.timeMod = 1 end

        -- Full-duration glow: only check that the aura hasn't already
        -- expired (defensive — should always be > 0 if FindAuraOnUnit
        -- just returned the aura, but the field can be secret).
        local now       = GetTime()
        local remaining = (sa.expirationTime - now) / sa.timeMod
        if remaining > 0 then
            local c = db.alertColors and db.alertColors.rm
                      or { r=0, g=1, b=0.612 }  -- #00FF9C fallback
            NHA:ShowFrameGlow(frame, c.r, c.g, c.b)
            cufStateMap[frame] = "rm"
            _perfCUFLastPath = "rm"
            return
        end
        -- Aura is present but already expired — fall through to clear.
        cufRMCache[frame] = nil
    else
        cufRMCache[frame] = nil
    end

    -- No glow conditions met
    if cufStateMap[frame] then
        NHA:HideFrameGlow(frame)
        cufStateMap[frame] = nil
    end
    _perfCUFLastPath = "none"
end

-- =============================================================
-- InstrumentedDoEvaluateCUFGlow — wraps DoEvaluateCUFGlow with
-- inline perf accounting (gated on state._perf.enabled).
-- =============================================================
-- Off-state cost: one table lookup + nil check (~10ns). On-state
-- cost: 2× debugprofilestop() + a few table writes (~5μs).
--
-- The accounting flows through the same perf.cuf accumulator that
-- the old external wrap on MonkMW.EvaluateCUFGlow used. After the
-- coalesce redesign, the public shim is too cheap to be worth
-- timing — actual work happens here, in batches from drain.
local function InstrumentedDoEvaluateCUFGlow(self, db, frame, unit)
    local perf = state._perf
    if not (perf and perf.enabled) then
        DoEvaluateCUFGlow(self, db, frame, unit)
        return
    end
    PerfFrameRoll()
    _perfCUFLastPath = nil
    local t0 = debugprofilestop()
    DoEvaluateCUFGlow(self, db, frame, unit)
    local dt  = debugprofilestop() - t0
    local cuf = perf.cuf
    cuf.calls   = cuf.calls + 1
    cuf.totalMs = cuf.totalMs + dt
    if dt > cuf.maxMs then cuf.maxMs = dt end
    local path = _perfCUFLastPath or "none"
    cuf.paths[path] = (cuf.paths[path] or 0) + 1
    _perfFrameTotal     = _perfFrameTotal     + dt
    _perfFrameCUF       = _perfFrameCUF       + dt
    _perfFrameCUFCount  = _perfFrameCUFCount  + 1
end

-- =============================================================
-- DrainGlowDirtySet — process the coalesced refresh queue
-- =============================================================
-- Called from RefreshGlows on each ticker pass (every 0.25s).
-- Walks every (frame, unit) pair queued since the last drain,
-- runs the priority chain on each via the instrumented worker,
-- and wipes the queue. Worst-case latency between an aura change
-- and its glow update: one ticker period (0.25s). For a coverage
-- signal you glance at every few seconds, imperceptible.
--
-- Frame validity: dirtyCUFFrames may contain frames that were
-- unhooked or reassigned to a different unit between mark-time
-- and drain-time. We prefer frame._nhaCUFUnit (the live token)
-- over the stashed unit — if the live token is nil the frame is
-- no longer tracked and we silently skip it.
local function DrainGlowDirtySet(self, db)
    if not next(dirtyCUFFrames) then return end
    for frame, unit in pairs(dirtyCUFFrames) do
        local liveUnit = frame._nhaCUFUnit or unit
        if liveUnit then
            InstrumentedDoEvaluateCUFGlow(self, db, frame, liveUnit)
        end
    end
    wipe(dirtyCUFFrames)
end

-- =============================================================
-- EvaluateCUFGlow (public — called by core's UNIT_AURA dispatch)
-- =============================================================
-- This is now a cheap dispatch shim. All it does is mark the
-- (frame, unit) pair as dirty; the actual priority-chain work
-- happens in DoEvaluateCUFGlow, called in a coalesced batch from
-- DrainGlowDirtySet on the next RefreshGlows ticker pass.
--
-- ── Combat gating ──
-- Out of combat, raid frames receive heavy UNIT_AURA traffic from
-- food/flask/world buffs being applied across the group, even when
-- nothing healing-relevant is happening. The v12.0.21 telemetry
-- showed 0.15-3% sustained CPU just standing in raid lobby. That
-- traffic is pure overhead: there's no in-combat healing decision
-- that needs glow updates, and the player isn't actively reading
-- the frames as a coverage signal pre-pull.
--
-- Out-of-combat path: shim returns immediately without enqueueing.
-- On combat enter (PLAYER_REGEN_DISABLED), OnEvent calls
-- NHA:RefreshAllCUFs() which drives a fresh evaluation of every
-- tracked frame, so any auras applied in the pre-pull window
-- light up the moment the pull starts.
--
-- ── Disabled path ──
-- When cufGlowEnabled is off, eagerly clean up any existing glow
-- state on this frame. Doesn't add to dirty queue.
function MonkMW:EvaluateCUFGlow(db, frame, unit)
    if not db or not db.enabled or not db.cufGlowEnabled then
        if cufStateMap[frame] then
            NHA:HideFrameGlow(frame)
            cufStateMap[frame] = nil
        end
        cufRMCache[frame] = nil
        cufEMCache[frame] = nil
        dirtyCUFFrames[frame] = nil
        return
    end
    if not UnitAffectingCombat("player") then
        return
    end
    dirtyCUFFrames[frame] = unit
end

-- =============================================================
-- RefreshGlows (called every 0.25s by ticker)
-- =============================================================
-- Two responsibilities, in order:
--   1. Drain the coalesced UNIT_AURA refresh queue. Every (frame,
--      unit) pair marked dirty since the last drain runs through
--      the priority chain exactly once. Multiple UNIT_AURA events
--      for the same frame collapse into one refresh — the v12.0.21
--      raid telemetry showed 51 synchronous CUF evals in a single
--      render frame; coalescing caps that to one per ticker pass.
--   2. Safety-net expire detection. Whole-frame glows are
--      full-duration: state is normally driven by UNIT_AURA
--      (apply → glow on, remove → glow off). If a removal event
--      is dropped under heavy aura traffic, the cache walks below
--      catch the stale entry once remaining drops to zero. Frames
--      whose top-priority cache just expired are re-evaluated so
--      a lower-priority glow (RM under EM) takes over without
--      waiting for the next UNIT_AURA event.
function MonkMW:RefreshGlows(db)
    if not db or not db.cufGlowEnabled then return end

    -- Drain first so freshly-marked dirty frames get evaluated this
    -- tick. Cheap when queue is empty (one `next` check).
    DrainGlowDirtySet(self, db)

    if not next(cufEMCache)
       and not next(cufRMCache) then
        return
    end

    local now = GetTime()
    local needsReeval

    for frame, sa in pairs(cufEMCache) do
        local remaining = (sa.expirationTime - now) / sa.timeMod
        if remaining <= 0 then
            cufEMCache[frame] = nil
            needsReeval = needsReeval or {}
            needsReeval[frame] = frame._nhaCUFUnit
        end
    end

    for frame, sa in pairs(cufRMCache) do
        local remaining = (sa.expirationTime - now) / sa.timeMod
        if remaining <= 0 then
            cufRMCache[frame] = nil
            needsReeval = needsReeval or {}
            needsReeval[frame] = frame._nhaCUFUnit
        end
    end

    if needsReeval then
        for frame, unit in pairs(needsReeval) do
            if unit then
                -- Bypass the public shim: combat is implied (we're
                -- here because a cache had a live entry to expire,
                -- which only happens in combat), and we want the
                -- re-eval to run THIS tick rather than wait for
                -- the next ticker pass to drain a re-enqueue.
                InstrumentedDoEvaluateCUFGlow(self, db, frame, unit)
            elseif cufStateMap[frame] then
                NHA:HideFrameGlow(frame)
                cufStateMap[frame] = nil
            end
        end
    end
end

-- =============================================================
-- Evaluate (called by core ticker and events)
-- =============================================================
function MonkMW:Evaluate(db)
    PerfBeginBlocks()
    -- ── Renewing Mist low coverage (combat only) ─────────────
    -- Process RM FIRST so a crash in statue code can't block it.
    --
    -- Throttled at RM_COUNT_PERIOD: the count-vs-threshold result
    -- is cached between scans, with sub-second alert latency.
    -- Mirrors the v12.0.19 Druid Abundance throttle pattern and
    -- cuts the per-tick cost in raid from ~30 unit walks at 4 Hz
    -- (~120/sec) to ~30 walks at 2 Hz (~60/sec). The earlyOut
    -- parameter further cuts cost when coverage is healthy: once
    -- count >= threshold we stop scanning, so a fully-covered
    -- raid only walks `threshold` units (e.g. 4) instead of 30.
    local rmLow = false
    if db.rmEnabled and UnitAffectingCombat("player") then
        local now = GetTime()
        if (now - lastRMCountScan) >= RM_COUNT_PERIOD then
            lastRMCountScan = now
            local threshold = GetRMThreshold()
            local count     = CountActiveRenewingMist(threshold)
            cachedRMLow     = count < threshold
        end
        rmLow = cachedRMLow
    else
        cachedRMLow = false
    end
    state.rmActive = rmLow
    PerfMarkBlock("RMCOUNT")

    -- ── Renewing Mist tracking (soonest-expiring) ─────────────
    -- Three-tier validation strategy (mirrors v12.0.19 Druid LB):
    --   1. Cached state still healthy (validated <0.25s ago AND
    --      expire >5s out)            → skip API call entirely.
    --   2. Cached state present, refresh via cheap instance-ID
    --      lookup                      → one API call, no scan.
    --   3. Lookup failed or no cache  → fall through to throttled
    --      group rescan (ScanRMOrThrottle).
    -- Worst-case alert delay for the 4.5s pandemic threshold: 0.25s
    -- — invisible. ResetRMFullScanThrottle() in OnEvent ensures
    -- genuine state changes (RM cast, removed, refreshed) bypass
    -- the throttle for sub-frame detection.
    --
    -- Combat-gated: out-of-combat RM tracking is wasted work — there's
    -- no expire-warning alert pre-pull, no Spread RM alert pre-pull,
    -- and any pre-pull RM that survives into combat will be picked
    -- up by the next ScanRMOrThrottle pass (state was cleared on the
    -- last PLAYER_REGEN_ENABLED, so the first in-combat tick takes
    -- the cache-miss → full-scan path, runs once, and we're back in
    -- steady state). Worst-case latency at pull: one ticker period
    -- before tracking populates.
    if UnitAffectingCombat("player") then
        if state.rmUnit and state.rmInstID then
            local now = GetTime()
            if state.rmValidatedAt
               and (now - state.rmValidatedAt) < 0.25
               and state.rmExpire and state.rmExpire > (now + 5) then
                -- Cached state is healthy and not approaching expiry.
                -- Trust it; downstream code reads state.rmExpire directly.
            else
                local ok, aura = pcall(C_UnitAuras.GetAuraDataByAuraInstanceID,
                    state.rmUnit, state.rmInstID)
                if ok and aura and not issecretvalue(aura.spellId)
                   and aura.spellId == RENEWING_MIST_ID
                   and IsPlayerOrUnknownSource(aura) then
                    StoreRMAura(state.rmUnit, aura)
                    state.rmValidatedAt = now
                else
                    local u, a = ScanRMOrThrottle()
                    if u and a then
                        StoreRMAura(u, a)
                        state.rmValidatedAt = now
                    elseif u == nil and a == nil then
                        -- Real scan happened, found nothing → clear tracking
                        ClearRMTracking()
                    end
                    -- u == false: throttled, leave state alone
                end
            end
        else
            local u, a = ScanRMOrThrottle()
            if u and a then
                StoreRMAura(u, a)
                state.rmValidatedAt = GetTime()
            elseif u == nil and a == nil then
                ClearRMTracking()
            end
        end
    end
    PerfMarkBlock("RMTRACK")

    -- ── Player's Soothing Mist target (for env + statue checks) ──
    -- Uses UnitChannelInfo to confirm the PLAYER is channeling,
    -- not just the statue. This prevents false alerts when the
    -- statue is soothing but the player isn't.
    --
    -- Tracks soothingStartTime on every transition (channel start,
    -- target switch, channel end). The EM alert below uses this to
    -- enforce a 3s grace period — short spot-heal channels shouldn't
    -- pester the player with EM alerts when no commitment is intended.
    --
    -- Combat-gated: SM channels out of combat are pre-pull top-offs
    -- where EM-missing alerts would be noise, not signal. If a channel
    -- is still active when combat begins (carry-over case), the gate
    -- opens at REGEN_DISABLED and the next Evaluate populates state
    -- from the live channel — alert fires on the first in-combat tick
    -- past the 3s grace.
    local now = GetTime()
    local soothUnit = nil
    if UnitAffectingCombat("player") then
        soothUnit = FindPlayerSoothingTarget()
    end
    if soothUnit ~= state.soothingUnit then
        if soothUnit then
            state.soothingStartTime = now
        else
            state.soothingStartTime = 0
        end
        -- New target (or channel end) → reset EM debounce so a stale
        -- envLastSeenTime from a prior target can't suppress a fresh
        -- "missing EM" detection on the new one.
        state.envLastSeenTime = 0
    end
    state.soothingUnit = soothUnit
    PerfMarkBlock("SOOTH")

    -- ── Enveloping Mist missing on Soothing Mist target ──────
    -- Only fires when:
    --   • the PLAYER is channeling (soothUnit set), AND
    --   • the channel has been on the SAME target for ≥ SOOTH_GRACE
    --     seconds (suppresses spot-heal noise during raid play), AND
    --   • the target doesn't already have Enveloping Mist (debounced
    --     at 0.5s to ride through aura list enumeration misses).
    local SOOTH_GRACE = 3.0
    local envMissing  = false
    local pastGrace   = soothUnit
        and state.soothingStartTime > 0
        and (now - state.soothingStartTime) >= SOOTH_GRACE
    if db.envEnabled and pastGrace then
        local hasEnv = UnitHasEnvelopingMist(soothUnit)
        if hasEnv then
            state.envLastSeenTime = now
            envMissing = false
        else
            -- EM not found — check debounce
            if state.envLastSeenTime > 0
               and (now - state.envLastSeenTime) < 0.5 then
                envMissing = false  -- seen recently, suppress flicker
            else
                envMissing = true
            end
        end
    elseif not soothUnit then
        -- Not channeling; reset debounce
        state.envLastSeenTime = 0
    end
    state.envActive = envMissing
    PerfMarkBlock("ENV")

    -- ── Rising-edge sounds ───────────────────────────────────
    if rmLow      and not state.rmWasActive  then NHA:PlayAlertSound("rm")  end
    if envMissing and not state.envWasActive then NHA:PlayAlertSound("env") end

    state.rmWasActive  = rmLow
    state.envWasActive = envMissing
    PerfMarkBlock("END")
end

-- =============================================================
-- OnActivate
-- =============================================================
function MonkMW:OnActivate(db)
    -- Populate raid-frame glows immediately rather than waiting for the
    -- next UNIT_AURA. CUFs may already be tracked at this point if the
    -- player just changed spec mid-group; without this nudge the glows
    -- would only appear after the first relevant aura change.
    if NHA.RefreshAllCUFs then
        C_Timer.After(0.1, function()
            NHA:RefreshAllCUFs()
        end)
    end
end

-- =============================================================
-- BuildAlertOptions (spec-specific options in the Alert Options section)
-- =============================================================
function MonkMW:BuildAlertOptions(parent, db, helpers)
    -- Single row with two numeric inputs side by side:
    --   "Target Renewing Mist (Party) [2]      (Raid) [4]"
    -- Built directly to control x positioning.
    -- Class-colored editboxes via GetClassColor.
    local r, g, b = GetClassColor(select(2, UnitClass("player")))
    r, g, b = r or 0.0, g or 1.0, b or 0.596

    -- Use MakeNumericInput for Party (advances cursor by -28, handles tracking)
    local partyBox = helpers.MakeNumericInput(
        "Target Renewing Mist (Party)",
        1, 20,
        function() return db.rmThresholdDungeon or 2 end,
        function(v)
            db.rmThresholdDungeon = v
            NHA.ScheduleEvaluate()
        end)
    partyBox:SetTextColor(r, g, b)

    -- Undo cursor advance — Raid will share the same row
    helpers.Spacer(-28)

    -- Raid input — use MakeNumericInput with short label then reposition
    local raidBox = helpers.MakeNumericInput(
        "Target Renewing Mist (Raid)",
        1, 40,
        function() return db.rmThresholdRaid or 4 end,
        function(v)
            db.rmThresholdRaid = v
            NHA.ScheduleEvaluate()
        end)
    raidBox:SetTextColor(r, g, b)

    -- Reanchor raidBox's label to sit right of the party editbox.
    -- partyBox is 4px below partyLbl (from the "LEFT, lbl, RIGHT, 8, 4" anchor).
    -- We anchor raidLbl LEFT of partyBox with +4 Y to compensate, keeping them
    -- on the same visual baseline.
    local _, partyLbl = partyBox:GetPoint(1)
    local _, raidLbl  = raidBox:GetPoint(1)
    if partyLbl and raidLbl
       and partyLbl ~= helpers.alertOptionsBox
       and raidLbl  ~= helpers.alertOptionsBox then
        raidLbl:ClearAllPoints()
        raidLbl:SetPoint("LEFT", partyLbl, "RIGHT", partyBox:GetWidth() + 24, 0)
    end
end

-- =============================================================
-- OnDeactivate
-- =============================================================
function MonkMW:OnDeactivate(db)
    -- State is cleared by core calling ClearAllState + ClearAllGlows
end

-- =============================================================
-- OnEvent
-- =============================================================
function MonkMW:OnEvent(db, event, ...)
    if event == "UNIT_AURA" then
        local unit, updateInfo = ...

        -- RM tracked unit: fast-path removal
        if unit == state.rmUnit then
            if not updateInfo or updateInfo.isFullUpdate then
                ResetRMFullScanThrottle()
                NHA.ScheduleEvaluate(); return true
            end
            if updateInfo.removedAuraInstanceIDs and state.rmInstID then
                for _, instID in ipairs(updateInfo.removedAuraInstanceIDs) do
                    if instID == state.rmInstID then
                        ClearRMTracking()
                        ResetRMFullScanThrottle()
                        NHA.ScheduleEvaluate()
                        return true
                    end
                end
            end
            if updateInfo.updatedAuraInstanceIDs and state.rmInstID then
                for _, instID in ipairs(updateInfo.updatedAuraInstanceIDs) do
                    if instID == state.rmInstID then
                        ResetRMFullScanThrottle()
                        NHA.ScheduleEvaluate(); return true
                    end
                end
            end
            if updateInfo.addedAuras then
                for _, aura in ipairs(updateInfo.addedAuras) do
                    if not issecretvalue(aura.spellId)
                       and aura.spellId == RENEWING_MIST_ID
                       and IsPlayerOrUnknownSource(aura) then
                        ResetRMFullScanThrottle()
                        NHA.ScheduleEvaluate(); return true
                    end
                end
            end
            return true
        end

        -- Other units: trigger scan if RM not yet tracked
        if not state.rmUnit and not state.rmScanPending then
            if not updateInfo or updateInfo.isFullUpdate or updateInfo.addedAuras then
                state.rmScanPending = true
                C_Timer.After(0.1, function()
                    state.rmScanPending = false
                    ResetRMFullScanThrottle()
                    NHA.Evaluate()
                end)
            end
        end

        -- General debounce
        if not state.playerAuraPending then
            state.playerAuraPending = true
            C_Timer.After(0.1, function()
                state.playerAuraPending = false
                NHA.Evaluate()
            end)
        end
        return true
    end

    if event == "GROUP_ROSTER_UPDATE" then
        if not state.rosterUpdatePending then
            state.rosterUpdatePending = true
            C_Timer.After(0.5, function()
                state.rosterUpdatePending = false
                NHA.Evaluate()
            end)
        end
        return true
    end

    if event == "PLAYER_REGEN_ENABLED" then
        ClearRMTracking()
        state.soothingUnit      = nil
        state.soothingGUID      = nil
        state.soothingStartTime = 0
        NHA.ScheduleEvaluate()
        return false
    end

    if event == "PLAYER_REGEN_DISABLED" then
        -- Combat enter: drive a fresh evaluation of every tracked
        -- CompactUnitFrame so any auras applied in the pre-pull
        -- window light up the moment the pull starts. Without this,
        -- the public EvaluateCUFGlow shim would have ignored every
        -- pre-pull UNIT_AURA event (it's combat-gated to suppress
        -- raid-lobby noise), so the dirty queue would be empty and
        -- the next ticker drain would have nothing to process.
        --
        -- RefreshAllCUFs in core walks _cufPool and calls
        -- EvaluateCUFGlow(db, frame, unit) for each — which now
        -- passes the combat check and enqueues into dirtyCUFFrames.
        -- DrainGlowDirtySet picks them up on the next ticker pass
        -- (worst case 0.25s after pull).
        if NHA.RefreshAllCUFs then
            NHA:RefreshAllCUFs()
        end
        NHA.ScheduleEvaluate()
        return false
    end

    if event == "PLAYER_TALENT_UPDATE"
    or event == "PLAYER_SPECIALIZATION_CHANGED"
    or event == "TRAIT_CONFIG_UPDATED" then
        NHA.ScheduleEvaluate()
        return false
    end

    if event == "PLAYER_ENTERING_WORLD" then
        NHA.ScheduleEvaluate()
        return false
    end

    return false
end

-- =============================================================
-- Slash Commands
-- =============================================================
MonkMW.slashCommands = {
    ["debug"] = function(self, db)
        NHA.Msg("|cffffd700Mistweaver Monk Debug:|r")
        NHA.Msg("  enabled: "          .. tostring(db.enabled))
        NHA.Msg("  rmEnabled: "        .. tostring(db.rmEnabled))
        NHA.Msg("  envEnabled: "       .. tostring(db.envEnabled))
        NHA.Msg("  cufGlowEnabled: "   .. tostring(db.cufGlowEnabled))
        NHA.Msg("  rmActive: "         .. tostring(state.rmActive))
        NHA.Msg("  envActive: "        .. tostring(state.envActive))
        NHA.Msg("  soothingUnit: "     .. tostring(state.soothingUnit))
        NHA.Msg("  rmThresholdDungeon: " .. tostring(db.rmThresholdDungeon))
        NHA.Msg("  rmThresholdRaid: "  .. tostring(db.rmThresholdRaid))

        -- RM tracking
        NHA.Msg("  rmUnit: "    .. tostring(state.rmUnit))
        NHA.Msg("  rmInstID: "  .. tostring(state.rmInstID))
        if state.rmUnit and state.rmExpire > 0 then
            local remaining = (state.rmExpire - GetTime()) / state.rmTimeMod
            NHA.Msg("  rmRemaining: " .. string_format("%.1f", remaining) .. "s")
        end

        -- Active Renewing Mist count
        local activeRM = CountActiveRenewingMist()
        local rmThreshold = GetRMThreshold()
        NHA.Msg("  activeRenewingMist: " .. activeRM .. " / threshold: " .. rmThreshold)

        if state.soothingUnit then
            local hasEnv = UnitHasEnvelopingMist(state.soothingUnit)
            NHA.Msg("  hasEnvelopingMist(soothingUnit): " .. tostring(hasEnv))
        end

        -- Soothing channel detection diagnostics — useful for
        -- troubleshooting cases where the EM alert doesn't fire
        -- when expected (e.g., self-channels, statue interference).
        local channelName = UnitChannelInfo and UnitChannelInfo("player")
        NHA.Msg("  UnitChannelInfo(player): " .. tostring(channelName or "(none)"))
        NHA.Msg("  IsPlayerChannelingSoothing: " .. tostring(IsPlayerChannelingSoothing()))
        NHA.Msg("  player has 115175: "
            .. tostring(FindAuraOnUnit("player", SOOTHING_MIST_ID, false) ~= nil))
        NHA.Msg("  detected soothUnit (live): " .. tostring(FindPlayerSoothingTarget()))
        NHA.Msg("  cachedSoothUnit: " .. tostring(cachedSoothUnit))
        -- Per-unit 115175 presence (helpful when the live detection
        -- returns a non-obvious target, e.g. statue interference).
        local smList = {}
        for _, unit in ipairs(NHA:GetGroupUnits()) do
            if FindAuraOnUnit(unit, SOOTHING_MIST_ID, false) then
                smList[#smList+1] = unit
            end
        end
        if #smList > 0 then
            NHA.Msg("  units with 115175: " .. table.concat(smList, ", "))
        else
            NHA.Msg("  units with 115175: (none)")
        end
    end,

    -- /nha cufglow — diagnose raid-frame whole-frame glow state
    -- Mirrors the Druid Restoration cufglow command. Reports hook
    -- install state, tracked CUF count, RM cache size, and per-unit
    -- aura state so we can pinpoint where a missing glow stops.
    ["cufglow"] = function(self, db)
        NHA.Msg("|cffffd700CUF Frame Glow Debug:|r")
        NHA.Msg("  cufGlowEnabled: " .. tostring(db.cufGlowEnabled))
        NHA.Msg("  cufHooks: "       .. tostring(NHA._cufHooksInstalled and "installed" or "not installed"))
        local trackedCount = 0
        for _ in pairs(NHA._cufPool or {}) do trackedCount = trackedCount + 1 end
        local emCacheCount = 0
        for _ in pairs(cufEMCache) do emCacheCount = emCacheCount + 1 end
        local rmCacheCount = 0
        for _ in pairs(cufRMCache) do rmCacheCount = rmCacheCount + 1 end
        local dirtyCount = 0
        for _ in pairs(dirtyCUFFrames) do dirtyCount = dirtyCount + 1 end
        local stateEMCount, stateRMCount = 0, 0
        for _, kind in pairs(cufStateMap) do
            if     kind == "em" then stateEMCount = stateEMCount + 1
            elseif kind == "rm" then stateRMCount = stateRMCount + 1
            end
        end
        NHA.Msg("  tracked CUFs: "    .. trackedCount)
        NHA.Msg("  in combat: "       .. tostring(UnitAffectingCombat("player")))
        NHA.Msg("  cufEMCache size: " .. emCacheCount)
        NHA.Msg("  cufRMCache size: " .. rmCacheCount)
        NHA.Msg("  dirtyCUFFrames: "  .. dirtyCount .. " (pending refreshes for next ticker drain)")
        NHA.Msg("  glowing (EM/RM): "
            .. stateEMCount .. " / " .. stateRMCount)

        -- Step 1: enumerate _unitCUFs — what unit tokens are tracked
        NHA.Msg("|cffffd700  Tracked _unitCUFs entries:|r")
        local entries = 0
        for unit, set in pairs(NHA._unitCUFs or {}) do
            local n = 0
            for _ in pairs(set) do n = n + 1 end
            local nameOk, name = pcall(UnitName, unit)
            local existsOk, exists = pcall(UnitExists, unit)
            NHA.Msg(string_format(
                "  %s -> %d frame(s)  name=%s  exists=%s",
                tostring(unit),
                n,
                (nameOk and tostring(name)) or "?",
                tostring(existsOk and exists)))
            entries = entries + 1
            if entries >= 12 then
                NHA.Msg("  ... (truncated)")
                break
            end
        end

        -- Step 2: per-unit EM/RM presence — which auras are detectable?
        NHA.Msg("|cffffd700  Per-unit aura detection (EM/RM):|r")
        local probedUnits = 0
        for unit in pairs(NHA._unitCUFs or {}) do
            if probedUnits >= 8 then break end
            local existsOk, exists = pcall(UnitExists, unit)
            if existsOk and exists then
                local nameOk, name = pcall(UnitName, unit)
                local hasEM = FindAuraOnUnit(unit, ENVELOPING_MIST_ID, true) ~= nil
                local rmAura = FindAuraOnUnit(unit, RENEWING_MIST_ID,  true)
                local rmStr  = "no"
                if rmAura then
                    local exp = SafeNum(rmAura.expirationTime, 0)
                    local tm  = SafeNum(rmAura.timeMod, 1)
                    if tm <= 0 then tm = 1 end
                    rmStr = string_format("%.1fs", (exp - GetTime()) / tm)
                end
                -- Find the frame for this unit to report its glow kind
                local glowKind = "none"
                if NHA._unitCUFs and NHA._unitCUFs[unit] then
                    for f in pairs(NHA._unitCUFs[unit]) do
                        if cufStateMap[f] then
                            glowKind = cufStateMap[f]
                            break
                        end
                    end
                end
                NHA.Msg(string_format(
                    "  %s (%s): EM=%s  RM=%s  glow=%s",
                    unit,
                    (nameOk and tostring(name)) or "?",
                    tostring(hasEM),
                    rmStr,
                    glowKind))
                probedUnits = probedUnits + 1
            end
        end
    end,

    -- =========================================================
    -- /nha perf — wraps Evaluate + EvaluateCUFGlow + RefreshGlows
    -- with debugprofilestop() timing and a per-frame spike detector.
    -- The core dispatches slash commands by exact-string match on
    -- the trimmed input, so each sub-command is its own key:
    --   /nha perf on   → start timing
    --   /nha perf      → mid-fight peek (no reset)
    --   /nha perf off  → stop and dump final stats
    --
    -- Wrapping is external (monkey-patched on MonkMW.Evaluate /
    -- .EvaluateCUFGlow / .RefreshGlows) so it can be enabled/disabled
    -- without /reload, and the OFF cost is exactly zero — the original
    -- functions are restored byref.
    --
    -- Reading the output:
    --   Evaluate avg > 1ms       → spec scans are hot
    --   Evaluate avg < 0.3ms but Encounter CPU still high
    --                            → drill into CUF GLOW + spike sections.
    --                              Worst-frame total > 10ms is the
    --                              most likely cause of perceived
    --                              "20% CPU spike" reports — those
    --                              are per-frame events that per-call
    --                              averages smooth away.
    --
    -- Block breakdown (RMCOUNT / RMTRACK / SOOTH / ENV / END):
    --   RMCOUNT — 30-unit walk for low-coverage Spread RM alert.
    --   RMTRACK — soonest-expiring RM validation cache + fallback.
    --   SOOTH   — UnitChannelInfo + cached/uncached SM target lookup.
    --   ENV     — single FindAuraOnUnit on soothUnit.
    --   END     — rising-edge sound dispatch + state assignments.
    --
    -- CUF GLOW path tags (em/rm/none/disabled):
    --   em  → glowed Enveloping Mist priority
    --   rm  → glowed Renewing Mist priority
    --   none → no aura matched (the most expensive case — runs both
    --          FindAuraOnUnit lookups). High `none` count relative to
    --          total = lots of wasted CUF glow refreshes.
    --   disabled → cufGlowEnabled=false; cheap.
    --
    -- Spike record reports the worst single render frame seen,
    -- attributed across the three instrumented functions. WoW frames
    -- run at ~16.7ms; a worst-frame total above ~12ms is what causes
    -- the addon panel's Peak CPU readouts to climb.
    -- =========================================================
    ["perf on"] = function(self, db)
        local perf = state._perf
        if not perf then
            perf = { enabled = false }
            state._perf = perf
        end
        if perf.enabled then NHA.Msg("|cffffd700NHA Perf:|r already on"); return end
        perf.enabled       = true
        perf.calls         = 0
        perf.totalMs       = 0
        perf.maxMs         = 0
        perf.startMs       = debugprofilestop()
        -- Per-block instrumentation — gated by blocksEnabled flag
        -- read inside Evaluate at each PerfMarkBlock checkpoint.
        perf.blocksEnabled = true
        perf.blocks        = {}
        -- CUF glow stats (per-path attribution + aggregate)
        perf.cuf = {
            calls = 0, totalMs = 0, maxMs = 0,
            paths = { em = 0, rm = 0, none = 0, disabled = 0 },
        }
        -- RefreshGlows (ticker safety net — should be cheap)
        perf.refresh = { calls = 0, totalMs = 0, maxMs = 0 }
        -- Spike record (worst single render frame seen)
        perf.spike = {
            totalMs = 0, evalMs = 0, cufMs = 0, refreshMs = 0,
            cufCount = 0, atTime = 0,
        }

        -- ── Evaluate wrap ──
        perf.origEvaluate  = MonkMW.Evaluate
        MonkMW.Evaluate = function(slf, sdb)
            PerfFrameRoll()
            local t0 = debugprofilestop()
            perf.origEvaluate(slf, sdb)
            local dt = debugprofilestop() - t0
            perf.calls   = perf.calls + 1
            perf.totalMs = perf.totalMs + dt
            if dt > perf.maxMs then perf.maxMs = dt end
            _perfFrameTotal = _perfFrameTotal + dt
            _perfFrameEval  = _perfFrameEval  + dt
        end

        -- ── CUF glow attribution ──
        -- Note: The public MonkMW.EvaluateCUFGlow is now a cheap shim
        -- that just enqueues into dirtyCUFFrames. Wrapping the shim
        -- would only measure the dispatch cost (~0.001ms) and miss
        -- the actual work. Per-call CUF stats (calls/totalMs/maxMs/
        -- paths) flow through inline instrumentation in
        -- InstrumentedDoEvaluateCUFGlow, called from DrainGlowDirtySet
        -- and the RefreshGlows safety-net re-eval. That instrumentation
        -- reads `perf.enabled` directly, so it activates without any
        -- wrap install on this side.

        -- ── RefreshGlows wrap ──
        perf.origRefresh = MonkMW.RefreshGlows
        MonkMW.RefreshGlows = function(slf, sdb)
            PerfFrameRoll()
            local t0 = debugprofilestop()
            perf.origRefresh(slf, sdb)
            local dt = debugprofilestop() - t0
            local r = perf.refresh
            r.calls   = r.calls + 1
            r.totalMs = r.totalMs + dt
            if dt > r.maxMs then r.maxMs = dt end
            _perfFrameTotal = _perfFrameTotal + dt
            _perfFrameRefr  = _perfFrameRefr  + dt
        end

        NHA.Msg("|cff00ff00NHA Perf: ENABLED|r — wraps on Evaluate + EvaluateCUFGlow + RefreshGlows. Run a pull, then /nha perf off")
    end,

    ["perf off"] = function(self, db)
        local perf = state._perf
        if not perf or not perf.enabled then
            NHA.Msg("|cffffd700NHA Perf:|r already off"); return
        end
        -- Restore byref before any final flush so the spike-roll
        -- sees the un-instrumented state on its next call. The CUF
        -- glow attribution doesn't need a restore — it's driven by
        -- inline instrumentation gated on perf.enabled, which we
        -- clear below.
        MonkMW.Evaluate         = perf.origEvaluate
        MonkMW.RefreshGlows     = perf.origRefresh
        perf.origEvaluate       = nil
        perf.origRefresh        = nil
        -- One last roll so the final frame's totals make it into spike
        -- before we read it (perf.enabled still true at this moment).
        PerfFrameRoll()
        perf.enabled            = false
        perf.blocksEnabled      = false

        if perf.calls == 0 then
            NHA.Msg("|cffffd700NHA Perf FINAL:|r no samples")
            return
        end

        local elapsed = (debugprofilestop() - perf.startMs) / 1000
        local rate    = elapsed > 0 and (perf.calls / elapsed) or 0
        local avg     = perf.totalMs / perf.calls
        NHA.Msg(string_format(
            "|cffffd700NHA Perf FINAL:|r %.1fs, %d calls (%.1f/s), avg=%.3fms max=%.3fms total=%.1fms",
            elapsed, perf.calls, rate, avg, perf.maxMs, perf.totalMs))

        -- Block breakdown — fixed display order so reads are stable
        local order = { "RMCOUNT", "RMTRACK", "SOOTH", "ENV", "END" }
        for _, name in ipairs(order) do
            local b = perf.blocks and perf.blocks[name]
            if b and b.calls > 0 then
                NHA.Msg(string_format(
                    "  %-8s avg=%.3fms max=%.3fms total=%.1fms (%d calls)",
                    name, b.totalMs / b.calls, b.maxMs, b.totalMs, b.calls))
            end
        end

        -- CUF GLOW aggregate + per-path breakdown
        local cuf = perf.cuf
        if cuf and cuf.calls > 0 then
            local cufRate = elapsed > 0 and (cuf.calls / elapsed) or 0
            local cufAvg  = cuf.totalMs / cuf.calls
            NHA.Msg(string_format(
                "|cffffd700CUF GLOW:|r %d calls (%.1f/s) avg=%.3fms max=%.3fms total=%.1fms",
                cuf.calls, cufRate, cufAvg, cuf.maxMs, cuf.totalMs))
            NHA.Msg(string_format(
                "  paths: EM=%d  RM=%d  NONE=%d  DISABLED=%d",
                cuf.paths.em or 0, cuf.paths.rm or 0,
                cuf.paths.none or 0, cuf.paths.disabled or 0))
        else
            NHA.Msg("|cffffd700CUF GLOW:|r no calls in window")
        end

        -- RefreshGlows aggregate
        local r = perf.refresh
        if r and r.calls > 0 then
            local rRate = elapsed > 0 and (r.calls / elapsed) or 0
            local rAvg  = r.totalMs / r.calls
            NHA.Msg(string_format(
                "|cffffd700REFRESH:|r %d calls (%.1f/s) avg=%.3fms max=%.3fms total=%.1fms",
                r.calls, rRate, rAvg, r.maxMs, r.totalMs))
        end

        -- Worst frame in window — the per-frame spike record
        local s = perf.spike
        if s and s.totalMs > 0 then
            NHA.Msg(string_format(
                "|cffffd700WORST FRAME:|r %.3fms total (Eval=%.3fms  CUF=%.3fms x%d  Refresh=%.3fms)",
                s.totalMs, s.evalMs, s.cufMs, s.cufCount, s.refreshMs))
        end
    end,

    ["perf"] = function(self, db)
        local perf = state._perf
        if not perf or perf.calls == 0 then
            NHA.Msg("|cffffd700NHA Perf:|r " ..
                ((perf and perf.enabled) and "RUNNING — no samples yet"
                                          or "off (use /nha perf on)"))
            return
        end
        local elapsed = (debugprofilestop() - perf.startMs) / 1000
        local rate    = elapsed > 0 and (perf.calls / elapsed) or 0
        local avg     = perf.totalMs / perf.calls
        NHA.Msg(string_format(
            "|cffffd700NHA Perf %s:|r %.1fs, %d Eval (%.1f/s), avg=%.3fms max=%.3fms",
            perf.enabled and "RUNNING" or "STOPPED",
            elapsed, perf.calls, rate, avg, perf.maxMs))
        local cuf = perf.cuf
        if cuf and cuf.calls > 0 then
            local cufRate = elapsed > 0 and (cuf.calls / elapsed) or 0
            NHA.Msg(string_format(
                "  CUF: %d calls (%.1f/s) avg=%.3fms max=%.3fms",
                cuf.calls, cufRate, cuf.totalMs / cuf.calls, cuf.maxMs))
        end
        local s = perf.spike
        if s and s.totalMs > 0 then
            NHA.Msg(string_format(
                "  worst frame: %.3fms (E=%.3f C=%.3f x%d R=%.3f)",
                s.totalMs, s.evalMs, s.cufMs, s.cufCount, s.refreshMs))
        end
    end,
}
-- Register with core
NHA:RegisterSpec("MONK_MW", MonkMW)
