<script lang="ts">
	import { createEventDispatcher, onMount } from 'svelte';

	export let open = false;
	export let title = '';
	export let size: 'sm' | 'md' | 'lg' | 'xl' = 'md';

	const dispatch = createEventDispatcher();

	let dialogElement: HTMLDialogElement;

	$: if (dialogElement) {
		if (open) {
			dialogElement.showModal();
		} else {
			dialogElement.close();
		}
	}

	function handleClose() {
		open = false;
		dispatch('close');
	}

	onMount(() => {
		const handleEscape = (e: KeyboardEvent) => {
			if (e.key === 'Escape' && open) {
				handleClose();
			}
		};

		document.addEventListener('keydown', handleEscape);
		return () => document.removeEventListener('keydown', handleEscape);
	});

	const sizeClasses = {
		sm: 'max-w-sm',
		md: 'max-w-xl',
		lg: 'max-w-3xl',
		xl: 'max-w-5xl'
	};
</script>

<dialog bind:this={dialogElement} class="modal" on:close={handleClose}>
	<div class="modal-box max-h-[97%] {sizeClasses[size]}">
		{#if title}
			<h3 class="text-lg font-bold">{title}</h3>
		{/if}

		<form method="dialog">
			<button class="btn btn-sm btn-circle btn-ghost absolute right-2 top-2">✕</button>
		</form>

		<slot />
	</div>

	<form method="dialog" class="modal-backdrop">
		<button>close</button>
	</form>
</dialog>
