--[[
	(Yields) Animates the camera to pan into a specific art spot on the wall.

	Target position: Center of the SurfaceSpot that we want to animate to (in studs)

	Parameters:
	- spot (Instance) - Frame of the target SurfaceSpot to animate to
]]

function CameraModule:animateToSpotAsync(spot)
	self.camera.CameraType = Enum.CameraType.Scriptable

	local adornee = self.surfaceGui.Adornee
	local face = self.surfaceGui.Face

	-- Calculate the actual position of the center of spot (in studs)
	local spotPosition = self:getSpotPosition(self.surfaceGui, spot)

	-- Make sure we're facing the surface at an offset
	local offset = adornee.CFrame:VectorToWorldSpace(Vector3.FromNormalId(face))

	local function getDistanceToSpot(fov, size, viewportSize)
		local angle = math.rad(fov / 2)
		local opp = (size / 2) / self.surfaceGui.PixelsPerStud
		local distance = opp / math.tan(angle)

		-- Move camera back based on ratio of viewport size
		distance *= (viewportSize / constants.SurfaceArtSelectorItemSize)

		return distance
	end

	local aspectRatio = self.camera.ViewportSize.X / self.camera.ViewportSize.Y
	local vertical = getDistanceToSpot(self.camera.FieldOfView, spot.AbsoluteSize.Y, self.camera.ViewportSize.Y)
	local horizontal = getDistanceToSpot(
		self.camera.FieldOfView * aspectRatio,
		spot.AbsoluteSize.X,
		self.camera.ViewportSize.X
	)
	local distance = math.max(horizontal, vertical)
	distance = math.clamp(distance, MIN_STUDS_OFFSET, MAX_STUDS_OFFSET)

	offset *= distance

	local upVector = self:_getUpVectorByFace(adornee.CFrame, face)
	local target = CFrame.lookAt(spotPosition + offset, spotPosition, upVector)

	-- Top view has a weird bug that turns things upside down
	if face == Enum.NormalId.Top then
		target *= CFrame.Angles(0, 0, math.pi)
	end

	self:_tweenCamera(target)
end
