<script lang="ts">
	import type { PageData } from './$types';
	import { goto, invalidateAll } from '$app/navigation';
	import { SvelteMap, SvelteSet } from 'svelte/reactivity';
	import { client } from '$lib/graphql/client';
	import { ContentContainer } from '$lib/components/layout';
	import { PageHeader, SectionHeader } from '$lib/components/admin';
	import { FormDrawer } from '$lib/components/drawers';
	import { DeleteModal } from '$lib/components/modals';
	import { IconTrash, IconPlus } from '$lib/components/icons';
	import {
		ProjectForm,
		ProjectScopeForm,
		ProjectCategoryForm,
		ProjectTaskForm,
		CalendarEventForm
	} from '$lib/components/forms';
	import {
		SessionContent,
		StartSessionButton,
		type ExtendedProjectTask,
		type ProjectArea,
		type ProjectAreaWithCompletions,
		type ProjectAreaWithTasks
	} from '$lib/components/session';
	import {
		DELETE_PROJECT,
		ASSIGN_PROJECT_TEAM_MEMBER,
		REMOVE_PROJECT_TEAM_MEMBER,
		DELETE_PROJECT_SCOPE,
		DELETE_PROJECT_SCOPE_CATEGORY,
		DELETE_PROJECT_SCOPE_TASK,
		UPDATE_PROJECT_SCOPE_CATEGORY,
		UPDATE_PROJECT_SCOPE_TASK
	} from '$lib/graphql/mutations/project';
	import { LINK_CALENDAR_EVENT_TO_PROJECT } from '$lib/graphql/mutations/calendar';
	import {
		OPEN_PROJECT_SESSION,
		CLOSE_PROJECT_SESSION,
		REVERT_PROJECT_SESSION,
		ADD_PROJECT_TASK_COMPLETION,
		REMOVE_PROJECT_TASK_COMPLETION,
		CREATE_PROJECT_SESSION_NOTE,
		UPDATE_PROJECT_SESSION_NOTE,
		DELETE_PROJECT_SESSION_NOTE,
		UPLOAD_PROJECT_SESSION_IMAGE,
		UPDATE_PROJECT_SESSION_IMAGE,
		DELETE_PROJECT_SESSION_IMAGE,
		UPLOAD_PROJECT_SESSION_VIDEO,
		UPDATE_PROJECT_SESSION_VIDEO,
		DELETE_PROJECT_SESSION_VIDEO
	} from '$lib/graphql/mutations/session';
	import type {
		WorkStatus,
		ProjectScopeCategory,
		ProjectScopeTask
	} from '$lib/graphql/queries/projects';
	import type { ProjectSession } from '$lib/graphql/queries/session';
	import { config } from '$lib/config';

	let { data }: { data: PageData } = $props();

	let project = $derived(data.project);

	// Get dispatch profile for dispatch functionality
	let dispatchProfile = $derived(
		(data.teamProfiles ?? []).find((p) => p.id === config.dispatch.profileId) ?? null
	);

	// Get the dispatch assignment (dispatch account team member entry)
	let dispatchAssignment = $derived(
		project.teamMembers.find((m) => m.teamProfileId === config.dispatch.profileId) ?? null
	);

	// Filter out dispatch account from team members display
	let teamMembers = $derived(
		project.teamMembers.filter((m) => m.teamProfileId !== config.dispatch.profileId)
	);

	let isDispatched = $derived(!!dispatchAssignment);

	let isAssigned = $derived(teamMembers.length > 0);

	// Team profiles for assignment
	let availableTeamProfiles = $derived(data.teamProfiles ?? []);

	// Get active scope
	let activeScope = $derived(project.scopes?.find((s) => s.isActive) ?? null);

	// Scope is locked when project is in progress or completed
	let isScopeLocked = $derived(project.status === 'IN_PROGRESS' || project.status === 'COMPLETED');

	// Drawer state
	type DrawerMode = 'project' | 'scope' | 'category' | 'task' | null;
	let drawerOpen = $state(false);
	let drawerMode = $state<DrawerMode>(null);
	let drawerEditMode = $state<'add' | 'edit'>('add');

	// For category/task editing, track the selected item
	let selectedCategory = $state<ProjectScopeCategory | null>(null);
	let selectedTask = $state<{ task: ProjectScopeTask | null; categoryId: string } | null>(null);

	// Delete modal state
	let deleteModalOpen = $state(false);
	let deleteTarget = $state<{
		type: 'project' | 'team_member' | 'scope' | 'category' | 'task';
		id: string;
		name: string;
	} | null>(null);
	let deleteLoading = $state(false);

	// Calendar event drawer state
	let calendarDrawerOpen = $state(false);

	// Team member assignment menu
	let assignMenuOpen = $state(false);
	let assignLoading = $state(false);
	let selectedTeamMembers = new SvelteSet<string>();

	// ==================== SESSION STATE ====================

	// Session data from server (can be active or closed)
	let session = $derived(data.session as ProjectSession | null);

	// Session loading states
	let sessionLoading = $state(false);
	let isClosingSession = $state(false);
	let isRevertingSession = $state(false);
	let submittingTaskId = $state<string | null>(null);
	let removingTaskId = $state<string | null>(null);

	// Convert scope categories to session areas format (projects use "categories" instead of "areas")
	const sessionAreas = $derived.by<ProjectArea[]>(() => {
		if (!activeScope) return [];
		return activeScope.categories.map((cat) => ({
			id: cat.id,
			name: cat.name,
			description: null,
			order: cat.order,
			tasks: cat.tasks
		}));
	});

	// Flatten tasks with area context
	const allTasks = $derived.by<ExtendedProjectTask[]>(() => {
		if (!activeScope) return [];
		return activeScope.categories.flatMap((cat) =>
			cat.tasks.map((task) => ({
				...task,
				uuid: task.id,
				areaId: cat.id,
				areaName: cat.name
			}))
		);
	});

	// Task selection state
	let selectedTaskIds = new SvelteSet<string>();
	const completedTaskIds = $derived.by(() => {
		const ids = new SvelteSet<string>();
		if (session) {
			for (const completion of session.completedTasks) {
				ids.add(completion.taskId);
			}
		}
		return ids;
	});

	// Group completed tasks by area
	const completedTasksByArea = $derived.by<ProjectAreaWithCompletions[]>(() => {
		if (!session || !activeScope) return [];
		const grouped = new SvelteMap<string, ProjectAreaWithCompletions>();

		for (const completion of session.completedTasks) {
			const task = allTasks.find((t) => t.id === completion.taskId);
			if (!task) continue;

			const cat = activeScope.categories.find((c) => c.id === task.areaId);
			if (!cat) continue;

			if (!grouped.has(cat.id)) {
				grouped.set(cat.id, {
					area: {
						id: cat.id,
						name: cat.name,
						description: null,
						order: cat.order,
						tasks: cat.tasks
					},
					completions: []
				});
			}
			grouped.get(cat.id)!.completions.push(completion);
		}

		return Array.from(grouped.values()).sort((a, b) => a.area.order - b.area.order);
	});

	// Group selected tasks (ready to submit) by area
	const readyToSubmitByArea = $derived.by<ProjectAreaWithTasks[]>(() => {
		const grouped = new SvelteMap<string, ProjectAreaWithTasks>();

		for (const taskId of selectedTaskIds) {
			const task = allTasks.find((t) => t.id === taskId);
			if (!task) continue;

			const cat = activeScope?.categories.find((c) => c.id === task.areaId);
			if (!cat) continue;

			if (!grouped.has(cat.id)) {
				grouped.set(cat.id, {
					area: {
						id: cat.id,
						name: cat.name,
						description: null,
						order: cat.order,
						tasks: cat.tasks
					},
					tasks: []
				});
			}
			grouped.get(cat.id)!.tasks.push(task);
		}

		return Array.from(grouped.values()).sort((a, b) => a.area.order - b.area.order);
	});

	// Count of available tasks (not selected, not completed)
	const availableTasksCount = $derived(
		allTasks.filter((t) => !selectedTaskIds.has(t.id) && !completedTaskIds.has(t.id)).length
	);

	// Can start session when project is SCHEDULED and has team members assigned
	const canStartSession = $derived(project.status === 'SCHEDULED' && isAssigned && !session);

	// Session helpers
	function getTeamMemberName(id: string | null | undefined): string {
		if (!id) return 'Unknown';
		const profile = data.teamProfiles?.find((p) => p.id === id);
		return profile?.fullName ?? 'Unknown';
	}

	// ==================== SESSION HANDLERS ====================

	async function handleStartSession() {
		sessionLoading = true;
		try {
			await client.mutate({
				mutation: OPEN_PROJECT_SESSION,
				variables: { input: { projectId: project.id } }
			});
			await invalidateAll();
		} catch (err) {
			console.error('Failed to start session:', err);
		} finally {
			sessionLoading = false;
		}
	}

	async function handleCloseSession() {
		if (!session) return;
		isClosingSession = true;
		try {
			const taskIds = Array.from(completedTaskIds);
			await client.mutate({
				mutation: CLOSE_PROJECT_SESSION,
				variables: { input: { projectId: project.id, taskIds } }
			});
			await invalidateAll();
		} catch (err) {
			console.error('Failed to close session:', err);
		} finally {
			isClosingSession = false;
		}
	}

	async function handleRevertSession() {
		isRevertingSession = true;
		try {
			await client.mutate({
				mutation: REVERT_PROJECT_SESSION,
				variables: { projectId: project.id }
			});
			await invalidateAll();
		} catch (err) {
			console.error('Failed to revert session:', err);
		} finally {
			isRevertingSession = false;
		}
	}

	function handleToggleTask(taskId: string) {
		if (selectedTaskIds.has(taskId)) {
			selectedTaskIds.delete(taskId);
		} else {
			selectedTaskIds.add(taskId);
		}
	}

	async function handleSubmitTask(taskId: string) {
		submittingTaskId = taskId;
		try {
			await client.mutate({
				mutation: ADD_PROJECT_TASK_COMPLETION,
				variables: { projectId: project.id, taskId }
			});
			selectedTaskIds.delete(taskId);
			await invalidateAll();
		} catch (err) {
			console.error('Failed to submit task:', err);
		} finally {
			submittingTaskId = null;
		}
	}

	function handleRemoveTask(taskId: string) {
		selectedTaskIds.delete(taskId);
	}

	async function handleRemoveCompletedTask(taskId: string) {
		removingTaskId = taskId;
		try {
			await client.mutate({
				mutation: REMOVE_PROJECT_TASK_COMPLETION,
				variables: { projectId: project.id, taskId }
			});
			await invalidateAll();
		} catch (err) {
			console.error('Failed to remove task completion:', err);
		} finally {
			removingTaskId = null;
		}
	}

	async function handleSubmitAllTasks() {
		for (const taskId of selectedTaskIds) {
			await handleSubmitTask(taskId);
		}
	}

	function handleClearSelection() {
		selectedTaskIds.clear();
	}

	// Note handlers
	async function handleAddNote(content: string, internal: boolean) {
		if (!session) return;
		await client.mutate({
			mutation: CREATE_PROJECT_SESSION_NOTE,
			variables: { input: { sessionId: session.id, content, internal } }
		});
		await invalidateAll();
	}

	async function handleUpdateNote(noteId: string, content: string, internal: boolean) {
		await client.mutate({
			mutation: UPDATE_PROJECT_SESSION_NOTE,
			variables: { id: noteId, input: { content, internal } }
		});
		await invalidateAll();
	}

	async function handleDeleteNote(noteId: string) {
		await client.mutate({
			mutation: DELETE_PROJECT_SESSION_NOTE,
			variables: { id: noteId }
		});
		await invalidateAll();
	}

	// Media handlers
	async function handleUploadPhoto(file: File, title: string, notes: string, internal: boolean) {
		if (!session) return;
		await client.mutate({
			mutation: UPLOAD_PROJECT_SESSION_IMAGE,
			variables: {
				sessionId: session.id,
				file,
				title: title || null,
				notes: notes || null,
				internal
			}
		});
		await invalidateAll();
	}

	async function handleUploadVideo(file: File, title: string, notes: string, internal: boolean) {
		if (!session) return;
		await client.mutate({
			mutation: UPLOAD_PROJECT_SESSION_VIDEO,
			variables: {
				sessionId: session.id,
				file,
				title: title || null,
				notes: notes || null,
				internal
			}
		});
		await invalidateAll();
	}

	async function handleUpdatePhoto(
		photoId: string,
		title: string,
		notes: string,
		internal: boolean
	) {
		await client.mutate({
			mutation: UPDATE_PROJECT_SESSION_IMAGE,
			variables: { id: photoId, input: { title: title || null, notes: notes || null, internal } }
		});
		await invalidateAll();
	}

	async function handleUpdateVideo(
		videoId: string,
		title: string,
		notes: string,
		internal: boolean
	) {
		await client.mutate({
			mutation: UPDATE_PROJECT_SESSION_VIDEO,
			variables: { id: videoId, input: { title: title || null, notes: notes || null, internal } }
		});
		await invalidateAll();
	}

	async function handleDeletePhoto(photoId: string) {
		await client.mutate({
			mutation: DELETE_PROJECT_SESSION_IMAGE,
			variables: { id: photoId }
		});
		await invalidateAll();
	}

	async function handleDeleteVideo(videoId: string) {
		await client.mutate({
			mutation: DELETE_PROJECT_SESSION_VIDEO,
			variables: { id: videoId }
		});
		await invalidateAll();
	}

	function toggleTeamMemberSelection(profileId: string) {
		if (selectedTeamMembers.has(profileId)) {
			selectedTeamMembers.delete(profileId);
		} else {
			selectedTeamMembers.add(profileId);
		}
	}

	function closeAssignMenu() {
		assignMenuOpen = false;
		selectedTeamMembers.clear();
	}

	function handleEditProject() {
		drawerMode = 'project';
		drawerOpen = true;
	}

	function closeDrawer() {
		drawerOpen = false;
		drawerMode = null;
		drawerEditMode = 'add';
		selectedCategory = null;
		selectedTask = null;
	}

	async function handleFormSuccess() {
		closeDrawer();
		await invalidateAll();
	}

	// Calendar event form initial values
	let calendarEventInitialValues = $derived(() => {
		const customerName = project.customer?.name ?? '';
		return {
			summary: customerName ? `${project.name} - ${customerName}` : project.name,
			description: project.notes ? `Notes: ${project.notes}` : undefined,
			location: project.formattedAddress || undefined,
			date: project.date
		};
	});

	function openCalendarDrawer() {
		calendarDrawerOpen = true;
	}

	function closeCalendarDrawer() {
		calendarDrawerOpen = false;
	}

	async function handleCalendarEventSuccess(eventId: string) {
		// Link the created event to this project
		try {
			await client.mutate({
				mutation: LINK_CALENDAR_EVENT_TO_PROJECT,
				variables: {
					projectId: project.id,
					eventId
				}
			});
			closeCalendarDrawer();
			await invalidateAll();
		} catch (err) {
			console.error('Failed to link calendar event:', err);
			// Event was created but not linked - still close drawer and refresh
			closeCalendarDrawer();
			await invalidateAll();
		}
	}

	function handleDeleteProject() {
		deleteTarget = {
			type: 'project',
			id: project.id,
			name: project.name
		};
		deleteModalOpen = true;
	}

	function handleRemoveTeamMember(memberId: string, memberName: string) {
		deleteTarget = {
			type: 'team_member',
			id: memberId,
			name: memberName
		};
		deleteModalOpen = true;
	}

	// Scope handlers
	function openScopeDrawer(mode: 'add' | 'edit') {
		drawerMode = 'scope';
		drawerEditMode = mode;
		drawerOpen = true;
	}

	function openCategoryDrawer(category?: ProjectScopeCategory) {
		selectedCategory = category ?? null;
		drawerMode = 'category';
		drawerEditMode = category ? 'edit' : 'add';
		drawerOpen = true;
	}

	function openTaskDrawer(categoryId: string, task?: ProjectScopeTask) {
		selectedTask = { task: task ?? null, categoryId };
		drawerMode = 'task';
		drawerEditMode = task ? 'edit' : 'add';
		drawerOpen = true;
	}

	function handleDeleteScope() {
		if (!activeScope) return;
		deleteTarget = {
			type: 'scope',
			id: activeScope.id,
			name: activeScope.name
		};
		deleteModalOpen = true;
	}

	function handleDeleteCategory(categoryId: string, categoryName: string) {
		deleteTarget = {
			type: 'category',
			id: categoryId,
			name: categoryName
		};
		deleteModalOpen = true;
	}

	function handleDeleteTask(taskId: string, taskName: string) {
		deleteTarget = {
			type: 'task',
			id: taskId,
			name: taskName
		};
		deleteModalOpen = true;
	}

	// Reorder functions
	const ORDER_INCREMENT = 5;

	async function reorderCategory(
		categoryId: string,
		currentOrder: number,
		direction: 'up' | 'down'
	) {
		const newOrder =
			direction === 'up' ? currentOrder - ORDER_INCREMENT : currentOrder + ORDER_INCREMENT;
		try {
			await client.mutate({
				mutation: UPDATE_PROJECT_SCOPE_CATEGORY,
				variables: { id: categoryId, input: { order: newOrder } }
			});
			await invalidateAll();
		} catch (err) {
			console.error('Reorder category failed:', err);
		}
	}

	async function reorderTask(taskId: string, currentOrder: number, direction: 'up' | 'down') {
		const newOrder =
			direction === 'up' ? currentOrder - ORDER_INCREMENT : currentOrder + ORDER_INCREMENT;
		try {
			await client.mutate({
				mutation: UPDATE_PROJECT_SCOPE_TASK,
				variables: { id: taskId, input: { order: newOrder } }
			});
			await invalidateAll();
		} catch (err) {
			console.error('Reorder task failed:', err);
		}
	}

	function closeDeleteModal() {
		deleteModalOpen = false;
		deleteTarget = null;
	}

	async function confirmDelete() {
		if (!deleteTarget) return;

		deleteLoading = true;
		try {
			if (deleteTarget.type === 'project') {
				await client.mutate({
					mutation: DELETE_PROJECT,
					variables: { id: deleteTarget.id }
				});
				closeDeleteModal();
				await goto(`/admin/projects?month=${backMonth()}`);
				return;
			} else if (deleteTarget.type === 'team_member') {
				await client.mutate({
					mutation: REMOVE_PROJECT_TEAM_MEMBER,
					variables: { id: deleteTarget.id }
				});
			} else if (deleteTarget.type === 'scope') {
				await client.mutate({
					mutation: DELETE_PROJECT_SCOPE,
					variables: { id: deleteTarget.id }
				});
			} else if (deleteTarget.type === 'category') {
				await client.mutate({
					mutation: DELETE_PROJECT_SCOPE_CATEGORY,
					variables: { id: deleteTarget.id }
				});
			} else if (deleteTarget.type === 'task') {
				await client.mutate({
					mutation: DELETE_PROJECT_SCOPE_TASK,
					variables: { id: deleteTarget.id }
				});
			}

			closeDeleteModal();
			await invalidateAll();
		} catch (err) {
			console.error('Delete failed:', err);
		} finally {
			deleteLoading = false;
		}
	}

	async function handleAssignSelectedTeamMembers() {
		if (selectedTeamMembers.size === 0) return;
		assignLoading = true;
		try {
			for (const teamProfileId of selectedTeamMembers) {
				await client.mutate({
					mutation: ASSIGN_PROJECT_TEAM_MEMBER,
					variables: {
						projectId: project.id,
						teamProfileId
					}
				});
			}
			closeAssignMenu();
			await invalidateAll();
		} catch (err) {
			console.error('Assignment failed:', err);
		} finally {
			assignLoading = false;
		}
	}

	// Dispatch state
	let dispatchLoading = $state(false);

	function handleMessageTeam() {
		if (teamMembers.length === 0) return;

		const participants = teamMembers.map((m) => m.teamProfileId).join(',');
		const subject = encodeURIComponent(`Project: ${project.name} - ${formatDate(project.date)}`);

		goto(
			`/messages/new?subject=${subject}&entityType=project&entityId=${project.id}&participants=${participants}`
		);
	}

	async function handleDispatch() {
		if (!dispatchProfile) return;
		dispatchLoading = true;
		try {
			await client.mutate({
				mutation: ASSIGN_PROJECT_TEAM_MEMBER,
				variables: {
					projectId: project.id,
					teamProfileId: dispatchProfile.id
				}
			});
			await invalidateAll();
		} catch (err) {
			console.error('Dispatch failed:', err);
		} finally {
			dispatchLoading = false;
		}
	}

	async function handleUndispatch() {
		if (!dispatchAssignment) return;
		dispatchLoading = true;
		try {
			// First remove all team members (non-admin)
			for (const member of teamMembers) {
				await client.mutate({
					mutation: REMOVE_PROJECT_TEAM_MEMBER,
					variables: { id: member.id }
				});
			}
			// Then remove dispatch (admin)
			await client.mutate({
				mutation: REMOVE_PROJECT_TEAM_MEMBER,
				variables: { id: dispatchAssignment.id }
			});
			await invalidateAll();
		} catch (err) {
			console.error('Undispatch failed:', err);
		} finally {
			dispatchLoading = false;
		}
	}

	// Drawer title
	let drawerTitle = $derived(() => {
		switch (drawerMode) {
			case 'project':
				return 'Edit Project';
			case 'scope':
				return drawerEditMode === 'add' ? 'Add Scope' : 'Edit Scope';
			case 'category':
				return drawerEditMode === 'add' ? 'Add Category' : 'Edit Category';
			case 'task':
				return drawerEditMode === 'add' ? 'Add Task' : 'Edit Task';
			default:
				return '';
		}
	});

	function getStatusBadgeClass(status: WorkStatus): string {
		switch (status) {
			case 'SCHEDULED':
				return 'bg-accent2-100 text-accent2-800 dark:bg-accent2-900/30 dark:text-accent2-400';
			case 'IN_PROGRESS':
				return 'bg-accent-100 text-accent-800 dark:bg-accent-900/30 dark:text-accent-400';
			case 'COMPLETED':
				return 'bg-primary-100 text-primary-800 dark:bg-primary-900/30 dark:text-primary-400';
			case 'CANCELLED':
				return 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400';
			default:
				return 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300';
		}
	}

	function formatStatusLabel(status: WorkStatus): string {
		switch (status) {
			case 'IN_PROGRESS':
				return 'In Progress';
			default:
				return status.charAt(0) + status.slice(1).toLowerCase();
		}
	}

	function formatDate(dateStr: string): string {
		const date = new Date(dateStr + 'T00:00:00');
		return date.toLocaleDateString('en-US', {
			weekday: 'long',
			year: 'numeric',
			month: 'long',
			day: 'numeric'
		});
	}

	function formatCurrency(amount: number | null): string {
		if (amount === null) return '-';
		return new Intl.NumberFormat('en-US', {
			style: 'currency',
			currency: 'USD',
			minimumFractionDigits: 2,
			maximumFractionDigits: 2
		}).format(amount);
	}

	// Get month from project date for back navigation
	let backMonth = $derived(() => {
		const [year, month] = project.date.split('-');
		return `${year}-${month}`;
	});
