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

	interface Props {
		title: string;
		subtitle?: string;
		subtitleSnippet?: Snippet<[{ toggleMenu: () => void }]>;
		colorScheme?:
			| 'primary'
			| 'secondary'
			| 'accent'
			| 'accent2'
			| 'accent3'
			| 'accent4'
			| 'accent5'
			| 'accent6'
			| 'accent7';
		showBackButton?: boolean;
		backHref?: string;
		showNavMenu?: boolean;
		invalidateOnBack?: boolean;
		onEdit?: () => void;
	}

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

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

	let menuOpen = $state(false);
	let isNavigatingBack = $state(false);

	// Track when we're navigating to the back URL
	beforeNavigate(({ to }) => {
		if (to?.url.pathname === backHref) {
			isNavigatingBack = true;
		}
	});

	function toggleMenu() {
		menuOpen = !menuOpen;
	}

	const colorClasses: Record<string, 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'
	};

	const navItems = [
		{
			label: 'Customers',
			href: '/admin/customers',
			color: 'text-accent3-600 dark:text-accent3-400'
		},
		{
			label: 'Accounts',
			href: '/admin/accounts',
			color: 'text-primary-600 dark:text-primary-400'
		},
		{
			label: 'Services',
			href: '/admin/services',
			color: 'text-secondary-600 dark:text-secondary-400'
		},
		{
			label: 'Projects',
			href: '/admin/projects',
			color: 'text-accent-600 dark:text-accent-400'
		},
		{
			label: 'Reports',
			href: '/admin/reports',
			color: 'text-accent2-600 dark:text-accent2-400'
		},
		{
			label: 'Invoices',
			href: '/admin/invoices',
			color: 'text-accent6-600 dark:text-accent6-400'
		},
		{
			label: 'Calendar',
			href: '/admin/calendar',
			color: 'text-accent7-600 dark:text-accent7-400'
		},
		{
			label: 'Profiles',
			href: '/admin/profiles',
			color: 'text-accent4-600 dark:text-accent4-400'
		}
	];

	function handleClickOutside(event: MouseEvent) {
		const target = event.target as HTMLElement;
		if (!target.closest('.nav-menu-container') && !target.closest('.menu-trigger')) {
			menuOpen = false;
		}
	}

	function handleKeydown(event: KeyboardEvent) {
		if (event.key === 'Escape') {
			menuOpen = false;
		}
	}
</script>

<svelte:window onclick={handleClickOutside} onkeydown={handleKeydown} />

<div class="mb-6">
	{#if showBackButton}
		<!-- 3-column grid: back button | content | spacer for centering -->
		<div class="grid grid-cols-[auto_1fr_auto] items-start gap-4">
			<a
				href={backHref}
				onclick={handleBack}
				class="rounded-lg p-1 text-theme-muted hover:bg-black/5 hover:text-theme dark:hover:bg-white/10"
				aria-label="Go back"
			>
				{#if isNavigatingBack}
					<svg
						class="h-5 w-5 animate-spin {colorClasses[colorScheme]}"
						style="fill: none"
						viewBox="0 0 24 24"
					>
						<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"
						></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}
					<svg class="h-5 w-5" style="fill: none" stroke="currentColor" viewBox="0 0 24 24">
						<path
							stroke-linecap="round"
							stroke-linejoin="round"
							stroke-width="2"
							d="M15 19l-7-7 7-7"
						/>
					</svg>
				{/if}
			</a>
			<div>
				<div class="flex items-center gap-2">
					<h1 class="page-title {colorClasses[colorScheme]}">{title}</h1>
					{#if showNavMenu}
						<div class="nav-menu-container relative">
							<button
								type="button"
								onclick={() => (menuOpen = !menuOpen)}
								class="rounded-lg p-1 text-theme-muted transition-colors hover:bg-black/5 hover:text-theme dark:hover:bg-white/10"
								aria-label="Navigation menu"
								aria-expanded={menuOpen}
							>
								<svg
									class="h-5 w-5 transition-transform {menuOpen ? 'rotate-90' : ''}"
									style="fill: none"
									stroke="currentColor"
									viewBox="0 0 24 24"
								>
									<path
										stroke-linecap="round"
										stroke-linejoin="round"
										stroke-width="2"
										d="M9 5l7 7-7 7"
									/>
								</svg>
							</button>

							{#if menuOpen}
								<div
									class="fixed z-50 mt-2 min-w-48 rounded-lg border border-theme bg-theme-card py-2 shadow-theme-lg"
								>
									{#each navItems as item (item.href)}
										<a
											href={item.href}
											class="block interactive px-4 py-2 text-sm {item.color} {page.url.pathname ===
											item.href
												? 'font-semibold'
												: ''}"
											onclick={() => (menuOpen = false)}
										>
											{item.label}
										</a>
									{/each}
								</div>
							{/if}
						</div>
					{/if}
				</div>
				{#if subtitleSnippet}
					<p class="page-subtitle">
						{@render subtitleSnippet({ toggleMenu })}
					</p>
				{:else if subtitle}
					<p class="page-subtitle">{subtitle}</p>
				{/if}
			</div>
			<!-- Edit button or spacer to balance the back button -->
			{#if onEdit}
				<button
					type="button"
					onclick={onEdit}
					class="rounded-lg p-2 text-theme-secondary transition-colors hover:bg-black/5 active:bg-black/10 dark:hover:bg-white/10 dark:active:bg-white/15"
					aria-label="Edit"
				>
					<IconEdit class="h-5 w-5" />
				</button>
			{:else}
				<div class="w-7"></div>
			{/if}
		</div>
	{:else}
		<!-- No back button - simple layout -->
		<div class="flex items-center gap-2">
			<h1 class="page-title {colorClasses[colorScheme]}">{title}</h1>
			{#if showNavMenu}
				<div class="nav-menu-container relative">
					<button
						type="button"
						onclick={() => (menuOpen = !menuOpen)}
						class="rounded-lg p-1 text-theme-muted transition-colors hover:bg-black/5 hover:text-theme dark:hover:bg-white/10"
						aria-label="Navigation menu"
						aria-expanded={menuOpen}
					>
						<svg
							class="h-5 w-5 transition-transform {menuOpen ? 'rotate-90' : ''}"
							style="fill: none"
							stroke="currentColor"
							viewBox="0 0 24 24"
						>
							<path
								stroke-linecap="round"
								stroke-linejoin="round"
								stroke-width="2"
								d="M9 5l7 7-7 7"
							/>
						</svg>
					</button>

					{#if menuOpen}
						<div
							class="fixed z-50 mt-2 min-w-48 rounded-lg border border-theme bg-theme-card py-2 shadow-theme-lg"
						>
							{#each navItems as item (item.href)}
								<a
									href={item.href}
									class="block interactive px-4 py-2 text-sm {item.color} {page.url.pathname ===
									item.href
										? 'font-semibold'
										: ''}"
									onclick={() => (menuOpen = false)}
								>
									{item.label}
								</a>
							{/each}
						</div>
					{/if}
				</div>
			{/if}
		</div>
		{#if subtitleSnippet}
			<p class="page-subtitle">
				{@render subtitleSnippet({ toggleMenu })}
			</p>
		{:else if subtitle}
			<p class="page-subtitle">{subtitle}</p>
		{/if}
	{/if}
</div>
