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

	interface Props {
		title: string;
		subtitle?: string;
		subtitleSnippet?: Snippet<[{ toggleMenu: () => void }]>;
		actions?: Snippet;
		showBackButton?: boolean;
		backHref?: string;
		invalidateOnBack?: boolean;
	}

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

	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 handleBack(event: MouseEvent) {
		if (invalidateOnBack) {
			event.preventDefault();
			goto(backHref, { invalidateAll: true });
		}
	}

	function toggleMenu() {
		menuOpen = !menuOpen;
	}

	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: 'Scopes', href: '/admin/scopes', color: 'text-accent3-600 dark:text-accent3-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}
		<!-- Flex layout: back button + content on left, actions on right -->
		<div class="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
			<div class="flex items-start gap-3">
				<a
					href={backHref}
					onclick={handleBack}
					class="mt-1 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 text-primary-600 dark:text-primary-400"
							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 text-primary-600 dark:text-primary-400">{title}</h1>
						<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>
					</div>
					{#if subtitleSnippet}
						<p class="page-subtitle">
							{@render subtitleSnippet({ toggleMenu })}
						</p>
					{:else if subtitle}
						<p class="page-subtitle">{subtitle}</p>
					{/if}
				</div>
			</div>
			{#if actions}
				<div class="flex flex-wrap gap-2">
					{@render actions()}
				</div>
			{/if}
		</div>
	{:else}
		<!-- No back button - simple layout -->
		<div class="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
			<div>
				<div class="flex items-center gap-2">
					<h1 class="page-title text-primary-600 dark:text-primary-400">{title}</h1>
					<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>
				</div>
				{#if subtitleSnippet}
					<p class="page-subtitle">
						{@render subtitleSnippet({ toggleMenu })}
					</p>
				{:else if subtitle}
					<p class="page-subtitle">{subtitle}</p>
				{/if}
			</div>
			{#if actions}
				<div class="flex flex-wrap gap-2">
					{@render actions()}
				</div>
			{/if}
		</div>
	{/if}
</div>
