--!strict
-- Initial spawn is in the lobby; players who entered a portal respawn in the arena.
local Players = game:GetService("Players")
local ArenaSpawns = require(script.Parent:WaitForChild("ArenaSpawns"))
local lobbySpawn = workspace:WaitForChild("HunterLobby"):WaitForChild("Arrival Spawn") :: SpawnLocation

local function onCharacterAdded(player: Player, character: Model)
	local root = character:WaitForChild("HumanoidRootPart", 10)
	local humanoid = character:WaitForChild("Humanoid", 10)
	if not root or not humanoid or not humanoid:IsA("Humanoid") or player.Character ~= character then return end
	local inArena = player:GetAttribute("InArena") == true
	local destination = if inArena then ArenaSpawns.choose(player) else lobbySpawn
	player.RespawnLocation = destination
	ArenaSpawns.place(character, destination)
	if inArena then
		local backpack = player:WaitForChild("Backpack", 5)
		local tool = backpack and backpack:WaitForChild("SniperRifle", 5)
		if tool and tool:IsA("Tool") and player.Character == character and humanoid.Health > 0 then
			humanoid:EquipTool(tool)
		end
	else
		humanoid:UnequipTools()
	end
end

local function onPlayerAdded(player: Player)
	player:SetAttribute("InArena", false)
	player.RespawnLocation = lobbySpawn
	player.CharacterAdded:Connect(function(character)
		onCharacterAdded(player, character)
	end)
	if player.Character then task.spawn(onCharacterAdded, player, player.Character) end
end

Players.PlayerAdded:Connect(onPlayerAdded)
for _, player in Players:GetPlayers() do onPlayerAdded(player) end
