<script lang="ts">
	import type { PageData } from './$types';
	import { client } from '$lib/graphql/client';
	import {
		SERVICE_SCOPE_TEMPLATES_QUERY,
		SERVICE_SCOPE_TEMPLATE_QUERY,
		type ServiceScopeTemplatesQueryResult,
		type ServiceScopeTemplateQueryResult,
		type ServiceScopeTemplateListItem,
		type ServiceScopeTemplate,
		type ServiceScopeTemplateArea,
		type ServiceScopeTemplateTask,
		type TaskFrequency,
		FREQUENCY_LABELS,
		FREQUENCY_SHORT_LABELS
	} from '$lib/graphql/queries/service-scope-templates';
	import {
		PROJECT_SCOPE_TEMPLATES_QUERY,
		PROJECT_SCOPE_TEMPLATE_QUERY,
		type ProjectScopeTemplatesQueryResult,
		type ProjectScopeTemplateQueryResult,
		type ProjectScopeTemplateListItem,
		type ProjectScopeTemplate,
		type ProjectScopeTemplateCategory,
		type ProjectScopeTemplateTask
	} from '$lib/graphql/queries/project-scope-templates';
	import {
		CREATE_SERVICE_SCOPE_TEMPLATE,
		UPDATE_SERVICE_SCOPE_TEMPLATE,
		DELETE_SERVICE_SCOPE_TEMPLATE,
		CREATE_SERVICE_SCOPE_TEMPLATE_AREA,
		UPDATE_SERVICE_SCOPE_TEMPLATE_AREA,
		DELETE_SERVICE_SCOPE_TEMPLATE_AREA,
		CREATE_SERVICE_SCOPE_TEMPLATE_TASK,
		UPDATE_SERVICE_SCOPE_TEMPLATE_TASK,
		DELETE_SERVICE_SCOPE_TEMPLATE_TASK,
		IMPORT_SERVICE_SCOPE_TEMPLATE,
		type ImportServiceScopeTemplateInput
	} from '$lib/graphql/mutations/service-scope-template';
	import {
		CREATE_PROJECT_SCOPE_TEMPLATE,
		UPDATE_PROJECT_SCOPE_TEMPLATE,
		DELETE_PROJECT_SCOPE_TEMPLATE,
		CREATE_PROJECT_SCOPE_TEMPLATE_CATEGORY,
		UPDATE_PROJECT_SCOPE_TEMPLATE_CATEGORY,
		DELETE_PROJECT_SCOPE_TEMPLATE_CATEGORY,
		CREATE_PROJECT_SCOPE_TEMPLATE_TASK,
		UPDATE_PROJECT_SCOPE_TEMPLATE_TASK,
		DELETE_PROJECT_SCOPE_TEMPLATE_TASK,
		IMPORT_PROJECT_SCOPE_TEMPLATE,
		type ImportProjectScopeTemplateInput
	} from '$lib/graphql/mutations/project-scope-template';

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

	// Tab state
	type TabType = 'service' | 'project';
	let activeTab = $state<TabType>('service');

	// Service scope template state - use $derived for initial sync, then manage locally
	let serviceTemplatesOverride = $state<ServiceScopeTemplateListItem[] | null>(null);
	let serviceTemplates = $derived(serviceTemplatesOverride ?? data.serviceTemplates);
	let selectedServiceTemplateId = $state<string | null>(null);
	let selectedServiceTemplate = $state<ServiceScopeTemplate | null>(null);

	// Project scope template state
	let projectTemplatesOverride = $state<ProjectScopeTemplateListItem[] | null>(null);
	let projectTemplates = $derived(projectTemplatesOverride ?? data.projectTemplates);
	let selectedProjectTemplateId = $state<string | null>(null);
	let selectedProjectTemplate = $state<ProjectScopeTemplate | null>(null);

	// Common state
	let loading = $state(false);
	let error = $state<string | null>(null);

	// UI State
	let showNewTemplateInput = $state(false);
	let newTemplateName = $state('');
	let expandedSections = $state<Set<string>>(new Set());
	let editingSectionId = $state<string | null>(null);
	let editingTaskId = $state<string | null>(null);
	let mobileView = $state<'list' | 'editor'>('list');

	// Import/Export state
	let showImportModal = $state(false);
	let importJson = $state('');
	let importReplace = $state(false);
	let importError = $state<string | null>(null);

	function handleImportFileChange(e: Event) {
		const input = e.currentTarget as HTMLInputElement;
		const file = input.files?.[0];
		if (file) {
			const reader = new FileReader();
			reader.onload = (event) => {
				const result = event.target?.result;
				importJson = typeof result === 'string' ? result : '';
			};
			reader.onerror = () => {
				importError = 'Failed to read file';
			};
			reader.readAsText(file);
		}
	}

	// Derived values
	let templates = $derived(activeTab === 'service' ? serviceTemplates : projectTemplates);
	let selectedTemplateId = $derived(
		activeTab === 'service' ? selectedServiceTemplateId : selectedProjectTemplateId
	);
	let selectedTemplate = $derived(
		activeTab === 'service' ? selectedServiceTemplate : selectedProjectTemplate
	);
	let sections = $derived(
		activeTab === 'service' && selectedServiceTemplate
			? selectedServiceTemplate.areas
			: activeTab === 'project' && selectedProjectTemplate
				? selectedProjectTemplate.categories
				: []
	);

	// Load full template when selected
	async function loadServiceTemplate(id: string) {
		loading = true;
		error = null;
		try {
			const result = await client.query<ServiceScopeTemplateQueryResult>({
				query: SERVICE_SCOPE_TEMPLATE_QUERY,
				variables: { id },
				fetchPolicy: 'network-only'
			});
			selectedServiceTemplate = result.data?.serviceScopeTemplate ?? null;
			if (selectedServiceTemplate) {
				expandedSections = new Set();
			}
		} catch (err) {
			error = err instanceof Error ? err.message : 'Failed to load template';
		} finally {
			loading = false;
		}
	}

	async function loadProjectTemplate(id: string) {
		loading = true;
		error = null;
		try {
			const result = await client.query<ProjectScopeTemplateQueryResult>({
				query: PROJECT_SCOPE_TEMPLATE_QUERY,
				variables: { id },
				fetchPolicy: 'network-only'
			});
			selectedProjectTemplate = result.data?.projectScopeTemplate ?? null;
			if (selectedProjectTemplate) {
				expandedSections = new Set();
			}
		} catch (err) {
			error = err instanceof Error ? err.message : 'Failed to load template';
		} finally {
			loading = false;
		}
	}

	async function selectTemplate(id: string) {
		if (activeTab === 'service') {
			if (selectedServiceTemplateId === id) {
				selectedServiceTemplateId = null;
				selectedServiceTemplate = null;
				return;
			}
			selectedServiceTemplateId = id;
			await loadServiceTemplate(id);
		} else {
			if (selectedProjectTemplateId === id) {
				selectedProjectTemplateId = null;
				selectedProjectTemplate = null;
				return;
			}
			selectedProjectTemplateId = id;
			await loadProjectTemplate(id);
		}
		mobileView = 'editor';
	}

	async function refreshTemplateList() {
		try {
			if (activeTab === 'service') {
				const result = await client.query<ServiceScopeTemplatesQueryResult>({
					query: SERVICE_SCOPE_TEMPLATES_QUERY,
					fetchPolicy: 'network-only'
				});
				serviceTemplatesOverride = result.data?.serviceScopeTemplates ?? [];
			} else {
				const result = await client.query<ProjectScopeTemplatesQueryResult>({
					query: PROJECT_SCOPE_TEMPLATES_QUERY,
					fetchPolicy: 'network-only'
				});
				projectTemplatesOverride = result.data?.projectScopeTemplates ?? [];
			}
		} catch (err) {
			console.error('Failed to refresh templates:', err);
		}
	}

	function switchTab(tab: TabType) {
		activeTab = tab;
		mobileView = 'list';
		error = null;
	}

	// Template CRUD
	async function createTemplate() {
		if (!newTemplateName.trim()) return;
		loading = true;
		try {
			if (activeTab === 'service') {
				const result = await client.mutate<{
					createServiceScopeTemplate: ServiceScopeTemplateListItem;
				}>({
					mutation: CREATE_SERVICE_SCOPE_TEMPLATE,
					variables: { input: { name: newTemplateName.trim() } }
				});
				const newTemplate = result.data?.createServiceScopeTemplate;
				if (newTemplate) {
					await refreshTemplateList();
					await selectTemplate(newTemplate.id);
				}
			} else {
				const result = await client.mutate<{
					createProjectScopeTemplate: ProjectScopeTemplateListItem;
				}>({
					mutation: CREATE_PROJECT_SCOPE_TEMPLATE,
					variables: { input: { name: newTemplateName.trim() } }
				});
				const newTemplate = result.data?.createProjectScopeTemplate;
				if (newTemplate) {
					await refreshTemplateList();
					await selectTemplate(newTemplate.id);
				}
			}
			newTemplateName = '';
			showNewTemplateInput = false;
		} catch (err) {
			error = err instanceof Error ? err.message : 'Failed to create template';
		} finally {
			loading = false;
		}
	}

	async function updateTemplateName(name: string) {
		if (!selectedTemplateId || !name.trim()) return;
		try {
			if (activeTab === 'service') {
				await client.mutate({
					mutation: UPDATE_SERVICE_SCOPE_TEMPLATE,
					variables: { id: selectedTemplateId, input: { name: name.trim() } }
				});
				if (selectedServiceTemplate) {
					selectedServiceTemplate = { ...selectedServiceTemplate, name: name.trim() };
				}
			} else {
				await client.mutate({
					mutation: UPDATE_PROJECT_SCOPE_TEMPLATE,
					variables: { id: selectedTemplateId, input: { name: name.trim() } }
				});
				if (selectedProjectTemplate) {
					selectedProjectTemplate = { ...selectedProjectTemplate, name: name.trim() };
				}
			}
			await refreshTemplateList();
		} catch (err) {
			error = err instanceof Error ? err.message : 'Failed to update template';
		}
	}

	async function updateTemplateDescription(description: string) {
		if (!selectedTemplateId) return;
		try {
			if (activeTab === 'service') {
				await client.mutate({
					mutation: UPDATE_SERVICE_SCOPE_TEMPLATE,
					variables: { id: selectedTemplateId, input: { description: description || null } }
				});
				if (selectedServiceTemplate) {
					selectedServiceTemplate = { ...selectedServiceTemplate, description };
				}
			} else {
				await client.mutate({
					mutation: UPDATE_PROJECT_SCOPE_TEMPLATE,
					variables: { id: selectedTemplateId, input: { description: description || null } }
				});
				if (selectedProjectTemplate) {
					selectedProjectTemplate = { ...selectedProjectTemplate, description };
				}
			}
		} catch (err) {
			error = err instanceof Error ? err.message : 'Failed to update template';
		}
	}

	async function toggleTemplateActive() {
		if (!selectedTemplateId || !selectedTemplate) return;
		try {
			if (activeTab === 'service' && selectedServiceTemplate) {
				await client.mutate({
					mutation: UPDATE_SERVICE_SCOPE_TEMPLATE,
					variables: {
						id: selectedTemplateId,
						input: { isActive: !selectedServiceTemplate.isActive }
					}
				});
				selectedServiceTemplate = {
					...selectedServiceTemplate,
					isActive: !selectedServiceTemplate.isActive
				};
			} else if (activeTab === 'project' && selectedProjectTemplate) {
				await client.mutate({
					mutation: UPDATE_PROJECT_SCOPE_TEMPLATE,
					variables: {
						id: selectedTemplateId,
						input: { isActive: !selectedProjectTemplate.isActive }
					}
				});
				selectedProjectTemplate = {
					...selectedProjectTemplate,
					isActive: !selectedProjectTemplate.isActive
				};
			}
			await refreshTemplateList();
		} catch (err) {
			error = err instanceof Error ? err.message : 'Failed to update template';
		}
	}

	async function deleteTemplate() {
		if (!selectedTemplateId) return;
		if (!confirm('Are you sure you want to delete this template? This cannot be undone.')) return;
		loading = true;
		try {
			if (activeTab === 'service') {
				await client.mutate({
					mutation: DELETE_SERVICE_SCOPE_TEMPLATE,
					variables: { id: selectedTemplateId }
				});
				selectedServiceTemplateId = null;
				selectedServiceTemplate = null;
			} else {
				await client.mutate({
					mutation: DELETE_PROJECT_SCOPE_TEMPLATE,
					variables: { id: selectedTemplateId }
				});
				selectedProjectTemplateId = null;
				selectedProjectTemplate = null;
			}
			mobileView = 'list';
			await refreshTemplateList();
		} catch (err) {
			error = err instanceof Error ? err.message : 'Failed to delete template';
		} finally {
			loading = false;
		}
	}

	// Section (Area/Category) CRUD
	async function createSection() {
		if (!selectedTemplateId) return;
		try {
			if (activeTab === 'service') {
				const result = await client.mutate<{
					createServiceScopeTemplateArea: ServiceScopeTemplateArea;
				}>({
					mutation: CREATE_SERVICE_SCOPE_TEMPLATE_AREA,
					variables: { templateId: selectedTemplateId, input: { name: 'New Area' } }
				});
				const newArea = result.data?.createServiceScopeTemplateArea;
				if (newArea && selectedServiceTemplate) {
					selectedServiceTemplate = {
						...selectedServiceTemplate,
						areas: [...selectedServiceTemplate.areas, { ...newArea, taskCount: 0, tasks: [] }]
					};
					expandedSections = new Set([...expandedSections, newArea.id]);
					editingSectionId = newArea.id;
				}
			} else {
				const result = await client.mutate<{
					createProjectScopeTemplateCategory: ProjectScopeTemplateCategory;
				}>({
					mutation: CREATE_PROJECT_SCOPE_TEMPLATE_CATEGORY,
					variables: { templateId: selectedTemplateId, input: { name: 'New Category' } }
				});
				const newCategory = result.data?.createProjectScopeTemplateCategory;
				if (newCategory && selectedProjectTemplate) {
					selectedProjectTemplate = {
						...selectedProjectTemplate,
						categories: [
							...selectedProjectTemplate.categories,
							{ ...newCategory, taskCount: 0, tasks: [] }
						]
					};
					expandedSections = new Set([...expandedSections, newCategory.id]);
					editingSectionId = newCategory.id;
				}
			}
			await refreshTemplateList();
		} catch (err) {
			error = err instanceof Error ? err.message : 'Failed to create section';
		}
	}

	async function updateSectionName(sectionId: string, name: string) {
		if (!name.trim()) return;
		try {
			if (activeTab === 'service') {
				await client.mutate({
					mutation: UPDATE_SERVICE_SCOPE_TEMPLATE_AREA,
					variables: { id: sectionId, input: { name: name.trim() } }
				});
				if (selectedServiceTemplate) {
					selectedServiceTemplate = {
						...selectedServiceTemplate,
						areas: selectedServiceTemplate.areas.map((a) =>
							a.id === sectionId ? { ...a, name: name.trim() } : a
						)
					};
				}
			} else {
				await client.mutate({
					mutation: UPDATE_PROJECT_SCOPE_TEMPLATE_CATEGORY,
					variables: { id: sectionId, input: { name: name.trim() } }
				});
				if (selectedProjectTemplate) {
					selectedProjectTemplate = {
						...selectedProjectTemplate,
						categories: selectedProjectTemplate.categories.map((c) =>
							c.id === sectionId ? { ...c, name: name.trim() } : c
						)
					};
				}
			}
			editingSectionId = null;
		} catch (err) {
			error = err instanceof Error ? err.message : 'Failed to update section';
		}
	}

	async function deleteSection(sectionId: string) {
		if (!confirm('Delete this section and all its tasks?')) return;
		try {
			if (activeTab === 'service') {
				await client.mutate({
					mutation: DELETE_SERVICE_SCOPE_TEMPLATE_AREA,
					variables: { id: sectionId }
				});
				if (selectedServiceTemplate) {
					selectedServiceTemplate = {
						...selectedServiceTemplate,
						areas: selectedServiceTemplate.areas.filter((a) => a.id !== sectionId)
					};
				}
			} else {
				await client.mutate({
					mutation: DELETE_PROJECT_SCOPE_TEMPLATE_CATEGORY,
					variables: { id: sectionId }
				});
				if (selectedProjectTemplate) {
					selectedProjectTemplate = {
						...selectedProjectTemplate,
						categories: selectedProjectTemplate.categories.filter((c) => c.id !== sectionId)
					};
				}
			}
			await refreshTemplateList();
		} catch (err) {
			error = err instanceof Error ? err.message : 'Failed to delete section';
		}
	}

	async function moveSection(sectionId: string, direction: 'up' | 'down') {
		if (activeTab === 'service' && selectedServiceTemplate) {
			const areas = [...selectedServiceTemplate.areas];
			const index = areas.findIndex((a) => a.id === sectionId);
			if (index === -1) return;
			if (direction === 'up' && index === 0) return;
			if (direction === 'down' && index === areas.length - 1) return;

			const newIndex = direction === 'up' ? index - 1 : index + 1;
			[areas[index], areas[newIndex]] = [areas[newIndex], areas[index]];

			try {
				await Promise.all(
					areas.map((area, i) =>
						client.mutate({
							mutation: UPDATE_SERVICE_SCOPE_TEMPLATE_AREA,
							variables: { id: area.id, input: { order: i } }
						})
					)
				);
				selectedServiceTemplate = { ...selectedServiceTemplate, areas };
			} catch (err) {
				error = err instanceof Error ? err.message : 'Failed to reorder sections';
			}
		} else if (activeTab === 'project' && selectedProjectTemplate) {
			const categories = [...selectedProjectTemplate.categories];
			const index = categories.findIndex((c) => c.id === sectionId);
			if (index === -1) return;
			if (direction === 'up' && index === 0) return;
			if (direction === 'down' && index === categories.length - 1) return;

			const newIndex = direction === 'up' ? index - 1 : index + 1;
			[categories[index], categories[newIndex]] = [categories[newIndex], categories[index]];

			try {
				await Promise.all(
					categories.map((cat, i) =>
						client.mutate({
							mutation: UPDATE_PROJECT_SCOPE_TEMPLATE_CATEGORY,
							variables: { id: cat.id, input: { order: i } }
						})
					)
				);
				selectedProjectTemplate = { ...selectedProjectTemplate, categories };
			} catch (err) {
				error = err instanceof Error ? err.message : 'Failed to reorder sections';
			}
		}
	}

	async function moveTask(sectionId: string, taskId: string, direction: 'up' | 'down') {
		if (activeTab === 'service' && selectedServiceTemplate) {
			const areaIndex = selectedServiceTemplate.areas.findIndex((a) => a.id === sectionId);
			if (areaIndex === -1) return;

			const tasks = [...selectedServiceTemplate.areas[areaIndex].tasks];
			const taskIndex = tasks.findIndex((t) => t.id === taskId);
			if (taskIndex === -1) return;
			if (direction === 'up' && taskIndex === 0) return;
			if (direction === 'down' && taskIndex === tasks.length - 1) return;

			const newIndex = direction === 'up' ? taskIndex - 1 : taskIndex + 1;
			[tasks[taskIndex], tasks[newIndex]] = [tasks[newIndex], tasks[taskIndex]];

			try {
				await Promise.all(
					tasks.map((task, i) =>
						client.mutate({
							mutation: UPDATE_SERVICE_SCOPE_TEMPLATE_TASK,
							variables: { id: task.id, input: { order: i } }
						})
					)
				);
				const updatedAreas = selectedServiceTemplate.areas.map((a, i) =>
					i === areaIndex ? { ...a, tasks } : a
				);
				selectedServiceTemplate = { ...selectedServiceTemplate, areas: updatedAreas };
			} catch (err) {
				error = err instanceof Error ? err.message : 'Failed to reorder tasks';
			}
		} else if (activeTab === 'project' && selectedProjectTemplate) {
			const catIndex = selectedProjectTemplate.categories.findIndex((c) => c.id === sectionId);
			if (catIndex === -1) return;

			const tasks = [...selectedProjectTemplate.categories[catIndex].tasks];
			const taskIndex = tasks.findIndex((t) => t.id === taskId);
			if (taskIndex === -1) return;
			if (direction === 'up' && taskIndex === 0) return;
			if (direction === 'down' && taskIndex === tasks.length - 1) return;

			const newIndex = direction === 'up' ? taskIndex - 1 : taskIndex + 1;
			[tasks[taskIndex], tasks[newIndex]] = [tasks[newIndex], tasks[taskIndex]];

			try {
				await Promise.all(
					tasks.map((task, i) =>
						client.mutate({
							mutation: UPDATE_PROJECT_SCOPE_TEMPLATE_TASK,
							variables: { id: task.id, input: { order: i } }
						})
					)
				);
				const updatedCategories = selectedProjectTemplate.categories.map((c, i) =>
					i === catIndex ? { ...c, tasks } : c
				);
				selectedProjectTemplate = { ...selectedProjectTemplate, categories: updatedCategories };
			} catch (err) {
				error = err instanceof Error ? err.message : 'Failed to reorder tasks';
			}
		}
	}

	// Task CRUD
	async function createTask(sectionId: string) {
		try {
			if (activeTab === 'service') {
				const result = await client.mutate<{
					createServiceScopeTemplateTask: ServiceScopeTemplateTask;
				}>({
					mutation: CREATE_SERVICE_SCOPE_TEMPLATE_TASK,
					variables: { areaId: sectionId, input: { scopeDescription: 'New task' } }
				});
				const newTask = result.data?.createServiceScopeTemplateTask;
				if (newTask && selectedServiceTemplate) {
					selectedServiceTemplate = {
						...selectedServiceTemplate,
						areas: selectedServiceTemplate.areas.map((a) =>
							a.id === sectionId
								? { ...a, tasks: [...a.tasks, newTask], taskCount: a.taskCount + 1 }
								: a
						)
					};
					editingTaskId = newTask.id;
				}
			} else {
				const result = await client.mutate<{
					createProjectScopeTemplateTask: ProjectScopeTemplateTask;
				}>({
					mutation: CREATE_PROJECT_SCOPE_TEMPLATE_TASK,
					variables: { categoryId: sectionId, input: { scopeDescription: 'New task' } }
				});
				const newTask = result.data?.createProjectScopeTemplateTask;
				if (newTask && selectedProjectTemplate) {
					selectedProjectTemplate = {
						...selectedProjectTemplate,
						categories: selectedProjectTemplate.categories.map((c) =>
							c.id === sectionId
								? { ...c, tasks: [...c.tasks, newTask], taskCount: c.taskCount + 1 }
								: c
						)
					};
					editingTaskId = newTask.id;
				}
			}
			await refreshTemplateList();
		} catch (err) {
			error = err instanceof Error ? err.message : 'Failed to create task';
		}
	}

	async function updateTask(
		taskId: string,
		updates: {
			scopeDescription?: string;
			checklistDescription?: string;
			sessionDescription?: string;
			frequency?: TaskFrequency;
			estimatedMinutes?: number | null;
		}
	) {
		try {
			if (activeTab === 'service') {
				await client.mutate({
					mutation: UPDATE_SERVICE_SCOPE_TEMPLATE_TASK,
					variables: { id: taskId, input: updates }
				});
				if (selectedServiceTemplate) {
					selectedServiceTemplate = {
						...selectedServiceTemplate,
						areas: selectedServiceTemplate.areas.map((a) => ({
							...a,
							tasks: a.tasks.map((t) => (t.id === taskId ? { ...t, ...updates } : t))
						}))
					};
				}
			} else {
				// Project tasks don't have frequency
				const { frequency, ...projectUpdates } = updates;
				await client.mutate({
					mutation: UPDATE_PROJECT_SCOPE_TEMPLATE_TASK,
					variables: { id: taskId, input: projectUpdates }
				});
				if (selectedProjectTemplate) {
					selectedProjectTemplate = {
						...selectedProjectTemplate,
						categories: selectedProjectTemplate.categories.map((c) => ({
							...c,
							tasks: c.tasks.map((t) => (t.id === taskId ? { ...t, ...projectUpdates } : t))
						}))
					};
				}
			}
			editingTaskId = null;
		} catch (err) {
			error = err instanceof Error ? err.message : 'Failed to update task';
		}
	}

	async function deleteTask(taskId: string, sectionId: string) {
		if (!confirm('Delete this task?')) return;
		try {
			if (activeTab === 'service') {
				await client.mutate({
					mutation: DELETE_SERVICE_SCOPE_TEMPLATE_TASK,
					variables: { id: taskId }
				});
				if (selectedServiceTemplate) {
					selectedServiceTemplate = {
						...selectedServiceTemplate,
						areas: selectedServiceTemplate.areas.map((a) =>
							a.id === sectionId
								? {
										...a,
										tasks: a.tasks.filter((t) => t.id !== taskId),
										taskCount: a.taskCount - 1
									}
								: a
						)
					};
				}
			} else {
				await client.mutate({
					mutation: DELETE_PROJECT_SCOPE_TEMPLATE_TASK,
					variables: { id: taskId }
				});
				if (selectedProjectTemplate) {
					selectedProjectTemplate = {
						...selectedProjectTemplate,
						categories: selectedProjectTemplate.categories.map((c) =>
							c.id === sectionId
								? {
										...c,
										tasks: c.tasks.filter((t) => t.id !== taskId),
										taskCount: c.taskCount - 1
									}
								: c
						)
					};
				}
			}
			await refreshTemplateList();
		} catch (err) {
			error = err instanceof Error ? err.message : 'Failed to delete task';
		}
	}

	// Helper for frequency select change
	function handleFrequencyChange(taskId: string, event: Event) {
		const target = event.currentTarget as HTMLSelectElement;
		updateTask(taskId, { frequency: target.value as TaskFrequency });
	}

	// Helper to get task frequency (for service tasks only)
	function getTaskFrequency(
		task: ServiceScopeTemplateTask | ProjectScopeTemplateTask
	): TaskFrequency {
		return (task as ServiceScopeTemplateTask).frequency ?? 'WEEKLY';
	}

	// Helper to get area count from service template list item
	function getAreaCount(
		template: ServiceScopeTemplateListItem | ProjectScopeTemplateListItem
	): number {
		return (template as ServiceScopeTemplateListItem).areaCount ?? 0;
	}

	// Helper to get category count from project template list item
	function getCategoryCount(
		template: ServiceScopeTemplateListItem | ProjectScopeTemplateListItem
	): number {
		return (template as ProjectScopeTemplateListItem).categoryCount ?? 0;
	}

	// Import/Export
	function exportTemplate() {
		if (activeTab === 'service' && selectedServiceTemplate) {
			const exportData = {
				name: selectedServiceTemplate.name,
				description: selectedServiceTemplate.description,
				areas: selectedServiceTemplate.areas.map((area) => ({
					name: area.name,
					order: area.order,
					tasks: area.tasks.map((task) => ({
						scope_description: task.scopeDescription,
						checklist_description: task.checklistDescription,
						session_description: task.sessionDescription,
						frequency: task.frequency,
						order: task.order,
						estimated_minutes: task.estimatedMinutes
					}))
				}))
			};
			const json = JSON.stringify(exportData, null, 2);
			const blob = new Blob([json], { type: 'application/json' });
			const url = URL.createObjectURL(blob);
			const a = document.createElement('a');
			a.href = url;
			a.download = `${selectedServiceTemplate.name.toLowerCase().replace(/\s+/g, '-')}-service-scope-template.json`;
			a.click();
			URL.revokeObjectURL(url);
		} else if (activeTab === 'project' && selectedProjectTemplate) {
			const exportData = {
				name: selectedProjectTemplate.name,
				description: selectedProjectTemplate.description,
				categories: selectedProjectTemplate.categories.map((cat) => ({
					name: cat.name,
					order: cat.order,
					tasks: cat.tasks.map((task) => ({
						scope_description: task.scopeDescription,
						checklist_description: task.checklistDescription,
						session_description: task.sessionDescription,
						order: task.order,
						estimated_minutes: task.estimatedMinutes
					}))
				}))
			};
			const json = JSON.stringify(exportData, null, 2);
			const blob = new Blob([json], { type: 'application/json' });
			const url = URL.createObjectURL(blob);
			const a = document.createElement('a');
			a.href = url;
			a.download = `${selectedProjectTemplate.name.toLowerCase().replace(/\s+/g, '-')}-project-scope-template.json`;
			a.click();
			URL.revokeObjectURL(url);
		}
	}

	async function importTemplate() {
		importError = null;
		try {
			const data = JSON.parse(importJson);

			if (activeTab === 'service') {
				const input: ImportServiceScopeTemplateInput = {
					name: data.name,
					description: data.description,
					replace: importReplace,
					areas: (data.areas || []).map((area: any, areaIndex: number) => ({
						name: area.name,
						order: area.order ?? areaIndex,
						tasks: (area.tasks || []).map((task: any, taskIndex: number) => ({
							scopeDescription: task.scope_description || task.scopeDescription,
							checklistDescription: task.checklist_description || task.checklistDescription,
							sessionDescription: task.session_description || task.sessionDescription,
							frequency: task.frequency,
							order: task.order ?? taskIndex,
							estimatedMinutes: task.estimated_minutes || task.estimatedMinutes
						}))
					}))
				};

				const result = await client.mutate<{
					importServiceScopeTemplate: ServiceScopeTemplateListItem;
				}>({
					mutation: IMPORT_SERVICE_SCOPE_TEMPLATE,
					variables: { input }
				});

				const imported = result.data?.importServiceScopeTemplate;
				if (imported) {
					await refreshTemplateList();
					await selectTemplate(imported.id);
				}
			} else {
				const input: ImportProjectScopeTemplateInput = {
					name: data.name,
					description: data.description,
					replace: importReplace,
					categories: (data.categories || []).map((cat: any, catIndex: number) => ({
						name: cat.name,
						order: cat.order ?? catIndex,
						tasks: (cat.tasks || []).map((task: any, taskIndex: number) => ({
							scopeDescription: task.scope_description || task.scopeDescription,
							checklistDescription: task.checklist_description || task.checklistDescription,
							sessionDescription: task.session_description || task.sessionDescription,
							order: task.order ?? taskIndex,
							estimatedMinutes: task.estimated_minutes || task.estimatedMinutes
						}))
					}))
				};

				const result = await client.mutate<{
					importProjectScopeTemplate: ProjectScopeTemplateListItem;
				}>({
					mutation: IMPORT_PROJECT_SCOPE_TEMPLATE,
					variables: { input }
				});

				const imported = result.data?.importProjectScopeTemplate;
				if (imported) {
					await refreshTemplateList();
					await selectTemplate(imported.id);
				}
			}
			showImportModal = false;
			importJson = '';
			importReplace = false;
		} catch (err) {
			importError = err instanceof Error ? err.message : 'Failed to import template';
		}
	}

	function toggleSection(sectionId: string) {
		const newSet = new Set(expandedSections);
		if (newSet.has(sectionId)) {
			newSet.delete(sectionId);
		} else {
			newSet.add(sectionId);
		}
		expandedSections = newSet;
	}

	function handleKeydown(event: KeyboardEvent) {
		if (event.key === 'Escape') {
			if (showImportModal) {
				showImportModal = false;
			}
			if (editingSectionId) {
				editingSectionId = null;
			}
			if (editingTaskId) {
				editingTaskId = null;
			}
		}
	}

	function getSectionLabel() {
		return activeTab === 'service' ? 'Area' : 'Category';
	}
