<script lang="ts">
	import type { Snippet } from "svelte";
	import icCross from "../assets/famfamfam-silk-svg/icons/Cross.svg";
	import { ui, t } from "./app.svelte.js";

	let {
		open = $bindable(false),
		title,
		children,
		modal = true,
		closable = true,
		onclose,
	} = $props<{
		open: boolean;
		title?: string;
		children?: Snippet;
		modal?: boolean;
		closable?: boolean;
		onclose?: () => void;
	}>();
	let dialog: HTMLDialogElement;

	$effect(() => {
		if (open && !dialog.open) {
			modal ? dialog.showModal() : dialog.show();
		} else if (!open && dialog.open) {
			dialog.close();
			onclose?.();
		}
	});
</script>

<!-- svelte-ignore a11y_click_events_have_key_events -->
<!-- svelte-ignore a11y_no_static_element_interactions -->
<!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
<dialog
	bind:this={dialog}
	onclose={() => {
		if (closable) open = false;
		else if (open) dialog.showModal();
	}}
	oncancel={(e) => !closable && e.preventDefault()}
	onclick={(e) => closable && modal && e.target === dialog && (open = false)}
>
	<header>
		<b>{title}</b>
		{#if closable}
			<button onclick={() => (open = false)} title={t("close")}
				><img src={icCross} alt="" /></button
			>
		{/if}
	</header>
	<div class="content">{@render children?.()}</div>
</dialog>

<style>
	dialog {
		border: 1px solid var(--border);
		padding: 0;
		background: Canvas;
		color: CanvasText;
	}
	header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 0.25rem 0.5rem;
		background: var(--bg-secondary);
		border-block-end: 1px solid var(--border-subtle);
	}
	.content {
		padding: 1rem;
	}
	button {
		background: none;
		border: none;
		display: flex;
		padding: 0.25rem;
	}
</style>
