There's a big problem with the Ai tracking system

This script going me crazy. When ai with this script sometimes hits a wall, when a player is in a building while invincible, or suddenly a player disappears within the distance, while is dead (anime runs always) and randomly unlocks when the player is approaching. It’s really going me crazy. Please help.

local jj = script.Parent
local humanoid = jj.Humanoid
local animate = script

jj.PrimaryPart:SetNetworkOwner(nil)
wait(1.5)

local walkAnim = humanoid:LoadAnimation(script:WaitForChild("WalkAnim"))
local runAnim = humanoid:LoadAnimation(script:WaitForChild("RunAnim"))

local detectionRadius = 200
local scareRadius = 10

local function canSeeTarget(target)
	local distance = (jj.HumanoidRootPart.Position - target.HumanoidRootPart.Position).Magnitude

	if distance <= detectionRadius then
		local origin = jj.HumanoidRootPart.Position
		local direction = (target.HumanoidRootPart.Position - origin).unit * distance
		local ray = Ray.new(origin, direction)

		local hit, pos = workspace:FindPartOnRay(ray, jj)

		if hit and hit:IsDescendantOf(target) then
			return true
		end
	end

	return false
end

local function findTarget()
	local players = game.Players:GetPlayers()
	local nearestTarget
	local maxDistance = detectionRadius
	for _, player in pairs(players) do
		if player.Character then
			local target = player.Character
			local targetHumanoid = target:FindFirstChildOfClass("Humanoid")

			if targetHumanoid and targetHumanoid.Health > 0 then
				local distance = (jj.HumanoidRootPart.Position - target.HumanoidRootPart.Position).Magnitude

				if distance <= maxDistance and canSeeTarget(target) then
					nearestTarget = target
					maxDistance = distance

					if distance <= scareRadius then

						local targetHumanoidRootPart = target:FindFirstChild("HumanoidRootPart")
						if targetHumanoidRootPart then
							targetHumanoid.Health = 0
					end
				end
			end
		end
	end

	return nearestTarget
end

function moveToTarget(target)
	if target and target:FindFirstChild("HumanoidRootPart") then
		humanoid:MoveTo(target.HumanoidRootPart.Position)
		wait(0.1)
	end
end

local function getPath(destination)
	local pathfindingService = game:GetService("PathfindingService")
	local path = pathfindingService:CreatePath({
		AgentRadius = 2,
		AgentHeight = 5,
		AgentCanJump = true,
		AgentMaxSlope = 45,
		AgentJumpHeight = 10,
		AgentMaxDistance = 100,
	})
	path:ComputeAsync(jj.HumanoidRootPart.Position, destination)
	return path
end

function walkTo(destination)
	local path = getPath(destination)

	if path.Status == Enum.PathStatus.Success then
		for _, waypoint in pairs(path:GetWaypoints()) do
			local target = findTarget()
			if target and target:FindFirstChildOfClass("Humanoid").Health > 0 then
				break	 
			else
				if waypoint.Action == Enum.PathWaypointAction.Jump then
					humanoid.Jump = true
				end

				humanoid:MoveTo(waypoint.Position)

				local moveFinished = humanoid.MoveToFinished:Wait(2)  -- 2초 동안 대기
				if not moveFinished then
					moveToRandomPart()
				end
			end
		end
	else
		print("경로를 찾을 수 없습니다.")
		-- 경로 실패 시 처리
	end
	end
end

function moveToRandomPart()
	local waypoints = workspace:WaitForChild('waypoint'):GetChildren()
	if #waypoints > 0 then
		local randomNum = math.random(1, #waypoints)
		walkTo(waypoints[randomNum].Position)
end
end

local function updateMovementAnim(isChasing)
	local velocity = jj.HumanoidRootPart.Velocity.Magnitude

	if isChasing then
		-- IsChasing이 활성화된 경우 RunAnim 고정
		if not runAnim.IsPlaying then
			runAnim:Play()
		end
		if walkAnim.IsPlaying then
			walkAnim:Stop()
		end
	else
		-- 일반 속도에 따라 애니메이션 조정
		if velocity >= 59 then
			if walkAnim.IsPlaying then
				walkAnim:Stop()
			end
			if not runAnim.IsPlaying then
				runAnim:Play()
			end
		else
			if runAnim.IsPlaying then
				runAnim:Stop()
			end
			if not walkAnim.IsPlaying then
				walkAnim:Play()
			end
		end
	end
end

function patrol(mazeParts)
	local target = findTarget()
	local isChasing = false

	if target then  
		local player = game.Players:GetPlayerFromCharacter(target)
		if player then
			local invincible = player:FindFirstChild("Invincible")  -- Check for the invincible BoolValue

			if invincible and invincible.Value == true then
				humanoid.WalkSpeed = 30
				moveToRandomPart()  -- Move to a random part if the player is invincible
			else
				humanoid.WalkSpeed = 80
				moveToTarget(target)  -- Chase the player if they are not invincible

				local isChasingObj = player:FindFirstChild('IsChasing')
				if isChasingObj and isChasingObj:IsA("BoolValue") then
					isChasingObj.Value = true
				end
				isChasing = true  -- IsChasing 활성화
			end
		end
	else
		humanoid.WalkSpeed = 30
		moveToRandomPart()

		-- Handle the case when there is no target
		local players = game.Players:GetPlayers()
		for _, player in pairs(players) do
			local isChasingObj = player:FindFirstChild('IsChasing')
			if isChasingObj and isChasingObj:IsA("BoolValue") then
				isChasingObj.Value = false
			end
		end
	end

	updateMovementAnim(isChasing)
end

while wait(0.1) do
	local success, err = pcall(function()
		local mazeModel = workspace:FindFirstChild("MazeModel")
		local mazeParts = mazeModel and mazeModel:GetChildren() or {}
		patrol(mazeParts)
	end)

	if not success then
		print("Error in main loop: " .. err)
	end
end