local LIMP_RECOVER_AT = 0.30

local function log(fmt, ...)
	DebugLog.log(("[ZR_ExhaustedLimp] " .. fmt):format(...))
end

local function setLimping(player, on)
	pcall(function()
		player:setVariable("ZR_ExhaustedLimp", on and "true" or "false")
	end)
end

local function stamina(player)
	local s = 1.0
	pcall(function() s = player:getStats():get(CharacterStat.ENDURANCE) or 1.0 end)
	return s
end

Events.OnGameStart.Add(function()
	if not (ZR_Surrender and ZR_Surrender.registerEscapeCallback) then
		log("ZR_Surrender missing — limp hook not registered")
		return
	end
	ZR_Surrender.registerEscapeCallback(function(player, st)
		if not player then return end
		if not (st and st.fromCollapse) then return end
		setLimping(player, true)
		log("collapse getup done -> limp walk ON (stamina %.2f, recovers at %.2f)",
			stamina(player), LIMP_RECOVER_AT)
	end)
end)

Events.OnPlayerUpdate.Add(function(player)
	if not player then return end
	local limping = false
	pcall(function() limping = player:getVariableBoolean("ZR_ExhaustedLimp") end)
	if not limping then return end
	if player:isDead() then
		setLimping(player, false)
		return
	end
	if stamina(player) >= LIMP_RECOVER_AT then
		setLimping(player, false)
		log("stamina recovered -> vanilla walk restored")
	end
end)
