setfenv(1, VoiceOver)

---@class Addon : AceAddon, AceAddon-3.0, AceEvent-3.0, AceTimer-3.0
---@field db VoiceOverConfig|AceDBObject-3.0
Addon = LibStub("AceAddon-3.0"):NewAddon("VoiceOver", "AceEvent-3.0", "AceTimer-3.0")

Addon.OnAddonLoad = {}

---@class VoiceOverConfig
local defaults = {
    profile = {
        SoundQueueUI = {
            LockFrame = false,
            FrameScale = 1.1,
            FrameStrata = "HIGH",
            HidePortrait = false,
            HideFrame = false,
        },
        Audio = {
            GossipFrequency = Enums.GossipFrequency.OncePerQuestNPC,
            SoundChannel = Enums.SoundChannel.Master,
            AutoToggleDialog = Version.IsLegacyVanilla or Version:IsRetailOrAboveLegacyVersion(60100),
            StopAudioOnDisengage = false,
        },
        MinimapButton = {
            LibDBIcon = {}, -- Table used by LibDBIcon to store position (minimapPos), dragging lock (lock) and hidden state (hide)
            Commands = {
                -- References keys from Options.table.args.SlashCommands.args table
                LeftButton = "Options",
                MiddleButton = "PlayPause",
                RightButton = "Clear",
            }
        },
        LegacyWrath = (Version.IsLegacyWrath or Version.IsLegacyBurningCrusade or nil) and {
            PlayOnMusicChannel = {
                Enabled = true,
                Volume = 1,
                FadeOutMusic = 0.5,
            },
            HDModels = false,
        },
        DebugEnabled = false,
        ShowQuestFrameButton = true, -- Añade esta línea
        ShowObjectiveTrackerButtons = true,
    },
    char = {
        IsPaused = false,
        hasSeenGossipForNPC = {},
        RecentQuestTitleToID = Version:IsBelowLegacyVersion(30300) and {},
    }
}

local lastGossipOptions
local selectedGossipOption
local currentQuestSoundData
local currentGossipSoundData

