-- ## Author: ChatGPT ## Version: 2.6.10
local THRESHOLD, SOUND_ON = 0.50, true
local alerted, ticker = false, nil

-- Visual flash helper
local flashFrame
local function Flash()
    if not flashFrame then
        flashFrame = CreateFrame("Frame", nil, UIParent)
        flashFrame:SetAllPoints(UIParent)
        flashFrame:SetFrameStrata("FULLSCREEN_DIALOG")
        local tex = flashFrame:CreateTexture(nil, "BACKGROUND")
        tex:SetAllPoints(flashFrame)
        tex:SetColorTexture(1, 0, 0, 0.45)
        flashFrame.texture = tex
    end
    flashFrame:Show()
    C_Timer.After(0.35, function() flashFrame:Hide() end)
end

local function PlayCue()
    if SOUND_ON then PlaySoundFile("Interface\\AddOns\\OrzUI\\Media\\Sounds\\Beep.ogg", "Master") end
end

local function Alert()
    Flash()
    PlayCue()
end

local function Evaluate()
    if UnitClassBase("player") ~= "HUNTER" then return end
    if not UnitExists("pet") or UnitIsDead("pet") then alerted = false return end
    local hp, max = UnitHealth("pet"), UnitHealthMax("pet")
    if max == 0 then return end
    if (hp / max) <= THRESHOLD then
        if not alerted then Alert(); alerted = true end
    else
        alerted = false
    end
end

local function StartTicker()
    if ticker then ticker:Cancel() end
    ticker = C_Timer.NewTicker(0.25, Evaluate)
end

local frame = CreateFrame("Frame")
frame:RegisterEvent("ADDON_LOADED")
frame:SetScript("OnEvent", function(_, event, arg)
    if arg == "OrzUI" then
        StartTicker()
    end
end)

-- Slash commands
SLASH_PHA1 = "/pha"
SlashCmdList["PHA"] = function(msg)
    msg = (msg or ""):match("^%s*(.-)%s*$"):lower()
    if msg == "sound" then
        SOUND_ON = not SOUND_ON
        print("Pet Heal Alert sound", SOUND_ON and "ON" or "OFF")
    elseif msg == "test" then
        PlayCue()
    elseif msg:match("^hp%s+") then
        local v = tonumber(msg:match("^hp%s+(%d?%.?%d+)"))
        if v and v > 0 and v < 1 then
            THRESHOLD = v
            print(string.format("Threshold set to %.0f%%", v * 100))
        end
    else
        print("|cff33ff99Pet Heal Alert commands:|r")
        print("  /pha sound        - toggle audio")
        print("  /pha test         - play alert immediately")
        print("  /pha hp X         - set threshold (0 < X < 1)")
    end
end
