<script lang="ts">
	import type { Snippet } from 'svelte';
	import { fade, fly } from 'svelte/transition';

	interface Props {
		open: boolean;
		title: string;
		onClose: () => void;
		children: Snippet;
		/** Optional footer slot for action buttons */
		footer?: Snippet;
	}

	let { open, title, onClose, children, footer }: Props = $props();

	function handleKeydown(event: KeyboardEvent) {
		if (event.key === 'Escape') {
			onClose();
		}
	}

	// Lock body scroll when open
	$effect(() => {
		if (open) {
			document.body.style.overflow = 'hidden';
			return () => {
				document.body.style.overflow = '';
			};
		}
	});
</script>

<svelte:window onkeydown={handleKeydown} />

{#if open}
	<!-- Backdrop -->
	<button
		type="button"
		class="fixed inset-0 z-40 cursor-default bg-overlay backdrop-blur-sm"
		onclick={onClose}
		aria-label="Close drawer"
		transition:fade={{ duration: 200 }}
	></button>

	<!-- Drawer Panel -->
	<!-- Mobile: full viewport, slides up from bottom -->
	<!-- Desktop (sm+): 50% viewport width, slides in from right -->
	<div
		class="fixed inset-0 z-50 flex flex-col bg-theme-card
			sm:inset-y-0 sm:right-0 sm:left-auto sm:w-1/2 sm:max-w-3xl sm:min-w-[400px] sm:border-l sm:border-theme sm:shadow-2xl"
		role="dialog"
		aria-modal="true"
		aria-labelledby="drawer-title"
		tabindex="-1"
		transition:fly={{ x: 400, duration: 250 }}
	>
		<!-- Header -->
		<div class="flex shrink-0 items-center justify-between border-b border-theme px-5 py-4">
			<h2 id="drawer-title" class="text-lg font-semibold text-theme">{title}</h2>
			<button
				type="button"
				class="rounded-lg p-2 text-theme-muted transition-colors hover:bg-theme-secondary hover:text-theme"
				onclick={onClose}
				aria-label="Close drawer"
			>
				<svg class="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
					<path
						stroke-linecap="round"
						stroke-linejoin="round"
						stroke-width="2"
						d="M6 18L18 6M6 6l12 12"
					/>
				</svg>
			</button>
		</div>

		<!-- Content -->
		<div class="flex-1 overflow-y-auto px-5 py-5">
			{@render children()}
		</div>

		<!-- Footer (optional) -->
		{#if footer}
			<div class="shrink-0 border-t border-theme px-5 py-4">
				{@render footer()}
			</div>
		{/if}
	</div>
{/if}
