<script lang="ts">
	let { title } = $props<{ title: string }>();

	let isHovered = $state(false);
	let x = $state(0);
	let y = $state(0);

	let div: HTMLDivElement;

	function mouseOver(event: MouseEvent) {
		isHovered = true;
		x = event.pageX + 5;
		y = event.pageY + 5;
	}
	function focus() {
		isHovered = true;

		const box = div.getBoundingClientRect();
		x = box.x + 5;
		y = box.y;
	}
	function mouseMove(event: MouseEvent) {
		x = event.pageX + 5;
		y = event.pageY + 5;
	}
	function mouseLeave() {
		isHovered = false;
	}
</script>

<div
	bind:this={div}
	on:mouseover={mouseOver}
	on:mouseleave={mouseLeave}
	on:mousemove={mouseMove}
	on:focus={focus}
	role="tooltip"
	class="tooltipContainer"
>
	<slot />
</div>

{#if isHovered}
	<div style="top: {y}px; left: {x}px;" class="tooltip">{title}</div>
{/if}

<style>
	.tooltipContainer {
		display: inline-block;
	}
	.tooltip {
		border: 1px solid #ddd;
		box-shadow: 1px 1px 1px #ddd;
		background: white;
		border-radius: 4px;
		padding: 4px;
		position: absolute;
	}
</style>
