<script lang="ts">
	import { slide } from 'svelte/transition';
	import type { Me$result } from '$houdini';
	import { page } from '$app/state';
	import { SvelteSet } from 'svelte/reactivity';
	import logoIcon from '$lib/assets/logo-icon.png';

	interface MenuItem {
		label: string;
		href: string;
		icon?: string;
	}

	interface MenuSection {
		title: string;
		items: MenuItem[];
		collapsible?: boolean;
		colorScheme?: 'primary' | 'secondary' | 'accent' | 'accent3';
	}

	interface Props {
		user: Me$result['me'] | undefined;
		open: boolean;
		onClose: () => void;
	}

	let { user, open, onClose }: Props = $props();
	let isTeamMember = $derived(user?.__typename === 'TeamProfileType');
	let isCustomer = $derived(user?.__typename === 'CustomerProfileType');
	let userRole = $derived(user?.__typename === 'TeamProfileType' ? user.role : null);
	let isAdmin = $derived(userRole === 'ADMIN');
	let isTeamLeader = $derived(userRole === 'TEAM_LEADER');
	let canAccessAdmin = $derived(isAdmin || isTeamLeader);

	// Track expanded state for collapsible sections
	let expandedSections = $state<Set<string>>(new Set());

	function toggleSection(title: string) {
		if (expandedSections.has(title)) {
			expandedSections.delete(title);
		} else {
			expandedSections.add(title);
		}
		expandedSections = new SvelteSet(expandedSections); // Trigger reactivity
	}

	// Public menu - visible to everyone (non-collapsible)
	const publicMenu: MenuSection = {
		title: 'General',
		items: [
			{ label: 'Home', href: '/' },
			{ label: 'Services', href: '/services' },
			{ label: 'Our Standard', href: '/standard' },
			{ label: 'Pricing', href: '/pricing' },
			{ label: 'About', href: '/about' },
			{ label: 'Contact', href: '/contact' }
		],
		collapsible: false
	};

	// Customer menu - visible only to logged in customers (collapsible, teal)
	const customerMenu: MenuSection = {
		title: 'Customer',
		items: [
			{ label: 'Dashboard', href: '/customer' },
			{ label: 'Accounts', href: '/customer/accounts' },
			{ label: 'Schedule', href: '/customer/schedule' },
			{ label: 'History', href: '/customer/history' },
			{ label: 'My Profile', href: '/customer/profile' }
		],
		collapsible: true,
		colorScheme: 'accent3'
	};

	// Team menu - visible only to team members (collapsible, green)
	const teamMenu: MenuSection = {
		title: 'Team',
		items: [
			{ label: 'Dashboard', href: '/team' },
			{ label: 'Accounts', href: '/team/accounts' },
			{ label: 'Services', href: '/team/services' },
			{ label: 'Projects', href: '/team/projects' },
			{ label: 'Reports', href: '/team/reports' },
			{ label: 'My Profile', href: '/team/profile' }
		],
		collapsible: true,
		colorScheme: 'secondary'
	};

	// Admin menu - visible only to team leaders and admins (collapsible, orange)
	let adminMenu = $derived<MenuSection>({
		title: 'Admin',
		items: [
			{ label: 'Dashboard', href: '/admin' },
			{ label: 'Customers', href: '/admin/customers' },
			{ label: 'Accounts', href: '/admin/accounts' },
			{ label: 'Services', href: '/admin/services' },
			{ label: 'Projects', href: '/admin/projects' },
			{ label: 'Scopes', href: '/admin/scopes' },
			{ label: 'Reports', href: '/admin/reports' },
			{ label: 'Invoices', href: '/admin/invoices' },
			{ label: 'Calendar', href: '/admin/calendar' },
			{ label: 'Profiles', href: '/admin/profiles' },
			// ADMIN-only items
			...(isAdmin
				? [
						{ label: 'Notifications', href: '/admin/notifications' },
						{ label: 'Event Log', href: '/admin/events' }
					]
				: [])
		],
		collapsible: true,
		colorScheme: 'accent'
	});

	// Portal menus (collapsible sections)
	let portalMenus = $derived.by(() => {
		const result: MenuSection[] = [];

		if (isCustomer) {
			result.push(customerMenu);
		}

		if (isTeamMember) {
			result.push(teamMenu);
		}

		if (canAccessAdmin) {
			result.push(adminMenu);
		}

		return result;
	});

	// Check if user has any portal access
	let hasPortalAccess = $derived(portalMenus.length > 0);

	// Get border color class for card-style headers
	function getBorderColor(scheme: MenuSection['colorScheme']): string {
		switch (scheme) {
			case 'accent3':
				return 'border-l-accent3-500';
			case 'secondary':
				return 'border-l-secondary-500';
			case 'accent':
				return 'border-l-accent-500';
			default:
				return 'border-l-primary-500';
		}
	}

	// Get text color class for card headers
	function getTextColor(scheme: MenuSection['colorScheme']): string {
		switch (scheme) {
			case 'accent3':
				return 'text-accent3-600 dark:text-accent3-400';
			case 'secondary':
				return 'text-secondary-600 dark:text-secondary-400';
			case 'accent':
				return 'text-accent-600 dark:text-accent-400';
			default:
				return 'text-primary-600 dark:text-primary-400';
		}
	}

	// Get chevron color for expanded state
	function getChevronColor(scheme: MenuSection['colorScheme'], isExpanded: boolean): string {
		if (isExpanded) {
			switch (scheme) {
				case 'accent3':
					return 'text-accent3-500';
				case 'secondary':
					return 'text-secondary-500';
				case 'accent':
					return 'text-accent-500';
				default:
					return 'text-primary-500';
			}
		}
		return 'text-theme-muted';
	}

	// Get active link colors based on section color scheme
	function getActiveLinkColors(scheme: MenuSection['colorScheme']): string {
		switch (scheme) {
			case 'accent3':
				return 'bg-accent3-100 font-medium text-accent3-700 dark:bg-accent3-900/50 dark:text-accent3-300';
			case 'secondary':
				return 'bg-secondary-100 font-medium text-secondary-700 dark:bg-secondary-900/50 dark:text-secondary-300';
			case 'accent':
				return 'bg-accent-100 font-medium text-accent-700 dark:bg-accent-900/50 dark:text-accent-300';
			default:
				return 'bg-primary-100 font-medium text-primary-700 dark:bg-primary-900/50 dark:text-primary-300';
		}
	}

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

	function handleLinkClick() {
		onClose();
	}
