-- ══════════════════════════════════════════════════════════════
-- UI SUB-MODULE: Gilden-Wettbewerb Chapter
-- Rendert das "Gilden-Wettbewerb"-Kapitel im Buch
-- Nutzt dieselbe UI-Table via addon._UI
-- Version 9.7.6
--
-- DESIGN: Ausschliesslich Pergament-Palette (Braun/Sepia).
-- Keine gesaettigten RGB-Farben! Kategorien werden durch
-- Textpraefixe und leichte Tonabstufungen unterschieden.
-- ══════════════════════════════════════════════════════════════

local addonName, addon = ...
local GDL = _G["GuildDeathLog"]
local UI = addon._UI

-- Local refs
local _  -- Wegwerf-Variable lokal halten (kein globales _ setzen)
local math_floor = math.floor
local math_max = math.max
local math_abs = math.abs
local string_format = string.format

-- ── BUCH-FARBPALETTE (einheitlich mit allen Kapiteln) ────────
local C = {
    HEAD     = "|cff3D2410",  -- Kapitel-Ueberschriften (MORPHEUS)
    BODY     = "|cff5E3E1C",  -- Standard-Text
    ACCENT   = "|cff7A2C14",  -- Zahlen, Akzente, Rang 1-3
    NUM      = "|cff8A5E14",  -- Werte, Punkte
    DIM      = "|cff5E3E1C",  -- Subtext, gedaempft
    DARK     = "|cff3D2410",  -- Noch dunkler
    MUTED    = "|cff5E3E1C",  -- Deaktiviert, unwichtig
    FADED    = "|cff7A6448",  -- Sehr blass (Legende)
    WARN     = "|cff7A3828",  -- Warnfarbe (Tode) — gedaempftes Rot-Braun
}

-- Fonts
local F_HEAD = "Fonts\\MORPHEUS.TTF"
local F_BODY = "Fonts\\FRIZQT__.TTF"

-- ── HELPERS ──────────────────────────────────────────────────

local function FormatNumber(n)
    if not n then return "0" end
    n = math_floor(n)
    if n < 1000 then return tostring(n) end
    local str = tostring(n)
    local result = ""
    local len = #str
    for i = 1, len do
        result = result .. str:sub(i, i)
        if (len - i) % 3 == 0 and i ~= len then
            result = result .. "."
        end
    end
    return result
end

-- Rangnummer-Prefix (Gold/Silber/Bronze nur via Braun-Abstufung)
local function RankColor(i)
    if i == 1 then return C.ACCENT end   -- kraeftiges Rot-Braun
    if i <= 3 then return C.NUM end      -- Amber-Braun
    return C.BODY                         -- Standard
end

-- Pergament-Trennlinie
local function Divider(parent, y)
    local d = parent:CreateTexture(nil, "ARTWORK")
    d:SetHeight(1)
    d:SetPoint("TOPLEFT", 8, y)
    d:SetPoint("TOPRIGHT", -8, y)
    d:SetColorTexture(0.45, 0.32, 0.10, 0.25)
    return y - 10
end

-- ══════════════════════════════════════════════════════════════
-- HAUPT-RENDER: Gilden-Wettbewerb
-- ══════════════════════════════════════════════════════════════

