-- ══════════════════════════════════════════════════════════════
-- MODUL: MemorialCard — teilbare Grabstein-Karte eines Gefallenen
-- ══════════════════════════════════════════════════════════════
-- Zeigt einen einzelnen Tod als huebsche Memorial-Karte im Buch-Look.
--   • Screenshot-Button: blendet die Bedienelemente kurz aus und knipst
--     eine saubere Karte (Screenshot()).
--   • Discord-Button: oeffnet ein Copy-Feld mit Discord-Text
--     (nutzt das vorhandene Export:FormatDeath).
-- Aufruf:  /gdl card [Name]   oder   MemorialCard:Show(death)
-- Bewusst ohne OnUpdate/Animationen -> kein Performance-Risiko.
-- ══════════════════════════════════════════════════════════════

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

local CARD_W = 360

-- ── Stil-Helfer (mit Fallbacks, falls UI-Modul noch nicht da) ─────────────────
local function ClassRGB(classId)
    local UI = GDL:GetModule("UI")
    if UI and UI.GetClassColor then
        local c = UI:GetClassColor(classId)
        if c then return c[1] or 0.8, c[2] or 0.8, c[3] or 0.8 end
    end
    return 0.8, 0.8, 0.8
end
local function ClassHex(classId)
    local UI = GDL:GetModule("UI")
    if UI and UI.ClassColorHex then return UI.ClassColorHex(classId) end
    return "ffcccccc"
end
local function ClassIconTex(classId)
    local UI = GDL:GetModule("UI")
    if UI and UI.GetClassIcon then return UI:GetClassIcon(classId) end
    return "Interface\\Icons\\INV_Misc_QuestionMark"
end
local function KillerOf(d)
    local k = d.killerName or d.killer or d.killedBy or d.source or ""
    local UI = GDL:GetModule("UI")
    if UI and UI.CleanKillerName and k ~= "" then return UI.CleanKillerName(k) end
    return k
end

-- ══════════════════════════════════════════════════════════════
-- COPY-FELD (Discord-Text) — eigenes kleines Fenster, vom Karten-
-- Layout entkoppelt.
-- ══════════════════════════════════════════════════════════════
function MemorialCard:ShowCopyText(text)
    if not self.copyFrame then
        local f = CreateFrame("Frame", "GDLMemorialCopy", UIParent, "BackdropTemplate")
        f:SetSize(420, 230)
        f:SetPoint("CENTER", 0, -40)
        f:SetFrameStrata("FULLSCREEN_DIALOG")
        f:SetMovable(true); f:EnableMouse(true)
        f:RegisterForDrag("LeftButton")
        f:SetScript("OnDragStart", f.StartMoving)
        f:SetScript("OnDragStop", f.StopMovingOrSizing)
        f:SetBackdrop({
            bgFile   = "Interface\\ChatFrame\\ChatFrameBackground",
            edgeFile = "Interface\\DialogFrame\\UI-DialogBox-Gold-Border",
            edgeSize = 24,
            insets   = { left = 5, right = 5, top = 5, bottom = 5 },
        })
        f:SetBackdropColor(0.10, 0.08, 0.05, 0.96)
        f:SetBackdropBorderColor(0.70, 0.60, 0.40, 1)

        local title = f:CreateFontString(nil, "OVERLAY")
        title:SetFont("Fonts\\MORPHEUS.TTF", 14, "")
        title:SetPoint("TOP", 0, -12)
        title:SetText("|cffFFD100" .. GDL:L("MC_COPY_TITLE") .. "|r")

        local close = CreateFrame("Button", nil, f, "UIPanelCloseButton")
        close:SetPoint("TOPRIGHT", -4, -4)

        local scroll = CreateFrame("ScrollFrame", nil, f, "UIPanelScrollFrameTemplate")
        scroll:SetPoint("TOPLEFT", 14, -38)
        scroll:SetPoint("BOTTOMRIGHT", -32, 46)
        local eb = CreateFrame("EditBox", nil, scroll)
        eb:SetMultiLine(true)
        eb:SetFontObject("ChatFontNormal")
        eb:SetWidth(scroll:GetWidth() - 16)
        eb:SetAutoFocus(false)
        eb:EnableMouse(true)
        eb:SetScript("OnEscapePressed", function() f:Hide() end)
        scroll:SetScrollChild(eb)
        f.editBox = eb

        local selBtn = CreateFrame("Button", nil, f, "UIPanelButtonTemplate")
        selBtn:SetSize(120, 24)
        selBtn:SetPoint("BOTTOM", 0, 14)
        selBtn:SetText(GDL:L("MC_SELECT_ALL"))
        selBtn:SetScript("OnClick", function()
            eb:HighlightText(); eb:SetFocus()
        end)

        self.copyFrame = f
    end
    self.copyFrame.editBox:SetText(text or "")
    self.copyFrame:Show()
    self.copyFrame.editBox:HighlightText()
    self.copyFrame.editBox:SetFocus()