</script>

<svelte:head>
	<title>Scope Templates - Admin - Nexus</title>
</svelte:head>

<svelte:window onkeydown={handleKeydown} />

<div class="h-[calc(100vh-4rem)] overflow-hidden">
	<div class="flex h-full">
		<!-- Template List (Left Pane) -->
		<div
			class="bg-theme-secondary/30 w-full shrink-0 border-r border-theme md:w-72 lg:w-80
				{mobileView === 'list' ? 'block' : 'hidden md:block'}"
		>
			<div class="flex h-full flex-col">
				<!-- Tab Buttons -->
				<div class="flex border-b border-theme">
					<button
						type="button"
						onclick={() => switchTab('service')}
						class="flex-1 px-4 py-3 text-sm font-medium transition-colors
							{activeTab === 'service'
							? 'border-b-2 border-primary-500 text-primary-500'
							: 'text-theme-muted hover:text-theme'}"
					>
						Service Scopes
					</button>
					<button
						type="button"
						onclick={() => switchTab('project')}
						class="flex-1 px-4 py-3 text-sm font-medium transition-colors
							{activeTab === 'project'
							? 'border-b-2 border-primary-500 text-primary-500'
							: 'text-theme-muted hover:text-theme'}"
					>
						Project Scopes
					</button>
				</div>

				<!-- List Header -->
				<div class="flex items-center justify-between border-b border-theme px-4 py-3">
					<h1 class="text-lg font-semibold text-theme">
						{activeTab === 'service' ? 'Service' : 'Project'} Templates
					</h1>
					<div class="flex items-center gap-2">
						<button
							type="button"
							onclick={() => (showImportModal = true)}
							class="rounded p-1.5 text-theme-muted hover:bg-theme-secondary hover:text-theme"
							title="Import Template"
						>
							<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="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12"
								/>
							</svg>
						</button>
						<button
							type="button"
							onclick={() => (showNewTemplateInput = true)}
							class="rounded p-1.5 text-primary-500 hover:bg-primary-500/10"
							title="New Template"
						>
							<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="M12 4v16m8-8H4"
								/>
							</svg>
						</button>
					</div>
				</div>

				<!-- New Template Input -->
				{#if showNewTemplateInput}
					<div class="border-b border-theme bg-theme p-3">
						<input
							type="text"
							bind:value={newTemplateName}
							placeholder="Template name..."
							class="mb-2 input-base"
							onkeydown={(e) => {
								if (e.key === 'Enter') createTemplate();
								if (e.key === 'Escape') {
									showNewTemplateInput = false;
									newTemplateName = '';
								}
							}}
						/>
						<div class="flex justify-end gap-2">
							<button
								type="button"
								onclick={() => {
									showNewTemplateInput = false;
									newTemplateName = '';
								}}
								class="text-sm text-theme-muted hover:text-theme"
							>
								Cancel
							</button>
							<button
								type="button"
								onclick={createTemplate}
								disabled={!newTemplateName.trim()}
								class="text-sm text-primary-500 hover:text-primary-600 disabled:opacity-50"
							>
								Create
							</button>
						</div>
					</div>
				{/if}

				<!-- Template List -->
				<div class="flex-1 overflow-y-auto">
					{#if templates.length === 0}
						<div class="p-4 text-center text-theme-muted">
							<p>No templates yet.</p>
							<button
								type="button"
								onclick={() => (showNewTemplateInput = true)}
								class="mt-2 text-sm text-primary-500 hover:text-primary-600"
							>
								Create your first template
							</button>
						</div>
					{:else}
						<div class="space-y-1 p-2">
							{#each templates as template (template.id)}
								<button
									type="button"
									onclick={() => selectTemplate(template.id)}
									class="w-full rounded-lg border-l-4 p-3 text-left transition-colors
										{activeTab === 'service' ? 'border-l-secondary-500' : 'border-l-accent-500'}
										{selectedTemplateId === template.id
										? activeTab === 'service'
											? 'bg-secondary-500/10'
											: 'bg-accent-500/10'
										: 'bg-theme-card hover:bg-black/5 dark:hover:bg-white/10'}"
								>
									<span class="flex items-center justify-between">
										<span class="font-medium text-theme">{template.name}</span>
										{#if !template.isActive}
											<span
												class="rounded bg-gray-100 px-1.5 py-0.5 text-xs text-gray-600 dark:bg-gray-700 dark:text-gray-400"
											>
												Inactive
											</span>
										{/if}
									</span>
									<span class="mt-1 block text-xs text-theme-muted">
										{#if activeTab === 'service'}
											{getAreaCount(template)} areas · {template.taskCount} tasks
										{:else}
											{getCategoryCount(template)} categories · {template.taskCount} tasks
										{/if}
									</span>
								</button>
							{/each}
						</div>
					{/if}
				</div>
			</div>
		</div>

		<!-- Editor (Right Pane) -->
		<div
			class="flex-1 overflow-hidden bg-theme
				{mobileView === 'editor' ? 'block' : 'hidden md:block'}"
		>
			{#if loading && !selectedTemplate}
				<div class="flex h-full items-center justify-center">
					<div class="text-theme-muted">Loading...</div>
				</div>
			{:else if selectedTemplate}
				<div class="flex h-full flex-col">
					<!-- Editor Header -->
					<div class="flex items-center justify-between border-b border-theme px-6 py-4">
						<div class="flex items-center gap-3">
							<!-- Mobile back button -->
							<button
								type="button"
								onclick={() => (mobileView = 'list')}
								class="rounded p-1 text-theme-muted hover:text-theme md:hidden"
								aria-label="Back to list"
							>
								<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="M15 19l-7-7 7-7"
									/>
								</svg>
							</button>
							<div>
								<input
									type="text"
									value={selectedTemplate.name}
									onblur={(e) => updateTemplateName(e.currentTarget.value)}
									onkeydown={(e) => {
										if (e.key === 'Enter') e.currentTarget.blur();
									}}
									class="-ml-1 rounded bg-transparent px-1 text-xl font-semibold text-theme focus:ring-1 focus:ring-primary-500 focus:outline-none"
								/>
								{#if !selectedTemplate.isActive}
									<span
										class="ml-2 rounded bg-gray-100 px-2 py-0.5 text-xs text-gray-600 dark:bg-gray-700 dark:text-gray-400"
									>
										Inactive
									</span>
								{/if}
							</div>
						</div>
						<div class="flex items-center gap-2">
							<button
								type="button"
								onclick={exportTemplate}
								class="rounded p-2 text-theme-muted hover:bg-theme-secondary hover:text-theme"
								title="Export Template"
							>
								<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="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"
									/>
								</svg>
							</button>
							<button
								type="button"
								onclick={toggleTemplateActive}
								class="rounded p-2 text-theme-muted hover:bg-theme-secondary hover:text-theme"
								title={selectedTemplate.isActive ? 'Deactivate' : 'Activate'}
							>
								{#if selectedTemplate.isActive}
									<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>
								{:else}
									<svg
										class="h-5 w-5 text-green-500"
										fill="none"
										stroke="currentColor"
										viewBox="0 0 24 24"
									>
										<path
											stroke-linecap="round"
											stroke-linejoin="round"
											stroke-width="2"
											d="M5 13l4 4L19 7"
										/>
									</svg>
								{/if}
							</button>
							<button
								type="button"
								onclick={deleteTemplate}
								class="rounded p-2 text-error-500 hover:bg-error-500/10"
								title="Delete Template"
							>
								<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="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>

					<!-- Description -->
					<div class="border-b border-theme px-6 py-3">
						<textarea
							placeholder="Add a description..."
							rows="2"
							onblur={(e) => updateTemplateDescription(e.currentTarget.value)}
							class="textarea-base resize-none">{selectedTemplate.description ?? ''}</textarea
						>
					</div>

					<!-- Error display -->
					{#if error}
						<div
							class="mx-6 mt-4 rounded-lg border border-error-500/30 bg-error-50/50 p-3 dark:bg-error-950/30"
						>
							<p class="text-sm text-error-700 dark:text-error-400">{error}</p>
						</div>
					{/if}

					<!-- Sections and Tasks -->
					<div class="flex-1 overflow-y-auto px-6 py-4">
						<div class="mb-4 flex items-center justify-between">
							<h2 class="font-medium text-theme">{getSectionLabel()}s & Tasks</h2>
							<button
								type="button"
								onclick={createSection}
								class="flex items-center gap-1 text-sm text-primary-500 hover:text-primary-600"
							>
								<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>
								Add {getSectionLabel()}
							</button>
						</div>

						{#if sections.length === 0}
							<div class="rounded-lg border border-dashed border-theme py-8 text-center">
								<p class="text-theme-muted">No {getSectionLabel().toLowerCase()}s yet.</p>
								<button
									type="button"
									onclick={createSection}
									class="mt-2 text-sm text-primary-500 hover:text-primary-600"
								>
									Add your first {getSectionLabel().toLowerCase()}
								</button>
							</div>
						{:else}
							<div class="space-y-4">
								{#each sections as section, sectionIndex (section.id)}
									<div
										class="rounded-lg border border-theme bg-theme-card {activeTab === 'service'
											? 'border-l-4 border-l-secondary-400'
											: 'border-l-4 border-l-accent-400'}"
									>
										<!-- Section Header -->
										<div class="flex items-center gap-2 px-3 py-2">
											<button
												type="button"
												onclick={() => toggleSection(section.id)}
												class="text-theme-muted hover:text-theme"
												aria-label="Toggle section"
											>
												<svg
													class="h-4 w-4 transition-transform {expandedSections.has(section.id)
														? '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>
											</button>

											{#if editingSectionId === section.id}
												<input
													type="text"
													value={section.name}
													onblur={(e) => updateSectionName(section.id, e.currentTarget.value)}
													onkeydown={(e) => {
														if (e.key === 'Enter') e.currentTarget.blur();
														if (e.key === 'Escape') editingSectionId = null;
													}}
													class="input-base flex-1 py-1"
												/>
											{:else}
												<button
													type="button"
													onclick={() => (editingSectionId = section.id)}
													class="flex-1 text-left font-semibold text-theme hover:opacity-80"
												>
													{section.name}
												</button>
											{/if}

											<span class="text-xs text-theme-muted">
												({section.tasks.length} task{section.tasks.length !== 1 ? 's' : ''})
											</span>

											<div class="flex items-center gap-1">
												<button
													type="button"
													onclick={() => moveSection(section.id, 'up')}
													disabled={sectionIndex === 0}
													class="rounded p-1 text-theme-muted hover:bg-black/5 hover:text-theme disabled:opacity-30 dark:hover:bg-white/10"
													aria-label="Move section 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={() => moveSection(section.id, 'down')}
													disabled={sectionIndex === sections.length - 1}
													class="rounded p-1 text-theme-muted hover:bg-black/5 hover:text-theme disabled:opacity-30 dark:hover:bg-white/10"
													aria-label="Move section 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>
												<button
													type="button"
													onclick={() => deleteSection(section.id)}
													class="rounded p-1 text-red-400 hover:bg-red-50 hover:text-red-500 dark:hover:bg-red-900/20"
													aria-label="Delete section"
												>
													<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="M6 18L18 6M6 6l12 12"
														/>
													</svg>
												</button>
											</div>
										</div>

										<!-- Tasks (expanded) -->
										{#if expandedSections.has(section.id)}
											<div class="space-y-1 border-t border-theme px-3 py-2">
												{#if section.tasks.length === 0}
													<p class="py-2 text-center text-sm text-theme-muted">No tasks yet</p>
												{:else}
													<div class="space-y-1">
														{#each section.tasks as task, taskIndex (task.id)}
															<div class="rounded bg-gray-50 p-2 dark:bg-gray-800/50">
																{#if editingTaskId === task.id}
																	<!-- Edit mode -->
																	<div class="space-y-3">
																		<label class="block">
																			<span class="text-xs font-medium text-theme-muted"
																				>Scope Description</span
																			>
																			<span class="text-theme-muted/60 ml-1 text-xs"
																				>(customer-facing)</span
																			>
																			<textarea
																				rows="2"
																				onblur={(e) =>
																					updateTask(task.id, {
																						scopeDescription: e.currentTarget.value
																					})}
																				class="mt-1 textarea-base text-sm"
																				>{task.scopeDescription}</textarea
																			>
																		</label>
																		<label class="block">
																			<span class="text-xs font-medium text-theme-muted"
																				>Checklist Description</span
																			>
																			<span class="text-theme-muted/60 ml-1 text-xs"
																				>(QA/punchlist)</span
																			>
																			<textarea
																				rows="2"
																				onblur={(e) =>
																					updateTask(task.id, {
																						checklistDescription: e.currentTarget.value
																					})}
																				class="mt-1 textarea-base text-sm"
																				>{task.checklistDescription ?? ''}</textarea
																			>
																		</label>
																		<label class="block">
																			<span class="text-xs font-medium text-theme-muted"
																				>Session Description</span
																			>
																			<span class="text-theme-muted/60 ml-1 text-xs"
																				>(work instructions)</span
																			>
																			<textarea
																				rows="2"
																				onblur={(e) =>
																					updateTask(task.id, {
																						sessionDescription: e.currentTarget.value
																					})}
																				class="mt-1 textarea-base text-sm"
																				>{task.sessionDescription ?? ''}</textarea
																			>
																		</label>
																		<div class="grid grid-cols-2 gap-3">
																			{#if activeTab === 'service'}
																				<label class="block">
																					<span class="text-xs font-medium text-theme-muted"
																						>Frequency</span
																					>
																					<select
																						onchange={(e) => handleFrequencyChange(task.id, e)}
																						class="mt-1 select-base"
																					>
																						{#each Object.entries(FREQUENCY_LABELS) as [freq, label]}
																							<option
																								value={freq}
																								selected={getTaskFrequency(task) === freq}
																								>{label}</option
																							>
																						{/each}
																					</select>
																				</label>
																			{/if}
																			<label class="block">
																				<span class="text-xs font-medium text-theme-muted"
																					>Est. Minutes</span
																				>
																				<input
																					type="number"
																					value={task.estimatedMinutes ?? ''}
																					onblur={(e) =>
																						updateTask(task.id, {
																							estimatedMinutes: e.currentTarget.value
																								? parseInt(e.currentTarget.value)
																								: null
																						})}
																					class="mt-1 input-base"
																					min="0"
																				/>
																			</label>
																		</div>
																		<button
																			type="button"
																			onclick={() => (editingTaskId = null)}
																			class="text-sm text-primary-500 hover:text-primary-600"
																		>
																			Done
																		</button>
																	</div>
																{:else}
																	<!-- View mode -->
																	<div class="flex items-start justify-between gap-2">
																		<div class="min-w-0 flex-1">
																			<p class="text-sm font-medium text-theme">
																				{task.scopeDescription}
																			</p>
																			{#if task.checklistDescription}
																				<p class="mt-0.5 text-xs text-theme-muted">
																					{task.checklistDescription}
																				</p>
																			{/if}
																			{#if task.sessionDescription}
																				<p class="mt-0.5 text-xs text-theme-muted italic">
																					{task.sessionDescription}
																				</p>
																			{/if}
																			<div class="mt-1.5 flex flex-wrap items-center gap-1.5">
																				{#if activeTab === 'service'}
																					<span
																						class="rounded-full bg-primary-500/20 px-2 py-0.5 text-xs text-primary-600 dark:text-primary-400"
																					>
																						{FREQUENCY_SHORT_LABELS[getTaskFrequency(task)]}
																					</span>
																				{/if}
																				{#if task.estimatedMinutes}
																					<span
																						class="rounded-full bg-surface-100 px-2 py-0.5 text-xs text-surface-600 dark:bg-surface-700 dark:text-surface-300"
																					>
																						{task.estimatedMinutes} min
																					</span>
																				{/if}
																			</div>
																		</div>
																		<div class="flex shrink-0 items-center gap-1">
																			<button
																				type="button"
																				onclick={() => moveTask(section.id, task.id, 'up')}
																				disabled={taskIndex === 0}
																				class="rounded p-1 text-theme-muted hover:bg-black/5 hover:text-theme disabled:opacity-30 disabled:cursor-not-allowed dark:hover:bg-white/10"
																				aria-label="Move task 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={() => moveTask(section.id, task.id, 'down')}
																				disabled={taskIndex === section.tasks.length - 1}
																				class="rounded p-1 text-theme-muted hover:bg-black/5 hover:text-theme disabled:opacity-30 disabled:cursor-not-allowed dark:hover:bg-white/10"
																				aria-label="Move task 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>
																			<button
																				type="button"
																				onclick={() => (editingTaskId = task.id)}
																				class="rounded p-1 text-theme-muted hover:bg-black/5 hover:text-theme dark:hover:bg-white/10"
																				aria-label="Edit task"
																			>
																				<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="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={() => deleteTask(task.id, section.id)}
																				class="rounded p-1 text-red-400 hover:bg-red-50 hover:text-red-500 dark:hover:bg-red-900/20"
																				aria-label="Delete task"
																			>
																				<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="M6 18L18 6M6 6l12 12"
																					/>
																				</svg>
																			</button>
																		</div>
																	</div>
																{/if}
															</div>
														{/each}
													</div>
												{/if}
												<button
													type="button"
													onclick={() => createTask(section.id)}
													class="mt-2 flex w-full items-center justify-center gap-1 rounded border border-dashed border-theme py-1.5 text-xs text-theme-muted hover:border-secondary-500 hover:text-secondary-500"
												>
													<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="M12 4v16m8-8H4"
														/>
													</svg>
													Add Task
												</button>
											</div>
										{/if}
									</div>
								{/each}
							</div>
						{/if}
					</div>
				</div>
			{:else}
				<div class="flex h-full items-center justify-center">
					<div class="text-center text-theme-muted">
						<svg class="mx-auto h-12 w-12" fill="none" stroke="currentColor" viewBox="0 0 24 24">
							<path
								stroke-linecap="round"
								stroke-linejoin="round"
								stroke-width="1.5"
								d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
							/>
						</svg>
						<p class="mt-4">Select a template to edit</p>
						<p class="mt-1 text-sm">or create a new one</p>
					</div>
				</div>
			{/if}
		</div>
	</div>
</div>

<!-- Import Modal -->
{#if showImportModal}
	<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm">
		<div
			class="mx-4 max-h-[90vh] w-full max-w-2xl overflow-y-auto rounded-xl border border-theme bg-theme-card p-6 shadow-2xl"
		>
			<h3 class="mb-4 text-lg font-semibold text-theme">
				Import {activeTab === 'service' ? 'Service' : 'Project'} Scope Template
			</h3>

			{#if importError}
				<div
					class="mb-4 rounded-lg border border-error-500/30 bg-error-50/50 p-3 dark:bg-error-950/30"
				>
					<p class="text-sm text-error-700 dark:text-error-400">{importError}</p>
				</div>
			{/if}

			<!-- Example JSON Format -->
			<details class="mb-4 rounded-lg border border-theme bg-gray-50 dark:bg-gray-800/50">
				<summary
					class="cursor-pointer px-3 py-2 text-sm font-medium text-theme-muted hover:text-theme"
				>
					Show example JSON format
				</summary>
				<div class="border-t border-theme px-3 py-2">
					{#if activeTab === 'service'}
						<pre class="overflow-x-auto text-xs text-theme-muted"><code
								>{`{
  "name": "Template Name",
  "description": "Optional description",
  "areas": [
    {
      "name": "Area Name",
      "order": 0,
      "tasks": [
        {
          "scope_description": "Customer-facing description",
          "checklist_description": "QA/punchlist description",
          "session_description": "Work instructions",
          "frequency": "WEEKLY",
          "order": 0,
          "estimated_minutes": 15
        }
      ]
    }
  ]
}`}</code
							></pre>
						<p class="mt-2 text-xs text-theme-muted">
							<strong>Frequency options:</strong> DAILY, WEEKLY, MONTHLY, QUARTERLY, TRIANNUAL, ANNUAL,
							AS_NEEDED
						</p>
					{:else}
						<pre class="overflow-x-auto text-xs text-theme-muted"><code
								>{`{
  "name": "Template Name",
  "description": "Optional description",
  "categories": [
    {
      "name": "Category Name",
      "order": 0,
      "tasks": [
        {
          "scope_description": "Customer-facing description",
          "checklist_description": "QA/punchlist description",
          "session_description": "Work instructions",
          "order": 0,
          "estimated_minutes": 30
        }
      ]
    }
  ]
}`}</code
							></pre>
						<p class="mt-2 text-xs text-theme-muted">
							<strong>Note:</strong> Project tasks don't have frequency (they're one-time tasks).
						</p>
					{/if}
				</div>
			</details>

			<div class="mb-4">
				<span class="form-label">Upload JSON File</span>
				<label
					class="mt-1 flex cursor-pointer items-center justify-center gap-2 rounded-lg border-2 border-dashed border-theme px-4 py-3 text-sm text-theme-muted transition-colors hover:border-primary-500 hover:text-primary-500"
				>
					<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="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"
						/>
					</svg>
					<span>Choose file or drag &amp; drop</span>
					<input
						type="file"
						accept=".json,application/json"
						class="hidden"
						onchange={handleImportFileChange}
					/>
				</label>
			</div>

			<div class="relative mb-4">
				<div class="absolute inset-0 flex items-center">
					<div class="w-full border-t border-theme"></div>
				</div>
				<div class="relative flex justify-center">
					<span class="bg-theme-card px-2 text-xs text-theme-muted">or paste JSON</span>
				</div>
			</div>

			<label class="mb-4 block">
				<span class="form-label">JSON Data</span>
				<textarea
					bind:value={importJson}
					placeholder="Paste JSON here..."
					rows="8"
					class="textarea-base font-mono text-sm"
				></textarea>
			</label>

			<div class="mb-4 flex items-center gap-2">
				<input
					type="checkbox"
					id="importReplace"
					bind:checked={importReplace}
					class="h-4 w-4 rounded border-theme text-primary-600 focus:ring-primary-500"
				/>
				<label for="importReplace" class="text-sm text-theme">
					Replace existing template with same name
				</label>
			</div>

			<div class="flex justify-end gap-3">
				<button
					type="button"
					onclick={() => {
						showImportModal = false;
						importJson = '';
						importError = null;
					}}
					class="btn-cancel"
				>
					Cancel
				</button>
				<button
					type="button"
					onclick={importTemplate}
					disabled={!importJson.trim()}
					class="btn-primary"
				>
					Import
				</button>
			</div>
		</div>
	</div>
{/if}
