<script lang="ts">
	import { cubicOut } from 'svelte/easing';
	import { tweened } from 'svelte/motion';

	export let source: string;
	export let duration = 300 * 1.75;
	export let easing = cubicOut;
	export let alternativeText: string;
	export let classList = '';
	export let style = '';
	export let factor = 1.25;
	export let limit = 300 * 1.75;
	export let borderRadius = '8px';

	let badgeReference: HTMLImageElement;
	const mouse = tweened({ x: 0, y: 0 }, { duration, easing });

	const handleMouseMove = (event: MouseEvent) => {
		const boundingRectangle = badgeReference.getBoundingClientRect();

		if ($mouse.x === 0 && $mouse.y === 0) $mouse = { x: event.clientX, y: event.clientY };

		$mouse.x +=
			(-(event.clientX - boundingRectangle.left - boundingRectangle.width / 2) - $mouse.x) * factor;
		$mouse.y +=
			(-(event.clientY - boundingRectangle.top - boundingRectangle.height / 2) - $mouse.y) * factor;
		$mouse.x = Math.max(Math.min($mouse.x, limit), -limit);
		$mouse.y = Math.max(Math.min($mouse.y, limit), -limit);
	};

	const handleMouseLeave = () => {
		$mouse = { x: 0, y: 0 };
	};
</script>

<img
	src={source}
	bind:this={badgeReference}
	style={`transform: perspective(1000px) rotateX(${$mouse.y / 10}deg) rotateY(${
		-$mouse.x / 10
	}deg); border-radius: ${borderRadius}; ${style}`}
	alt={alternativeText}
	on:mousemove={handleMouseMove}
	on:mouseleave={handleMouseLeave}
	class={classList}
/>
