local fearSpell = "Psychic Scream"
local fearID = 10890
local activeFears = {}

local f = CreateFrame("Frame")
f:RegisterEvent("COMBAT_LOG_EVENT_UNFILTERED")

f:SetScript("OnEvent", function(self, event, ...)
    local _, subEvent, _, _, _, destGUID, destName, _, arg9, arg10, _, arg12 = ...

    if subEvent == "SPELL_AURA_APPLIED" and (arg10 == fearSpell or arg9 == fearID) then
        local maxHP = 20000 
        if UnitGUID("target") == destGUID then maxHP = UnitHealthMax("target") end
        
        activeFears[destGUID] = {
            name = destName,
            limit = maxHP * 0.10,
            active = true,
        }
    
    elseif subEvent:find("_DAMAGE") and activeFears[destGUID] and activeFears[destGUID].active then
        local damage = (subEvent == "SWING_DAMAGE") and arg9 or arg12
        if damage and damage > 0 then
            activeFears[destGUID].limit = activeFears[destGUID].limit - damage
            if activeFears[destGUID].limit <= 0 then activeFears[destGUID].active = false end
        end

    elseif subEvent == "SPELL_AURA_REMOVED" and (arg10 == fearSpell or arg9 == fearID) then
        activeFears[destGUID] = nil
    end
end)

local function GetPlateData(frame)
    local healthBar, nameRegion
    for _, child in ipairs({frame:GetChildren()}) do
        if child:IsObjectType("StatusBar") then healthBar = child break end
    end
    for _, region in ipairs({frame:GetRegions()}) do
        if region:IsObjectType("FontString") then nameRegion = region break end
    end
    return healthBar, nameRegion
end

-- 3. Отрисовка
f:SetScript("OnUpdate", function(self, elapsed)
    self.timer = (self.timer or 0) + elapsed
    if self.timer < 0.05 then return end
    self.timer = 0

    local kids = {WorldFrame:GetChildren()}
    for _, frame in ipairs(kids) do
        if not frame:GetName() or frame:GetName():find("NamePlate") then
            local healthBar, nameRegion = GetPlateData(frame)
            
            if healthBar and nameRegion then
                local unitName = nameRegion:GetText()
                
                if not frame.fearText then
                    frame.fearText = frame:CreateFontString(nil, "OVERLAY")
                    frame.fearText:SetFont("Fonts\\FRIZQT__.TTF", 16, "OUTLINE")
                    frame.fearText:SetPoint("BOTTOM", healthBar, "TOP", 8, -28)
                    frame.fearText:SetTextColor(1, 1, 0)
                end

                local found = false
                for guid, data in pairs(activeFears) do
                    if data.name == unitName and data.active then
                        frame.fearText:SetText(math.max(0, math.floor(data.limit)))
                        frame.fearText:Show()
                        found = true
                        break
                    end
                end
                
                if not found then frame.fearText:Hide() end
            end
        end
    end
end)
