<script lang="ts">
	import { fly } from 'svelte/transition';
	import { offCanvas } from '$lib/stores/offCanvas.svelte';

	let isOpen = $derived(offCanvas.isRightOpen);
	let content = $derived(offCanvas.rightContent);

	function close() {
		offCanvas.closeRight();
	}

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

	function handleBackdropClick(event: MouseEvent) {
		if (event.target === event.currentTarget) {
			close();
		}
	}
</script>

<svelte:window onkeydown={handleKeydown} />

{#if isOpen}
	<!-- Backdrop -->
	<button
		type="button"
		class="fixed inset-0 z-40 bg-black/50 transition-opacity"
		onclick={handleBackdropClick}
		aria-label="Close panel"
	></button>

	<!-- Off-canvas panel -->
	<div
		class="fixed top-0 right-0 z-50 flex h-full max-w-full flex-col bg-theme shadow-theme-lg {content?.width ||
			'w-full sm:w-96 md:w-[480px]'} {content?.class || ''}"
		transition:fly={{ x: 320, duration: 300 }}
		role="dialog"
		aria-modal="true"
		aria-labelledby={content?.title ? 'offcanvas-title' : undefined}
	>
		{#if content?.title}
			<div class="flex flex-shrink-0 items-center justify-between border-b border-theme p-4">
				<h3 id="offcanvas-title" class="text-lg font-semibold text-theme">
					{content.title}
				</h3>
				<button
					type="button"
					onclick={close}
					class="rounded-lg p-1.5 text-theme-muted hover:bg-black/5 hover:text-theme dark:hover:bg-white/10"
					aria-label="Close"
				>
					<svg class="h-5 w-5" style="fill: currentColor" viewBox="0 0 20 20">
						<path
							fill-rule="evenodd"
							d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z"
							clip-rule="evenodd"
						/>
					</svg>
				</button>
			</div>
		{:else}
			<!-- Close button when no title -->
			<div class="absolute top-4 right-4">
				<button
					type="button"
					onclick={close}
					class="rounded-lg p-1.5 text-theme-muted hover:bg-black/5 hover:text-theme dark:hover:bg-white/10"
					aria-label="Close"
				>
					<svg class="h-5 w-5" style="fill: currentColor" viewBox="0 0 20 20">
						<path
							fill-rule="evenodd"
							d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z"
							clip-rule="evenodd"
						/>
					</svg>
				</button>
			</div>
		{/if}

		<div class="min-w-0 flex-1 overflow-y-auto p-4">
			{#if content?.content}
				{@render content.content()}
			{/if}
		</div>
	</div>
{/if}