</script>

<svelte:head>
	<title>{project.name} - Projects - Admin - Nexus</title>
</svelte:head>

<div class="py-8">
	<ContentContainer>
		<PageHeader
			title={project.name}
			subtitle={project.customer?.name ?? undefined}
			backHref="/admin/projects?month={backMonth()}"
			colorScheme="accent"
		>
			<div class="flex flex-wrap items-center gap-2">
				<span
					class="inline-flex rounded-full px-2 py-0.5 text-xs font-semibold {getStatusBadgeClass(
						project.status
					)}"
				>
					{formatStatusLabel(project.status)}
				</span>
				{#if isDispatched}
					<span
						class="inline-flex rounded-full bg-purple-100 px-2 py-0.5 text-xs font-semibold text-purple-800 dark:bg-purple-900/30 dark:text-purple-400"
					>
						Dispatched
					</span>
				{/if}
				{#if isAssigned}
					<span
						class="inline-flex rounded-full bg-blue-100 px-2 py-0.5 text-xs font-semibold text-blue-800 dark:bg-blue-900/30 dark:text-blue-400"
					>
						Assigned
					</span>
				{/if}
				<span class="text-sm text-theme-secondary">{formatDate(project.date)}</span>
			</div>
		</PageHeader>

		<div class="space-y-6">
			<!-- Project Details Section -->
			<section
				class="overflow-hidden rounded-xl border border-accent-500/20 bg-theme-card shadow-theme-md"
			>
				<div class="section-header-accent px-6 py-4">
					<SectionHeader
						title="Project Details"
						buttonText="Edit"
						buttonIcon="edit"
						onButtonClick={handleEditProject}
					/>
				</div>
				<div class="grid grid-cols-1 gap-4 p-6 sm:grid-cols-2 lg:grid-cols-3">
					<div>
						<dt class="text-sm font-medium text-theme-secondary">Date</dt>
						<dd class="mt-1 text-theme">{formatDate(project.date)}</dd>
					</div>
					<div>
						<dt class="text-sm font-medium text-theme-secondary">Status</dt>
						<dd class="mt-1">
							<span
								class="inline-flex rounded-full px-2 py-0.5 text-xs font-semibold {getStatusBadgeClass(
									project.status
								)}"
							>
								{formatStatusLabel(project.status)}
							</span>
						</dd>
					</div>
					<div>
						<dt class="text-sm font-medium text-theme-secondary">Labor</dt>
						<dd class="mt-1 text-theme">{formatCurrency(project.labor)}</dd>
					</div>
					<div>
						<dt class="text-sm font-medium text-theme-secondary">Amount</dt>
						<dd class="mt-1">
							{#if project.amount}
								<div class="flex items-center gap-2">
									<span class="text-theme">{formatCurrency(project.amount)}</span>
									{#if project.waveServiceId}
										<span class="badge-primary">Wave</span>
										{#if project.waveProductName}
											<span class="text-sm text-theme-secondary">({project.waveProductName})</span>
										{/if}
									{/if}
								</div>
							{:else}
								<span class="text-theme-muted">Not set</span>
							{/if}
						</dd>
					</div>
					<div>
						<dt class="text-sm font-medium text-theme-secondary">Calendar Event</dt>
						<dd class="mt-1">
							{#if project.calendarEventId}
								<a
									href="/admin/calendar/{project.calendarEventId}"
									class="text-sm font-medium text-accent7-600 hover:text-accent7-700 dark:text-accent7-400 dark:hover:text-accent7-300"
								>
									View Event →
								</a>
							{:else}
								<button
									type="button"
									onclick={openCalendarDrawer}
									class="inline-flex items-center gap-1.5 text-sm font-medium text-accent7-600 hover:text-accent7-700 dark:text-accent7-400 dark:hover:text-accent7-300"
								>
									<svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
										<path
											stroke-linecap="round"
											stroke-linejoin="round"
											stroke-width="2"
											d="M12 4v16m8-8H4"
										/>
									</svg>
									Schedule Event
								</button>
							{/if}
						</dd>
					</div>
				</div>
			</section>

			<!-- Account & Location Section -->
			<section
				class="overflow-hidden rounded-xl border border-accent-500/20 bg-theme-card shadow-theme-md"
			>
				<div class="section-header-accent px-6 py-4">
					<h2 class="text-lg font-semibold text-theme">Account & Location</h2>
				</div>
				<div class="grid grid-cols-1 gap-4 p-6 sm:grid-cols-2">
					<div>
						<dt class="text-sm font-medium text-theme-secondary">Account</dt>
						<dd class="mt-1">
							{#if project.accountAddress?.account}
								<a
									href="/admin/accounts/{project.accountAddress.account.id}"
									class="text-primary-500 hover:text-primary-600"
								>
									{project.accountAddress.account.name}
								</a>
							{:else}
								<span class="text-theme-muted">No account linked</span>
							{/if}
						</dd>
					</div>
					{#if project.customer}
						<div>
							<dt class="text-sm font-medium text-theme-secondary">Customer</dt>
							<dd class="mt-1">
								<a
									href="/admin/customers/{project.customer.id}"
									class="text-accent3-500 hover:text-accent3-600"
								>
									{project.customer.name}
								</a>
							</dd>
						</div>
					{/if}
					<div class="sm:col-span-2">
						<dt class="text-sm font-medium text-theme-secondary">Location</dt>
						<dd class="mt-1">
							{#if project.accountAddress}
								<a
									href="/admin/accounts/{project.accountAddress.account.id}/locations/{project
										.accountAddress.id}"
									class="text-primary-500 hover:text-primary-600"
								>
									{#if project.accountAddress.name}
										{project.accountAddress.name} -
									{/if}
									{project.formattedAddress}
								</a>
							{:else if project.formattedAddress}
								<span class="text-theme">{project.formattedAddress}</span>
							{:else}
								<span class="text-theme-muted">No location specified</span>
							{/if}
						</dd>
					</div>
				</div>
			</section>

			<!-- Project Notes Section -->
			{#if project.notes}
				<section
					class="overflow-hidden rounded-xl border border-accent-500/20 bg-theme-card shadow-theme-md"
				>
					<div class="section-header-accent px-6 py-4">
						<h2 class="text-lg font-semibold text-theme">Project Notes</h2>
					</div>
					<div class="p-6">
						<p class="whitespace-pre-wrap text-theme">{project.notes}</p>
					</div>
				</section>
			{/if}

			<!-- Scope Section -->
			<section
				class="overflow-hidden rounded-xl border border-accent-500/20 bg-theme-card shadow-theme-md"
			>
				<div class="section-header-accent px-6 py-4">
					{#if isScopeLocked}
						<h2 class="text-lg font-semibold text-theme">Scope</h2>
					{:else}
						<SectionHeader
							title="Scope"
							buttonText={activeScope ? 'Edit' : 'Add'}
							buttonIcon={activeScope ? 'edit' : 'plus'}
							onButtonClick={() => openScopeDrawer(activeScope ? 'edit' : 'add')}
						/>
					{/if}
				</div>
				<div class="px-6 py-5">
					{#if activeScope}
						<div class="space-y-4">
							{#if activeScope.name}
								<h3 class="font-medium text-theme">{activeScope.name}</h3>
							{/if}
							{#if activeScope.description}
								<p class="text-theme-secondary">{activeScope.description}</p>
							{/if}
							{#each activeScope.categories as category (category.id)}
								<details class="group bg-theme-secondary/30 rounded-lg border border-theme">
									<summary class="flex cursor-pointer items-center justify-between p-4 select-none">
										<span class="flex items-center gap-2">
											<svg
												class="h-4 w-4 text-theme-muted transition-transform group-open:rotate-90"
												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>
											<span class="font-medium text-theme">{category.name}</span>
											<span class="text-xs text-theme-muted"
												>({category.tasks.length} task{category.tasks.length === 1
													? ''
													: 's'})</span
											>
										</span>
										{#if !isScopeLocked}
											<span class="flex items-center gap-1">
												<!-- Order/reorder - hidden on mobile -->
												<span class="hidden items-center gap-1 sm:flex">
													<span class="mr-2 text-xs text-theme-muted">#{category.order}</span>
													<button
														type="button"
														onclick={(e) => {
															e.preventDefault();
															reorderCategory(category.id, category.order, 'up');
														}}
														class="hover:bg-theme-secondary/50 rounded p-1 text-theme-muted hover:text-theme"
														title="Move up"
													>
														<svg
															class="h-4 w-4"
															fill="none"
															stroke="currentColor"
															viewBox="0 0 24 24"
														>
															<path
																stroke-linecap="round"
																stroke-linejoin="round"
																stroke-width="2"
																d="M5 15l7-7 7 7"
															/>
														</svg>
													</button>
													<button
														type="button"
														onclick={(e) => {
															e.preventDefault();
															reorderCategory(category.id, category.order, 'down');
														}}
														class="hover:bg-theme-secondary/50 rounded p-1 text-theme-muted hover:text-theme"
														title="Move down"
													>
														<svg
															class="h-4 w-4"
															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>
													<span class="text-theme-muted/30 mx-1 hidden group-open:inline">|</span>
												</span>
												<!-- Edit/Delete - show on expand -->
												<span class="hidden items-center gap-2 group-open:flex">
													<button
														type="button"
														onclick={(e) => {
															e.preventDefault();
															openCategoryDrawer(category);
														}}
														class="text-xs text-accent-600 hover:text-accent-700 dark:text-accent-400 dark:hover:text-accent-300"
													>
														Edit
													</button>
													<button
														type="button"
														onclick={(e) => {
															e.preventDefault();
															handleDeleteCategory(category.id, category.name);
														}}
														class="text-xs text-error-600 hover:text-error-700 dark:text-error-400 dark:hover:text-error-300"
													>
														Delete
													</button>
												</span>
											</span>
										{/if}
									</summary>
									<div class="border-t border-theme px-4 pb-4">
										{#if category.tasks.length > 0}
											<ul class="divide-theme-muted/20 mt-3 divide-y">
												{#each category.tasks as task (task.id)}
													<li>
														<details class="group/task">
															<summary
																class="hover:bg-theme-secondary/30 -mx-2 flex cursor-pointer items-start justify-between gap-3 rounded px-2 py-2 select-none"
															>
																<span class="flex min-w-0 items-start gap-2">
																	<svg
																		class="mt-0.5 h-4 w-4 shrink-0 text-theme-muted transition-transform group-open/task:rotate-90"
																		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>
																	<span class="min-w-0">
																		<span class="text-sm text-theme">{task.scopeDescription}</span>
																		{#if task.estimatedMinutes}
																			<span class="mt-0.5 block text-xs text-theme-muted"
																				>{task.estimatedMinutes} min</span
																			>
																		{/if}
																	</span>
																</span>
																{#if !isScopeLocked}
																	<span class="flex shrink-0 items-center gap-1">
																		<!-- Order/reorder - hidden on mobile -->
																		<span class="hidden items-center gap-1 sm:flex">
																			<span class="mr-1 text-xs text-theme-muted"
																				>#{task.order}</span
																			>
																			<button
																				type="button"
																				onclick={(e) => {
																					e.preventDefault();
																					e.stopPropagation();
																					reorderTask(task.id, task.order, 'up');
																				}}
																				class="hover:bg-theme-secondary/50 rounded p-0.5 text-theme-muted hover:text-theme"
																				title="Move up"
																			>
																				<svg
																					class="h-3.5 w-3.5"
																					fill="none"
																					stroke="currentColor"
																					viewBox="0 0 24 24"
																				>
																					<path
																						stroke-linecap="round"
																						stroke-linejoin="round"
																						stroke-width="2"
																						d="M5 15l7-7 7 7"
																					/>
																				</svg>
																			</button>
																			<button
																				type="button"
																				onclick={(e) => {
																					e.preventDefault();
																					e.stopPropagation();
																					reorderTask(task.id, task.order, 'down');
																				}}
																				class="hover:bg-theme-secondary/50 rounded p-0.5 text-theme-muted hover:text-theme"
																				title="Move down"
																			>
																				<svg
																					class="h-3.5 w-3.5"
																					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>
																			<span
																				class="text-theme-muted/30 mx-0.5 hidden group-open/task:inline"
																				>|</span
																			>
																		</span>
																		<!-- Edit/Delete - show on expand -->
																		<span class="hidden items-center gap-2 group-open/task:flex">
																			<button
																				type="button"
																				onclick={(e) => {
																					e.preventDefault();
																					openTaskDrawer(category.id, task);
																				}}
																				class="text-xs text-accent-600 hover:text-accent-700 dark:text-accent-400 dark:hover:text-accent-300"
																			>
																				Edit
																			</button>
																			<button
																				type="button"
																				onclick={(e) => {
																					e.preventDefault();
																					handleDeleteTask(task.id, task.scopeDescription);
																				}}
																				class="text-xs text-error-600 hover:text-error-700 dark:text-error-400 dark:hover:text-error-300"
																			>
																				Delete
																			</button>
																		</span>
																	</span>
																{/if}
															</summary>
															<div class="ml-4 space-y-2 pb-2 text-sm sm:ml-6">
																<div class="flex flex-col sm:flex-row sm:gap-6">
																	<span class="shrink-0 text-xs text-theme-muted sm:w-24 sm:text-sm"
																		>Checklist:</span
																	>
																	<span class="text-theme-secondary"
																		>{task.checklistDescription || '—'}</span
																	>
																</div>
																<div class="flex flex-col sm:flex-row sm:gap-6">
																	<span class="shrink-0 text-xs text-theme-muted sm:w-24 sm:text-sm"
																		>Instructions:</span
																	>
																	<span class="text-theme-secondary"
																		>{task.sessionDescription || '—'}</span
																	>
																</div>
															</div>
														</details>
													</li>
												{/each}
											</ul>
										{/if}
										{#if !isScopeLocked}
											<button
												type="button"
												onclick={() => openTaskDrawer(category.id)}
												class="mt-3 text-xs text-accent-600 hover:text-accent-700 dark:text-accent-400 dark:hover:text-accent-300"
											>
												+ Add Task
											</button>
										{/if}
									</div>
								</details>
							{/each}
							{#if !isScopeLocked}
								<!-- Add Category button -->
								<button
									type="button"
									onclick={() => openCategoryDrawer()}
									class="border-theme-muted/50 w-full rounded-lg border-2 border-dashed py-3 text-sm text-theme-muted transition-colors hover:border-accent-500/50 hover:text-accent-600 dark:hover:text-accent-400"
								>
									+ Add Category
								</button>
								<div class="pt-2">
									<button
										type="button"
										onclick={handleDeleteScope}
										class="text-sm text-error-600 hover:text-error-700 dark:text-error-400 dark:hover:text-error-300"
									>
										Delete Scope
									</button>
								</div>
							{/if}
						</div>
					{:else}
						<p class="py-6 text-center text-theme-muted">No scope defined yet.</p>
					{/if}
				</div>
			</section>

			<!-- Team Members Section -->
			<section
				class="overflow-hidden rounded-xl border border-accent-500/20 bg-theme-card shadow-theme-md"
			>
				<div class="section-header-accent px-6 py-4">
					<div class="flex items-center justify-between">
						<h2 class="text-lg font-semibold text-theme">Team Members</h2>
						<div class="flex items-center gap-3">
							{#if teamMembers.length > 0}
								<button
									type="button"
									onclick={handleMessageTeam}
									class="flex items-center gap-1 text-sm font-medium text-accent2-600 hover:text-accent2-700 dark:text-accent2-400 dark:hover:text-accent2-300"
								>
									<svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
										<path
											stroke-linecap="round"
											stroke-linejoin="round"
											stroke-width="2"
											d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"
										/>
									</svg>
									Message Team
								</button>
							{/if}
							{#if !isDispatched}
								<!-- Not dispatched: show Dispatch button -->
								<button
									type="button"
									onclick={handleDispatch}
									disabled={dispatchLoading || !dispatchProfile}
									class="flex items-center gap-1 text-sm font-medium text-purple-600 hover:text-purple-700 disabled:opacity-50 dark:text-purple-400 dark:hover:text-purple-300"
								>
									{#if dispatchLoading}
										<svg class="h-4 w-4 animate-spin" 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}
										<IconPlus class="h-4 w-4" />
									{/if}
									Dispatch
								</button>
							{:else}
								<!-- Dispatched: show Assign button and Undispatch option -->
								<div class="relative">
									<button
										type="button"
										onclick={() => (assignMenuOpen = !assignMenuOpen)}
										class="flex items-center gap-1 text-sm font-medium text-accent-600 hover:text-accent-700 dark:text-accent-400 dark:hover:text-accent-300"
									>
										<IconPlus class="h-4 w-4" />
										Assign
									</button>
									{#if assignMenuOpen}
										<div class="fixed inset-0 z-50 flex items-center justify-center p-4">
											<button
												type="button"
												class="absolute inset-0 bg-black/50"
												onclick={closeAssignMenu}
												aria-label="Close menu"
											></button>
											<div
												class="relative w-full max-w-xs rounded-xl border border-theme bg-theme-card py-2 shadow-xl"
											>
												<p
													class="px-4 py-2 text-xs font-medium tracking-wide text-theme-muted uppercase"
												>
													Assign Team Members
												</p>
												{#each availableTeamProfiles.filter((p) => p.id !== config.dispatch.profileId) as profile (profile.id)}
													{@const alreadyAssigned = project.teamMembers.some(
														(m) => m.teamProfileId === profile.id
													)}
													{@const isSelected = selectedTeamMembers.has(profile.id)}
													<button
														type="button"
														onclick={() => toggleTeamMemberSelection(profile.id)}
														disabled={alreadyAssigned || assignLoading}
														class="flex w-full items-center gap-3 px-4 py-3 text-theme hover:bg-theme-secondary disabled:cursor-not-allowed disabled:opacity-50"
													>
														<span
															class="flex h-5 w-5 items-center justify-center rounded border {isSelected
																? 'border-accent-500 bg-accent-500'
																: 'border-theme-secondary'}"
														>
															{#if isSelected}
																<svg
																	class="h-3 w-3 text-white"
																	fill="none"
																	stroke="currentColor"
																	viewBox="0 0 24 24"
																>
																	<path
																		stroke-linecap="round"
																		stroke-linejoin="round"
																		stroke-width="3"
																		d="M5 13l4 4L19 7"
																	/>
																</svg>
															{/if}
														</span>
														<span class="text-left">
															<span class="block text-sm font-medium">{profile.fullName}</span>
															<span class="block text-xs text-theme-muted">
																{profile.role === 'TEAM_LEADER' ? 'Team Leader' : 'Team Member'}
																{#if alreadyAssigned}
																	<span class="text-accent-500"> (assigned)</span>
																{/if}
															</span>
														</span>
													</button>
												{/each}
												{#if availableTeamProfiles.filter((p) => p.id !== config.dispatch.profileId).length === 0}
													<p class="px-4 py-3 text-sm text-theme-muted">
														No team members available
													</p>
												{/if}
												{#if selectedTeamMembers.size > 0}
													<div class="my-1 border-t border-theme"></div>
													<button
														type="button"
														onclick={handleAssignSelectedTeamMembers}
														disabled={assignLoading}
														class="flex w-full items-center justify-center gap-2 px-4 py-3 text-sm font-medium text-accent-600 hover:bg-accent-50 disabled:opacity-50 dark:text-accent-400 dark:hover:bg-accent-950/50"
													>
														{#if assignLoading}
															<svg class="h-4 w-4 animate-spin" 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>
														{/if}
														Assign {selectedTeamMembers.size} Member{selectedTeamMembers.size > 1
															? 's'
															: ''}
													</button>
												{/if}
												<div class="my-1 border-t border-theme"></div>
												{#if teamMembers.length > 0}
													<p class="px-4 py-2 text-xs text-error-500 dark:text-error-400">
														This will also remove {teamMembers.length} assigned team member{teamMembers.length >
														1
															? 's'
															: ''}
													</p>
												{/if}
												<button
													type="button"
													onclick={() => {
														closeAssignMenu();
														handleUndispatch();
													}}
													disabled={dispatchLoading}
													class="flex w-full items-center gap-3 px-4 py-3 text-error-600 hover:bg-error-50 disabled:opacity-50 dark:text-error-400 dark:hover:bg-error-950/50"
												>
													<svg
														class="h-5 w-5"
														fill="none"
														stroke="currentColor"
														viewBox="0 0 24 24"
													>
														<path
															stroke-linecap="round"
															stroke-linejoin="round"
															stroke-width="2"
															d="M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636"
														/>
													</svg>
													Remove From Dispatch
												</button>
											</div>
										</div>
									{/if}
								</div>
							{/if}
						</div>
					</div>
				</div>
				{#if teamMembers.length > 0}
					<div class="p-6">
						<ul class="divide-theme divide-y">
							{#each teamMembers as member (member.id)}
								<li class="group py-3">
									<div class="flex items-center justify-between">
										<div class="flex items-center gap-3">
											<div
												class="flex h-8 w-8 items-center justify-center rounded-full bg-accent-100 text-accent-600 dark:bg-accent-900/30 dark:text-accent-400"
											>
												<svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
													<path
														stroke-linecap="round"
														stroke-linejoin="round"
														stroke-width="2"
														d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"
													/>
												</svg>
											</div>
											<div>
												<p class="text-sm font-medium text-theme">
													{member.teamProfile?.fullName ?? 'Unknown'}
												</p>
												{#if member.teamProfile?.role}
													<p class="text-xs text-theme-muted">
														{member.teamProfile.role === 'TEAM_LEADER'
															? 'Team Leader'
															: 'Team Member'}
													</p>
												{/if}
											</div>
										</div>
										<button
											type="button"
											onclick={() =>
												handleRemoveTeamMember(
													member.id,
													member.teamProfile?.fullName ?? 'Unknown'
												)}
											class="btn-icon-sm btn-delete-hover text-theme-muted opacity-0 group-hover:opacity-100"
											aria-label="Remove team member"
										>
											<IconTrash />
										</button>
									</div>
								</li>
							{/each}
						</ul>
					</div>
				{:else if isDispatched}
					<p class="p-6 text-sm text-theme-muted">Dispatched. Ready to assign team members.</p>
				{:else}
					<p class="p-6 text-sm text-theme-muted">Dispatch first to assign team members.</p>
				{/if}
			</section>

			<!-- Work Session Section -->
			<section
				class="overflow-hidden rounded-xl border border-accent-500/20 bg-theme-card shadow-theme-md"
			>
				<div class="section-header-accent px-6 py-4">
					<h2 class="text-lg font-semibold text-theme">Work Session</h2>
				</div>
				<div class="p-6">
					{#if session}
						<!-- Active or completed session -->
						<SessionContent
							sessionType="project"
							isActive={session.isActive}
							session={{
								isActive: session.isActive,
								start: session.start,
								end: session.end,
								durationSeconds: session.durationSeconds,
								images: session.images,
								videos: session.videos,
								notes: session.notes,
								completedTasks: session.completedTasks,
								createdBy: session.createdBy,
								closedBy: session.closedBy
							}}
							entityName={project.name}
							scopeName={activeScope?.name}
							scopeDescription={activeScope?.description}
							addressInfo={project.formattedAddress}
							teamMembers={data.teamProfiles?.map((p) => ({ id: p.id, fullName: p.fullName })) ??
								[]}
							areas={sessionAreas}
							tasks={allTasks}
							{selectedTaskIds}
							{completedTaskIds}
							{completedTasksByArea}
							{readyToSubmitByArea}
							{availableTasksCount}
							isSubmitting={isClosingSession}
							isReverting={isRevertingSession}
							{submittingTaskId}
							{removingTaskId}
							onClose={handleCloseSession}
							onRevert={handleRevertSession}
							onToggleTask={handleToggleTask}
							onSubmitTask={handleSubmitTask}
							onRemoveTask={handleRemoveTask}
							onRemoveCompletedTask={handleRemoveCompletedTask}
							onSubmitAllTasks={handleSubmitAllTasks}
							onClearSelection={handleClearSelection}
							onAddNote={handleAddNote}
							onUpdateNote={handleUpdateNote}
							onDeleteNote={handleDeleteNote}
							onUploadPhoto={handleUploadPhoto}
							onUploadVideo={handleUploadVideo}
							onUpdatePhoto={handleUpdatePhoto}
							onUpdateVideo={handleUpdateVideo}
							onDeletePhoto={handleDeletePhoto}
							onDeleteVideo={handleDeleteVideo}
							{getTeamMemberName}
						/>
					{:else if canStartSession}
						<!-- Can start a new session -->
						<div class="flex flex-col items-center gap-4 py-8">
							<p class="text-sm text-theme-muted">
								Start a work session to track time, complete tasks, and capture notes/photos.
							</p>
							<StartSessionButton
								sessionType="project"
								isLoading={sessionLoading}
								onStart={handleStartSession}
							/>
						</div>
					{:else if project.status === 'IN_PROGRESS'}
						<p class="text-sm text-theme-muted">
							This project has an active session but it was not loaded. Try refreshing the page.
						</p>
					{:else if project.status === 'COMPLETED'}
						<p class="text-sm text-theme-muted">
							This project has been completed. View the session history for details.
						</p>
					{:else if !isAssigned}
						<p class="text-sm text-theme-muted">Assign team members to enable work sessions.</p>
					{:else if !activeScope}
						<p class="text-sm text-theme-muted">
							No active scope found for this project. Configure a scope to enable work sessions.
						</p>
					{:else}
						<p class="text-sm text-theme-muted">
							Work session is not available for this project status.
						</p>
					{/if}
				</div>
			</section>

			<!-- Danger Zone -->
			<details
				class="group overflow-hidden rounded-xl border border-error-500/30 bg-error-50/50 shadow-theme dark:bg-error-950/20"
			>
				<summary
					class="flex cursor-pointer items-center justify-between bg-linear-to-r from-error-500/10 to-transparent px-5 py-3 select-none"
				>
					<span class="text-lg font-semibold text-error-700 dark:text-error-400">Danger Zone</span>
					<svg
						class="h-5 w-5 text-error-500 transition-transform group-open:rotate-180"
						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>
				</summary>
				<div class="space-y-4 border-t border-error-500/20 px-5 py-5">
					<p class="text-sm text-error-600 dark:text-error-300">
						Deleting this project will permanently remove it and all associated data. This action
						cannot be undone.
					</p>
					<button type="button" class="btn-danger" onclick={handleDeleteProject}>
						Delete Project
					</button>
				</div>
			</details>
		</div>

		<!-- Form Drawer -->
		<FormDrawer open={drawerOpen} title={drawerTitle()} onClose={closeDrawer}>
			{#if drawerMode === 'project'}
				<ProjectForm
					{project}
					waveProducts={data.waveProducts ?? []}
					onSuccess={handleFormSuccess}
					onCancel={closeDrawer}
				/>
			{:else if drawerMode === 'scope'}
				<ProjectScopeForm
					scope={drawerEditMode === 'edit' ? activeScope : null}
					projectId={project.id}
					onSuccess={handleFormSuccess}
					onCancel={closeDrawer}
				/>
			{:else if drawerMode === 'category' && activeScope}
				<ProjectCategoryForm
					category={selectedCategory}
					scopeId={activeScope.id}
					onSuccess={handleFormSuccess}
					onCancel={closeDrawer}
				/>
			{:else if drawerMode === 'task' && selectedTask}
				<ProjectTaskForm
					task={selectedTask.task}
					categoryId={selectedTask.categoryId}
					onSuccess={handleFormSuccess}
					onCancel={closeDrawer}
				/>
			{/if}
		</FormDrawer>

		<!-- Calendar Event Drawer -->
		<FormDrawer
			open={calendarDrawerOpen}
			title="Schedule Calendar Event"
			onClose={closeCalendarDrawer}
		>
			<CalendarEventForm
				teamProfiles={data.teamProfiles ?? []}
				initialValues={calendarEventInitialValues()}
				onSuccess={handleCalendarEventSuccess}
				onCancel={closeCalendarDrawer}
			/>
		</FormDrawer>

		<!-- Delete Modal -->
		<DeleteModal
			open={deleteModalOpen}
			title={deleteTarget
				? `Delete ${deleteTarget.type === 'team_member' ? 'Team Member' : deleteTarget.type === 'scope' ? 'Scope' : deleteTarget.type === 'category' ? 'Category' : deleteTarget.type === 'task' ? 'Task' : 'Project'}`
				: ''}
			message={deleteTarget
				? deleteTarget.type === 'team_member'
					? `Are you sure you want to remove "${deleteTarget.name}" from this project?`
					: deleteTarget.type === 'scope'
						? 'Are you sure you want to delete this scope? All categories and tasks will also be removed.'
						: deleteTarget.type === 'category'
							? `Are you sure you want to delete "${deleteTarget.name}"? All tasks in this category will also be removed.`
							: deleteTarget.type === 'task'
								? `Are you sure you want to delete "${deleteTarget.name}"?`
								: `Are you sure you want to delete "${deleteTarget.name}"? This action cannot be undone.`
				: ''}
			loading={deleteLoading}
			onConfirm={confirmDelete}
			onCancel={closeDeleteModal}
		/>
	</ContentContainer>
</div>