end

-- ══════════════════════════════════════════════════════════════
-- DIE KARTE
-- ══════════════════════════════════════════════════════════════
function MemorialCard:Build()
    local f = CreateFrame("Frame", "GDLMemorialCard", UIParent, "BackdropTemplate")
    f:SetSize(CARD_W, 360)
    f:SetPoint("CENTER", 0, 60)
    f:SetFrameStrata("FULLSCREEN_DIALOG")
    f:SetToplevel(true)
    f:SetMovable(true); f:EnableMouse(true)
    f:RegisterForDrag("LeftButton")
    f:SetScript("OnDragStart", f.StartMoving)
    f:SetScript("OnDragStop", f.StopMovingOrSizing)
    f:SetBackdrop({
        bgFile   = "Interface\\ChatFrame\\ChatFrameBackground",
        edgeFile = "Interface\\DialogFrame\\UI-DialogBox-Gold-Border",
        edgeSize = 26,
        insets   = { left = 6, right = 6, top = 6, bottom = 6 },
    })
    f:SetBackdropColor(0.07, 0.05, 0.03, 0.97)
    f:SetBackdropBorderColor(0.66, 0.52, 0.24, 1)

    -- Atmosphaerischer Hintergrund (verzeiht Seitenverhaeltnis bei niedriger Alpha)
    local bg = f:CreateTexture(nil, "BACKGROUND")
    bg:SetPoint("TOPLEFT", 7, -7)
    bg:SetPoint("BOTTOMRIGHT", -7, 7)
    bg:SetTexture("Interface\\AddOns\\GuildDeathLog\\Textures\\GDL_DeathBanner.png")
    bg:SetAlpha(0.14)
    f.bg = bg

    -- Klassen-Akzentbalken oben
    local accent = f:CreateTexture(nil, "ARTWORK")
    accent:SetHeight(3)
    accent:SetPoint("TOPLEFT", 10, -10)
    accent:SetPoint("TOPRIGHT", -10, -10)
    f.accent = accent

    -- Kopfzeile
    local header = f:CreateFontString(nil, "OVERLAY")
    header:SetFont("Fonts\\MORPHEUS.TTF", 13, "")
    header:SetPoint("TOP", 0, -18)
    header:SetText("|cffBFA66A\226\128\148  " .. GDL:L("MC_IN_MEMORIAM") .. "  \226\128\148|r")
    f.header = header

    -- Klassen-Icon (gerahmt)
    local iconBack = f:CreateTexture(nil, "BACKGROUND")
    iconBack:SetSize(50, 50)
    iconBack:SetPoint("TOP", 0, -38)
    iconBack:SetColorTexture(0, 0, 0, 0.5)
    f.iconBack = iconBack
    local icon = f:CreateTexture(nil, "ARTWORK")
    icon:SetSize(44, 44)
    icon:SetPoint("CENTER", iconBack, "CENTER", 0, 0)
    icon:SetTexCoord(0.07, 0.93, 0.07, 0.93)
    f.icon = icon

    -- Name
    local nameFS = f:CreateFontString(nil, "OVERLAY")
    nameFS:SetFont("Fonts\\MORPHEUS.TTF", 22, "")
    nameFS:SetPoint("TOP", iconBack, "BOTTOM", 0, -8)
    nameFS:SetShadowOffset(1, -1); nameFS:SetShadowColor(0, 0, 0, 0.8)
    f.nameFS = nameFS

    -- Stufe / Klasse
    local subFS = f:CreateFontString(nil, "OVERLAY")
    subFS:SetFont("Fonts\\FRIZQT__.TTF", 12, "")
    subFS:SetPoint("TOP", nameFS, "BOTTOM", 0, -4)
    subFS:SetTextColor(0.80, 0.72, 0.55)
    f.subFS = subFS

    -- Trennlinie
    local div = f:CreateTexture(nil, "ARTWORK")
    div:SetHeight(1)
    div:SetPoint("TOPLEFT", 28, 0)   -- y in Layout()
    div:SetPoint("TOPRIGHT", -28, 0)
    div:SetColorTexture(0.55, 0.42, 0.16, 0.55)
    f.div = div

    -- Detailzeilen (zentriert)
    local function detailFS()
        local fs = f:CreateFontString(nil, "OVERLAY")
        fs:SetFont("Fonts\\FRIZQT__.TTF", 11, "")
        fs:SetPoint("TOP", 0, 0)  -- y in Layout()
        fs:SetWidth(CARD_W - 40)
        fs:SetJustifyH("CENTER")
        return fs
    end
    f.zoneFS   = detailFS()
    f.killerFS = detailFS()
    f.dateFS   = detailFS()

    -- Letzte Worte (Zitatblock)
    local lwFS = f:CreateFontString(nil, "OVERLAY")
    lwFS:SetFont("Fonts\\FRIZQT__.TTF", 12, "")
    lwFS:SetPoint("TOP", 0, 0)  -- y in Layout()
    lwFS:SetWidth(CARD_W - 50)
    lwFS:SetJustifyH("CENTER")
    lwFS:SetTextColor(0.78, 0.68, 0.50)
    f.lwFS = lwFS

    -- Fusszeile (Gilde)
    local footFS = f:CreateFontString(nil, "OVERLAY")
    footFS:SetFont("Fonts\\FRIZQT__.TTF", 9, "")
    footFS:SetPoint("BOTTOM", 0, 46)  -- y in Layout()
    footFS:SetTextColor(0.50, 0.42, 0.30)
    f.footFS = footFS

    -- ── Bedienleiste (wird beim Screenshot kurz versteckt) ───────────────────
    local bar = CreateFrame("Frame", nil, f)
    bar:SetPoint("BOTTOMLEFT", 8, 8)
    bar:SetPoint("BOTTOMRIGHT", -8, 8)
    bar:SetHeight(30)
    f.bar = bar

    local shotBtn = CreateFrame("Button", nil, bar, "UIPanelButtonTemplate")
    shotBtn:SetSize(108, 22)
    shotBtn:SetPoint("LEFT", 2, 0)
    shotBtn:SetText("Screenshot")
    shotBtn:SetScript("OnClick", function() MemorialCard:Snapshot() end)

    local discBtn = CreateFrame("Button", nil, bar, "UIPanelButtonTemplate")
    discBtn:SetSize(108, 22)
    discBtn:SetPoint("CENTER", 0, 0)
    discBtn:SetText("Discord-Text")
    discBtn:SetScript("OnClick", function()
        local Export = GDL:GetModule("Export")
        local txt
        if Export and Export.FormatDeath and f._death then
            txt = Export:FormatDeath(f._death, "discord")
        end
        MemorialCard:ShowCopyText(txt or "—")
    end)

    local closeBtn = CreateFrame("Button", nil, bar, "UIPanelButtonTemplate")
    closeBtn:SetSize(80, 22)
    closeBtn:SetPoint("RIGHT", -2, 0)
    closeBtn:SetText(GDL:L("CLOSE"))
    closeBtn:SetScript("OnClick", function() f:Hide() end)

    -- Hint (Screenshot landet in WoW\Screenshots)
    local hint = f:CreateFontString(nil, "OVERLAY")
    hint:SetFont("Fonts\\FRIZQT__.TTF", 8, "")
    hint:SetPoint("BOTTOM", bar, "TOP", 0, 2)
    hint:SetTextColor(0.45, 0.40, 0.30)
    hint:SetText(GDL:L("MC_SHOT_HINT"))
    f.hint = hint

    self.frame = f
