Placement system rotational bug

So currently i am working on a placement system for a small project. Ive encountered this bug and have tried to explain it to the best of my ability in this screenshot.


here’s my code for anyone who needs it

local player = game.Players.LocalPlayer
local mouse = player:GetMouse()
local down
local mtarget = true

function clickObj()
	if mouse.Target ~= nil then
		mtarget = mouse.Target
		if(mtarget ~= game.Workspace.Part) then
			game.Workspace.Selection.Transparency = .5
			local dist = (mouse.Hit - mtarget.position)
			local xdist = dist.x
			local zdist = dist.z
			if(math.abs(xdist) > math.abs(zdist)) then
				game.Workspace.Selection.Position = (mtarget.position + Vector3.new(xdist/math.abs(xdist)*8,xdist/math.abs(xdist)*8,xdist/math.abs(xdist)*8) * mtarget.CFrame.XVector)
			else
				if(math.abs(zdist) > math.abs(xdist)) then
					game.Workspace.Selection.Position = mtarget.position + Vector3.new(zdist/math.abs(zdist)*8,zdist/math.abs(zdist)*8,zdist/math.abs(zdist)*8) * mtarget.CFrame.ZVector
				end
			end
			game.Workspace.Selection.Rotation = mtarget.Rotation
		else
			game.Workspace.Selection.Transparency = 1
		end
	end
end
mouse.Move:connect(clickObj)

function mouseDown()
	if mouse.Target ~= nil then
		
		mtarget = mouse.Target
		if(mtarget ~= game.Workspace.Part and mtarget.Parent == game.Workspace.TestRaft) then
			game.Workspace.Selection.Transparency = .5
			local xdist = mouse.Hit.x - mtarget.position.x
			local zdist = mouse.Hit.z - mtarget.position.z
			if(math.abs(xdist) > math.abs(zdist)) then
				game.Workspace.Selection.Position = (mtarget.position + Vector3.new(xdist/math.abs(xdist)*8,0,0) * mtarget.CFrame.XVector)
			else
				if(math.abs(zdist) > math.abs(xdist)) then

					game.Workspace.Selection.Position = mtarget.position + Vector3.new(0,0,zdist/math.abs(zdist)*8) * mtarget.CFrame.ZVector
				end
			end
			game.Workspace.RemoteEvents.PlaceObject:FireServer(game.ReplicatedStorage.Pallet,true, mouse.Target, game.Workspace.Selection.CFrame)
		else
		game.Workspace.Selection.Transparency = 1
		end

	end
end

mouse.Button1Down:Connect(mouseDown)