<script lang="ts">
	import type { Snippet } from 'svelte';

	const {
		trigger
	}: {
		trigger?: Snippet;
	} = $props();

	let open = $state(false);

	function toggle() {
		open = !open;
	}

	function handleClickOutside(e: MouseEvent) {
		const target = e.target as HTMLElement;
		if (!target.closest('[data-policy-popover]')) {
			open = false;
		}
	}

	function handleKeydown(e: KeyboardEvent) {
		if (e.key === 'Escape') open = false;
	}
</script>

<svelte:window onclick={handleClickOutside} onkeydown={handleKeydown} />

<span data-policy-popover class="relative inline-block">
	<button
		type="button"
		onclick={toggle}
		class="inline cursor-pointer text-xs underline hover:text-amber-700"
	>
		{#if trigger}
			{@render trigger()}
		{:else}
			cancellation policy
		{/if}
	</button>

	{#if open}
		<div
			class="absolute top-full left-0 z-50 mt-1 w-48 rounded-md border border-gray-200 bg-white p-2 shadow-lg"
		>
			<a
				href="/cancellation-policy"
				target="_blank"
				rel="external"
				class="block w-full rounded px-3 py-2 text-left text-sm hover:bg-gray-100"
				onclick={() => (open = false)}
			>
				Open
			</a>
			<button
				type="button"
				class="block w-full rounded px-3 py-2 text-left text-sm hover:bg-gray-100"
				onclick={() => {
					open = false;
					const win = window.open('/cancellation-policy?format=pdf', '_blank');
					if (win) win.focus();
				}}
			>
				Download PDF
			</button>
		</div>
	{/if}
</span>
