-- ══════════════════════════════════════════════════════════════
-- MODUL: Insights - Mehrwert-Features rund um die Gildendaten
--   1) "Waehrend du weg warst" - Login-Digest der Tode seit letztem Besuch
--   2) Toedlichste-Stufe-Warnung beim Aufstieg (aus echten Gildendaten)
--   3) /gdl threats - Hallen der Furcht (toedlichste Gebiete & Stufen)
--   4) Gilden-Meilenstein: "Die Chronik zaehlt nun N Gefallene"
-- Read-only auf den Todesdaten, DE/EN per GetLocale, 1.15.8 + 2.2.5 safe.
-- ══════════════════════════════════════════════════════════════

local addonName, addon = ...
local GDL = _G["GuildDeathLog"]
local Insights = {}

local DE = (GetLocale() == "deDE")
local function T(de, en) return DE and de or en end

local function charKey()
    return (UnitName("player") or "?")
end

-- Todesliste der AKTUELLEN Gilde (oder nil)
local function guildDeaths()
    local g = GDL.currentGuildName
    if not g then return nil end
    local gd = GuildDeathLogDB and GuildDeathLogDB.guilds and GuildDeathLogDB.guilds[g]
    return gd and gd.deaths or nil
end

local function store()
    GuildDeathLogDB.insights = GuildDeathLogDB.insights or {}
    local s = GuildDeathLogDB.insights
    s.lastSeen    = s.lastSeen    or {}
    s.levelWarned = s.levelWarned or {}
    return s
end

local function className(classId)
    return (GDL.GetClassName and GDL:GetClassName(classId)) or ""
end

-- ── 1) "Waehrend du weg warst" ────────────────────────────────────────────────
function Insights:ShowWelcomeBack(manual)
    local deaths = guildDeaths()
    if not deaths then
        if manual then GDL:Print("|cffFF4444" .. T("Keine Gildendaten.", "No guild data.") .. "|r") end
        return
    end
    local s   = store()
    local key = charKey()
    local now = time()
    local since = s.lastSeen[key]

    -- Fenster: manuell = letzte 7 Tage; auto = seit letztem Besuch (max 30 Tage)
    local windowStart
    if manual then
        windowStart = now - 7 * 86400
    else
        windowStart = since or (now - 1)
        if since and (now - since) > 30 * 86400 then windowStart = now - 30 * 86400 end
    end

    local list, count = {}, 0
    for _, d in pairs(deaths) do
        if d.timestamp and d.name and d.timestamp > windowStart and d.timestamp <= now + 60 then
            count = count + 1
            list[#list + 1] = d
        end
    end

    if not manual then
        s.lastSeen[key] = now          -- Marke immer aktualisieren
        if not since then return end   -- Erstlauf: kein Spam
    end

    if count == 0 then
        if manual then
            GDL:Print("|cff8A6A20" .. T("[Chronik]", "[Chronicle]") .. "|r " ..
                T("In den letzten 7 Tagen ist niemand gefallen. Stark!",
                  "No one fell in the last 7 days. Strong!"))
        end
        return
    end

    table.sort(list, function(a, b) return (a.timestamp or 0) > (b.timestamp or 0) end)

    local header
    if manual then
        header = T("In den letzten 7 Tagen gefallen:", "Fallen in the last 7 days:")
    else
        header = string.format(
            T("Seit deinem letzten Besuch sind %d Gildengeschwister gefallen:",
              "%d guildmates fell since your last visit:"), count)
    end
    GDL:Print("|cff8A6A20" .. T("[Buch der Gefallenen]", "[Book of the Fallen]") ..
        "|r |cffCCB070" .. header .. "|r")

    local shown = 0
    for _, d in ipairs(list) do
        shown = shown + 1
        if shown > 8 then break end
        local cn = className(d.classId)
        GDL:Print(string.format("   |cffFF6B6B%s|r |cff888888(%s %d%s)|r %s",
            d.name, T("Stufe", "Level"), d.level or 0,
            cn ~= "" and (", " .. cn) or "",
            d.zone and ("|cff69CCF0" .. d.zone .. "|r") or ""))
    end
    if count > 8 then
        GDL:Print("   |cff666666" .. string.format(T("… und %d weitere", "… and %d more"), count - 8) .. "|r")
    end
end

-- ── 2) Toedlichste-Stufe-Warnung ──────────────────────────────────────────────
function Insights:CheckDeadlyLevel(level)
    level = level or UnitLevel("player")
    if not level or level <= 0 then return end
    local deaths = guildDeaths()
    if not deaths then return end

    local n = 0
    for _, d in pairs(deaths) do
        if d.level == level then n = n + 1 end
    end
    if n < 3 then return end   -- erst ab 3 Toden auf dieser Stufe relevant

    local s = store()
    local key = charKey()
    s.levelWarned[key] = s.levelWarned[key] or {}
    if s.levelWarned[key][level] then return end
    s.levelWarned[key][level] = true

    local msg = string.format(
        T("Vorsicht: Stufe %d war fuer %d Gildenmitglieder toedlich. Bleib wachsam.",
          "Caution: level %d was deadly for %d guildmates. Stay sharp."),
        level, n)

    local UI = GDL:GetModule("UI")
    if UI and UI.ShowMilestoneToast then
        UI:ShowMilestoneToast({
            name     = T("Gefaehrliche Stufe", "Deadly Level"),
            desc     = msg,
            icon     = "Interface\\Icons\\INV_Misc_Bone_HumanSkull_01",
            category = "warning",
        })
    end
    GDL:Print("|cffFF4422" .. T("[Warnung]", "[Warning]") .. "|r |cffFFCC88" .. msg .. "|r")
