<svelte:options
	customElement={{
		tag: 'eve-dialog',
		shadow: 'none'
	}}
/>

<script lang="ts">
	import LiquidGlass from './LiquidGlass.svelte';

	let {
		open = $bindable(),
		icon = '',
		title
	}: { open: boolean; icon?: string; title?: string } = $props();

	let dialog: HTMLDialogElement;
	let target: HTMLDivElement;

	$effect(() => {
		if (open) {
			dialog.showModal();
			$host()?.dispatchEvent(new CustomEvent('open'));
		} else {
			dialog.close();
			$host()?.dispatchEvent(new CustomEvent('close'));
		}
	});

	$effect(() => {
		const host = $host();
		if (!host) return;
		const firstChild = host.firstChild;
		if (!firstChild) return;
		if (firstChild instanceof HTMLDialogElement) return;
		target.innerHTML = '';
		host.removeChild(firstChild);
		target.appendChild(firstChild);
	});
</script>

<dialog class="modal backdrop-blur-xl" onclose={() => (open = false)} bind:this={dialog}>
	<LiquidGlass class="modal-box">
		<div class="flex flex-row gap-3">
			{#if icon}
				<iconify-icon {icon} class="w-8 h-8 text-white"></iconify-icon>
			{/if}
			{#if title}
				<h2 class="flex-1 font-bold text-lg">{title}</h2>
			{:else}
				<div class="flex-1"></div>
			{/if}
			<form method="dialog">
				<button class="btn btn-sm btn-circle btn-ghost">✕</button>
			</form>
		</div>
		<div bind:this={target}>
			<slot />
		</div>
	</LiquidGlass>
</dialog>