end

-- Positioniert die fliessenden Elemente je nach Inhalt + setzt die Hoehe.
function MemorialCard:Layout(hasLastWords, lwHeight)
    local f = self.frame
    local y = -120                       -- unter Stufe/Klasse
    f.div:SetPoint("TOPLEFT", 28, y)
    f.div:SetPoint("TOPRIGHT", -28, y)
    y = y - 12
    f.zoneFS:SetPoint("TOP", 0, y);   y = y - 16
    f.killerFS:SetPoint("TOP", 0, y); y = y - 16
    f.dateFS:SetPoint("TOP", 0, y);   y = y - 18

    if hasLastWords then
        f.lwFS:SetPoint("TOP", 0, y - 4)
        f.lwFS:Show()
        y = y - (lwHeight or 16) - 14
    else
        f.lwFS:Hide()
        y = y - 4
    end

    -- Gesamthoehe: Kopf bis hier + Fuss (Footer + Bar)
    local contentBottom = -y          -- positiver Abstand von oben
    local total = contentBottom + 64  -- Platz fuer Footer + Bedienleiste
    if total < 300 then total = 300 end
    f:SetHeight(total)
end

function MemorialCard:Show(death)
    if not death then
        GDL:Print("|cffFF4444" .. GDL:L("MC_NO_DATA") .. "|r")
        return
    end
    if not self.frame then self:Build() end
    local f = self.frame
    f._death = death

    local classId = death.classId or death.class or 0
    local r, g, b = ClassRGB(classId)
    local hex     = ClassHex(classId)

    f.accent:SetColorTexture(r, g, b, 0.85)
    f.icon:SetTexture(ClassIconTex(classId))
    f.nameFS:SetText("|c" .. hex .. (death.name or GDL:T("Unbekannt")) .. "|r")
    f.subFS:SetText(GDL:L("MC_LEVEL") .. " " .. (death.level or "?") .. "  \194\183  " .. (GDL:GetClassName(classId) or "?"))

    local zone = death.zone
    f.zoneFS:SetText((zone and zone ~= "") and (GDL:L("MC_FELL_IN") .. " |cffCBB890" .. zone .. "|r") or "")

    local killer = KillerOf(death)
    if killer and killer ~= "" and killer ~= "Unknown" then
        f.killerFS:SetText(GDL:L("MC_BY") .. " |cffE08D7A" .. killer .. "|r")
        f.killerFS:Show()
    else
        f.killerFS:SetText("")
    end

    if death.timestamp and death.timestamp > 0 then
        f.dateFS:SetText("|cff9A8B70" .. date("%d.%m.%Y  ·  %H:%M", death.timestamp) .. GDL:L("MC_CLOCK") .. "|r")
    else
        f.dateFS:SetText("")
    end

    local hasLW = death.lastWords and death.lastWords ~= ""
    if hasLW then
        f.lwFS:SetText("|cffBFA98A\226\128\158" .. death.lastWords .. "\226\128\156|r")  -- „ ... “
    end

    f.footFS:SetText("\226\128\148  " .. (GDL.currentGuildName or GDL:T("Buch der Gefallenen")) .. "  \226\128\148")

    -- Layout (Hoehe der letzten Worte erst nach SetText bekannt)
    self:Layout(hasLW, hasLW and (f.lwFS:GetStringHeight() or 16) or 0)
    f:Show()