function Addon:OnInitialize()
    self.db = LibStub("AceDB-3.0"):New("VoiceOverDB", defaults)
    self.db.RegisterCallback(self, "OnProfileChanged", "RefreshConfig")
    self.db.RegisterCallback(self, "OnProfileReset", "RefreshConfig")

    -- Detectar la configuración regional del cliente
    local locale = GetLocale()

    -- Verificar si es la primera vez que se carga el addon
    if not self.db.profile.isFirstRun then
        if locale == "esMX" or locale == "esES" then
            -- Configuraciones predeterminadas para español
            self.db.profile.QuestProgressEnabled = true
            self.db.profile.QuestProgressDebugEnabled = false
            self.db.profile.ItemReaderEnabled = true
            self.db.profile.BonusQuestDetectorEnabled = true
            self.db.profile.RareAnnounceEnabled = true
            self.db.profile.GameObjectReaderEnabled = true
            self.db.profile.NPCLiveIAEnabled = true
        else
            -- Configuraciones predeterminadas para cualquier otra región
            self.db.profile.QuestProgressEnabled = true
            self.db.profile.ItemReaderEnabled = false
            self.db.profile.BonusQuestDetectorEnabled = false
            self.db.profile.RareAnnounceEnabled = false
            self.db.profile.GameObjectReaderEnabled = false
            self.db.profile.NPCLiveIAEnabled = false
        end

        -- Marcar que ya no es la primera vez que se ejecuta
        self.db.profile.isFirstRun = true
    end

    -- Inicializar QuestFrameAudioButton
    if QuestFrameAudioButton and QuestFrameAudioButton.Initialize then
        QuestFrameAudioButton:Initialize()
    end

    -- Inicializar módulos
    if self.db.profile.QuestProgressEnabled and VoiceOver.MissionProgress and VoiceOver.MissionProgress.Activate then
        VoiceOver.MissionProgress.Activate()
    elseif VoiceOver.MissionProgress and VoiceOver.MissionProgress.Deactivate then
        VoiceOver.MissionProgress.Deactivate()
    end

    -- Activación/Desactivación del modo de depuración para MissionProgress
    if self.db.profile.QuestProgressDebugEnabled and VoiceOver.MissionProgress and VoiceOver.MissionProgress.ActivateDebug then
        VoiceOver.MissionProgress.ActivateDebug()
    elseif VoiceOver.MissionProgress and VoiceOver.MissionProgress.DeactivateDebug then
        VoiceOver.MissionProgress.DeactivateDebug()
    end

    if self.db.profile.ItemReaderEnabled and VoiceOver.ItemReader and VoiceOver.ItemReader.Activate then
        VoiceOver.ItemReader.Activate()
    elseif VoiceOver.ItemReader and VoiceOver.ItemReader.Deactivate then
        VoiceOver.ItemReader.Deactivate()
    end

    if self.db.profile.BonusQuestDetectorEnabled and VoiceOver.BonusQuestDetector and VoiceOver.BonusQuestDetector.Activate then
        VoiceOver.BonusQuestDetector.Activate()
    elseif VoiceOver.BonusQuestDetector and VoiceOver.BonusQuestDetector.Deactivate then
        VoiceOver.BonusQuestDetector.Deactivate()
    end

    if self.db.profile.RareAnnounceEnabled and VoiceOver.RareAnnounce and VoiceOver.RareAnnounce.Activate then
        VoiceOver.RareAnnounce.Activate()
    elseif VoiceOver.RareAnnounce and VoiceOver.RareAnnounce.Deactivate then
        VoiceOver.RareAnnounce.Deactivate()
    end

    -- Inicializar módulos
    if self.db.profile.GameObjectReaderEnabled and VoiceOver.GameObjectReader and VoiceOver.GameObjectReader.Activate then
        VoiceOver.GameObjectReader.Activate()
    elseif VoiceOver.GameObjectReader and VoiceOver.GameObjectReader.Deactivate then
        VoiceOver.GameObjectReader.Deactivate()
    end

    -- Activación/Desactivación del modo de depuración para GameObjectReader
    if self.db.profile.GameObjectReaderDebugEnabled and VoiceOver.GameObjectReader and VoiceOver.GameObjectReader.ActivateDebug then
        VoiceOver.GameObjectReader.ActivateDebug()
    elseif VoiceOver.GameObjectReader and VoiceOver.GameObjectReader.DeactivateDebug then
        VoiceOver.GameObjectReader.DeactivateDebug()
    end

    if self.db.profile.NPCLiveIAEnabled and VoiceOver.NPCLiveIA and VoiceOver.NPCLiveIA.Activate then
        VoiceOver.NPCLiveIA.Activate()
    elseif VoiceOver.NPCLiveIA and VoiceOver.NPCLiveIA.Deactivate then
        VoiceOver.NPCLiveIA.Deactivate()
    end

    -- Activación/Desactivación del modo de depuración para SoundControl
    if self.db.profile.SoundControlDebugEnabled and VoiceOver.SoundControlUI and VoiceOver.SoundControlUI.ActivateDebug then
        VoiceOver.SoundControlUI.ActivateDebug()
    elseif VoiceOver.SoundControlUI and VoiceOver.SoundControlUI.DeactivateDebug then
        VoiceOver.SoundControlUI.DeactivateDebug()
    end

    StaticPopupDialogs["VOICEOVER_ERROR"] =
    {
        text = "VoiceOver|n|n%s",
        button1 = OKAY,
        timeout = 0,
        whileDead = 1,
    }

    SoundQueueUI:Initialize()
    DataModules:EnumerateAddons()
    Options:Initialize()

    self:RegisterEvent("ADDON_LOADED")
    self:RegisterEvent("QUEST_DETAIL")
    -- self:RegisterEvent("QUEST_PROGRESS")
    self:RegisterEvent("QUEST_COMPLETE")
    self:RegisterEvent("QUEST_GREETING")
    self:RegisterEvent("QUEST_FINISHED")
    self:RegisterEvent("GOSSIP_SHOW")
    self:RegisterEvent("GOSSIP_CLOSED")

    if select(5, C_AddOns.GetAddOnInfo("VoiceOver")) ~= "MISSING" then
        C_AddOns.DisableAddOn("VoiceOver")
        if not self.db.profile.SeenDuplicateDialog then
            StaticPopupDialogs["VOICEOVER_DUPLICATE_ADDON"] =
            {
                text =
                [[VoiceOver|n|nTo fix the quest autoaccept bugs we had to rename the addon folder. If you're seeing this popup, it means the old one wasn't automatically removed.|n|nYou can safely delete "VoiceOver" from your Addons folder. "AI_VoiceOver" is the new folder.]],
                button1 = OKAY,
                timeout = 0,
                whileDead = 1,
                OnAccept = function()
                    self.db.profile.SeenDuplicateDialog = true
                end,
            }
            StaticPopup_Show("VOICEOVER_DUPLICATE_ADDON")
        end
    end

    if select(5, C_AddOns.GetAddOnInfo("AI_VoiceOver_112")) ~= "MISSING" then
        C_AddOns.DisableAddOn("AI_VoiceOver_112")
        if not self.db.profile.SeenDuplicateDialog112 then
            StaticPopupDialogs["VOICEOVER_DUPLICATE_ADDON_112"] =
            {
                text =
                [[VoiceOver|n|nVoiceOver port for 1.12 has been merged together with other versions and is no longer distributed as a separate addon.|n|nYou can safely delete "AI_VoiceOver_112" from your Addons folder. "AI_VoiceOver" is the new folder.]],
                button1 = OKAY,
                timeout = 0,
                whileDead = 1,
                OnAccept = function()
                    self.db.profile.SeenDuplicateDialog112 = true
                end,
            }
            StaticPopup_Show("VOICEOVER_DUPLICATE_ADDON_112")
        end
    end

    if not DataModules:HasRegisteredModules() then
        StaticPopupDialogs["VOICEOVER_NO_REGISTERED_DATA_MODULES"] =
        {
            text =
            [[VoiceOver|n|nNo sound packs were found.|n|nUse the "/vo options" command, (or Interface Options in newer clients) and go to the DataModules tab for information on where to download sound packs.]],
            button1 = OKAY,
            timeout = 0,
            whileDead = 1,
        }
        StaticPopup_Show("VOICEOVER_NO_REGISTERED_DATA_MODULES")
    end

    local function MakeAbandonQuestHook(field, getFieldData)
        return function()
            local data = getFieldData()
            local soundsToRemove = {}
            for _, soundData in pairs(SoundQueue.sounds) do
                if Enums.SoundEvent:IsQuestEvent(soundData.event) and soundData[field] == data then
                    table.insert(soundsToRemove, soundData)
                end
            end

            for _, soundData in pairs(soundsToRemove) do
                SoundQueue:RemoveSoundFromQueue(soundData)
            end
        end
    end
    if C_QuestLog and C_QuestLog.AbandonQuest then
        hooksecurefunc(C_QuestLog, "AbandonQuest",
            MakeAbandonQuestHook("questID", function() return C_QuestLog.GetAbandonQuest() end))
    elseif AbandonQuest then
        hooksecurefunc("AbandonQuest", MakeAbandonQuestHook("questName", function() return GetAbandonQuestName() end))
    end

    if QuestLog_Update then
        hooksecurefunc("QuestLog_Update", function()
            QuestOverlayUI:Update()
        end)
    end

    if C_GossipInfo and C_GossipInfo.SelectOption then
        hooksecurefunc(C_GossipInfo, "SelectOption", function(optionID)
            if lastGossipOptions then
                for _, info in ipairs(lastGossipOptions) do
                    if info.gossipOptionID == optionID then
                        selectedGossipOption = info.name
                        break
                    end
                end
                lastGossipOptions = nil
            end
        end)
    elseif SelectGossipOption then
        hooksecurefunc("SelectGossipOption", function(index)
            if lastGossipOptions then
                selectedGossipOption = lastGossipOptions[1 + (index - 1) * 2]
                lastGossipOptions = nil
            end
        end)
    end
    -- Gestión de versiones de avisos
    local currentNoticeVersion = 0.9 -- Versión del aviso actual
    if not self.db.char.noticeVersion or self.db.char.noticeVersion < currentNoticeVersion then
        -- Forzar que se muestre el nuevo aviso
        self.db.char.dontShowWelcome = false
        self.db.char.noticeVersion = currentNoticeVersion -- Actualiza la versión del aviso en la base de datos
    end
