<script lang="ts">
	let {
		x1,
		x2,
		y1,
		y2
	}: {
		x1?: number;
		x2?: number;
		y1?: number;
		y2?: number;
	} = $props();

	let x = $state(0);
	let y = $state(0);
	let width = $state(0);
	let height = $state(0);

	let path = $state('');

	const padding = 20;

	$effect(() => {
		if (x1 !== undefined && x2 !== undefined && y1 !== undefined && y2 !== undefined) {
			const xMin = Math.min(x1, x2);
			const yMin = Math.min(y1, y2);

			x = xMin;
			width = Math.abs(x1 - x2);
			y = yMin;
			height = Math.abs(y1 - y2);

			const w = width;
			const h = height;
			const p = padding;

			// Start on bottom left conner
			if (xMin !== x1 && yMin === y1) {
				path = `M ${p} ${h + p} Q ${w * 0.1 + p} ${h * 0.4 + p}, ${w / 2 + p} ${h / 2 + p} T ${w + p} ${p}`;

				// Start on bottom right conner
			} else if (xMin === x1 && yMin === y1) {
				path = `M ${w + p} ${h + p} Q ${w * 0.9 + p} ${h * 0.4 + p}, ${w / 2 + p} ${h / 2 + p} T ${p} ${p}`;

				// Start on top left conner
			} else if (xMin !== x1 && yMin !== y1) {
				path = `M ${p} ${p} Q ${w * 0.1 + p} ${h * 0.6 + p}, ${w / 2 + p} ${h / 2 + p} T ${w + p} ${h + p}`;

				// Start on top right conner
			} else if (xMin === x1 && yMin !== y1) {
				path = `M ${w + p} ${p} Q ${w * 0.9 + p} ${h * 0.6 + p}, ${w / 2 + p} ${h / 2 + p} T ${p} ${h + p}`;
			}
		}
	});
</script>

<svg
	viewBox="0 0 {width + padding * 2} {height + padding * 2}"
	class="absolute"
	width={width + padding * 2}
	height={height + padding * 2}
	style="width: {width + padding * 2}px; height: {height + padding * 2}px; top: {y -
		padding}px; left: {x - padding}px"
>
	<marker
		id="arrow"
		viewBox="0 0 10 10"
		refX="5"
		refY="5"
		markerWidth="6"
		markerHeight="6"
		orient="auto-start-reverse"
	>
		<path d="M 0 0 L 10 5 L 0 10 z" />
	</marker>

	<path d={path} stroke="black" stroke-width="2" fill="transparent" marker-start="url(#arrow)" />
</svg>
