<script lang="ts">
	import OutlineIcon from '$lib/components/ui/OutlineIcon.svelte';
	import type { OutlineIconName } from '$lib/components/ui/OutlineIcon.svelte';
	import { closeConfirm, getConfirmState, type ConfirmTone } from '$lib/stores/confirm.svelte';

	const dialog = $derived(getConfirmState());

	const toneConfig: Record<
		ConfirmTone,
		{ ring: string; icon: OutlineIconName; confirm: string }
	> = {
		danger: {
			ring: 'icon-ring-rose',
			icon: 'warning',
			confirm: 'btn-error'
		},
		warning: {
			ring: 'icon-ring-amber',
			icon: 'warning',
			confirm: 'btn-warning'
		},
		info: {
			ring: 'icon-ring-sky',
			icon: 'check',
			confirm: 'btn-primary'
		}
	};

	const config = $derived(toneConfig[dialog.tone ?? 'danger']);

	function handleBackdrop(event: MouseEvent) {
		if (event.target === event.currentTarget) closeConfirm(false);
	}

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

<svelte:window onkeydown={dialog.open ? handleKeydown : undefined} />

{#if dialog.open}
	<div
		class="confirm-overlay"
		role="presentation"
		onclick={handleBackdrop}
	>
		<div
			class="confirm-dialog"
			role="alertdialog"
			aria-modal="true"
			aria-labelledby="confirm-title"
			aria-describedby="confirm-message"
		>
			<span class="icon-ring icon-ring-rounded icon-ring-md {config.ring}">
				<OutlineIcon name={config.icon} size="md" />
			</span>

			<h2 id="confirm-title" class="confirm-title">{dialog.title}</h2>
			<p id="confirm-message" class="confirm-message">{dialog.message}</p>

			<div class="confirm-actions">
				<button type="button" class="btn btn-ghost rounded-xl" onclick={() => closeConfirm(false)}>
					{dialog.cancelText}
				</button>
				<button
					type="button"
					class="btn rounded-xl {config.confirm}"
					onclick={() => closeConfirm(true)}
				>
					{dialog.confirmText}
				</button>
			</div>
		</div>
	</div>
{/if}