end

function Addon:RefreshConfig()
    SoundQueueUI:RefreshConfig()
end

function Addon:ADDON_LOADED(event, addon)
    addon = addon or arg1 -- Thanks, Ace3v...
    local hook = self.OnAddonLoad[addon]
    if hook then
        hook()
    end
end

local function GossipSoundDataAdded(soundData)
    Utils:CreateNPCModelFrame(soundData)

    -- Save current gossip sound data for dialog/frame sync option
    currentGossipSoundData = soundData
end

local function QuestSoundDataAdded(soundData)
    Utils:CreateNPCModelFrame(soundData)

    -- Save current quest sound data for dialog/frame sync option
    currentQuestSoundData = soundData
end

local GetTitleText =
    GetTitleText -- Store original function before EQL3 (Extended Quest Log 3) overrides it and starts prepending quest level
function Addon:QUEST_DETAIL()
    if self.db.profile.ManualMode then
        return
    end

    local questID = GetQuestID()
    local questTitle = GetTitleText()
    local questText = GetQuestText()
    local guid = Utils:GetNPCGUID()
    local targetName = Utils:GetNPCName()

    if not questID or questID == 0 then
        return
    end

    -- Can happen if the player interacted with an NPC while having main menu or options opened
    if not guid and not targetName then
        return
    end

    if Addon.db.char.RecentQuestTitleToID and questID ~= 0 then
        Addon.db.char.RecentQuestTitleToID[questTitle] = questID
    end

    local type = guid and Utils:GetGUIDType(guid)
    if type == Enums.GUID.Item then
        -- Allow quests started from items to have VO, book icon will be displayed for them
    elseif not type or not Enums.GUID:CanHaveID(type) then
        -- If the quest is started by something that we cannot extract the ID of (e.g. Player, when sharing a quest) - try to fallback to a questgiver from a module's database
        local id
        type, id = DataModules:GetQuestLogQuestGiverTypeAndID(questID)
        guid = id and Enums.GUID:CanHaveID(type) and Utils:MakeGUID(type, id) or guid
        targetName = id and DataModules:GetObjectName(type, id) or targetName or "Unknown Name"
    end

    -- print("QUEST_DETAIL", questID, questTitle);
    ---@type SoundData
    local soundData = {
        event = Enums.SoundEvent.QuestAccept,
        questID = questID,
        name = targetName,
        title = questTitle,
        text = questText,
        unitGUID = guid,
        unitIsObjectOrItem = Utils:IsNPCObjectOrItem(),
        addedCallback = QuestSoundDataAdded,
    }

    if not self.db.profile.ManualMode then
        SoundQueue:AddSoundToQueue(soundData)
    end
