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

-- Variables globales del módulo
local isModuleActive = false
local isDebugEnabled = false

-- Función para imprimir mensajes de depuración en el chat
local function DebugPrint(message)
    if isDebugEnabled then
        Debug:Print(message, "ItemReader")
    end
end

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

DebugPrint(RED .. "ItemSoundPlayer module loaded" .. RESET)

local frame = CreateFrame("Frame")
frame:RegisterEvent("CHAT_MSG_LOOT")
frame:RegisterEvent("CHAT_MSG_MONSTER_SAY")
frame:RegisterEvent("CHAT_MSG_MONSTER_YELL")
frame:RegisterEvent("CHAT_MSG_MONSTER_WHISPER")
frame:RegisterEvent("CHAT_MSG_MONSTER_EMOTE")

-- NPC ID predeterminado
local DEFAULT_CREATURE_ID = 15608

-- Definición de mapeo de sonidos (mantén tu tabla actual)
local soundMapping = {
    ["Papiro de maderaférrea petrificado"] = { fileName = "Papiro_de_maderaférrea_petrificado-nota", duration = 25.63, creatureID = 15608 },
    ["Cuerno prístino"] = { fileName = "Cuerno_prístino-nota", duration = 10.84, creatureID = 15608 },
    ["Corazón de piedra roto"] = { fileName = "Corazón_de_piedra_roto-nota", duration = 2.38, creatureID = 15608 },
    ["Corazón corrupto"] = { fileName = "Corazón_corrupto-nota", duration = 7.78, creatureID = 15608 },
    ["Ojo invidente"] = { fileName = "Ojo_invidente-nota", duration = 7.08, creatureID = 15608 },
    ["Tajada de raíz"] = { fileName = "Tajada_de_raíz-nota", duration = 10.50, creatureID = 15608 },
    ["Esencia discordante"] = { fileName = "Esencia_discordante-nota", duration = 11, creatureID = 15608 },
    ["Poción de sombra brillante"] = { fileName = "Poción_de_sombra_brillante-nota", duration = 5.90, creatureID = 15608 },
    ["Cristal de sintonía"] = { fileName = "Cristal_de_sintonía-nota", duration = 3.74, creatureID = 15608 },
    ["Trozo de sivpétrea"] = { fileName = "Trozo_de_sivpétrea-nota", duration = 6.74, creatureID = 15608 },
    ["Piedra cantora"] = { fileName = "Piedra_cantora-nota", duration = 6.11, creatureID = 15608 },
    ["Coraza de herrero"] = { fileName = "Coraza_de_herrero-nota", duration = 12.04, creatureID = 15608 },
    ["Simplemente bife"] = { fileName = "Simplemente_bife-nota", duration = 6.58, creatureID = 15608 },
    ["Espíritu de tormenta"] = { fileName = "Espíritu_de_tormenta-nota", duration = 5.67, creatureID = 15608 },
    ["Emisor de feromonas de Zev'kall"] = { fileName = "Emisor_de_feromonas_de_Zev'kall-nota", duration = 6.82, creatureID = 15608 },
    ["Inteligencia nerubiana"] = { fileName = "Inteligencia_nerubiana-nota", duration = 6.77, creatureID = 15608 },
    ["Cuchillas de Flynn"] = { fileName = "Cuchillas_de_Flynn-nota", duration = 4.78, creatureID = 15608 },
    ["Huesos blanqueados"] = { fileName = "Huesos_blanqueados-nota", duration = 8.91, creatureID = 15608 },
    ["Retazo de tela desgastada"] = { fileName = "Retazo_de_tela_desgastada-nota", duration = 8.36, creatureID = 15608 },
    ["Guantelete de león abollado"] = { fileName = "Guantelete_de_león_abollado-nota", duration = 6.87, creatureID = 15608 },
    ["Llaves de Mascaengranajes"] = { fileName = "Llaves_de_Mascaengranajes-nota", duration = 4.60, creatureID = 15608 },
    ["Mena brillante"] = { fileName = "Mena_brillante-nota", duration = 10.06, creatureID = 15608 },
    ["Trozos de fungálidos"] = { fileName = "Trozos_de_fúngalidos-nota", duration = 9.56, creatureID = 15608 },
    ["Gancho de telarañas"] = { fileName = "Gancho_de_telarañas-nota", duration = 5.43, creatureID = 15608 },
    ["Perla robada"] = { fileName = "Perla_robada-nota", duration = 5.51, creatureID = 15608 },
    ["Esporas de boscorraíz"] = { fileName = "Esporas_de_boscorraíz-nota", duration = 4.60, creatureID = 15608 },
    ["Fibra de hiedra fuerte"] = { fileName = "Fibra_de_hiedra_fuerte-nota", duration = 4.55, creatureID = 15608 },
    ["Carne de huelehoja colmicadena"] = { fileName = "Carne_de_huelehoja_colmicadena-nota", duration = 7.00, creatureID = 15608 },
    ["Diario calcificado"] = { fileName = "Diario_calcificado-nota", duration = 10.53, creatureID = 15608 },
    ["Moneda gastada"] = { fileName = "Moneda_gastada-nota", duration = 3.42, creatureID = 15608 },
    ["Guardapelo resistente"] = { fileName = "Guardapelo_resistente-nota", duration = 6.82, creatureID = 15608 },
    ["Montón de hilos de cuero"] = { fileName = "Montón_de_hilos_de_cuero-nota", duration = 5.02, creatureID = 15608 },
    ["Figura de madera"] = { fileName = "Figura_de_madera-nota", duration = 6.30, creatureID = 15608 },
    ["Pez de juguete"] = { fileName = "Pez_de_juguete-nota", duration = 6.50, creatureID = 15608 },
    ["Mensaje de Orren"] = { fileName = "Mensaje_de_Orren-nota", duration = 43.62, creatureID = 15608 },
    ["Don de la cosecha levemente masticado"] = { fileName = "Don_de_la_cosecha_levemente_masticado-nota", duration = 5.46, creatureID = 15608 },
    ["Propaganda de la Orden de la Noche"] = { fileName = "Propaganda_de_la_Orden_de_la_Noche-nota", duration = 31.16, creatureID = 15608 },
    ["Página manchada y destrozada"] = { fileName = "Página_manchada_y_destrozada-nota", duration = 10.21, creatureID = 15608 },
    ["Cebo de turbialeta"] = { fileName = "Cebo_de_turbialeta-nota", duration = 10.21, creatureID = 15608 },
    ["Pieza de juego"] = { fileName = "Pieza_de_juego-nota", duration = 7.37, creatureID = 15608 },
    ["Abalorio roto"] = { fileName = "Abalorio_roto-nota", duration = 7.42, creatureID = 15608 },
    ["Daga grabada"] = { fileName = "Daga_grabada-nota", duration = 9.98, creatureID = 15608 },
    ["Pertenencias perdidas"] = { fileName = "Pertenencias_perdidas-nota", duration = 6.40, creatureID = 15608 },
    ["Veneno de dulceaguijón"] = { fileName = "Veneno_de_dulceaguijón-nota", duration = 6.30, creatureID = 217398 },
    ["Códice de estructura dimensional de Palawltar"] = { fileName = "Códice_de_estructura_dimensional_de_Palawltar-nota", duration = 8.44, creatureID = 15608 },
    ["Órgano coalescente arcano"] = { fileName = "Órgano_coalescente_arcano-nota", duration = 5.85, creatureID = 219135 },
    ["Libro de grado chispa de luz"] = { fileName = "Libro_de_grado_chispa_de_luz-nota", duration = 7.76, creatureID = 15608 },
    ["Carta empantanada"] = { fileName = "Carta_empantanada-nota", duration = 6.40, creatureID = 229244 },
    ["Caja de yesca de marfil"] = { fileName = "Caja_de_yesca_de_marfil-nota", duration = 11.70, creatureID = 229244 },
    ["Punta de lanza abollada"] = { fileName = "Punta_de_lanza_abollada-nota", duration = 10.27, creatureID = 229244 },
    ["Himnos de la Llama"] = { fileName = "Himnos_de_la_Llama-nota", duration = 7.29, creatureID = 229244 },
    ["Catalejo crujiente"] = { fileName = "Catalejo_crujiente-nota", duration = 9.09, creatureID = 229244 },
    ["Clérigo de filigrana"] = { fileName = "Clérigo_de_filigrana-nota", duration = 14.71, creatureID = 229244 },
    ["Bufanda de aviador anudada"] = { fileName = "Bufanda_de_aviador_anudada-nota", duration = 5.04, creatureID = 15608 },
    ["Brújula deteriorada"] = { fileName = "Brújula_deteriorada-nota", duration = 7.34, creatureID = 15608 },
    ["Brazalete roto"] = { fileName = "Brazalete_roto-nota", duration = 7.13, creatureID = 15608 },
    ["Empuñadura pequeña"] = { fileName = "Empuñadura_pequeña-nota", duration = 4.83, creatureID = 15608 },
    ["Lince de peluche"] = { fileName = "Lince_de_peluche-nota", duration = 5.15, creatureID = 15608 },
    ["Antorcha oxidada"] = { fileName = "Antorcha_oxidada-nota", duration = 6.82, creatureID = 15608 },
    ["Brújula de Maevest"] = { fileName = "Brújula_de_Maevest-nota", duration = 5.02, creatureID = 15608 },
    ["Brut imperial"] = { fileName = "Brut_imperial-nota", duration = 6.16, creatureID = 15608 },
    ["Corazón de salamantra"] = { fileName = "Corazón_de_salamandra-nota", duration = 5.46, creatureID = 15608 },
    ["Engrandecedor de Curioseadora"] = { fileName = "Engrandecedor_de_Curioseadora-nota", duration = 7.29, creatureID = 15608 },
    ["Rubíes indiscutibles de Curioseadora"] = { fileName = "Rubíes_indiscutibles_de_Curioseadora-nota", duration = 7.34, creatureID = 15608 },
    ["Botella de poción de Curioseadora"] = { fileName = "Botella_de_poción_de_Curioseadora-nota", duration = 4.49, creatureID = 15608 },
    ["Vela roja de Curioseadora"] = { fileName = "Vela_roja_de_Curioseadora-nota", duration = 6.30, creatureID = 15608 },
    ["Partes de puestos de mercader"] = { fileName = "Partes_de_puestos_de_mercader-nota", duration = 11.89, creatureID = 15608 },
    ["Hidromiel cinéreo vertido de mala gana"] = { fileName = "Hidromiel_cinéreo_vertido_de_mala_gana-nota", duration = 7.89, creatureID = 15608 },
    ["Carbón activo elemental"] = { fileName = "Carbón_activo_elemental-nota", duration = 6.30, creatureID = 15608 },
    ["Cera de igniabeja"] = { fileName = "Cera_de_igniabeja-nota", duration = 6.30, creatureID = 15608 },
    ["Polvo de champiazote"] = { fileName = "Polvo_de_champiazote-nota", duration = 8.20, creatureID = 215788 },
    ["Espinas de esporas"] = { fileName = "Espinas_de_esporas-nota", duration = 11.23, creatureID = 15608 },
    ["Esquirla de día sombrío"] = { fileName = "Esquirla_de_día_sombrío-nota", duration = 6.71, creatureID = 15608 },
    ["Arma de asta de la Orden de la Noche"] = { fileName = "Arma_de_asta_de_la_Orden_de_la_Noche-nota", duration = 12.38, creatureID = 18166 },
    ["Caja de yesca arathi"] = { fileName = "Caja_de_yesca_arathi-nota", duration = 6.09, creatureID = 213116 },
    ["Remanentes destrozados"] = { fileName = "Remanentes_destrozados-nota", duration = 4.68, creatureID = DEFAULT_CREATURE_ID },
    ["Cristales de resonancia"] = { fileName = "Cristales_de_resonancia-nota", duration = 15.18, creatureID = DEFAULT_CREATURE_ID },
    ["Remanente radiante"] = { fileName = "Remanente_radiante-nota", duration = 6.50, creatureID = DEFAULT_CREATURE_ID },
    ["Pegote inusual de cera"] = { fileName = "Pegote_inusual_de_cera-nota", duration = 6.03, creatureID = DEFAULT_CREATURE_ID },
    ["Tonel casi vacío"] = { fileName = "Tonel_casi_vacío-nota", duration = 4.62, creatureID = DEFAULT_CREATURE_ID },
    ["Frasco de hidromiel cinéreo"] = { fileName = "Frasco_de_hidromiel_cinéreo-nota", duration = 4.13, creatureID = DEFAULT_CREATURE_ID },
    ["Residuo espacial"] = { fileName = "Residuo_espacial-nota", duration = 7.11, creatureID = DEFAULT_CREATURE_ID },
    ["Cera pegajosa"] = { fileName = "Cera_pegajosa-nota", duration = 4.83, creatureID = DEFAULT_CREATURE_ID },
    ["Huevo de larva"] = { fileName = "Huevo_de_larva-nota", duration = 4.91, creatureID = DEFAULT_CREATURE_ID },
    ["Veneno de infrarreptador"] = { fileName = "Veneno_de_infrarreptador-nota", duration = 6.87, creatureID = DEFAULT_CREATURE_ID },
    ["Montón de velas"] = { fileName = "Montón_de_velas-nota", duration = 4.86, creatureID = DEFAULT_CREATURE_ID },
    ["Herramienta extraviada"] = { fileName = "Herramienta_extraviada-nota", duration = 4.78, creatureID = DEFAULT_CREATURE_ID },
    ["Ropas de minero"] = { fileName = "Ropas_de_minero-nota", duration = 5.75, creatureID = DEFAULT_CREATURE_ID },
    ["Carne jugosa de krolusko"] = { fileName = "Carne_jugosa_de_krolusko-nota", duration = 5.20, creatureID = DEFAULT_CREATURE_ID },
    ["Gema de recuerdos de Arbauch"] = { fileName = "Gema_de_recuerdos_de_Arbauch-nota", duration = 5.75, creatureID = DEFAULT_CREATURE_ID },
    ["Glándula galvánica"] = { fileName = "Glándula_galvánica-nota", duration = 7.13, creatureID = DEFAULT_CREATURE_ID },
    ["Calavera de Alhainr"] = { fileName = "Calavera_de_Alhainr-nota", duration = 3.66, creatureID = DEFAULT_CREATURE_ID },
    ["Fardo ceroso"] = { fileName = "Fardo_ceroso-nota", duration = 7.42, creatureID = DEFAULT_CREATURE_ID },
    ["Esquirla de rubí de lumbre"] = { fileName = "Esquirla_de_rubí_de_lumbre-nota", duration = 6.77, creatureID = DEFAULT_CREATURE_ID },
    ["Mondadientes de Brax"] = { fileName = "Mondadientes_de_Brax-nota", duration = 4.68, creatureID = DEFAULT_CREATURE_ID },
    ["Extracto de reptador puro"] = { fileName = "Extracto_de_reptador_puro-nota", duration = 12.56, creatureID = DEFAULT_CREATURE_ID },
    ["Prueba floral"] = { fileName = "Prueba_floral-nota", duration = 6.69, creatureID = DEFAULT_CREATURE_ID },
    ["Pala favorita de Morrosuave"] = { fileName = "Pala_favorita_de_Morrosuave-nota", duration = 4.41, creatureID = DEFAULT_CREATURE_ID },
    ["Roca brillante"] = { fileName = "Roca_brillante-nota", duration = 4.36, creatureID = DEFAULT_CREATURE_ID },
    ["Carne dulce"] = { fileName = "Carne_dulce-nota", duration = 5.51, creatureID = DEFAULT_CREATURE_ID },
    ["Capa de las barbas"] = { fileName = "Capa_de_las_barbas-nota", duration = 12.96, creatureID = DEFAULT_CREATURE_ID },
    ["Monedas de chocolate"] = { fileName = "Monedas_de_chocolate-nota", duration = 6.58, creatureID = DEFAULT_CREATURE_ID },
    ["Velas de repuesto"] = { fileName = "Velas_de_repuesto-nota", duration = 5.56, creatureID = DEFAULT_CREATURE_ID },
    ["DIARIO DEL REY VELA"] = { fileName = "DIARIO_DEL_REY_VELA-nota", duration = 34.38, creatureID = DEFAULT_CREATURE_ID },
    ["Corona de velas"] = { fileName = "Corona_de_velas-nota", duration = 7.24, creatureID = DEFAULT_CREATURE_ID },
    ["Muñeca muy desgastada"] = { fileName = "Muñeca_muy_desgastada-nota", duration = 7.05, creatureID = DEFAULT_CREATURE_ID },
    ["Recogeúñas Real"] = { fileName = "Recogeúñas_Real-nota", duration = 8.67, creatureID = DEFAULT_CREATURE_ID },
    ["Recogeuñas Real"] = { fileName = "Recogeuñas_Real-nota", duration = 8.62, creatureID = DEFAULT_CREATURE_ID },
    ["Cáliz con costra"] = { fileName = "Cáliz_con_costra-nota", duration = 5.43, creatureID = DEFAULT_CREATURE_ID },
    ["Collar de dientes de kóbold"] = { fileName = "Collar_de_dientes_de_kóbold-nota", duration = 5.25, creatureID = DEFAULT_CREATURE_ID },
    ["Las llaves de vela"] = { fileName = "Las_llaves_de_vela-nota", duration = 9.51, creatureID = DEFAULT_CREATURE_ID },
    ["Barril de hidromiel cinérea inestable"] = { fileName = "Barril_de_hidromiel_cinérea_inestable-nota", duration = 5.09, creatureID = DEFAULT_CREATURE_ID },
    ["Chatarra que parece útil"] = { fileName = "Chatarra_que_parece_útil-nota", duration = 9.64, creatureID = DEFAULT_CREATURE_ID },
    ["Placa de identificación terránea 3481a662"] = { fileName = "Placa_de_identificación_terránea_3481a662-nota", duration = 11.28, creatureID = DEFAULT_CREATURE_ID },
    ["Placa de identificación terránea 1103a572"] = { fileName = "Placa_de_identificación_terránea_1103a572-nota", duration = 10.58, creatureID = DEFAULT_CREATURE_ID },
    ["Placa de identificación terránea 2672b138"] = { fileName = "Placa_de_identificación_terránea_2672b138-nota", duration = 11.47, creatureID = DEFAULT_CREATURE_ID },
    ["Placa de identificación terránea 0985e438"] = { fileName = "Placa_de_identificación_terránea_0985e438-nota", duration = 14.63, creatureID = DEFAULT_CREATURE_ID },
    ["Vela de Llamachispa"] = { fileName = "Vela_de_Llamachispa-nota", duration = 2.40, creatureID = DEFAULT_CREATURE_ID },
    ["Placa de identificación terránea"] = { fileName = "Placa_de_identificación_terránea-nota", duration = 14.89, creatureID = DEFAULT_CREATURE_ID },
    ["Dinamita inestable"] = { fileName = "Dinamita_inestable-nota", duration = 8.07, creatureID = DEFAULT_CREATURE_ID },
    ["Gema morada sin facetar"] = { fileName = "Gema_morada_sin_facetar-nota", duration = 4.49, creatureID = DEFAULT_CREATURE_ID },
    ["Gema robada"] = { fileName = "Gema_robada-nota", duration = 7.60, creatureID = DEFAULT_CREATURE_ID },
    ["Solvente cáustico"] = { fileName = "Solvente_cáustico-nota", duration = 8.39, creatureID = DEFAULT_CREATURE_ID },
    ["Cubo perdido"] = { fileName = "Cubo_perdido-nota", duration = 4.86, creatureID = DEFAULT_CREATURE_ID },
    ["Flor cáustica"] = { fileName = "Flor_cáustica-nota", duration = 5.85, creatureID = DEFAULT_CREATURE_ID },
    ["Sombrero de champiazote perfecto"] = { fileName = "Sombrero_de_champiazote_perfecto-nota", duration = 9.93, creatureID = DEFAULT_CREATURE_ID },
    ["Lista de quehaceres de Brax"] = { fileName = "Lista_de_quehaceres_de_Brax-nota", duration = 9.38, creatureID = DEFAULT_CREATURE_ID },
    ["Llave de descifrador arcaico"] = { fileName = "Llave_de_descifrador_arcaico-nota", duration = 6.45, creatureID = DEFAULT_CREATURE_ID },
    ["Nudillos de latón de Brax"] = { fileName = "Nudillos_de_latón_de_Brax-nota", duration = 13.79, creatureID = DEFAULT_CREATURE_ID },
    ["Zapato izquierdo de Brax"] = { fileName = "Zapato_izquierdo_de_Brax-nota", duration = 6.11, creatureID = DEFAULT_CREATURE_ID },
    ["Engranaje favorito de Brax."] = { fileName = "Engranaje_favorito_de_Brax.-nota", duration = 12.85, creatureID = DEFAULT_CREATURE_ID },
    ["Sombrero secundario de Brax"] = { fileName = "Sombrero_secundario_de_Brax-nota", duration = 3.84, creatureID = DEFAULT_CREATURE_ID },
    ["Partes valiosas"] = { fileName = "Partes_valiosas-nota", duration = 4.00, creatureID = DEFAULT_CREATURE_ID },
    ["Núcleo cargado"] = { fileName = "nucleo-nota", duration = 8, creatureID = 119723 },
    ["Cúmulo de menas"] = { fileName = "cumulo-nota", duration = 7, creatureID = 119723 },
    ["Gema de recuerdos terránea"] = { fileName = "recuerdo-nota", duration = 18, creatureID = 119723 },
    -- Puedes agregar más ítems aquí siguiendo el mismo formato
}
-- Variable para rastrear si un NPC está hablando
local isNpcSpeaking = false