end

-- ── 3) /gdl threats - Hallen der Furcht ───────────────────────────────────────
local TRANSPORT = {
    ["DNL-Channel"] = true, ["DNL"] = true, ["System"] = true, ["Blizzard"] = true,
    ["HCDeathAlerts"] = true, ["Unbekannt"] = true, ["Unknown"] = true,
}

local function topN(tbl, n)
    local arr = {}
    for k, v in pairs(tbl) do arr[#arr + 1] = { k = k, v = v } end
    table.sort(arr, function(a, b) return a.v > b.v end)
    local out = {}
    for i = 1, math.min(n, #arr) do out[i] = arr[i] end
    return out
end

function Insights:PrintThreats()
    local deaths = guildDeaths()
    if not deaths then
        GDL:Print("|cffFF4444" .. T("Keine Gildendaten.", "No guild data.") .. "|r")
        return
    end

    local zoneCt, lvlCt, causeCt, total = {}, {}, {}, 0
    local KT = GDL:GetModule("KillerTracker")
    for _, d in pairs(deaths) do
        total = total + 1
        if d.zone and d.zone ~= "" then zoneCt[d.zone] = (zoneCt[d.zone] or 0) + 1 end
        if d.level and d.level > 0 then lvlCt[d.level] = (lvlCt[d.level] or 0) + 1 end
        local cause = (KT and KT.CauseName and KT:CauseName(d)) or d.killer or d.killerName
        if cause and cause ~= "" and not TRANSPORT[cause] then
            causeCt[cause] = (causeCt[cause] or 0) + 1
        end
    end

    if total == 0 then
        GDL:Print("|cff8A6A20" .. T("Noch keine Tode verzeichnet.", "No deaths recorded yet.") .. "|r")
        return
    end

    GDL:Print("|cff8A1A1A=== " .. T("Hallen der Furcht", "Halls of Fear") .. " ===|r |cff666666(" ..
        total .. " " .. T("Gefallene", "fallen") .. ")|r")

    GDL:Print("|cffCC8844" .. T("Toedlichste Gebiete:", "Deadliest zones:") .. "|r")
    for i, e in ipairs(topN(zoneCt, 5)) do
        GDL:Print(string.format("   %d. |cff69CCF0%s|r — |cffFF6B6B%d|r", i, tostring(e.k), e.v))
    end

    GDL:Print("|cffCC8844" .. T("Toedlichste Stufen:", "Deadliest levels:") .. "|r")
    for i, e in ipairs(topN(lvlCt, 5)) do
        GDL:Print(string.format("   %d. %s %s — |cffFF6B6B%d|r", i, T("Stufe", "Level"), tostring(e.k), e.v))
    end

    local causes = topN(causeCt, 5)
    if #causes > 0 then
        GDL:Print("|cffCC8844" .. T("Haeufigste Todesursachen:", "Most common causes:") .. "|r")
        for i, e in ipairs(causes) do
            GDL:Print(string.format("   %d. |cffDDAA66%s|r — |cffFF6B6B%d|r", i, tostring(e.k), e.v))
        end
    end
end

-- ── 4) Gilden-Meilenstein-Toast ───────────────────────────────────────────────
local LANDMARKS = { 25, 50, 100, 150, 200, 250, 300, 400, 500, 750, 1000, 1500, 2000 }

function Insights:CheckDeathMilestone()
    local deaths = guildDeaths()
    if not deaths then return end
    local total = 0
    for _ in pairs(deaths) do total = total + 1 end

    local s = store()
    local highest = 0
    for _, m in ipairs(LANDMARKS) do if total >= m then highest = m end end

    if s.deathMileMax == nil then
        s.deathMileMax = highest   -- Erstlauf: Stand merken, nicht melden
        return
    end
    if highest > s.deathMileMax then
        s.deathMileMax = highest
        local msg = string.format(
            T("Die Chronik zaehlt nun %d Gefallene.", "The chronicle now holds %d fallen."),
            highest)
        local UI = GDL:GetModule("UI")
        if UI and UI.ShowMilestoneToast then
            UI:ShowMilestoneToast({
                name     = T("Mahnmal", "Memorial"),
                desc     = msg,
                icon     = "Interface\\Icons\\Spell_Holy_GuardianSpirit",
                category = "memorial",
            })
        end
        GDL:Print("|cff8A6A20" .. T("[Mahnmal]", "[Memorial]") .. "|r |cffCCB070" .. msg .. "|r")
    end
end

-- ── Init ──────────────────────────────────────────────────────────────────────
function Insights:Initialize()
    if self._initialized then return end
    self._initialized = true

    local f = CreateFrame("Frame")
    f:RegisterEvent("PLAYER_LEVEL_UP")
    f:SetScript("OnEvent", function(_, _, lvl)
        Insights:CheckDeadlyLevel(tonumber(lvl) or UnitLevel("player"))
    end)

    -- Nach Login: Gildendaten/Gildenname sind dann da
    C_Timer.After(14, function()
        Insights:ShowWelcomeBack(false)
        Insights:CheckDeathMilestone()
    end)
    C_Timer.NewTicker(300, function() Insights:CheckDeathMilestone() end)
end

GDL:RegisterModule("Insights", Insights)