end

function Addon:QUEST_COMPLETE()
    if self.db.profile.ManualMode then
        return
    end

    local questID = GetQuestID()
    local questTitle = GetTitleText()
    local questText = GetRewardText()
    local guid = Utils:GetNPCGUID()
    local targetName = Utils:GetNPCName()

    if not questID or questID == 0 then
        return
    end

    -- Can happen if the player interacted with an NPC while having main menu or options opened
    if not guid and not targetName then
        return
    end

    if Addon.db.char.RecentQuestTitleToID and questID ~= 0 then
        Addon.db.char.RecentQuestTitleToID[questTitle] = questID
    end

    -- print("QUEST_COMPLETE", questID, questTitle);
    ---@type SoundData
    local soundData = {
        event = Enums.SoundEvent.QuestComplete,
        questID = questID,
        name = targetName,
        title = questTitle,
        text = questText,
        unitGUID = guid,
        unitIsObjectOrItem = Utils:IsNPCObjectOrItem(),
        addedCallback = QuestSoundDataAdded,
    }

    if not self.db.profile.ManualMode then
        SoundQueue:AddSoundToQueue(soundData)
    end
end

function Addon:ShouldPlayGossip(guid, text)
    local npcKey = guid or "unknown"

    local gossipSeenForNPC = self.db.char.hasSeenGossipForNPC[npcKey]

    if self.db.profile.Audio.GossipFrequency == Enums.GossipFrequency.OncePerQuestNPC then
        local numActiveQuests = C_GossipInfo.GetNumActiveQuests()
        local numAvailableQuests = C_GossipInfo.GetNumAvailableQuests()
        local npcHasQuests = (numActiveQuests > 0 or numAvailableQuests > 0)
        if npcHasQuests and gossipSeenForNPC then
            return
        end
    elseif self.db.profile.Audio.GossipFrequency == Enums.GossipFrequency.OncePerNPC then
        if gossipSeenForNPC then
            return
        end
    elseif self.db.profile.Audio.GossipFrequency == Enums.GossipFrequency.Never then
        return
    end

    return true, npcKey
