util.AddNetworkString("bladw_deathscreen_open")
util.AddNetworkString("bladw_deathscreen_close")

local CFG = bladw_deathscreen and bladw_deathscreen.Config or {}
local RespawnTime = CFG.Timer or 60

local function Open_ds(ply, remaining, killerName)
    if not IsValid(ply) or not ply:IsPlayer() then return end

    local now = CurTime()
    local dur = math.max(0, tonumber(remaining or RespawnTime) or 0)
    ply._bladwUnLock = now + dur

    net.Start("bladw_deathscreen_open")
        net.WriteUInt(math.Clamp(dur, 0, 65535), 16)
        net.WriteString(killerName or "Inconnu")
    net.Send(ply)
end

local function Close_ds(ply)
    if not IsValid(ply) or not ply:IsPlayer() then return end
    net.Start("bladw_deathscreen_close")
    net.Send(ply)
end

hook.Add("PlayerDeath", "bladw_ds_open", function(victim, inflictor, attacker)
    local killerName = "INCONNU"
    if IsValid(attacker) and attacker:IsPlayer() then
        killerName = string.upper(attacker:Nick())
    end

    -- Adjusts respawn delay based on players in a specified team.
    local hasResponder = false
    for _, p in ipairs(player.GetAll()) do
        local job = p:getDarkRPVar("job")
        if job == "Citizen" or job == "Citizen" then  
            hasResponder = true
            break
        end
    end

    local respawnTime = hasResponder and 10 or RespawnTime

    timer.Simple(0, function()
        if IsValid(victim) then Open_ds(victim, respawnTime, killerName) end
    end)
end)

hook.Add("CanPlayerSuicide", "bladw_ds_blocksuicide", function(ply)
    local unlock = ply._bladwUnLock or 0
    if CurTime() < unlock then return false end
end)

hook.Add("PlayerDeathThink", "bladw_ds_blockThink", function(ply)
    local unlock = ply._bladwUnLock or 0
    if CurTime() < unlock then return false end
end)

hook.Add("PlayerSpawn", "bladw_ds_close", function(ply)
    Close_ds(ply)
    ply._bladwUnLock = nil
end)