<script lang="ts">
	import type { Snippet } from 'svelte';
	import { goto } from '$app/navigation';
	import { IconChevronLeft, IconEdit } from '$lib/components/icons';

	type ColorScheme =
		| 'primary'
		| 'secondary'
		| 'accent'
		| 'accent2'
		| 'accent3'
		| 'accent4'
		| 'accent5'
		| 'accent6'
		| 'accent7'
		| 'gray';

	interface Props {
		title: string;
		subtitle?: string;
		children?: Snippet;
		colorScheme?: ColorScheme;
		backHref?: string;
		invalidateOnBack?: boolean;
		onEdit?: () => void;
	}

	let {
		title,
		subtitle,
		children,
		colorScheme = 'primary',
		backHref = '/admin',
		invalidateOnBack = false,
		onEdit
	}: Props = $props();

	let isNavigating = $state(false);

	function handleBack(event: MouseEvent) {
		event.preventDefault();
		isNavigating = true;
		goto(backHref, { invalidateAll: invalidateOnBack });
	}

	const colorClasses: Record<ColorScheme, string> = {
		primary: 'text-primary-600 dark:text-primary-400',
		secondary: 'text-secondary-600 dark:text-secondary-400',
		accent: 'text-accent-600 dark:text-accent-400',
		accent2: 'text-accent2-600 dark:text-accent2-400',
		accent3: 'text-accent3-600 dark:text-accent3-400',
		accent4: 'text-accent4-600 dark:text-accent4-400',
		accent5: 'text-accent5-600 dark:text-accent5-400',
		accent6: 'text-accent6-600 dark:text-accent6-400',
		accent7: 'text-accent7-600 dark:text-accent7-400',
		gray: 'text-gray-500 dark:text-gray-400'
	};
</script>

<div class="mb-6">
	<div class="grid grid-cols-[auto_1fr_auto] items-start gap-2 sm:gap-4">
		<!-- Back button -->
		<a
			href={backHref}
			onclick={handleBack}
			class="rounded-lg p-1 text-theme-muted transition-colors hover:bg-black/5 hover:text-theme dark:hover:bg-white/10"
			aria-label="Go back"
		>
			{#if isNavigating}
				<svg class="h-5 w-5 animate-spin {colorClasses[colorScheme]}" viewBox="0 0 24 24">
					<circle
						class="opacity-25"
						cx="12"
						cy="12"
						r="10"
						stroke="currentColor"
						stroke-width="4"
						fill="none"
					></circle>
					<path
						class="opacity-75"
						fill="currentColor"
						d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
					></path>
				</svg>
			{:else}
				<IconChevronLeft class="h-5 w-5" />
			{/if}
		</a>

		<!-- Title and subtitle -->
		<div>
			<h1 class="text-2xl font-bold md:text-3xl {colorClasses[colorScheme]}">{title}</h1>
			{#if subtitle}
				<p class="mt-1 text-theme-secondary">{subtitle}</p>
			{/if}
			{#if children}
				<div class="mt-2">
					{@render children()}
				</div>
			{/if}
		</div>

		<!-- Edit button -->
		{#if onEdit}
			<button
				type="button"
				onclick={onEdit}
				class="btn-icon text-theme-secondary"
				aria-label="Edit"
			>
				<IconEdit class="h-5 w-5" />
			</button>
		{/if}
	</div>
</div>