end

function Addon:QUEST_GREETING()
    local guid = Utils:GetNPCGUID()
    local targetName = Utils:GetNPCName()
    local greetingText = GetGreetingText()

    -- Can happen if the player interacted with an NPC while having main menu or options opened
    if not guid and not targetName then
        return
    end

    local play, npcKey = self:ShouldPlayGossip(guid, greetingText)
    if not play then
        return
    end

    -- Play the gossip sound
    ---@type SoundData
    local soundData = {
        event = Enums.SoundEvent.QuestGreeting,
        name = targetName,
        text = greetingText,
        unitGUID = guid,
        unitIsObjectOrItem = Utils:IsNPCObjectOrItem(),
        addedCallback = GossipSoundDataAdded,
        startCallback = function()
            self.db.char.hasSeenGossipForNPC[npcKey] = true
        end
    }
    SoundQueue:AddSoundToQueue(soundData)
end

function Addon:GOSSIP_SHOW()
    local guid = Utils:GetNPCGUID()
    local targetName = Utils:GetNPCName()
    local gossipText = C_GossipInfo.GetText()

    -- Can happen if the player interacted with an NPC while having main menu or options opened
    if not guid and not targetName then
        return
    end

    local play, npcKey = self:ShouldPlayGossip(guid, gossipText)
    if not play then
        return
    end

    -- Play the gossip sound
    ---@type SoundData
    local soundData = {
        event = Enums.SoundEvent.Gossip,
        name = targetName,
        title = selectedGossipOption and format([["%s"]], selectedGossipOption),
        text = gossipText,
        unitGUID = guid,
        unitIsObjectOrItem = Utils:IsNPCObjectOrItem(),
        addedCallback = GossipSoundDataAdded,
        startCallback = function()
            self.db.char.hasSeenGossipForNPC[npcKey] = true
        end
    }
    SoundQueue:AddSoundToQueue(soundData)

    selectedGossipOption = nil
    lastGossipOptions = nil
    if C_GossipInfo and C_GossipInfo.GetOptions then
        lastGossipOptions = C_GossipInfo.GetOptions()
    elseif GetGossipOptions then
        lastGossipOptions = { GetGossipOptions() }
    end
end

function Addon:QUEST_FINISHED()
    if Addon.db.profile.Audio.StopAudioOnDisengage and currentQuestSoundData then
        SoundQueue:RemoveSoundFromQueue(currentQuestSoundData)
    end
    currentQuestSoundData = nil
end

function Addon:GOSSIP_CLOSED()
    if Addon.db.profile.Audio.StopAudioOnDisengage and currentGossipSoundData then
        SoundQueue:RemoveSoundFromQueue(currentGossipSoundData)
    end
    currentGossipSoundData = nil

    selectedGossipOption = nil
end

--AVISO
-- Inicializar el frame principal
local f = CreateFrame("Frame", "VoiceOverRaiderFrame", UIParent, "BackdropTemplate")
f:SetSize(850, 400) -- Aumentar tamaño para acomodar mejor los elementos (doble de ancho)
f:SetPoint("CENTER")
f:SetBackdrop({
    bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background-Dark",
    edgeFile = "Interface\\DialogFrame\\UI-DialogBox-Border", -- Añadir el archivo de borde estándar de WoW
    tile = true,
    tileSize = 32,
    edgeSize = 32, -- Tamaño del borde, ajustar según prefieras
    insets = { left = 0, right = 0, top = 0, bottom = 0 }
})
f:SetBackdropColor(0, 0, 0, 0.8)

-- Establecer el color del borde a naranjado brillante
f:SetBackdropBorderColor(1, 0.647, 0, 1) -- RGB: #FFA500 (Naranjado brillante)

-- Título del aviso
local title = f:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
title:SetPoint("TOP", f, "TOP", 0, -20) -- Ajustar el espacio superior
title:SetWidth(800)                     -- Ancho suficiente para el título
title:SetJustifyH("CENTER")

