<script lang="ts">
	import ContentContainer from '$lib/components/layout/ContentContainer.svelte';
	import AdminPageHeader from '$lib/components/admin/AdminPageHeader.svelte';
	import {
		SessionSectionHeader,
		SessionContent,
		StartSessionButton,
		type ExtendedProjectTask,
		type ProjectAreaWithCompletions,
		type ProjectAreaWithTasks
	} from '$lib/components/session';
	import ProjectForm from '$lib/components/admin/projects/ProjectForm.svelte';
	import EventForm from '$lib/components/admin/calendar/EventForm.svelte';
	import { UpdateProjectStore } from '$houdini';
	import ProjectScopeSection from '$lib/components/admin/projects/ProjectScopeSection.svelte';
	import type {
		ProjectScopeType,
		ProjectCategoryType,
		ProjectTaskType
	} from '$lib/components/admin/projects/ProjectScopeSection.svelte';
	import ProjectScopeForm from '$lib/components/admin/projects/ProjectScopeForm.svelte';
	import ProjectCategoryForm from '$lib/components/admin/projects/ProjectCategoryForm.svelte';
	import ProjectTaskForm from '$lib/components/admin/projects/ProjectTaskForm.svelte';
	import ProjectDetailsCard from '$lib/components/admin/projects/ProjectDetailsCard.svelte';
	import ScopeTemplateDropdown from '$lib/components/admin/projects/ScopeTemplateDropdown.svelte';
	import {
		openProjectSession,
		closeProjectSession,
		revertProjectSession,
		addProjectTask,
		removeProjectTask,
		createProjectNote,
		updateProjectNote,
		removeProjectNote,
		uploadProjectPhoto,
		updateProjectPhoto,
		removeProjectPhoto,
		uploadProjectVideo,
		updateProjectVideo,
		removeProjectVideo
	} from '$lib/utils/session';
	import {
		createProjectScopeFromTemplate,
		deleteProjectScope,
		deleteProjectScopeCategory,
		deleteProjectScopeTask
	} from '$lib/utils/scopes';
	import DeleteConfirmModal from '$lib/components/admin/DeleteConfirmModal.svelte';
	import { offCanvas } from '$lib/stores/offCanvas.svelte';
	import type { PageData } from './$types';
	import { formatAddress } from '$lib/utils/lookup';
	import { fromGlobalId, toGlobalId } from '$lib/utils/relay';
	import { goto, invalidateAll } from '$app/navigation';
	import { SvelteSet, SvelteMap } from 'svelte/reactivity';

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

	// Core data
	let project = $derived(data.project);
	let session = $derived(data.session);
	let scope = $derived(data.scope);
	let projectUuid = $derived(data.projectUuid);
	let accountLookup = $derived(data.accountLookup);
	let customerLookup = $derived(data.customerLookup);
	let nonAdminTeamIds = $derived(data.nonAdminTeamIds);
	let teamMemberLookup = $derived(data.teamMemberLookup);
	let projectScopeTemplates = $derived(data.projectScopeTemplates ?? []);
	let customers = $derived(data.customers?.data?.customers ?? []);
	let accounts = $derived(data.accounts?.data?.accounts ?? []);
	let teamProfiles = $derived(data.team?.data?.teamProfiles ?? []);
	let waveProducts = $derived(data.waveProducts ?? []);

	// Current user for note authorship
	let currentUserProfileId = $derived(data.user?.data?.me?.id ?? null);

	// Admin always has permission to revert
	let canRevertSession = true;

	// Account or customer info
	let accountInfo = $derived(
		project.accountAddressId ? (accountLookup.get(project.accountAddressId) ?? null) : null
	);
	let customerInfo = $derived(
		project.customerId ? (customerLookup.get(project.customerId) ?? null) : null
	);

	// Display name (account or customer)
	let displayName = $derived(
		accountInfo?.accountName ?? customerInfo?.customerName ?? 'Project Details'
	);

	// Address - from account or direct project fields
	let address = $derived(() => {
		if (accountInfo) {
			return formatAddress(accountInfo);
		}
		return formatAddress({
			streetAddress: project.streetAddress,
			city: project.city,
			state: project.state,
			zipCode: project.zipCode
		});
	});

	// Team members (non-admin only)
	let teamMembers = $derived(() => {
		if (!project.teamMembers) return [];
		return project.teamMembers
			.filter((m) => nonAdminTeamIds.has(m.pk))
			.map((m) => teamMemberLookup.get(m.pk))
			.filter((m): m is NonNullable<typeof m> => m !== undefined);
	});

	// Check if admin is dispatched (admin profile is in teamMembers)
	let adminProfile = $derived(teamProfiles.find((p) => p.role === 'ADMIN'));
	let adminProfileUuid = $derived(adminProfile ? fromGlobalId(adminProfile.id) : null);
	let isDispatched = $derived(
		adminProfileUuid
			? (project.teamMembers?.some((m) => m.pk === adminProfileUuid) ?? false)
			: false
	);

	// Loading states
	let isStartingSession = $state(false);
	let isSubmitting = $state(false);
	let isReverting = $state(false);
	let submittingTaskId = $state<string | null>(null);
	let removingTaskId = $state<string | null>(null);

	// Scope management state
	let expandedCategories = new SvelteSet<string>();

	// Delete confirmation state
	let deleteScopeId = $state<string | null>(null);
	let deleteCategoryId = $state<string | null>(null);
	let deleteTaskId = $state<string | null>(null);
	let deleteLoading = $state(false);

	// Form context state for off-canvas snippets
	let formContext = $state<{
		type: 'addCategory' | 'editCategory' | 'addTask' | 'editTask' | 'editScope';
		scopeId?: string;
		categoryId?: string;
		nextOrder?: number;
		scope?: ProjectScopeType;
		category?: ProjectCategoryType;
		task?: ProjectTaskType;
	} | null>(null);

	// Check if scope can support session start
	let hasScopeWithTasks = $derived(() => {
		if (!scope) return false;
		const totalTasks =
			scope.projectAreas?.reduce((acc, cat) => acc + (cat.projectTasks?.length ?? 0), 0) ?? 0;
		return totalTasks > 0;
	});

	// Check if scope editing is allowed (only for SCHEDULED projects)
	let canEditScope = $derived(project.status === 'SCHEDULED');

	// Note: Delete functions are imported from $lib/utils/scopes

	// Build extended tasks from scope (projects use projectAreas and projectTasks)
	let tasks = $derived<ExtendedProjectTask[]>(
		scope?.projectAreas?.flatMap(
			(area) =>
				area.projectTasks?.map((task) => ({
					...task,
					uuid: fromGlobalId(task.id),
					areaId: area.id,
					areaName: area.name
				})) || []
		) || []
	);

	// Task tracking
	let completedTaskIds = $derived(
		new SvelteSet(session?.completedTasks?.map((ct) => ct.taskId) || [])
	);
	let selectedTaskIds = new SvelteSet<string>();
	let availableTasksCount = $derived(
		tasks.filter((t) => !completedTaskIds.has(t.uuid) && !selectedTaskIds.has(t.uuid)).length
	);

	// Group completed tasks by area
	let completedTasksByArea = $derived.by((): ProjectAreaWithCompletions[] => {
		if (!session?.completedTasks || !scope?.projectAreas) return [];
		const areaMap = new SvelteMap<string, ProjectAreaWithCompletions>();
		scope.projectAreas.forEach((area) => {
			const areaTasks = session.completedTasks.filter((completion) => {
				const task = tasks.find((t) => t.uuid === completion.taskId);
				return task && task.areaId === area.id;
			});
			if (areaTasks.length > 0) {
				areaMap.set(area.id, { area, completions: areaTasks });
			}
		});
		return Array.from(areaMap.values());
	});

	// Group ready to submit tasks by area
	let readyToSubmitByArea = $derived.by((): ProjectAreaWithTasks[] => {
		if (!scope?.projectAreas) return [];
		const areaMap = new SvelteMap<string, ProjectAreaWithTasks>();
		scope.projectAreas.forEach((area) => {
			const areaTasks = tasks.filter((t) => t.areaId === area.id && selectedTaskIds.has(t.uuid));
			if (areaTasks.length > 0) {
				areaMap.set(area.id, { area, tasks: areaTasks });
			}
		});
		return Array.from(areaMap.values());
	});

	// Helper function to get team member name by ID
	function getTeamMemberName(completedById: string | null | undefined): string {
		if (!completedById) return 'Unknown';
		const member = teamMemberLookup.get(completedById);
		return member?.fullName || 'Unknown';
	}

	// Edit project
	function showEditForm() {
		offCanvas.showRight({
			title: 'Edit Project',
			content: editFormContent
		});
	}

	async function handleEditSuccess() {
		await invalidateAll();
	}

	// Schedule calendar event
	const updateProjectStore = new UpdateProjectStore();

	function showScheduleEventForm() {
		offCanvas.showRight({
			title: 'Schedule Calendar Event',
			content: scheduleEventContent
		});
	}

	async function handleEventSuccess(eventId: string) {
		// Save the calendar event ID to the project
		await updateProjectStore.mutate({
			input: {
				id: project.id,
				calendarEventId: eventId
			}
		});
		await invalidateAll();
	}

	// Build initial values for calendar event from project data
	let eventInitialValues = $derived(() => {
		const projectAddress = address();
		const titleParts = ['PROJECT:', project.name];
		if (accountInfo?.accountName) {
			titleParts.push('-', accountInfo.accountName);
		}
		if (customerInfo?.customerName) {
			titleParts.push('-', customerInfo.customerName);
		}
		return {
			summary: titleParts.join(' '),
			location: projectAddress || undefined,
			date: project.date
		};
	});

	// Scope management handlers
	function toggleCategory(categoryId: string) {
		if (expandedCategories.has(categoryId)) {
			expandedCategories.delete(categoryId);
		} else {
			expandedCategories.add(categoryId);
		}
	}

	let showScopeTemplateDropdown = $state(false);
	let scopeLoading = $state(false);

	function showCreateScopeForm() {
		offCanvas.showRight({
			title: 'Create Project Scope',
			content: createScopeFormContent
		});
	}

	async function handleCreateScopeFromTemplate(templateId: string) {
		scopeLoading = true;
		try {
			const projectGlobalId = toGlobalId('ProjectType', projectUuid);
			await createProjectScopeFromTemplate({
				templateId,
				projectId: projectGlobalId,
				isActive: true
			});
			await invalidateAll();
		} catch (err) {
			console.error('Failed to create project scope from template:', err);
		} finally {
			scopeLoading = false;
		}
	}

	function showEditScopeForm(scopeToEdit: ProjectScopeType) {
		formContext = { type: 'editScope', scope: scopeToEdit };
		offCanvas.showRight({
			title: 'Edit Project Scope',
			content: editScopeFormContent
		});
	}

	function handleDeleteScope(scopeId: string) {
		deleteScopeId = scopeId;
	}

	async function confirmDeleteScope() {
		if (!deleteScopeId) return;
		deleteLoading = true;
		try {
			await deleteProjectScope(deleteScopeId);
			deleteScopeId = null;
			await invalidateAll();
		} catch (err) {
			console.error('Failed to delete scope:', err);
			throw err;
		} finally {
			deleteLoading = false;
		}
	}

	function showAddCategoryForm(scopeId: string, nextOrder: number) {
		formContext = { type: 'addCategory', scopeId, nextOrder };
		offCanvas.showRight({
			title: 'Add Category',
			content: addCategoryFormContent
		});
	}

	function showEditCategoryForm(scopeId: string, category: ProjectCategoryType) {
		formContext = { type: 'editCategory', scopeId, category };
		offCanvas.showRight({
			title: 'Edit Category',
			content: editCategoryFormContent
		});
	}

	function handleDeleteCategory(categoryId: string) {
		deleteCategoryId = categoryId;
	}

	async function confirmDeleteCategory() {
		if (!deleteCategoryId) return;
		deleteLoading = true;
		try {
			await deleteProjectScopeCategory(deleteCategoryId);
			deleteCategoryId = null;
			await invalidateAll();
		} catch (err) {
			console.error('Failed to delete category:', err);
			throw err;
		} finally {
			deleteLoading = false;
		}
	}

	function showAddTaskForm(categoryId: string, nextOrder: number) {
		formContext = { type: 'addTask', categoryId, nextOrder };
		offCanvas.showRight({
			title: 'Add Task',
			content: addTaskFormContent
		});
	}

	function showEditTaskForm(categoryId: string, task: ProjectTaskType) {
		formContext = { type: 'editTask', categoryId, task };
		offCanvas.showRight({
			title: 'Edit Task',
			content: editTaskFormContent
		});
	}

	function handleDeleteTask(taskId: string) {
		deleteTaskId = taskId;
	}

	async function confirmDeleteTask() {
		if (!deleteTaskId) return;
		deleteLoading = true;
		try {
			await deleteProjectScopeTask(deleteTaskId);
			deleteTaskId = null;
			await invalidateAll();
		} catch (err) {
			console.error('Failed to delete task:', err);
			throw err;
		} finally {
			deleteLoading = false;
		}
	}

	async function handleScopeSuccess() {
		await invalidateAll();
	}

	// Session handlers
	async function handleStartSession() {
		isStartingSession = true;
		try {
			await openProjectSession({ projectId: projectUuid });
			await invalidateAll();
		} catch (err) {
			console.error('Failed to start session:', err);
		} finally {
			isStartingSession = false;
		}
	}

	async function handleCloseSession() {
		if (!session) return;
		isSubmitting = true;
		try {
			if (selectedTaskIds.size > 0) {
				const promises = Array.from(selectedTaskIds).map((taskUuid) =>
					addProjectTask(projectUuid, taskUuid)
				);
				await Promise.all(promises);
				selectedTaskIds.clear();
			}
			await closeProjectSession({ projectId: projectUuid });
			await goto('/admin/projects', { invalidateAll: true });
		} catch (err) {
			console.error('Failed to close session:', err);
		} finally {
			isSubmitting = false;
		}
	}

	async function handleRevertSession() {
		if (
			!confirm(
				'Are you sure you want to cancel this session? All completed tasks, photos, videos, and notes will be deleted.'
			)
		) {
			return;
		}
		isReverting = true;
		try {
			await revertProjectSession(projectUuid);
			await goto('/admin/projects', { invalidateAll: true });
		} catch (err) {
			console.error('Failed to revert session:', err);
		} finally {
			isReverting = false;
		}
	}

	// Task handlers
	function toggleTask(taskUuid: string) {
		if (selectedTaskIds.has(taskUuid)) {
			selectedTaskIds.delete(taskUuid);
		} else {
			selectedTaskIds.add(taskUuid);
		}
	}

	async function handleSubmitTask(taskUuid: string) {
		if (!session) return;
		try {
			submittingTaskId = taskUuid;
			await addProjectTask(projectUuid, taskUuid);
			selectedTaskIds.delete(taskUuid);
			await invalidateAll();
		} catch (err) {
			console.error('Failed to submit task:', err);
		} finally {
			submittingTaskId = null;
		}
	}

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

	async function handleRemoveCompletedTask(taskUuid: string) {
		if (!session) return;
		try {
			removingTaskId = taskUuid;
			await removeProjectTask(projectUuid, taskUuid);
			await invalidateAll();
		} catch (err) {
			console.error('Failed to remove completed task:', err);
		} finally {
			removingTaskId = null;
		}
	}

	async function handleSubmitAllTasks() {
		if (!session || selectedTaskIds.size === 0) return;
		try {
			isSubmitting = true;
			const promises = Array.from(selectedTaskIds).map((taskUuid) =>
				addProjectTask(projectUuid, taskUuid)
			);
			await Promise.all(promises);
			selectedTaskIds.clear();
			await invalidateAll();
		} catch (err) {
			console.error('Failed to submit all tasks:', err);
		} finally {
			isSubmitting = false;
		}
	}

	// Note handlers
	async function handleAddNote(content: string, internal: boolean) {
		if (!session) return;
		await createProjectNote({
			sessionId: session.id,
			content,
			internal,
			authorId: currentUserProfileId
		});
		await invalidateAll();
	}

	async function handleUpdateNote(noteId: string, content: string, internal: boolean) {
		await updateProjectNote({ id: noteId, content, internal });
		await invalidateAll();
	}

	async function handleDeleteNote(noteId: string) {
		await removeProjectNote(noteId);
		await invalidateAll();
	}

	// Media handlers
	async function handleUploadPhoto(file: File, title: string, notes: string, internal: boolean) {
		if (!session) return;
		await uploadProjectPhoto(file, session.id, title, notes, internal);
		await invalidateAll();
	}

	async function handleUploadVideo(file: File, title: string, notes: string, internal: boolean) {
		if (!session) return;
		await uploadProjectVideo(file, session.id, title, notes, internal);
		await invalidateAll();
	}

	async function handleUpdatePhoto(
		photoId: string,
		title: string,
		notes: string,
		internal: boolean
	) {
		await updateProjectPhoto({ id: photoId, title, notes, internal });
		await invalidateAll();
	}

	async function handleUpdateVideo(
		videoId: string,
		title: string,
		notes: string,
		internal: boolean
	) {
		await updateProjectVideo({ id: videoId, title, notes, internal });
		await invalidateAll();
	}

	async function handleDeletePhoto(photoId: string) {
		await removeProjectPhoto(photoId);
		await invalidateAll();
	}

	async function handleDeleteVideo(videoId: string) {
		await removeProjectVideo(videoId);
		await invalidateAll();
	}
