--[[
    There is a bug where the Humanoid will enter RunningNoPhysics and pass though the barriers,
    here we disable that state.

    Also, set the character's Z velocity to match that of the platform when the character is in Freefall
]]

local function setupPlatformMinigame()
	local localPlayer = Players.localPlayer
	local character = localPlayer.Character

	if character then
		local humanoid = character:FindFirstChildOfClass("Humanoid")
		if humanoid then
			humanoid:SetStateEnabled(Enum.HumanoidStateType.RunningNoPhysics, false)
			if humanoid:GetState() == Enum.HumanoidStateType.RunningNoPhysics then
				humanoid:ChangeState(Enum.HumanoidStateType.Running)
			end

			local platformPart

			connection =
				RunService.Stepped:Connect(
				function()
					-- The platform part may not have replicated yet, so we need to make sure it exists
					if not platformPart then
						local map = workspace:FindFirstChild("Platform")
						if map then
							local platformModel = map:FindFirstChild("Platform")
							if platformModel then
								platformPart = platformModel.PrimaryPart
							end
						end
					end

					if not platformPart then
						return
					end

					-- When the Humanoid is in Freefall it will no longer be governed by the platform's velocity
					if humanoid.RootPart and humanoid:GetState() == Enum.HumanoidStateType.Freefall then
						local rootPos = humanoid.RootPart.Position
						-- Check if the character is in bounds of the platform
						if not isVector3InBoundsOfPart(rootPos, platformPart) then
							return
						end

						local rootVelocity = humanoid.RootPart.Velocity
						humanoid.RootPart.Velocity = Vector3.new(rootVelocity.X, rootVelocity.Y, platformPart.Velocity.Z)
					end
				end
			)
		end
	end
end

return function(minigameName)
	if connection then
		connection:Disconnect()
		connection = nil
	end
	if minigameName == "Platform Panic" then
		setupPlatformMinigame()
	end
end
