<script lang="ts">
	import { boxWith, mergeProps } from "svelte-toolbelt";
	import { DialogContentState } from "../dialog.svelte.js";
	import type { DialogContentProps } from "../types.js";
	import DismissibleLayer from "../../utilities/dismissible-layer/dismissible-layer.svelte";
	import EscapeLayer from "../../utilities/escape-layer/escape-layer.svelte";
	import FocusScope from "../../utilities/focus-scope/focus-scope.svelte";
	import TextSelectionLayer from "../../utilities/text-selection-layer/text-selection-layer.svelte";
	import { createId } from "../../../internal/create-id.js";
	import { noop } from "../../../internal/noop.js";
	import ScrollLock from "../../utilities/scroll-lock/scroll-lock.svelte";
	const uid = $props.id();

	let {
		id = createId(uid),
		children,
		child,
		ref = $bindable(null),
		forceMount = false,
		onCloseAutoFocus = noop,
		onOpenAutoFocus = noop,
		onEscapeKeydown = noop,
		onInteractOutside = noop,
		trapFocus = true,
		preventScroll = true,
		restoreScrollDelay = null,
		...restProps
	}: DialogContentProps = $props();

	const contentState = DialogContentState.create({
		id: boxWith(() => id),
		ref: boxWith(
			() => ref,
			(v) => (ref = v)
		),
	});

	const mergedProps = $derived(mergeProps(restProps, contentState.props));
</script>

{#if contentState.shouldRender || forceMount}
	<FocusScope
		ref={contentState.opts.ref}
		loop
		{trapFocus}
		enabled={contentState.root.opts.open.current}
		{onOpenAutoFocus}
		{onCloseAutoFocus}
	>
		{#snippet focusScope({ props: focusScopeProps })}
			<EscapeLayer
				{...mergedProps}
				enabled={contentState.root.opts.open.current}
				ref={contentState.opts.ref}
				onEscapeKeydown={(e) => {
					onEscapeKeydown(e);
					if (e.defaultPrevented) return;
					contentState.root.handleClose();
				}}
			>
				<DismissibleLayer
					{...mergedProps}
					ref={contentState.opts.ref}
					enabled={contentState.root.opts.open.current}
					onInteractOutside={(e) => {
						onInteractOutside(e);
						if (e.defaultPrevented) return;
						contentState.root.handleClose();
					}}
				>
					<TextSelectionLayer
						{...mergedProps}
						ref={contentState.opts.ref}
						enabled={contentState.root.opts.open.current}
					>
						{#if child}
							{#if contentState.root.opts.open.current}
								<ScrollLock {preventScroll} {restoreScrollDelay} />
							{/if}
							{@render child({
								props: mergeProps(mergedProps, focusScopeProps),
								...contentState.snippetProps,
							})}
						{:else}
							<ScrollLock {preventScroll} />
							<div {...mergeProps(mergedProps, focusScopeProps)}>
								{@render children?.()}
							</div>
						{/if}
					</TextSelectionLayer>
				</DismissibleLayer>
			</EscapeLayer>
		{/snippet}
	</FocusScope>
{/if}