</script>

{#snippet editFormContent()}
	<ProjectForm
		{project}
		{customers}
		{accounts}
		{teamProfiles}
		{waveProducts}
		onSuccess={handleEditSuccess}
	/>
{/snippet}

{#snippet scheduleEventContent()}
	<EventForm {teamProfiles} initialValues={eventInitialValues()} onSuccess={handleEventSuccess} />
{/snippet}

{#snippet createScopeFormContent()}
	<ProjectScopeForm projectId={project.id} onSuccess={handleScopeSuccess} />
{/snippet}

{#snippet editScopeFormContent()}
	{#if formContext?.scope}
		<ProjectScopeForm
			projectId={project.id}
			scope={formContext.scope}
			onSuccess={handleScopeSuccess}
		/>
	{/if}
{/snippet}

{#snippet addCategoryFormContent()}
	{#if formContext?.scopeId}
		<ProjectCategoryForm
			scopeId={formContext.scopeId}
			nextOrder={formContext.nextOrder ?? 0}
			onSuccess={handleScopeSuccess}
		/>
	{/if}
{/snippet}

{#snippet editCategoryFormContent()}
	{#if formContext?.scopeId && formContext?.category}
		<ProjectCategoryForm
			scopeId={formContext.scopeId}
			category={formContext.category}
			onSuccess={handleScopeSuccess}
		/>
	{/if}
{/snippet}

{#snippet addTaskFormContent()}
	{#if formContext?.categoryId}
		<ProjectTaskForm
			categoryId={formContext.categoryId}
			nextOrder={formContext.nextOrder ?? 0}
			onSuccess={handleScopeSuccess}
		/>
	{/if}
{/snippet}

{#snippet editTaskFormContent()}
	{#if formContext?.categoryId && formContext?.task}
		<ProjectTaskForm
			categoryId={formContext.categoryId}
			task={formContext.task}
			onSuccess={handleScopeSuccess}
		/>
	{/if}
{/snippet}

<svelte:head>
	<title>{displayName} - Projects - Admin - Nexus</title>
</svelte:head>

<div class="py-8">
	<ContentContainer>
		<AdminPageHeader
			title={displayName}
			subtitle={project.name}
			colorScheme="accent"
			backHref="/admin/projects"
			invalidateOnBack
			onEdit={showEditForm}
		/>

		<!-- Project Details Card -->
		<ProjectDetailsCard
			projectId={project.id}
			projectName={project.name}
			status={project.status}
			date={project.date}
			amount={project.amount}
			labor={project.labor}
			address={address()}
			teamMembers={teamMembers()}
			notes={project.notes}
			calendarEventId={project.calendarEventId}
			waveServiceId={project.waveServiceId}
			{waveProducts}
			onScheduleEvent={showScheduleEventForm}
			{accountInfo}
			{customerInfo}
			{isDispatched}
		/>

		<!-- Project Scope Section (always visible for admin) -->
		<div class="mb-6 rounded-xl border border-theme bg-theme-card p-6">
			<div class="mb-4 flex items-center justify-between">
				<h2 class="text-lg font-semibold text-theme">Project Scope</h2>
				{#if !scope && canEditScope && !scopeLoading}
					<ScopeTemplateDropdown
						templates={projectScopeTemplates}
						isOpen={showScopeTemplateDropdown}
						onToggle={() => (showScopeTemplateDropdown = !showScopeTemplateDropdown)}
						onCreateBlank={showCreateScopeForm}
						onCreateFromTemplate={handleCreateScopeFromTemplate}
					/>
				{/if}
			</div>

			<!-- Lock notice when scope cannot be edited -->
			{#if !canEditScope && scope}
				<div class="mb-4 rounded-lg border border-warning bg-warning p-3">
					<div class="flex items-center gap-2">
						<svg
							class="h-5 w-5 flex-shrink-0 text-warning-500"
							style="fill: none"
							stroke="currentColor"
							viewBox="0 0 24 24"
						>
							<path
								stroke-linecap="round"
								stroke-linejoin="round"
								stroke-width="2"
								d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"
							/>
						</svg>
						<div>
							<p class="text-sm font-medium text-warning">Scope is locked</p>
							<p class="text-xs text-warning-700 dark:text-warning-300">
								{#if project.status === 'IN_PROGRESS'}
									The scope cannot be modified while the project session is active. Revert the
									session first to make changes.
								{:else}
									The scope cannot be modified after the project has been completed.
								{/if}
							</p>
						</div>
					</div>
				</div>
			{/if}

			{#if scopeLoading}
				<div class="py-8 text-center">
					<svg
						class="mx-auto h-8 w-8 animate-spin text-accent-500"
						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>
					<p class="mt-3 text-sm text-theme-muted">Creating scope from template...</p>
				</div>
			{:else if scope}
				<ProjectScopeSection
					{scope}
					{expandedCategories}
					editable={canEditScope}
					onToggleCategory={toggleCategory}
					onEditScope={canEditScope ? showEditScopeForm : undefined}
					onDeleteScope={canEditScope ? handleDeleteScope : undefined}
					onAddCategory={canEditScope ? showAddCategoryForm : undefined}
					onEditCategory={canEditScope ? showEditCategoryForm : undefined}
					onDeleteCategory={canEditScope ? handleDeleteCategory : undefined}
					onAddTask={canEditScope ? showAddTaskForm : undefined}
					onEditTask={canEditScope ? showEditTaskForm : undefined}
					onDeleteTask={canEditScope ? handleDeleteTask : undefined}
				/>
			{:else}
				<div class="py-8 text-center">
					<svg
						class="mx-auto h-12 w-12 text-theme-muted"
						style="fill: none"
						stroke="currentColor"
						viewBox="0 0 24 24"
					>
						<path
							stroke-linecap="round"
							stroke-linejoin="round"
							stroke-width="1.5"
							d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"
						/>
					</svg>
					<h3 class="mt-2 text-sm font-medium text-theme">No Scope Defined</h3>
					<p class="mt-1 text-sm text-theme-muted">
						{#if canEditScope}
							A scope with categories and tasks is required before starting a session.
						{:else}
							This project does not have a scope assigned.
						{/if}
					</p>
				</div>
			{/if}
		</div>

		<!-- Session Section -->
		{#if project.status === 'IN_PROGRESS' && session}
			<section>
				<SessionSectionHeader isActive={true} sessionType="project" />
				<SessionContent
					sessionType="project"
					isActive={true}
					{session}
					entityName={displayName}
					scopeName={scope?.name}
					scopeDescription={scope?.description}
					addressInfo={address()}
					teamMembers={teamMembers()}
					areas={scope?.projectAreas || []}
					{tasks}
					{selectedTaskIds}
					{completedTaskIds}
					{completedTasksByArea}
					{readyToSubmitByArea}
					{availableTasksCount}
					{isSubmitting}
					{isReverting}
					{submittingTaskId}
					{removingTaskId}
					{getTeamMemberName}
					onClose={handleCloseSession}
					onRevert={canRevertSession ? handleRevertSession : undefined}
					onToggleTask={toggleTask}
					onSubmitTask={handleSubmitTask}
					onRemoveTask={handleRemoveTask}
					onRemoveCompletedTask={handleRemoveCompletedTask}
					onSubmitAllTasks={handleSubmitAllTasks}
					onClearSelection={() => selectedTaskIds.clear()}
					onAddNote={handleAddNote}
					onUpdateNote={handleUpdateNote}
					onDeleteNote={handleDeleteNote}
					onUploadPhoto={handleUploadPhoto}
					onUploadVideo={handleUploadVideo}
					onUpdatePhoto={handleUpdatePhoto}
					onUpdateVideo={handleUpdateVideo}
					onDeletePhoto={handleDeletePhoto}
					onDeleteVideo={handleDeleteVideo}
				/>
			</section>
		{:else if project.status === 'COMPLETED' && session}
			<section>
				<SessionSectionHeader isActive={false} sessionType="project" />
				<SessionContent
					sessionType="project"
					isActive={false}
					{session}
					entityName={displayName}
					scopeName={scope?.name}
					addressInfo={address()}
					teamMembers={teamMembers()}
					areas={scope?.projectAreas || []}
					{tasks}
					{selectedTaskIds}
					{completedTaskIds}
					{completedTasksByArea}
					{readyToSubmitByArea}
					{availableTasksCount}
					{getTeamMemberName}
					onAddNote={handleAddNote}
					onUpdateNote={handleUpdateNote}
					onDeleteNote={handleDeleteNote}
					onUploadPhoto={handleUploadPhoto}
					onUpdatePhoto={handleUpdatePhoto}
					onDeletePhoto={handleDeletePhoto}
					onUploadVideo={handleUploadVideo}
					onUpdateVideo={handleUpdateVideo}
					onDeleteVideo={handleDeleteVideo}
				/>
			</section>
		{:else if project.status === 'SCHEDULED'}
			{#if hasScopeWithTasks()}
				<StartSessionButton
					isLoading={isStartingSession}
					backLabel="Back to Projects"
					onStart={handleStartSession}
					onBack={() => goto('/admin/projects', { invalidateAll: true })}
				/>
			{:else}
				<div class="warning-box">
					<div class="flex items-start gap-3">
						<svg
							class="warning-box-icon"
							style="fill: none"
							stroke="currentColor"
							viewBox="0 0 24 24"
						>
							<path
								stroke-linecap="round"
								stroke-linejoin="round"
								stroke-width="2"
								d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"
							/>
						</svg>
						<div>
							<h3 class="warning-box-title">Scope Required</h3>
							<p class="warning-box-text">
								{#if !scope}
									Create a project scope with categories and tasks before starting a session.
								{:else}
									Add at least one category with tasks to the scope before starting a session.
								{/if}
							</p>
						</div>
					</div>
					<div class="mt-4 flex items-center gap-3">
						<a
							href="/admin/projects"
							class="rounded-lg border border-theme interactive bg-theme px-4 py-2 text-sm font-medium text-theme"
						>
							Back to Projects
						</a>
					</div>
				</div>
			{/if}
		{/if}
	</ContentContainer>
</div>

<!-- Delete Confirmation Modals -->
<DeleteConfirmModal
	open={!!deleteScopeId}
	title="Delete Project Scope"
	message="Are you sure you want to delete this scope? All categories and tasks will be removed."
	loading={deleteLoading}
	onconfirm={confirmDeleteScope}
	oncancel={() => (deleteScopeId = null)}
/>

<DeleteConfirmModal
	open={!!deleteCategoryId}
	title="Delete Category"
	message="Are you sure you want to delete this category? All tasks will be removed."
	loading={deleteLoading}
	onconfirm={confirmDeleteCategory}
	oncancel={() => (deleteCategoryId = null)}
/>

<DeleteConfirmModal
	open={!!deleteTaskId}
	title="Delete Task"
	message="Are you sure you want to delete this task?"
	loading={deleteLoading}
	onconfirm={confirmDeleteTask}
	oncancel={() => (deleteTaskId = null)}
/>