function UI:RenderGuildCompetition()
    local parent = self.mainFrame.scrollChild
    local y = 0

    local GuildComp = GDL:GetModule("GuildCompetition")
    if not GuildComp then
        _, y = self:MakeBookLine(parent, y, "Gilden-Wettbewerb nicht verfuegbar.", 11, C.DIM)
        parent:SetHeight(math_abs(y) + 20)
        return
    end

    -- Medaillen-Farben (wie Rang-Badges in den anderen Kapiteln)
    local MEDAL = { "|cffA8761E", "|cff8C8478", "|cff96522A" }
    local function RankTag(i)
        return (MEDAL[i] or C.FADED) .. "#" .. i .. "|r"
    end

    -- ══════════════════════════════════════════════════════════
    -- KOPF: Gilde, Punkte, Rang
    -- ══════════════════════════════════════════════════════════
    local myGuild = GDL.guildName or (GetGuildInfo and GetGuildInfo("player")) or "Unbekannte Gilde"
    local score = GuildComp:GetGuildScore()
    local rank, totalGuilds = GuildComp:GetGuildRank()

    local guildFS = parent:CreateFontString(nil, "OVERLAY")
    guildFS:SetFont(F_HEAD, 16, "")
    guildFS:SetPoint("TOPLEFT", 8, y)
    guildFS:SetWidth(310); guildFS:SetJustifyH("LEFT")
    guildFS:SetShadowOffset(1, -1); guildFS:SetShadowColor(0.35, 0.22, 0.08, 0.25)
    guildFS:SetText(C.HEAD .. myGuild .. "|r")
    y = y - 24

    -- Punkte gross: Zahl in dunkelster Tinte, "Punkte" klein in Gold
    local scoreFS = parent:CreateFontString(nil, "OVERLAY")
    scoreFS:SetFont(F_HEAD, 24, "")
    scoreFS:SetPoint("TOPLEFT", 10, y)
    scoreFS:SetShadowOffset(1, -1); scoreFS:SetShadowColor(0.35, 0.22, 0.08, 0.25)
    scoreFS:SetText("|cff2A1606" .. FormatNumber(score) .. "|r")

    local scoreLbl = parent:CreateFontString(nil, "OVERLAY")
    scoreLbl:SetFont(F_BODY, 10, "")
    scoreLbl:SetPoint("BOTTOMLEFT", scoreFS, "BOTTOMRIGHT", 6, 3)
    scoreLbl:SetShadowOffset(1, -1); scoreLbl:SetShadowColor(0, 0, 0, 0.10)
    scoreLbl:SetText(C.NUM .. "PUNKTE|r")
    y = y - 30

    if totalGuilds > 1 then
        _, y = self:MakeBookLine(parent, y,
            "Rang " .. RankTag(rank) .. C.BODY .. " von " .. totalGuilds .. " bekannten Gilden",
            10, C.BODY)
    end

    local deathPenalty = GuildComp:GetDeathPenaltyTotal()
    local deathCount = GuildComp:GetDeathCount()
    if deathPenalty > 0 then
        _, y = self:MakeBookLine(parent, y,
            deathCount .. " gefallene Mitglieder  =  -" .. FormatNumber(deathPenalty) .. " Strafpunkte",
            9, C.WARN)
    end

    y = y - 4
    y = Divider(parent, y)

    -- ══════════════════════════════════════════════════════════
    -- GILDEN-RANGLISTE — zweizeilige Eintraege:
    -- oben Name + Punkte, darunter eine duenne Gold-Fortschrittslinie.
    -- (Vorher lag der Text AUF einem dunklen Balken — Matsch.)
    -- ══════════════════════════════════════════════════════════
    _, y = self:MakeBookLine(parent, y, "Gilden-Rangliste", 14, C.HEAD)
    y = y + 2

    local leaderboard = GuildComp:GetSortedLeaderboard()
    if #leaderboard == 0 then
        _, y = self:MakeBookLine(parent, y,
            "Noch keine Daten. Begegne anderen Addon-Nutzern!", 9, C.DIM)
    else
        local maxScore = 1
        for _, entry in ipairs(leaderboard) do
            if entry.points > maxScore then maxScore = entry.points end
        end

        for i, entry in ipairs(leaderboard) do
            if i > 12 then
                _, y = self:MakeBookLine(parent, y,
                    "... und " .. (#leaderboard - 12) .. " weitere Gilden", 9, C.DIM)
                break
            end

            local row = CreateFrame("Frame", nil, parent)
            row:SetSize(316, 26)
            row:SetPoint("TOPLEFT", 4, y)

            -- Eigene Gilde: warme Toenung + Gold-Akzentbalken links
            if entry.isOwn then
                local ownBg = row:CreateTexture(nil, "BACKGROUND")
                ownBg:SetAllPoints()
                ownBg:SetColorTexture(0.45, 0.32, 0.10, 0.10)
                local ownBar = row:CreateTexture(nil, "ARTWORK")
                ownBar:SetSize(2, 22)
                ownBar:SetPoint("LEFT", 0, 0)
                ownBar:SetColorTexture(0.66, 0.46, 0.12, 0.90)
            end

            -- Rang-Medaille
            local rankFS = row:CreateFontString(nil, "OVERLAY")
            rankFS:SetFont(F_BODY, 10, "")
            rankFS:SetPoint("TOPLEFT", 6, -2)
            rankFS:SetWidth(24); rankFS:SetJustifyH("LEFT")
            rankFS:SetShadowOffset(1, -1); rankFS:SetShadowColor(0, 0, 0, 0.12)
            rankFS:SetText(RankTag(i))

            -- Gildenname (eigene Gilde: dunkelste Tinte + Zusatz)
            local nameFS = row:CreateFontString(nil, "OVERLAY")
            nameFS:SetFont(F_BODY, 10, "")
            nameFS:SetPoint("TOPLEFT", 32, -2)
            nameFS:SetWidth(190); nameFS:SetJustifyH("LEFT")
            nameFS:SetShadowOffset(1, -1); nameFS:SetShadowColor(0, 0, 0, 0.12)
            if entry.isOwn then
                nameFS:SetText("|cff2A1606" .. entry.name .. "|r " .. C.FADED .. "(wir)|r")
            else
                nameFS:SetText(C.BODY .. entry.name .. "|r")
            end

            -- Punkte rechts
            local ptsFS = row:CreateFontString(nil, "OVERLAY")
            ptsFS:SetFont(F_BODY, 10, "")
            ptsFS:SetPoint("TOPRIGHT", -4, -2)
            ptsFS:SetShadowOffset(1, -1); ptsFS:SetShadowColor(0, 0, 0, 0.12)
            ptsFS:SetText(C.NUM .. FormatNumber(entry.points) .. "|r")

            -- Fortschrittslinie: blasse Spur + Gold-Fuellung (4px)
            local track = row:CreateTexture(nil, "BACKGROUND")
            track:SetSize(284, 4)
            track:SetPoint("BOTTOMLEFT", 32, 3)
            track:SetColorTexture(0.30, 0.20, 0.08, 0.14)

            local fillPct = entry.points / math_max(1, maxScore)
            local fillW = math_max(2, 284 * fillPct)
            local fill = row:CreateTexture(nil, "ARTWORK")
            fill:SetSize(fillW, 4)
            fill:SetPoint("BOTTOMLEFT", 32, 3)
            if entry.isOwn then
                fill:SetColorTexture(0.66, 0.46, 0.12, 0.80)
            else
                fill:SetColorTexture(0.54, 0.37, 0.08, 0.45)
            end

            y = y - 27
        end
    end

    y = y - 6
    y = Divider(parent, y)

    -- ══════════════════════════════════════════════════════════
    -- UNSERE KAEMPFER — Medaillen-Raenge, Punkte gold, Kills blass
    -- ══════════════════════════════════════════════════════════
    _, y = self:MakeBookLine(parent, y, "Unsere Kaempfer", 14, C.HEAD)
    y = y + 2

    local players = GuildComp:GetPlayerRanking()
    if #players == 0 then
        _, y = self:MakeBookLine(parent, y,
            "Noch keine Kills aufgezeichnet.", 9, C.DIM)
    else
        for i, p in ipairs(players) do
            if i > 15 then
                _, y = self:MakeBookLine(parent, y,
                    "... und " .. (#players - 15) .. " weitere Kaempfer", 9, C.DIM)
                break
            end

            local isMe = (p.name == GDL.playerName)
            local row = CreateFrame("Frame", nil, parent)
            row:SetSize(316, 18)
            row:SetPoint("TOPLEFT", 4, y)

            if isMe then
                local meBg = row:CreateTexture(nil, "BACKGROUND")
                meBg:SetAllPoints()
                meBg:SetColorTexture(0.45, 0.32, 0.10, 0.10)
            end

            local rankFS = row:CreateFontString(nil, "OVERLAY")
            rankFS:SetFont(F_BODY, 10, "")
            rankFS:SetPoint("LEFT", 6, 0)
            rankFS:SetWidth(24); rankFS:SetJustifyH("LEFT")
            rankFS:SetShadowOffset(1, -1); rankFS:SetShadowColor(0, 0, 0, 0.12)
            rankFS:SetText(RankTag(i))

            local nameFS = row:CreateFontString(nil, "OVERLAY")
            nameFS:SetFont(F_BODY, 10, "")
            nameFS:SetPoint("LEFT", 32, 0)
            nameFS:SetWidth(140); nameFS:SetJustifyH("LEFT")
            nameFS:SetShadowOffset(1, -1); nameFS:SetShadowColor(0, 0, 0, 0.12)
            nameFS:SetText((isMe and "|cff2A1606" or C.BODY) .. p.name .. "|r")

            local valFS = row:CreateFontString(nil, "OVERLAY")
            valFS:SetFont(F_BODY, 9, "")
            valFS:SetPoint("RIGHT", -4, 0)
            valFS:SetShadowOffset(1, -1); valFS:SetShadowColor(0, 0, 0, 0.12)
            valFS:SetText(C.NUM .. FormatNumber(p.points) .. " Pkt|r" ..
                C.FADED .. "   " .. FormatNumber(p.totalKills) .. " Kills|r")

            y = y - 18
        end
    end

    y = y - 6
    y = Divider(parent, y)

    -- ══════════════════════════════════════════════════════════
    -- PERSOENLICHE JAGDSTATISTIK — mit Mini-Balken pro Kategorie
    -- ══════════════════════════════════════════════════════════
    local myStats = GuildComp:GetPlayerStats(GDL.playerName)
    if myStats and myStats.totalKills > 0 then
        _, y = self:MakeBookLine(parent, y, "Deine Jagdstatistik", 14, C.HEAD)
        y = y + 2

        _, y = self:MakeBookLine(parent, y,
            FormatNumber(myStats.totalKills) .. " Gegner besiegt  =  " ..
            FormatNumber(myStats.points) .. " Punkte",
            10, C.BODY)
        y = y - 2

        -- Groesste Kategorie als Referenz fuer die Mini-Balken
        local maxCnt = 1
        for _, ke in ipairs(myStats.kills) do
            if ke.count > maxCnt then maxCnt = ke.count end
        end

        for _, killEntry in ipairs(myStats.kills) do
            local row = CreateFrame("Frame", nil, parent)
            row:SetSize(316, 17)
            row:SetPoint("TOPLEFT", 4, y)

            local catFS = row:CreateFontString(nil, "OVERLAY")
            catFS:SetFont(F_BODY, 9, "")
            catFS:SetPoint("TOPLEFT", 12, -1)
            catFS:SetShadowOffset(1, -1); catFS:SetShadowColor(0, 0, 0, 0.12)
            catFS:SetText(C.BODY .. killEntry.name .. "|r")

            local valFS = row:CreateFontString(nil, "OVERLAY")
            valFS:SetFont(F_BODY, 9, "")
            valFS:SetPoint("TOPRIGHT", -4, -1)
            valFS:SetShadowOffset(1, -1); valFS:SetShadowColor(0, 0, 0, 0.12)
            valFS:SetText(C.DIM .. killEntry.count .. "x  =  " .. C.NUM ..
                FormatNumber(killEntry.points) .. " Pkt|r")

            -- Mini-Balken: Anteil an der groessten Kategorie
            local barW = math_max(2, 150 * (killEntry.count / maxCnt))
            local bar = row:CreateTexture(nil, "ARTWORK")
            bar:SetSize(barW, 3)
            bar:SetPoint("BOTTOMLEFT", 12, 2)
            bar:SetColorTexture(0.54, 0.37, 0.08, 0.40)

            y = y - 17
        end
    else
        _, y = self:MakeBookLine(parent, y, "Deine Jagdstatistik", 14, C.HEAD)
        _, y = self:MakeBookLine(parent, y, "Toete Gegner um Punkte zu sammeln!", 9, C.DIM)
    end

    y = y - 8
    y = Divider(parent, y)

    -- ══════════════════════════════════════════════════════════
    -- PUNKTELEGENDE — zweispaltig, kompakt
    -- ══════════════════════════════════════════════════════════
    _, y = self:MakeBookLine(parent, y, "Punktewerte", 12, C.HEAD)
    y = y + 2

    local POINTS_TABLE = GuildComp:GetPointValues()
    local catOrder = GuildComp:GetCategoryOrder()
    local catNames = GuildComp:GetCategoryNames()

    local col, rowY = 0, y
    for _, cat in ipairs(catOrder) do
        local pts = POINTS_TABLE[cat]
        if pts and pts > 0 then
            local fs = parent:CreateFontString(nil, "OVERLAY")
            fs:SetFont(F_BODY, 8, "")
            fs:SetPoint("TOPLEFT", 12 + col * 158, rowY)
            fs:SetShadowOffset(1, -1); fs:SetShadowColor(0, 0, 0, 0.1)
            fs:SetText(C.FADED .. catNames[cat] .. "  =  " .. pts .. " Pkt|r")
            col = col + 1
            if col >= 2 then col = 0; rowY = rowY - 12 end
        end
    end
    if col > 0 then rowY = rowY - 12 end
    y = rowY

    local deathFS = parent:CreateFontString(nil, "OVERLAY")
    deathFS:SetFont(F_BODY, 8, "")
    deathFS:SetPoint("TOPLEFT", 12, y)
    deathFS:SetShadowOffset(1, -1); deathFS:SetShadowColor(0, 0, 0, 0.1)
    deathFS:SetText(C.WARN .. "Gildenmitglied-Tod  =  " .. POINTS_TABLE.member_death .. " Pkt|r")
    y = y - 14

    parent:SetHeight(math_abs(y) + 20)
end