-- Crear la textura de la imagen (logo) en la columna izquierda
local logo = f:CreateTexture(nil, "ARTWORK")
logo:SetSize(300, 300)                                                          -- Ajusta el tamaño de la imagen según tus necesidades
logo:SetPoint("LEFT", f, "LEFT", 10, 15)                                        -- Posicionar la imagen en la columna izquierda, ajusta Y según sea necesario
logo:SetTexture("Interface\\AddOns\\AI_VoiceOver\\LOGO_VOICEOVER_MOD_v2.0.tga") -- Ruta a tu imagen

-- Crear un contenedor para la columna derecha
local rightColumn = CreateFrame("Frame", nil, f)
rightColumn:SetSize(500, 350)                       -- Ajustar tamaño según el contenido
rightColumn:SetPoint("RIGHT", f, "RIGHT", -20, -20) -- Posicionar en la columna derecha

-- Función para establecer el texto según el idioma del cliente
local function SetLanguageText()
    local locale = GetLocale()
    local descriptionText = ""
    local discordText = ""
    local youtubeText = ""
    local importantNoticeText = ""
    local versionText = "v2.0.1" -- Actualiza la versión según corresponda
    local modifiedByText = ""
    local dontShowAgainText = ""
    local closeButtonText = ""
    local titleText = ""

    -- Selección de color: naranjado brillante (#FFA500)
    local titleColor = "|cffffa500"

    if locale == "esES" or locale == "esMX" then
        titleText = titleColor .. "¡Bienvenido a VoiceOver Mod 2.0!" .. "|r"
        descriptionText =
        "VoiceOver Mod 2.0 es un addon que reproduce diálogos de quest y eventos en el juego. Añade voces a NPCs, misiones y eventos del mundo para una experiencia más inmersiva.\n\nActualizado hasta el Parche 11.0.7 Isla de las Sirenas\n\nPara más información y para dar tu feedback, siguenos en nuestros sitios."
        discordText = "Únete a nuestro Discord:"
        youtubeText = "Visita nuestro canal de YouTube:"
        importantNoticeText =
        "|TInterface\\Icons\\INV_Misc_Note_01:20:20|t Notas del Parche.\n\n- Algunas funcionalidades pueden contener errores o estar incompletas.\n\n- Asegúrate de tener instalada la última versión de VoiceOver Mod 2.0."
        dontShowAgainText = "No volver a mostrar"
        closeButtonText = "Cerrar"
        modifiedByText = "|cff808080Developed by Darkneo|r"
    else
        titleText = titleColor .. "Welcome to VoiceOver Mod 2.0!" .. "|r"
        descriptionText =
        "VoiceOver Mod 2.0 is an addon that plays quest dialogues and in-game events. It adds voices to NPCs, quests, and world events for a more immersive experience.\n\nUpdated to Patch 11.0.7 Isle of the Sirens\n\nFor more information and to provide feedback, follow us on our sites."
        discordText = "Join our Discord:"
        youtubeText = "Visit our YouTube channel:"
        importantNoticeText =
        "|TInterface\\Icons\\INV_Misc_Note_01:20:20|t Patch Notes.\n\n- Some features may contain errors or be incomplete.\n\n- Make sure you have the latest version of VoiceOver Mod 2.0 installed."
        dontShowAgainText = "Don't show again"
        closeButtonText = "Close"
        modifiedByText = "|cff808080Developed by Darkneo|r"
    end

    -- Configurar el título
    title:SetText(titleText)

    -- Descripción del addon
    local description = rightColumn:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
    description:SetPoint("TOPLEFT", rightColumn, "TOPLEFT", 0, -5)
    description:SetJustifyH("LEFT")
    description:SetWidth(480)
    description:SetHeight(100) -- Ajustar altura según sea necesario
    description:SetText(descriptionText)

    -- Discord label
    local discordLabel = rightColumn:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
    discordLabel:SetPoint("TOPLEFT", description, "BOTTOMLEFT", 0, -20)
    discordLabel:SetJustifyH("LEFT")
    discordLabel:SetWidth(480)
    discordLabel:SetText(discordText)

    -- Discord box
    local discordBox = CreateFrame("EditBox", nil, rightColumn, "InputBoxTemplate")
    discordBox:SetSize(480, 20)
    discordBox:SetPoint("TOPLEFT", discordLabel, "BOTTOMLEFT", 0, -5)
    discordBox:SetAutoFocus(false)
    discordBox:SetText("discord.gg/jHPsF2dt9y") -- Enlace de Discord proporcionado
    discordBox:HighlightText()
    discordBox:SetScript("OnTextChanged", function(self)
        self:SetText("discord.gg/jHPsF2dt9y")
    end)

    -- YouTube label
    local youtubeLabel = rightColumn:CreateFontString(nil, "OVERLAY", "GameFontHighlight")
    youtubeLabel:SetPoint("TOPLEFT", discordBox, "BOTTOMLEFT", 0, -20)
    youtubeLabel:SetJustifyH("LEFT")
    youtubeLabel:SetWidth(480)
    youtubeLabel:SetText(youtubeText)

    -- YouTube box
    local youtubeBox = CreateFrame("EditBox", nil, rightColumn, "InputBoxTemplate")
    youtubeBox:SetSize(480, 20)
    youtubeBox:SetPoint("TOPLEFT", youtubeLabel, "BOTTOMLEFT", 0, -5)
    youtubeBox:SetAutoFocus(false)
    youtubeBox:SetText("https://www.youtube.com/@NeoLabs7") -- Enlace de YouTube proporcionado
    youtubeBox:HighlightText()
    youtubeBox:SetScript("OnTextChanged", function(self)
        self:SetText("https://www.youtube.com/@NeoLabs7")
    end)

    -- Aviso importante
    local importantNotice = rightColumn:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    importantNotice:SetPoint("TOPLEFT", youtubeBox, "BOTTOMLEFT", 0, -20)
    importantNotice:SetJustifyH("LEFT")
    importantNotice:SetWidth(480)
    importantNotice:SetText(importantNoticeText)

    -- Versión del addon
    local versionLabel = rightColumn:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
    versionLabel:SetPoint("LEFT", importantNotice, "BOTTOMLEFT", -300, 33)
    versionLabel:SetText(versionText)

    -- Texto "Desarrollado por Darkneo" o "Developed by Darkneo"
    local modifiedByLabel = rightColumn:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
    modifiedByLabel:SetPoint("TOPLEFT", versionLabel, "BOTTOMLEFT", 0, -10)
    modifiedByLabel:SetJustifyH("LEFT")
    modifiedByLabel:SetText(modifiedByText)

    -- Checkbox para "No volver a mostrar"
    local dontShowAgain = CreateFrame("CheckButton", nil, rightColumn, "UICheckButtonTemplate")
    dontShowAgain:SetPoint("TOPLEFT", modifiedByLabel, "BOTTOMLEFT", -4, -7)

    -- Crear el FontString para el texto del checkbox
    dontShowAgain.text = dontShowAgain:CreateFontString(nil, "ARTWORK", "GameFontNormal")
    dontShowAgain.text:SetPoint("LEFT", dontShowAgain, "RIGHT", 0, 1)
    dontShowAgain.text:SetText(dontShowAgainText)

    dontShowAgain:SetChecked(Addon.db.char.dontShowWelcome)

    dontShowAgain:SetScript("OnClick", function(self)
        Addon.db.char.dontShowWelcome = self:GetChecked()
    end)

    -- Botón de cierre
    local closeButton = CreateFrame("Button", nil, rightColumn, "UIPanelButtonTemplate")
    closeButton:SetSize(100, 24)
    closeButton:SetPoint("BOTTOMRIGHT", rightColumn, "BOTTOMRIGHT", 0, 10)
    closeButton:SetText(closeButtonText)
    closeButton:SetScript("OnClick", function()
        f:Hide()
    end)
end

-- Usar el método OnEnable para inicializar después de que el addon esté cargado
function Addon:OnEnable()
    local currentNoticeVersion = 0.8 -- Versión del aviso actual

    -- Verifica si se debe mostrar el nuevo aviso
    if not self.db.char.noticeVersion or self.db.char.noticeVersion < currentNoticeVersion then
        -- Forzar que se muestre el nuevo aviso
        self.db.char.dontShowWelcome = false
        self.db.char.noticeVersion = currentNoticeVersion -- Actualiza la versión del aviso en la base de datos
    end

    -- Solo llamamos a SetLanguageText si db está correctamente inicializado
    if self.db and self.db.char then
        SetLanguageText()

        -- Mostrar el frame si la opción "dontShowWelcome" no está marcada
        if not self.db.char.dontShowWelcome then
            f:Show()
        end
    end
end

f:Hide()
