local modName, addonTable = ...
local L = addonTable or {} 

ForTheWarCry = {}
local frame = CreateFrame("Frame", modName)
ForTheWarCry.gvif = frame
frame:SetSize(500, 500)
frame.name = "For The War Cry"

local versions = {"horde", "alliance", "azeroth", "loktar"}
local languages = {"cn", "de", "en", "es", "fr", "it", "ko", "mx", "pt", "ru"}
local volumes = {"1", "2", "3", "4", "5"} 

local triggers = {
    { spellID = 90355,   var_name="ancient_hysteria", gv="FTH_AH", default=1 },
    { spellID = 2825,    var_name="bloodlust", gv="FTH_BL", default=1 },
    { spellID = 178207,  var_name="drums_of_fury", gv="FTH_DOF", default=1 },
    { spellID = 230935,  var_name="drums_of_the_mountain", gv="FTH_DOM", default=1 },
    { spellID = 32182,   var_name="heroism", gv="FTH_H", default=1 },
    { spellID = 160452,  var_name="netherwinds", gv="FTH_NW", default=1 },
    { spellID = 80353,   var_name="time_warp", gv="FTH_TW", default=1 },
    { spellID = 292686,  var_name="mallet_of_thunderous_skins", gv="FTH_MTS", default=1 },
    { spellID = 256740,  var_name="drums_of_the_maelstrom", gv="FTH_DM", default=1 },
    { spellID = 309658,  var_name="drums_of_deathly_ferocity", gv="FTH_DDM", default=1 },
    { spellID = 390386,  var_name="fury_of_the_aspects", gv="FTH_FOA", default=1 },
    { spellID = 264667,  var_name="primal_rage", gv="FTH_PR", default=1 },
    { spellID = 444122,  var_name="thunderous_drums", gv="FTH_TDD", default=1 },
    { spellID = 1237547, var_name="void_touched_drums", gv="FTH_VTD", default=1 },
    { spellID = 466904,  var_name="harriers_cry", gv="FTH_HC", default=1 },
}

local activeStates = {}
local lastPlayed = {} 

local function PlayCurrentSound()
    local v = FTH_VERSION or "horde"
    local l = FTH_LANGUAGE or "en"
    local vol = tonumber(FTH_VOLUME) or 1
    local path = "Interface\\AddOns\\ForTheWarCry\\Sounds\\"..v.."\\"..l..".mp3"
    local channel = (FTH_SND_OVERRIDE == 1) and "Master" or "SFX"
    for i = 1, vol do PlaySoundFile(path, channel) end
end

local function CreateClassicDropdown(parent, label, x, y, options, currentVar, width)
    local text = parent:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    text:SetPoint("TOPLEFT", x, y)
    text:SetText(label)
    local f = CreateFrame("Frame", modName..currentVar.."DropDown", parent, "UIDropDownMenuTemplate")
    f:SetPoint("TOPLEFT", x - 15, y - 15)
    UIDropDownMenu_SetWidth(f, width or 100)
    UIDropDownMenu_Initialize(f, function(self, level)
        local info = UIDropDownMenu_CreateInfo()
        for _, opt in ipairs(options) do
            info.text = opt; info.value = opt; info.func = function(s) 
                _G[currentVar] = s.value; UIDropDownMenu_SetSelectedValue(f, s.value); UIDropDownMenu_SetText(f, s.value) 
            end
            info.checked = (tostring(_G[currentVar]) == tostring(opt))
            UIDropDownMenu_AddButton(info, level)
        end
    end)
    UIDropDownMenu_SetSelectedValue(f, _G[currentVar]); UIDropDownMenu_SetText(f, _G[currentVar])
end

frame:RegisterEvent("ADDON_LOADED")
frame:RegisterEvent("UNIT_AURA")
frame:RegisterEvent("PLAYER_LOGOUT")

frame:SetScript("OnEvent", function(self, event, ...)
    if event == "UNIT_AURA" then
        local unit = ...
        -- Solo comprobamos las auras que aparecen en el JUGADOR (vengan de quien vengan)
        if unit ~= "player" then return end
        
        local currentTime = GetTime()

        for _, t in ipairs(triggers) do
            if ForTheWarCry["sound_on_"..t.var_name] == 1 then
                local aura = C_UnitAuras.GetPlayerAuraBySpellID(t.spellID)
                local auraExists = (aura and aura.spellId)
                
                if auraExists then
                    -- Si el aura existe y no estaba marcada como activa
                    if not activeStates[t.spellID] then
                        -- Anti-spam: solo suena si han pasado más de 30 segundos desde la última vez (ajustable)
                        if not lastPlayed[t.spellID] or (currentTime - lastPlayed[t.spellID] > 30) then
                            activeStates[t.spellID] = true
                            lastPlayed[t.spellID] = currentTime
                            PlayCurrentSound()
                        end
                    end
                else
                    -- Si el aura ya no está, reseteamos el estado para que pueda volver a sonar
                    activeStates[t.spellID] = false
                end
            end
        end

    elseif event == "ADDON_LOADED" then
        local arg1 = ...
        if arg1 == modName then
            FTH_VERSION = FTH_VERSION or "horde"
            FTH_LANGUAGE = FTH_LANGUAGE or "en"
            FTH_VOLUME = FTH_VOLUME or "1"
            FTH_SND_OVERRIDE = FTH_SND_OVERRIDE or 0
            
            for _, t in ipairs(triggers) do
                _G[t.gv] = (_G[t.gv] == nil) and t.default or _G[t.gv]
                ForTheWarCry["sound_on_"..t.var_name] = _G[t.gv]
                activeStates[t.spellID] = false
                lastPlayed[t.spellID] = 0
            end
            
            local category = Settings.RegisterCanvasLayoutCategory(frame, "For The War Cry")
            Settings.RegisterAddOnCategory(category)

            local y = -30
            for _, t in ipairs(triggers) do
                local spell = C_Spell.GetSpellInfo(t.spellID)
                if spell then
                    local cb = CreateFrame("CheckButton", "FTH_CB_"..t.var_name, frame, "InterfaceOptionsCheckButtonTemplate")
                    cb:SetPoint("TOPLEFT", 10, y)
                    local txt = _G[cb:GetName().."Text"]
                    if txt then txt:SetText(spell.name) end
                    cb:SetChecked(ForTheWarCry["sound_on_"..t.var_name] == 1)
                    cb:SetScript("OnClick", function(s) 
                        local v = s:GetChecked() and 1 or 0
                        ForTheWarCry["sound_on_"..t.var_name] = v; _G[t.gv] = v 
                    end)
                    y = y - 22
                end
            end
            
            y = y - 25
            CreateClassicDropdown(frame, "Versión:", 10, y, versions, "FTH_VERSION", 80)
            CreateClassicDropdown(frame, "Idioma:", 120, y, languages, "FTH_LANGUAGE", 60)
            CreateClassicDropdown(frame, "Volumen:", 220, y, volumes, "FTH_VOLUME", 50)
            
            local test = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate")
            test:SetPoint("TOPLEFT", 350, y - 20)
            test:SetSize(100, 25)
            test:SetText("Test Sound")
            test:SetScript("OnClick", PlayCurrentSound)
        end
        
    elseif event == "PLAYER_LOGOUT" then
        for _, t in ipairs(triggers) do 
            _G[t.gv] = ForTheWarCry["sound_on_"..t.var_name] 
        end
    end
end)