end

-- ── Sauberer Schnappschuss: Chrome kurz ausblenden, knipsen, zurueck ──────────
function MemorialCard:Snapshot()
    local f = self.frame
    if not f then return end
    if self.copyFrame then self.copyFrame:Hide() end
    f.bar:Hide(); f.hint:Hide()
    -- einen Frame warten, damit das Ausblenden sicher gerendert ist
    C_Timer.After(0.05, function()
        if Screenshot then Screenshot() end
        C_Timer.After(0.25, function()
            if f:IsShown() then f.bar:Show(); f.hint:Show() end
        end)
    end)
end

-- ── Tod finden (neuester, optional nach Name gefiltert) ───────────────────────
function MemorialCard:ShowLatest(nameFilter)
    local gd = GDL:GetGuildData()
    if not gd or not gd.deaths or #gd.deaths == 0 then
        GDL:Print("|cffFF4444" .. GDL:L("MC_NO_DEATHS") .. "|r")
        return
    end
    nameFilter = nameFilter and nameFilter:lower():gsub("%s+$", ""):gsub("^%s+", "")
    local best
    for _, d in ipairs(gd.deaths) do
        local ok = true
        if nameFilter and nameFilter ~= "" then
            ok = ((d.name or ""):lower():find(nameFilter, 1, true)) ~= nil
        end
        if ok and (not best or (d.timestamp or 0) > (best.timestamp or 0)) then
            best = d
        end
    end
    if not best then
        GDL:Print("|cffFF4444" .. string.format(GDL:L("MC_NOT_FOUND"), nameFilter or "?") .. "|r")
        return
    end
    self:Show(best)
end

function MemorialCard:Toggle(death)
    if self.frame and self.frame:IsShown() then
        self.frame:Hide()
    elseif death then
        self:Show(death)
    else
        self:ShowLatest(nil)
    end
end

GDL:RegisterModule("MemorialCard", MemorialCard)
