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

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

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

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

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

	beforeNavigate(({ to }) => {
		if (to?.url.pathname === backHref) {
			isNavigatingBack = true;
		}
	});

	function toggleMenu() {
		menuOpen = !menuOpen;
	}

	const colorClasses: Record<string, string> = {
		accent: 'text-accent-600 dark:text-accent-400',
		primary: 'text-primary-600 dark:text-primary-400',
		secondary: 'text-secondary-600 dark:text-secondary-400',
		accent6: 'text-accent6-600 dark:text-accent6-400'
	};

	const navItems = [
		{
			label: 'Accounts',
			href: '/customer/accounts',
			color: 'text-primary-600 dark:text-primary-400'
		},
		{
			label: 'Schedule',
			href: '/customer/schedule',
			color: 'text-secondary-600 dark:text-secondary-400'
		},
		{
			label: 'History',
			href: '/customer/history',
			color: 'text-accent-600 dark:text-accent-400'
		},
		{
			label: 'Invoices',
			href: '/customer/invoices',
			color: 'text-accent6-600 dark:text-accent6-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="menu-trigger 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 || page.url.pathname.startsWith(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>
			<!-- Spacer to balance the back button and center the content -->
			<div class="w-7"></div>
		</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="menu-trigger 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 || page.url.pathname.startsWith(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>
