<script lang="ts">
	let { text = '' } = $props<{ text: string }>();
	let visible = $state(false);
	let tooltipStyle = $state('');
	let btnEl: HTMLButtonElement;

	function show() {
		if (!btnEl) return;
		visible = true;
		const rect = btnEl.getBoundingClientRect();
		const tooltipWidth = 272;
		let left = rect.left + rect.width / 2 - tooltipWidth / 2;
		if (left < 8) left = 8;
		if (left + tooltipWidth > window.innerWidth - 8) left = window.innerWidth - tooltipWidth - 8;
		tooltipStyle = `position:fixed; z-index:99999; bottom:${window.innerHeight - rect.top + 8}px; left:${left}px; width:${tooltipWidth}px;`;
	}

	function hide() {
		visible = false;
	}
</script>

<button type="button" bind:this={btnEl}
	class="inline-flex items-center justify-center w-4 h-4 rounded-full text-[11px] font-bold leading-none
		border border-[var(--color-border)] bg-[var(--color-muted)] text-[var(--color-muted-foreground)]
		hover:bg-[var(--color-border)] hover:text-[var(--color-foreground)]
		focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--color-primary)]
		transition-colors cursor-help align-middle ml-2 flex-shrink-0"
	onmouseenter={show}
	onmouseleave={hide}
	onfocus={show}
	onblur={hide}
	aria-label={text}
	title={text}
	tabindex="0"
>?</button>

{#if visible}
	<div role="tooltip" style="{tooltipStyle} background:var(--color-card); color:var(--color-foreground); border:1px solid var(--color-border); box-shadow:0 10px 30px rgba(0,0,0,0.3); padding:0.625rem 0.75rem; border-radius:0.5rem; font-size:0.8125rem; white-space:normal; line-height:1.625; pointer-events:none;">
		{text}
	</div>
{/if}
