<script lang="ts">
	import type { ScopeType, AreaType, TaskType } from '$lib/stores/scopeEditor.svelte';
	import { getFrequencyShortLabel } from '$lib/stores/scopeEditor.svelte';
	import type { GetScopeTemplates$result } from '$houdini';

	type ScopeTemplateType = GetScopeTemplates$result['scopeTemplates'][number];

	interface Props {
		scopes: ScopeType[];
		scopeTemplates?: ScopeTemplateType[];
		expandedScopes: Set<string>;
		expandedAreas: Set<string>;
		scopeError?: string;
		onToggleScope: (scopeId: string) => void;
		onToggleArea: (areaId: string) => void;
		onAddScope: () => void;
		onAddScopeFromTemplate?: (templateId: string) => void;
		onEditScope: (scope: ScopeType) => void;
		onDeleteScope: (scopeId: string) => void;
		onAddArea: (scopeId: string, nextOrder: number) => void;
		onEditArea: (scopeId: string, area: AreaType) => void;
		onDeleteArea: (areaId: string) => void;
		onAddTask: (areaId: string, nextOrder: number) => void;
		onEditTask: (areaId: string, task: TaskType) => void;
		onDeleteTask: (taskId: string) => void;
		onClearError?: () => void;
	}

	let {
		scopes,
		scopeTemplates = [],
		expandedScopes,
		expandedAreas,
		scopeError = '',
		onToggleScope,
		onToggleArea,
		onAddScope,
		onAddScopeFromTemplate,
		onEditScope,
		onDeleteScope,
		onAddArea,
		onEditArea,
		onDeleteArea,
		onAddTask,
		onEditTask,
		onDeleteTask,
		onClearError
	}: Props = $props();

	let showTemplateDropdown = $state(false);

	// Separate active and inactive scopes
	let activeScopes = $derived(scopes.filter((s) => s.isActive));
	let inactiveScopes = $derived(scopes.filter((s) => !s.isActive));

	// Toggle for showing scope history
	let showScopeHistory = $state(false);

	function getTotalTasks(scope: ScopeType): number {
		return scope.areas?.reduce((acc, area) => acc + (area.tasks?.length ?? 0), 0) ?? 0;
	}

	function sortedAreas(areas: AreaType[]): AreaType[] {
		return [...areas].sort((a, b) => a.order - b.order);
	}

	function sortedTasks(tasks: TaskType[]): TaskType[] {
		return [...tasks].sort((a, b) => a.order - b.order);
	}
</script>

