local addonName, addon = ...
local GDL = addon
local ZoneWarning = {}
GDL.modules = GDL.modules or {}
GDL.modules["ZoneWarning"] = ZoneWarning

local lastZone = ""
local warned = {}

function ZoneWarning:GetZoneDeathCount(zoneName)
    if not GDL.currentGuildName or not zoneName then return 0 end
    local guildData = GuildDeathLogDB and GuildDeathLogDB.guilds and GuildDeathLogDB.guilds[GDL.currentGuildName]
    if not guildData or not guildData.deaths then return 0 end
    
    local count = 0
    local names = {}
    for _, death in pairs(guildData.deaths) do
        if death.zone and death.zone:lower() == zoneName:lower() then
            count = count + 1
            if death.name and #names < 3 then
                table.insert(names, death.name)
            end
        end
    end
    return count, names
end

function ZoneWarning:OnZoneChanged()
    if not GDL.currentGuildName then return end
    if not GuildDeathLogDB or not GuildDeathLogDB.settings then return end
    if GuildDeathLogDB.settings.zoneWarning == false then return end
    
    local zone = GetZoneText() or ""
    if zone == "" or zone == lastZone then return end
    lastZone = zone
    
    if warned[zone] then return end
    
    local count, names = self:GetZoneDeathCount(zone)
    if count >= 2 then
        warned[zone] = true
        local severity = count >= 10 and "|cffFF0000TODESZONE|r" or (count >= 5 and "|cffFF6600GEFAEHRLICH|r" or "|cffFFCC00VORSICHT|r")
        local nameStr = ""
        if #names > 0 then
            nameStr = " (u.a. " .. table.concat(names, ", ") .. ")"
        end
        GDL:Print(severity .. " |cff69CCF0" .. zone .. "|r - |cffFFD100" .. count .. " Gildenmitglieder|r fielen hier" .. nameStr)
        
        if count >= 5 and GuildDeathLogDB.settings.sound ~= false then
            PlaySound(8959, "Master")
        end
    end
end

function ZoneWarning:Initialize()
    local f = CreateFrame("Frame")
    f:RegisterEvent("ZONE_CHANGED_NEW_AREA")
    f:RegisterEvent("ZONE_CHANGED")
    f:RegisterEvent("PLAYER_ENTERING_WORLD")
    f:SetScript("OnEvent", function()
        C_Timer.After(2, function()
            ZoneWarning:OnZoneChanged()
        end)
    end)
end