-- Tabla para rastrear los ítems ya reproducidos
local playedItems = {}

frame:SetScript("OnEvent", function(self, event, ...)
    if not isModuleActive then return end -- No hacer nada si el módulo está desactivado

    if event == "CHAT_MSG_MONSTER_SAY" or event == "CHAT_MSG_MONSTER_YELL"
        or event == "CHAT_MSG_MONSTER_WHISPER" or event == "CHAT_MSG_MONSTER_EMOTE"
        or event == "CHAT_MSG_MONSTER_TEXT" then
        isNpcSpeaking = true
        DebugPrint(GREEN .. "NPC is speaking, blocking item sounds" .. RESET)

        -- Después de 5 segundos (o la duración que necesites), asumimos que el NPC ha terminado de hablar
        C_Timer.After(5, function()
            isNpcSpeaking = false
            DebugPrint(GREEN .. "NPC has likely finished speaking, resuming item sounds" .. RESET)
        end)
    elseif event == "CHAT_MSG_LOOT" then
        local message = ...
        DebugPrint("Loot message received: " .. message)

        -- Buscar coincidencias de nombres de objetos en el mensaje de botín
        for itemName, soundInfo in pairs(soundMapping) do
            if string.find(message, "%[" .. itemName .. "%]") then
                if not playedItems[itemName] then
                    DebugPrint("Detected item: [" .. itemName .. "]")
                    TryQueueItemSound(soundInfo.fileName, itemName, soundInfo.duration, soundInfo.creatureID)
                    playedItems[itemName] = true
                else
                    DebugPrint(RED .. "Item [" .. itemName .. "] sound has already been played" .. RESET)
                end
                break
            end
        end
    end
end)