<div class="mt-3 border-t border-theme pt-3">
	<!-- Scope Error Alert -->
	{#if scopeError}
		<div class="mb-2 flex items-start gap-2 rounded-lg border border-amber-400 bg-amber-50 p-2 text-xs text-amber-800 dark:border-amber-600 dark:bg-amber-900/20 dark:text-amber-300">
			<svg class="mt-0.5 h-4 w-4 shrink-0" style="fill: none" viewBox="0 0 24 24" stroke="currentColor">
				<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>
			<span class="flex-1">{scopeError}</span>
			{#if onClearError}
				<button
					type="button"
					onclick={onClearError}
					class="shrink-0 font-medium underline hover:no-underline"
				>
					Dismiss
				</button>
			{/if}
		</div>
	{/if}

	<div class="mb-2 flex items-center justify-between">
		<p class="text-xs font-medium tracking-wide text-theme-muted uppercase">Scopes</p>
		<div class="relative">
			{#if scopeTemplates.length > 0 && onAddScopeFromTemplate}
				<button
					type="button"
					onclick={() => (showTemplateDropdown = !showTemplateDropdown)}
					class="flex items-center gap-1 text-xs font-medium text-secondary-500 hover:text-secondary-600"
				>
					+ Add Scope
					<svg class="h-3 w-3" 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 showTemplateDropdown}
					<!-- Backdrop to close dropdown -->
					<button
						type="button"
						class="fixed inset-0 z-10"
						onclick={() => (showTemplateDropdown = false)}
						aria-label="Close dropdown"
					></button>
					<!-- Dropdown menu -->
					<div
						class="absolute right-0 z-20 mt-1 w-48 rounded-lg border border-theme bg-theme-card py-1 shadow-theme-lg"
					>
						<button
							type="button"
							onclick={() => {
								showTemplateDropdown = false;
								onAddScope();
							}}
							class="block w-full interactive px-3 py-1.5 text-left text-xs text-theme"
						>
							Blank Scope
						</button>
						<div class="my-1 border-t border-theme"></div>
						<p class="px-3 py-1 text-[10px] font-medium text-theme-muted uppercase">
							From Template
						</p>
						{#each scopeTemplates as template (template.id)}
							<button
								type="button"
								onclick={() => {
									showTemplateDropdown = false;
									onAddScopeFromTemplate(template.id);
								}}
								class="block w-full interactive px-3 py-1.5 text-left text-xs text-theme"
							>
								{template.name}
							</button>
						{/each}
					</div>
				{/if}
			{:else}
				<button
					type="button"
					onclick={onAddScope}
					class="text-xs font-medium text-secondary-500 hover:text-secondary-600"
				>
					+ Add Scope
				</button>
			{/if}
		</div>
	</div>

	{#if activeScopes.length > 0 || inactiveScopes.length > 0}
		<div class="space-y-2">
			<!-- Active Scopes (always visible) -->
			{#each activeScopes as scope (scope.id)}
				{@const isExpanded = expandedScopes.has(scope.id)}
				{@const totalAreas = scope.areas?.length ?? 0}
				{@const totalTasks = getTotalTasks(scope)}

				<div
					class="rounded-lg border border-theme bg-theme-card {scope.isActive
						? 'border-l-2 border-l-secondary-500'
						: ''}"
				>
					<!-- Scope Header -->
					<div class="flex items-start justify-between gap-1 p-2">
						<button
							type="button"
							onclick={() => onToggleScope(scope.id)}
							class="min-w-0 flex-1 text-left"
						>
							<span class="flex items-center gap-2">
								<svg
									class="h-4 w-4 flex-shrink-0 text-theme-muted transition-transform {isExpanded
										? 'rotate-90'
										: ''}"
									style="fill: none"
									stroke="currentColor"
									viewBox="0 0 24 24"
								>
									<path
										stroke-linecap="round"
										stroke-linejoin="round"
										stroke-width="2"
										d="M9 5l7 7-7 7"
									/>
								</svg>
								<span class="font-medium text-theme">{scope.name}</span>
								{#if scope.isActive}
									<span
										class="rounded bg-secondary-100 px-1.5 py-0.5 text-xs font-medium text-secondary-700 dark:bg-secondary-900/40 dark:text-secondary-400"
									>
										Active
									</span>
								{/if}
							</span>
							<span class="mt-0.5 block pl-6 text-xs text-theme-muted">
								{totalAreas}
								{totalAreas === 1 ? 'area' : 'areas'}, {totalTasks}
								{totalTasks === 1 ? 'task' : 'tasks'}
							</span>
						</button>
						<div class="flex shrink-0 items-center gap-1">
							<button
								type="button"
								onclick={() => onEditScope(scope)}
								class="rounded p-1 text-theme-muted hover:bg-black/5 hover:text-theme dark:hover:bg-white/10"
								aria-label="Edit scope"
							>
								<svg
									class="h-3.5 w-3.5"
									style="fill: none"
									stroke="currentColor"
									viewBox="0 0 24 24"
								>
									<path
										stroke-linecap="round"
										stroke-linejoin="round"
										stroke-width="2"
										d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"
									/>
								</svg>
							</button>
							<button
								type="button"
								onclick={() => onDeleteScope(scope.id)}
								class="rounded p-1 text-theme-muted hover:bg-red-50 hover:text-red-500 dark:hover:bg-red-900/20"
								aria-label="Delete scope"
							>
								<svg
									class="h-3.5 w-3.5"
									style="fill: none"
									stroke="currentColor"
									viewBox="0 0 24 24"
								>
									<path
										stroke-linecap="round"
										stroke-linejoin="round"
										stroke-width="2"
										d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
									/>
								</svg>
							</button>
						</div>
					</div>

					<!-- Expanded Content -->
					{#if isExpanded}
						<div class="border-t border-theme px-2 pb-2">
							{#if scope.description}
								<p class="mt-2 text-xs text-theme-muted italic">{scope.description}</p>
							{/if}

							<!-- Areas -->
							<div class="mt-2">
								<div class="mb-1 flex items-center justify-between">
									<span class="text-xs font-medium text-theme-secondary">Areas</span>
									<button
										type="button"
										onclick={() => onAddArea(scope.id, totalAreas)}
										class="text-xs text-secondary-500 hover:text-secondary-600"
									>
										+ Add
									</button>
								</div>

								{#if scope.areas && scope.areas.length > 0}
									<div class="space-y-1">
										{#each sortedAreas(scope.areas) as area (area.id)}
											{@const taskCount = area.tasks?.length ?? 0}
											{@const isAreaExpanded = expandedAreas.has(area.id)}
											<div
												class="rounded border border-l-2 border-theme border-l-secondary-400 bg-theme"
											>
												<!-- Area Header -->
												<div class="flex items-start justify-between gap-1 p-2">
													<button
														type="button"
														onclick={() => onToggleArea(area.id)}
														class="min-w-0 flex-1 text-left"
													>
														<span class="flex items-center gap-2">
															<svg
																class="h-3 w-3 flex-shrink-0 text-theme-muted transition-transform {isAreaExpanded
																	? 'rotate-90'
																	: ''}"
																style="fill: none"
																stroke="currentColor"
																viewBox="0 0 24 24"
															>
																<path
																	stroke-linecap="round"
																	stroke-linejoin="round"
																	stroke-width="2"
																	d="M9 5l7 7-7 7"
																/>
															</svg>
															<span class="text-sm font-medium text-theme">{area.name}</span>
														</span>
														<span class="mt-0.5 block pl-5 text-xs text-theme-muted">
															{taskCount}
															{taskCount === 1 ? 'task' : 'tasks'}
														</span>
													</button>
													<div class="flex shrink-0 items-center gap-1">
														<button
															type="button"
															onclick={() => onAddTask(area.id, taskCount)}
															class="rounded p-1 text-secondary-500 hover:bg-secondary-500/10"
															aria-label="Add task"
															title="Add task"
														>
															<svg
																class="h-3 w-3"
																style="fill: none"
																stroke="currentColor"
																viewBox="0 0 24 24"
															>
																<path
																	stroke-linecap="round"
																	stroke-linejoin="round"
																	stroke-width="2"
																	d="M12 4v16m8-8H4"
																/>
															</svg>
														</button>
														<button
															type="button"
															onclick={() => onEditArea(scope.id, area)}
															class="rounded p-1 text-theme-muted hover:bg-black/5 hover:text-theme dark:hover:bg-white/10"
															aria-label="Edit area"
														>
															<svg
																class="h-3 w-3"
																style="fill: none"
																stroke="currentColor"
																viewBox="0 0 24 24"
															>
																<path
																	stroke-linecap="round"
																	stroke-linejoin="round"
																	stroke-width="2"
																	d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"
																/>
															</svg>
														</button>
														<button
															type="button"
															onclick={() => onDeleteArea(area.id)}
															class="rounded p-1 text-theme-muted hover:bg-red-50 hover:text-red-500 dark:hover:bg-red-900/20"
															aria-label="Delete area"
														>
															<svg
																class="h-3 w-3"
																style="fill: none"
																stroke="currentColor"
																viewBox="0 0 24 24"
															>
																<path
																	stroke-linecap="round"
																	stroke-linejoin="round"
																	stroke-width="2"
																	d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
																/>
															</svg>
														</button>
													</div>
												</div>

												<!-- Tasks (expanded content) -->
												{#if isAreaExpanded}
													<div class="border-t border-theme px-2 pb-2">
														{#if area.tasks && area.tasks.length > 0}
															<div class="mt-2 space-y-2">
																{#each sortedTasks(area.tasks) as task (task.id)}
																	<div class="rounded bg-gray-50 p-2 text-xs dark:bg-gray-800/50">
																		<!-- Task actions -->
																		<div class="mb-2 flex items-center justify-end gap-0.5">
																			<button
																				type="button"
																				onclick={() => onEditTask(area.id, task)}
																				class="rounded p-0.5 text-theme-muted hover:bg-black/5 hover:text-theme dark:hover:bg-white/10"
																				aria-label="Edit task"
																			>
																				<svg
																					class="h-3 w-3"
																					style="fill: none"
																					stroke="currentColor"
																					viewBox="0 0 24 24"
																				>
																					<path
																						stroke-linecap="round"
																						stroke-linejoin="round"
																						stroke-width="2"
																						d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"
																					/>
																				</svg>
																			</button>
																			<button
																				type="button"
																				onclick={() => onDeleteTask(task.id)}
																				class="rounded p-0.5 text-theme-muted hover:bg-red-50 hover:text-red-500 dark:hover:bg-red-900/20"
																				aria-label="Delete task"
																			>
																				<svg
																					class="h-3 w-3"
																					style="fill: none"
																					stroke="currentColor"
																					viewBox="0 0 24 24"
																				>
																					<path
																						stroke-linecap="round"
																						stroke-linejoin="round"
																						stroke-width="2"
																						d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
																					/>
																				</svg>
																			</button>
																		</div>
																		<!-- Task fields stacked vertically -->
																		<div class="space-y-2">
																			<div>
																				<span
																					class="inline-flex items-center gap-1 text-[10px] font-medium text-theme-muted uppercase"
																				>
																					Scope Description
																					<button
																						type="button"
																						class="group relative"
																						aria-label="What is scope description?"
																					>
																						<svg
																							class="h-3 w-3 text-theme-muted hover:text-theme"
																							style="fill: none"
																							stroke="currentColor"
																							viewBox="0 0 24 24"
																						>
																							<path
																								stroke-linecap="round"
																								stroke-linejoin="round"
																								stroke-width="2"
																								d="M8.228 9c.549-1.165 2.03-2 3.772-2 2.21 0 4 1.343 4 3 0 1.4-1.278 2.575-3.006 2.907-.542.104-.994.54-.994 1.093m0 3h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
																							/>
																						</svg>
																						<span
																							class="pointer-events-none absolute bottom-full left-1/2 z-10 mb-1 hidden w-48 -translate-x-1/2 rounded bg-gray-900 px-2 py-1 text-[10px] text-white normal-case group-hover:block dark:bg-gray-700"
																						>
																							The customer-facing description of the task
																						</span>
																					</button>
																				</span>
																				<p class="text-theme">{task.description}</p>
																			</div>
																			<div>
																				<span
																					class="inline-flex items-center gap-1 text-[10px] font-medium text-theme-muted uppercase"
																				>
																					Checklist Description
																					<button
																						type="button"
																						class="group relative"
																						aria-label="What is checklist description?"
																					>
																						<svg
																							class="h-3 w-3 text-theme-muted hover:text-theme"
																							style="fill: none"
																							stroke="currentColor"
																							viewBox="0 0 24 24"
																						>
																							<path
																								stroke-linecap="round"
																								stroke-linejoin="round"
																								stroke-width="2"
																								d="M8.228 9c.549-1.165 2.03-2 3.772-2 2.21 0 4 1.343 4 3 0 1.4-1.278 2.575-3.006 2.907-.542.104-.994.54-.994 1.093m0 3h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
																							/>
																						</svg>
																						<span
																							class="pointer-events-none absolute bottom-full left-1/2 z-10 mb-1 hidden w-48 -translate-x-1/2 rounded bg-gray-900 px-2 py-1 text-[10px] text-white normal-case group-hover:block dark:bg-gray-700"
																						>
																							What team members see during a session
																						</span>
																					</button>
																				</span>
																				<p class="text-theme">{task.checklistDescription || '—'}</p>
																			</div>
																			<div>
																				<span
																					class="text-[10px] font-medium text-theme-muted uppercase"
																					>Frequency</span
																				>
																				<p class="text-theme">
																					{getFrequencyShortLabel(task.frequency)}
																				</p>
																			</div>
																		</div>
																	</div>
																{/each}
															</div>
														{:else}
															<p class="mt-2 text-center text-xs text-theme-muted">No tasks yet</p>
														{/if}
													</div>
												{/if}
											</div>
										{/each}
									</div>
								{:else}
									<p class="text-center text-xs text-theme-muted">No areas yet</p>
								{/if}
							</div>
						</div>
					{/if}
				</div>
			{/each}

			<!-- Inactive Scopes (collapsed by default) -->
			{#if inactiveScopes.length > 0}
				<div class="mt-2">
					<button
						type="button"
						onclick={() => (showScopeHistory = !showScopeHistory)}
						class="text-xs font-medium text-theme-muted hover:text-theme-secondary"
					>
						{showScopeHistory ? 'Hide' : 'Show'} scope history ({inactiveScopes.length})
					</button>

					{#if showScopeHistory}
						<div class="mt-2 space-y-2">
							{#each inactiveScopes as scope (scope.id)}
								{@const isExpanded = expandedScopes.has(scope.id)}
								{@const totalAreas = scope.areas?.length ?? 0}
								{@const totalTasks = getTotalTasks(scope)}

								<div class="rounded-lg border border-theme bg-theme-card opacity-60">
									<!-- Scope Header -->
									<div class="flex items-start justify-between gap-1 p-2">
										<button
											type="button"
											onclick={() => onToggleScope(scope.id)}
											class="min-w-0 flex-1 text-left"
										>
											<span class="flex items-center gap-2">
												<svg
													class="h-4 w-4 flex-shrink-0 text-theme-muted transition-transform {isExpanded
														? 'rotate-90'
														: ''}"
													style="fill: none"
													stroke="currentColor"
													viewBox="0 0 24 24"
												>
													<path
														stroke-linecap="round"
														stroke-linejoin="round"
														stroke-width="2"
														d="M9 5l7 7-7 7"
													/>
												</svg>
												<span class="font-medium text-theme">{scope.name}</span>
												<span class="badge-neutral">Inactive</span>
											</span>
											<span class="mt-0.5 block pl-6 text-xs text-theme-muted">
												{totalAreas}
												{totalAreas === 1 ? 'area' : 'areas'}, {totalTasks}
												{totalTasks === 1 ? 'task' : 'tasks'}
											</span>
										</button>
									</div>

									<!-- Expanded Content (read-only for inactive scopes) -->
									{#if isExpanded}
										<div class="border-t border-theme px-2 pb-2">
											{#if scope.description}
												<p class="mt-2 text-xs text-theme-muted italic">{scope.description}</p>
											{/if}

											<!-- Areas (read-only) -->
											<div class="mt-2">
												<span class="mb-1 text-xs font-medium text-theme-secondary">Areas</span>

												{#if scope.areas && scope.areas.length > 0}
													<div class="space-y-1">
														{#each sortedAreas(scope.areas) as area (area.id)}
															{@const taskCount = area.tasks?.length ?? 0}
															{@const isAreaExpanded = expandedAreas.has(area.id)}
															<div
																class="rounded border border-l-2 border-theme border-l-secondary-400 bg-theme"
															>
																<!-- Area Header -->
																<div class="flex items-start justify-between gap-1 p-2">
																	<button
																		type="button"
																		onclick={() => onToggleArea(area.id)}
																		class="min-w-0 flex-1 text-left"
																	>
																		<span class="flex items-center gap-2">
																			<svg
																				class="h-3 w-3 flex-shrink-0 text-theme-muted transition-transform {isAreaExpanded
																					? 'rotate-90'
																					: ''}"
																				style="fill: none"
																				stroke="currentColor"
																				viewBox="0 0 24 24"
																			>
																				<path
																					stroke-linecap="round"
																					stroke-linejoin="round"
																					stroke-width="2"
																					d="M9 5l7 7-7 7"
																				/>
																			</svg>
																			<span class="text-sm font-medium text-theme">{area.name}</span
																			>
																		</span>
																		<span class="mt-0.5 block pl-5 text-xs text-theme-muted">
																			{taskCount}
																			{taskCount === 1 ? 'task' : 'tasks'}
																		</span>
																	</button>
																</div>

																<!-- Tasks (expanded content, read-only) -->
																{#if isAreaExpanded}
																	<div class="border-t border-theme px-2 pb-2">
																		{#if area.tasks && area.tasks.length > 0}
																			<div class="mt-2 space-y-2">
																				{#each sortedTasks(area.tasks) as task (task.id)}
																					<div
																						class="rounded bg-gray-50 p-2 text-xs dark:bg-gray-800/50"
																					>
																						<!-- Task fields stacked vertically (no actions) -->
																						<div class="space-y-2">
																							<div>
																								<span
																									class="inline-flex items-center gap-1 text-[10px] font-medium text-theme-muted uppercase"
																								>
																									Scope Description
																								</span>
																								<p class="text-theme">{task.description}</p>
																							</div>
																							<div>
																								<span
																									class="inline-flex items-center gap-1 text-[10px] font-medium text-theme-muted uppercase"
																								>
																									Checklist Description
																								</span>
																								<p class="text-theme">
																									{task.checklistDescription || '—'}
																								</p>
																							</div>
																							<div>
																								<span
																									class="text-[10px] font-medium text-theme-muted uppercase"
																									>Frequency</span
																								>
																								<p class="text-theme">
																									{getFrequencyShortLabel(task.frequency)}
																								</p>
																							</div>
																						</div>
																					</div>
																				{/each}
																			</div>
																		{:else}
																			<p class="mt-2 text-center text-xs text-theme-muted">
																				No tasks
																			</p>
																		{/if}
																	</div>
																{/if}
															</div>
														{/each}
													</div>
												{:else}
													<p class="text-center text-xs text-theme-muted">No areas</p>
												{/if}
											</div>
										</div>
									{/if}
								</div>
							{/each}
						</div>
					{/if}
				</div>
			{/if}
		</div>
	{:else}
		<p class="text-xs text-theme-muted">No scopes defined for this address.</p>
	{/if}
</div>
