local ADDON, ns = ...

ns.Interrupt = ns.Interrupt or {}
local I = ns.Interrupt

local function Now()
    return GetTime()
end

function I:Trigger(plate)
    if not plate or not ns.DB then return end
    local ttl = (ns.DB.interrupt and ns.DB.interrupt.ttl) or 0.8
    plate.NPCT_InterruptedUntil = Now() + ttl
end

function I:IsActive(plate)
    local untilT = plate and plate.NPCT_InterruptedUntil
    if not untilT then return false end
    return Now() < untilT
end

function I:Clear(plate)
    if plate then plate.NPCT_InterruptedUntil = nil end
end

-- Hook Blizzard castbar OnEvent (Blizzard already registered events)
function I:HookBlizzCastbar(blizz, plate)
    if not blizz or blizz._npctHooked then return end
    blizz._npctHooked = true

    blizz:HookScript("OnEvent", function(self, event, unitArg)
        local u = self.unit or unitArg
        if type(u) ~= "string" then return end
        if not (plate and plate.unitToken) then return end
        if u ~= plate.unitToken then return end

        if event == "UNIT_SPELLCAST_INTERRUPTED"
        or event == "UNIT_SPELLCAST_FAILED"
        or event == "UNIT_SPELLCAST_FAILED_QUIET" then
            I:Trigger(plate)
        end
    end)
end