-- Intentar añadir un sonido a la cola solo cuando la cola esté vacía y no haya un NPC hablando
function TryQueueItemSound(soundFileName, itemName, duration, creatureID)
    local function attemptPlaySound()
        if isNpcSpeaking then
            DebugPrint(RED .. "NPC is speaking, delaying sound for item: " .. itemName .. RESET)
            C_Timer.After(3, attemptPlaySound) -- Reintentar en 3 segundos
        elseif SoundQueue:IsEmpty() then
            DebugPrint("Sound queue is empty and no NPC is speaking, queuing item sound: " .. itemName)
            QueueItemSound(soundFileName, itemName, duration, creatureID)
        else
            DebugPrint("Sound queue is not empty, retrying in 3 seconds for item: " .. itemName)
            C_Timer.After(3, attemptPlaySound) -- Reintentar en 3 segundos
        end
    end

    attemptPlaySound()
end

-- Función para reproducir el sonido del ítem y mostrar el retrato
function QueueItemSound(soundFileName, itemName, duration, creatureID)
    -- Usar barras normales en la ruta del archivo
    local soundFilePath = "Interface/AddOns/AI_VoiceOverData_WarWithin_es/generated/sounds/items/" ..
    soundFileName .. ".mp3"

    DebugPrint("Attempting to queue item sound file: " .. soundFilePath)

    local npcID = creatureID

    -- Crear datos del sonido
    local soundData = {
        event = Enums.SoundEvent.ItemReceived,
        fileName = soundFileName,
        filePath = soundFilePath,
        length = duration, -- Duración en segundos
        title = itemName,
        name = GREEN .. "Objeto Encontrado" .. RESET,
        unitGUID = npcID and string.format("Creature-0-0-0-0-%d", npcID) or nil,

        addedCallback = function(sd)
            DebugPrint(GREEN .. "Sound added to queue: " .. sd.fileName .. RESET)
            SoundQueueUI:UpdateSoundQueueDisplay() -- Actualizar la UI al agregar el sonido
        end,
        startCallback = function(sd)
            DebugPrint(GREEN .. "Sound started playing: " .. sd.fileName .. RESET)
            SoundQueueUI.frame.portrait:Configure(sd) -- Mostrar el retrato al comenzar la reproducción
        end,
        stopCallback = function(sd)
            DebugPrint(GREEN .. "Sound stopped: " .. sd.fileName .. RESET)
            -- Limpiar retrato o hacer alguna otra acción al detener
            SoundQueueUI.frame.portrait:Configure(nil)
        end,
    }

    -- Verificar si SoundQueue está disponible y añadir el sonido a la cola
    if SoundQueue and SoundQueue.AddSoundToQueue then
        DebugPrint("SoundQueue is available")

        -- Asegúrate de que el archivo de sonido exista y esté preparado
        local soundExists = DataModules:PrepareSound(soundData)
        if soundExists then
            DebugPrint("Sound exists in DataModules")
            SoundQueue:AddSoundToQueue(soundData)
        else
            DebugPrint(RED .. "Error: Sound does not exist for: " .. soundFileName .. RESET)
        end
    else
        DebugPrint(RED .. "Error: SoundQueue no está disponible." .. RESET)
    end
end

-- Función para reiniciar la tabla de ítems reproducidos (puedes llamarla cuando sea necesario, por ejemplo, al cambiar de zona)
function ResetPlayedItems()
    playedItems = {}
    DebugPrint(GREEN .. "Reset played items table" .. RESET)
end

-- Función para activar el módulo
function ActivateItemReader()
    isModuleActive = true
    isDebugEnabled = Addon.db.profile.ItemReaderDebugEnabled
    DebugPrint("|cff00ff00Item Reader Module Activated|r")
end

-- Función para desactivar el módulo
function DeactivateItemReader()
    isModuleActive = false
    isDebugEnabled = false
    DebugPrint("|cffff0000Item Reader Module Deactivated|r")
end

-- Exponer las funciones de activación/desactivación
VoiceOver.ItemReader = VoiceOver.ItemReader or {}
VoiceOver.ItemReader.Activate = ActivateItemReader
VoiceOver.ItemReader.Deactivate = DeactivateItemReader