</script>

<svelte:window onkeydown={handleKeydown} />

{#if open}
	<!-- Backdrop - clicking closes menu -->
	<!-- svelte-ignore a11y_no_static_element_interactions -->
	<div
		class="fixed inset-0 z-40 overflow-y-auto bg-black/60 backdrop-blur-sm transition-opacity"
		onclick={onClose}
		onkeydown={(e) => e.key === 'Enter' && onClose()}
	>
		<!-- Menu container - centered in viewport -->
		<div class="flex min-h-full items-center justify-center p-4">
			<!-- Menu panel - stop click propagation so clicking menu doesn't close it -->
			<div
				class="w-full max-w-sm overflow-hidden rounded-2xl border border-theme bg-theme-card shadow-theme-lg"
				onclick={(e) => e.stopPropagation()}
				onkeydown={(e) => e.stopPropagation()}
			>
				<!-- Header -->
				<div class="flex h-14 items-center justify-between border-b border-theme px-4">
					<button
						onclick={onClose}
						class="-ml-2 rounded-lg interactive p-2"
						aria-label="Close menu"
					>
						<svg
							class="h-5 w-5 text-theme"
							style="fill: none"
							stroke="currentColor"
							viewBox="0 0 24 24"
						>
							<path
								stroke-linecap="round"
								stroke-linejoin="round"
								stroke-width="2"
								d="M6 18L18 6M6 6l12 12"
							/>
						</svg>
					</button>
					<span class="flex items-center gap-2 text-lg font-semibold text-theme">
						<img src={logoIcon} alt="Logo" class="h-8 w-8" />
						Nexus
					</span>
					<div class="w-9"></div>
				</div>

				<!-- Menu sections -->
				<nav class="max-h-[60vh] overflow-y-auto py-4">
					<!-- Public Menu (General) -->
					<div class="mb-4 px-3">
						<h3
							class="mb-3 text-center text-[11px] font-semibold tracking-wider text-theme-muted uppercase"
						>
							{publicMenu.title}
						</h3>
						<div class="space-y-1.5">
							{#each publicMenu.items as item (item.label)}
								<a
									href={item.href}
									onclick={handleLinkClick}
									data-sveltekit-preload-data="hover"
									class="block rounded-md border bg-theme-card px-3 py-2 text-center text-sm shadow-sm transition-all duration-150 {page
										.url.pathname === item.href
										? 'border-l-2 border-l-primary-500 bg-primary-100 font-medium text-primary-700 dark:bg-primary-900/50 dark:text-primary-300'
										: 'border-theme text-theme-secondary hover:bg-black/5 hover:shadow-theme active:scale-[0.98] dark:hover:bg-white/10'}"
									aria-current={page.url.pathname === item.href ? 'page' : undefined}
								>
									{item.label}
								</a>
							{/each}
						</div>
					</div>

					<!-- Nexus Portal Section (bordered container for collapsible menus) -->
					{#if hasPortalAccess}
						<div class="bg-theme/50 mx-3 rounded-xl border border-theme">
							<!-- Portal Header -->
							<div class="border-b border-theme px-4 py-2.5">
								<h3 class="text-center text-xs font-semibold tracking-wide text-theme">
									Nexus Portal
								</h3>
							</div>

							<!-- Collapsible Sections -->
							<div class="space-y-2 p-2">
								{#each portalMenus as section (section.title)}
									{@const isExpanded = expandedSections.has(section.title)}
									<!-- Card-style section -->
									<div
										class="overflow-hidden rounded-lg border border-theme bg-theme-card shadow-sm transition-shadow duration-150 {isExpanded
											? 'shadow-theme'
											: ''}"
									>
										<!-- Card header with colored left border -->
										<button
											onclick={() => toggleSection(section.title)}
											class="flex w-full items-center justify-between border-l-4 px-3 py-2.5 transition-all duration-150 hover:bg-black/5 dark:hover:bg-white/10 {getBorderColor(
												section.colorScheme
											)}"
										>
											<span class="text-sm font-semibold {getTextColor(section.colorScheme)}"
												>{section.title}</span
											>
											<svg
												class="h-4 w-4 transition-transform duration-150 {isExpanded
													? 'rotate-180'
													: ''} {getChevronColor(section.colorScheme, isExpanded)}"
												style="fill: none"
												stroke="currentColor"
												viewBox="0 0 24 24"
											>
												<path
													stroke-linecap="round"
													stroke-linejoin="round"
													stroke-width="2"
													d="M19 9l-7 7-7-7"
												/>
											</svg>
										</button>

										{#if isExpanded}
											<div
												class="space-y-1.5 border-t border-theme p-2"
												transition:slide={{ duration: 150 }}
											>
												{#each section.items as item (item.label)}
													<a
														href={item.href}
														onclick={handleLinkClick}
														data-sveltekit-preload-data="hover"
														class="block rounded-md border bg-theme-card px-3 py-2 text-center text-sm shadow-sm transition-all duration-150 {page
															.url.pathname === item.href
															? `border-l-2 ${getBorderColor(section.colorScheme)} ${getActiveLinkColors(section.colorScheme)}`
															: 'border-theme text-theme-secondary hover:border-theme hover:bg-black/5 hover:shadow-theme active:scale-[0.98] dark:hover:bg-white/10'}"
														aria-current={page.url.pathname === item.href ? 'page' : undefined}
													>
														{item.label}
													</a>
												{/each}
											</div>
										{/if}
									</div>
								{/each}
							</div>
						</div>
					{/if}
				</nav>

				<!-- Footer -->
				<div class="border-t border-theme p-4">
					{#if user}
						<a
							href="/logout"
							onclick={handleLinkClick}
							class="flex w-full items-center justify-center gap-2 rounded-xl px-4 py-2.5 text-error-600 transition-colors hover:bg-error-50 dark:text-error-400 dark:hover:bg-error-950/50"
						>
							<svg class="h-4 w-4" style="fill: none" stroke="currentColor" viewBox="0 0 24 24">
								<path
									stroke-linecap="round"
									stroke-linejoin="round"
									stroke-width="2"
									d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"
								/>
							</svg>
							Sign Out
						</a>
					{:else}
						<a
							href="/login"
							onclick={handleLinkClick}
							class="flex w-full items-center justify-center gap-2 rounded-xl bg-primary-600 px-4 py-2.5 font-medium text-white transition-colors hover:bg-primary-700"
						>
							<svg class="h-4 w-4" style="fill: none" stroke="currentColor" viewBox="0 0 24 24">
								<path
									stroke-linecap="round"
									stroke-linejoin="round"
									stroke-width="2"
									d="M11 16l-4-4m0 0l4-4m-4 4h14m-5 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h7a3 3 0 013 3v1"
								/>
							</svg>
							Sign In
						</a>
					{/if}
				</div>
			</div>
		</div>
	</div>
{/if}
