const getScaledOffset = (
	sourceWidth,
	sourceHeight,
	targetWidth,
	targetHeight,
) => {
	const sourceRatio = sourceWidth / sourceHeight;
	const targetRatio = targetWidth / targetHeight;

	// same ratio. no adjustment needed.
	if (sourceRatio === targetRatio) {
		return {
			width: targetWidth,
			height: targetHeight,
			scaleFactor: targetWidth / sourceWidth,
			offset: {
				x: 0,
				y: 0,
			},
			bounds: {
				start: {
					x: 0,
					y: 0,
				},
				end: {
					x: targetWidth,
					y: targetHeight,
				},
			},
		};
	}

	// source is higher than target. height scaling and y offset required.
	if (sourceRatio < targetRatio) {
		const scaleFactor = targetWidth / sourceWidth;
		const adjustedHeight = sourceHeight * scaleFactor;
		const yOffset = (adjustedHeight - targetHeight) / 2;

		return {
			width: targetWidth,
			height: adjustedHeight,
			scaleFactor,
			offset: {
				x: 0,
				y: -yOffset,
			},
			bounds: {
				start: {
					x: 0,
					y: yOffset,
				},
				end: {
					x: targetWidth,
					y: yOffset + adjustedHeight,
				},
			},
		};
	}

	// source is wider than target. width scaling and x offset required.
	if (sourceRatio > targetRatio) {
		const scaleFactor = targetHeight / sourceHeight;
		const adjustedWidth = sourceWidth * scaleFactor;
		const xOffset = (adjustedWidth - targetWidth) / 2;

		return {
			width: adjustedWidth,
			height: targetHeight,
			scaleFactor,
			offset: {
				x: -xOffset,
				y: 0,
			},
			bounds: {
				start: {
					x: xOffset,
					y: 0,
				},
				end: {
					x: xOffset + adjustedWidth,
					y: targetHeight,
				},
			},
		};
	}
};

export default getScaledOffset;
