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

	type Props = {
		open?: boolean;
		title?: string;
		description?: string;
	};

	export let open = false;
	export let title: string = "Sample Modal";
	export let description: string = "Use this dialog as a starting point for your own content.";

	const dispatch = createEventDispatcher<{ close: void }>();

	let dialogElement: HTMLDialogElement | null = null;

	onMount(() => {
		if (open) {
			show();
		}
	});

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

	function show() {
		dialogElement?.showModal();
		open = true;
	}

	function hide() {
		dialogElement?.close();
		open = false;
		dispatch("close");
	}
</script>

<dialog bind:this={dialogElement} class="modal" on:cancel|preventDefault={hide}>
	<div class="modal-box sm:max-w-xl">
		<header class="flex items-start justify-between gap-4">
			<div>
				<h2 class="text-2xl font-semibold">{title}</h2>
				<p class="text-base-content/70 mt-2 text-sm">{description}</p>
			</div>
			<button class="btn btn-circle btn-ghost" type="button" on:click={hide}>
				✕
			</button>
		</header>

		<slot />

		<footer class="mt-6 flex justify-end gap-3">
			<button class="btn btn-ghost" type="button" on:click={hide}>
				Cancel
			</button>
			<button class="btn btn-primary" type="button" on:click={hide}>
				Okay
			</button>
		</footer>
	</div>

	<form method="dialog" class="modal-backdrop" aria-label="Close modal">
		<button type="submit">Close</button>
	</form>
</dialog>

<style>
	:global(.modal.is-open) {
		display: flex;
	}
</style>
