<script lang="ts">
let { children, onclose }: {
	children?: import('svelte').Snippet;
	onclose?: () => void
} = $props();
let dialog: HTMLDialogElement = $state()

export const open = (origin: DOMRect|MouseEvent) => {
	// Show the window so we can get the location
	dialog.showModal()

	const edge_offset = 10

	// Get the egdes of the screen, so the window does not spawn off-screen
	const dialog_rect = dialog.getBoundingClientRect()
	const max_left = document.documentElement.clientWidth - dialog_rect.width - edge_offset
	const max_top = document.documentElement.clientHeight - dialog_rect.height - edge_offset

	let min_left: number, min_top: number
	if (origin instanceof DOMRect) {
		// Position the dialog in horizontally in the center of the button and
		// verticially below it
		min_left = Math.max((origin.left + (origin.width/2)) - (dialog_rect.width/2), edge_offset)
		min_top = Math.max(origin.bottom, edge_offset)
	} else if (origin instanceof MouseEvent) {
		// Place the dialog at the bottom right of the mouse pointer, like
		// regular context menus
		min_left = Math.max(origin.clientX, edge_offset)
		min_top = Math.max(origin.clientY, edge_offset)
	}

	// Place the window
	dialog.style.left = Math.round(Math.min(min_left, max_left)) + "px"
	dialog.style.top = Math.round(Math.min(min_top, max_top)) + "px"
}

export const close = () => {
	dialog.close()
	if (onclose !== undefined) {
		onclose()
	}
}

// Attach a click handler so that the dialog is closed when the user clicks
// outside the dialog. The way this check works is that there is usually an
// element inside the dialog with all the content. When the click target is
// the dialog itself then the click was on the dialog background
const click = (e: MouseEvent) => {
	if (e.target === dialog) {
		e.preventDefault()
		close()
	}
}
</script>

<!-- svelte-ignore a11y_click_events_have_key_events -->
<!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
<dialog bind:this={dialog} onclick={click} oncontextmenu={click}>
	{@render children?.()}
</dialog>

<style>
dialog {
	background-color: var(--card_color);
	color: var(--body_text_color);
	border-radius: 8px;
	border: none;
	padding: 4px;
	margin: 0;
	box-shadow: 2px 2px 10px -4px #000000;
}
</style>
