VoiceOver = VoiceOver or {}
setfenv(1, VoiceOver)
SoundQueue = SoundQueue or {}

local MAX_SOUND_DURATION = 4.0
local SOUND_CHANNEL = "Master" -- Asegura que no se silencien otros canales
local soundCooldown = false    -- Bloqueo temporal para evitar duplicados

-- Variables para el estado del módulo
local isRareAnnounceActive = false
local isRareAnnounceDebugEnabled = false

-- Función para imprimir mensajes de depuración en el chat
local function RareAnnounceDebugPrint(message)
    if isRareAnnounceDebugEnabled then
        DEFAULT_CHAT_FRAME:AddMessage("|cFF00FF00[Rare Announce Debug]|r " .. message)
    end
end

local RED = "|cFFFF0000"
local GREEN = "|cFF00FF00"
local RESET = "|r"

-- DebugPrint(RED .. "RareTracker module loaded" .. RESET)

local frame = CreateFrame("Frame")
frame:RegisterEvent("VIGNETTE_MINIMAP_UPDATED")

local playedRares = {}

local genericSound = {
    fileName = "Rare_Detected_Generic",
    duration = 4.0,
}

frame:SetScript("OnEvent", function(self, event, ...)
    if not isRareAnnounceActive then return end -- No hacer nada si el módulo está desactivado
    if event == "VIGNETTE_MINIMAP_UPDATED" and not soundCooldown then
        local vignettes = C_VignetteInfo.GetVignettes()
        for _, vignetteGUID in pairs(vignettes) do
            local vignetteInfo = C_VignetteInfo.GetVignetteInfo(vignetteGUID)
            if vignetteInfo and vignetteInfo.atlasName == "VignetteKill" then
                local npcID = vignetteInfo.objectGUID and tonumber(vignetteInfo.objectGUID:match("-(%d+)-%x+$"))
                if npcID and not playedRares[npcID] then
                    playedRares[npcID] = true
                    TryQueueRareSound(genericSound.fileName, npcID, genericSound.duration, vignetteInfo.name)
                    -- Mostrar letrero en pantalla
                    --RaidNotice_AddMessage(RaidWarningFrame, GREEN .. vignetteInfo.name .. " ha sido detectado y sonado!" .. RESET, ChatTypeInfo["RAID_WARNING"])
                end
            end
        end
    end
end)

function TryQueueRareSound(soundFileName, npcID, duration, npcName)
    local function attemptPlaySound()
        if SoundQueue:IsEmpty() then
            QueueRareSound(soundFileName, npcID, duration, npcName)
        else
            C_Timer.After(3, attemptPlaySound)
        end
    end

    attemptPlaySound()
end

local function CheckSoundQueueTimeout()
    local currentSound = SoundQueue:GetCurrentSound()
    if currentSound then
        local elapsed = GetTime() - (currentSound.startTime or GetTime())
        if elapsed > MAX_SOUND_DURATION then
            SoundQueue:RemoveAllSoundsFromQueue()
        end
    end
    C_Timer.After(5, CheckSoundQueueTimeout)
end

CheckSoundQueueTimeout()

function QueueRareSound(soundFileName, npcID, duration, npcName)
    if soundCooldown then return end
    soundCooldown = true

    local soundFilePath = "Interface/AddOns/AI_VoiceOverData_WarWithin_es/generated/sounds/rares/" ..
    soundFileName .. ".mp3"

    local soundData = {
        event = Enums.SoundEvent.NPCDialogue,
        fileName = soundFileName,
        filePath = soundFilePath,
        length = duration,
        title = "Rare Detectado",
        name = GREEN .. npcName .. RESET,
        unitGUID = npcID and string.format("Creature-0-0-0-0-%d", npcID) or nil,
        startTime = GetTime(),

        addedCallback = function(sd)
            SoundQueueUI:UpdateSoundQueueDisplay()
        end,
        startCallback = function(sd)
            if sd.unitGUID and SoundQueueUI.frame.portrait.SetCreature then
                SoundQueueUI.frame.portrait:SetCreature(sd.unitGUID)
                SoundQueueUI.frame.portrait:Show()
                SoundQueueUI.frame.portrait:SetAnimation(60)
            end
        end,
        stopCallback = function(sd)
            SoundQueue:RemoveSoundFromQueue(sd)
            if SoundQueue:IsEmpty() then
                SoundQueueUI.frame.container.name:SetText("")
                SoundQueueUI.frame.container:Hide()
                soundCooldown = false -- Desbloquea para permitir nuevos sonidos
            end
        end,
    }

    if SoundQueue and SoundQueue.AddSoundToQueue then
        local soundExists = DataModules:PrepareSound(soundData)
        if soundExists then
            SoundQueue:AddSoundToQueue(soundData)
            PlaySoundFile(soundFilePath, SOUND_CHANNEL)
        else
            soundCooldown = false -- Desbloquea si no existe el sonido
        end
    else
        soundCooldown = false -- Desbloquea si no hay cola de sonido disponible
    end
end

function ResetPlayedRares()
    playedRares = {}
    RareAnnounceDebugPrint(GREEN .. "Reset played rares table" .. RESET)
end

-- Función para activar el módulo
function ActivateRareAnnounce()
    isRareAnnounceActive = true
    isRareAnnounceDebugEnabled = Addon.db.profile.RareAnnounceDebugEnabled
    RareAnnounceDebugPrint("|cff00ff00Rare Announce Module Activated|r")
end

-- Función para desactivar el módulo
function DeactivateRareAnnounce()
    isRareAnnounceActive = false
    isRareAnnounceDebugEnabled = false
    RareAnnounceDebugPrint("|cffff0000Rare Announce Module Deactivated|r")
end

-- Exponer las funciones de activación/desactivación
VoiceOver.RareAnnounce = VoiceOver.RareAnnounce or {}
VoiceOver.RareAnnounce.Activate = ActivateRareAnnounce
VoiceOver.RareAnnounce.Deactivate = DeactivateRareAnnounce
