-- Enemy AI system

follow.Event:Connect(require(enemyFunctions).Follow)

while true do
	local enemiesToConsider = {}
	for _,player in pairs(players:GetChildren()) do -- Adds all enemies in loaded areas to the considered table
		if player.Character and player.Character:FindFirstChild("Humanoid") and player.Character.Humanoid.Health > 0 then
			if player:FindFirstChild("Stats") and player.Stats:FindFirstChild("CurrentArea") and player.Stats.CurrentArea.Value then
				local enemiesFolder = player.Stats.CurrentArea.Value:FindFirstChild("Enemies")
				if enemiesFolder then
					for _,enemy in pairs(enemiesFolder:GetChildren()) do
						if not table.find(enemiesToConsider, enemy) then
							table.insert(enemiesToConsider, enemy)
						end
					end
				end
			end
		end
	end
	for _,enemy in pairs(enemiesToConsider) do
		local closestPlayer = require(enemyFunctions).FindClosestPlayer(enemy, true)
		if closestPlayer then
			if closestPlayer.Character then
				local rootPart = closestPlayer.Character:FindFirstChild("HumanoidRootPart")
				if rootPart then
					follow:Fire(enemy, rootPart)
				end
			end
		elseif enemy:FindFirstChild("Stats") and enemy.Stats:FindFirstChild("OriginalPosition") then
			enemy.EnemyHumanoid:MoveTo(enemy.Stats.OriginalPosition.Value)
		end
	end
	wait()
end
