local RNDX = include("lib/rndx.lua")

local function RX(x) return x * (ScrW() / 1920) end 
local function RY(y) return y * (ScrH() / 1080) end 


local ds = {
    active     = false,
    startTime  = 0,
    duration   = 0,
    killerName = "Inconnu",
}


local CFG = bladw_deathscreen and bladw_deathscreen.Config or {}
local deathscreen = nil 

local function closeDeathscreen()
    if IsValid(deathscreen) then deathscreen:Remove() end 
end

local function openDeathscreen()

    local sw, sh = ScrW(), ScrH()

    deathscreen = vgui.Create("DFrame")
    deathscreen:SetSize(sw, sh)
    deathscreen:SetPos(0, 0)
    deathscreen:SetTitle("")
    deathscreen:ShowCloseButton(false)
    deathscreen.Paint = function(self, w, h)
        draw.RoundedBox(0, 0, 0, w, h, Color(0, 0, 0, 253))

        draw.SimpleText("TU ES MORT TROP TÔT.", "bladw_text_Bold", w / 2, h / 2.7, Color(76, 119, 227), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
        draw.SimpleText("TUÉ PAR ".. ds.killerName, "bladw_text_Regular", w / 2, h / 2.4, Color(255, 255, 255), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)

            -- Barre de progression
        local barW   = w * 0.47        -- largeur totale de la barre
        local barH   = 12              -- épaisseur
        local barX   = (w - barW) / 2  -- centrée
        local barY   = h / 1.6       -- position verticale

        local elapsed  = CurTime() - ds.startTime
        local progress = math.Clamp(elapsed / ds.duration, 0, 1)
        local filledW  = barW * progress

        -- Fond gris (temps restant)
        draw.RoundedBox(barH / 2, barX, barY, barW, barH, Color(60, 60, 60))

        -- Remplissage bleu (temps écoulé)
        if filledW > 0 then
            draw.RoundedBox(barH / 2, barX, barY, filledW, barH, Color(76, 119, 227))
        end

        -- Curseur blanc
        local cursorR = 8
        local cursorX = barX + filledW
        local cursorY = barY + barH / 2
        draw.RoundedBox(cursorR, cursorX - cursorR, cursorY - cursorR, cursorR * 2, cursorR * 2, Color(255, 255, 255, 255))

        local remaining = ds.duration - (CurTime() - ds.startTime)

        if ds.active and remaining <= 0 then
            draw.SimpleText("Cliquez pour réapparaître.", "bladw_text2", w / 2, h / 1.47, Color(255,255,255), TEXT_ALIGN_CENTER, TEXT_ALIGN_BOTTOM)
        else
            draw.SimpleText("PATIENTEZ JUSQU'A CE QU'UN MEDECIN VOUS STABILISE. LES MEDECINS SONT EN ROUTE", "bladw_text2", w / 2, h / 1.47, Color(255,255,255), TEXT_ALIGN_CENTER, TEXT_ALIGN_BOTTOM)
        end
    end
end

net.Receive("bladw_deathscreen_open", function()
    ds.duration   = net.ReadUInt(16)
    ds.killerName = net.ReadString()
    ds.startTime  = CurTime()
    ds.active     = true
    openDeathscreen()
end)

net.Receive("bladw_deathscreen_close", function()
    ds.active = false
    closeDeathscreen()
end)

hook.Add("HUDShouldDraw", "bladw_ds_hidehud", function(name)
    if not ds.active then return end
    return false
end)