-- Set up quest triggers

for _,trigger in pairs(workspace.QuestTriggers:GetChildren()) do
	local quest = replicatedStorage.Quests:FindFirstChild(trigger.Name)
	if quest then
		trigger.Touched:Connect(function(part)
			local player = players:GetPlayerFromCharacter(part.Parent)
			if player and not script:FindFirstChild(player.Name .. "Deciding") and not player.Quests:FindFirstChild(quest.Name) and not player.CompletedQuests:FindFirstChild(quest.Name) then
				local tag = Instance.new("Model")
				tag.Name = player.Name .. "Deciding"
				tag.Parent = script
				local acceptedQuest
				pcall(function() -- Player might leave during the invoke, causing the tag to stay forever
					acceptedQuest = replicatedStorage.ClientRemotes.OfferQuest:InvokeClient(player, quest)
				end)
				if acceptedQuest then
					local quest = require(questSystem).GiveQuest(player, quest.Name)
					require(questSystem[quest.QuestType.Value]).CheckIfCompleted(player, quest) -- Player may have already met the completion requirements
				end
				wait(2)
				tag:Destroy()
			end
		end)
	else
		warn('Could not find a matching quest in ReplicatedStorage.Quests for the trigger named "' .. trigger.Name .. '"')
	end
end
for _,quest in pairs(replicatedStorage.Quests:GetChildren()) do
	if quest.QuestType.Value == "TouchOrb" then -- Make quest touch connections
		local destinationOrb = quest.Requirements:FindFirstChildOfClass("ObjectValue")
		if destinationOrb and destinationOrb.Value then
			destinationOrb.Value.Touched:Connect(function(part)
				local player = players:GetPlayerFromCharacter(part.Parent)
				if player then
					local matchingQuest = player.Quests:FindFirstChild(quest.Name)
					if matchingQuest then
						require(questSystem.TouchOrb).CheckIfCompleted(player, matchingQuest)
					end
				end
			end)
		end
	end
end
