<script lang="ts">
	import type {PageData} from './$types';
	import {GetProjectScopeTemplatesStore, GetScopeTemplatesStore} from '$houdini';
	import {
		createAreaTemplate,
		createProjectAreaTemplate,
		createProjectScopeTemplate,
		createProjectScopeTemplateFromJson,
		createProjectTaskTemplate,
		createScopeTemplate,
		createScopeTemplateFromJson,
		createTaskTemplate,
		deleteAreaTemplate,
		deleteProjectAreaTemplate,
		deleteProjectScopeTemplate,
		deleteProjectTaskTemplate,
		deleteScopeTemplate,
		deleteTaskTemplate,
		updateAreaTemplate,
		updateProjectAreaTemplate,
		updateProjectScopeTemplate,
		updateProjectTaskTemplate,
		updateScopeTemplate,
		updateTaskTemplate
	} from '$lib/utils/scopes';
	import {slide} from 'svelte/transition';
	import {SvelteSet} from 'svelte/reactivity';
	import TemplateList from '$lib/components/admin/scopes/TemplateList.svelte';
	import TemplateEditor from '$lib/components/admin/scopes/TemplateEditor.svelte';

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

	// Types
	type TaskTemplate = {
		id: string;
		description: string;
		checklistDescription: string | null;
		frequency?: string | null;
		isConditional?: boolean;
		order: number;
		estimatedMinutes: number | null;
	};

	type AreaTemplate = {
		id: string;
		name: string;
		order: number;
		taskTemplates: TaskTemplate[];
	};

	type ScopeTemplate = {
		id: string;
		name: string;
		description: string | null;
		isActive: boolean;
		areaTemplates: AreaTemplate[];
	};

	type CategoryTemplate = {
		id: string;
		name: string;
		order: number;
		taskTemplates: TaskTemplate[];
	};

	type ProjectScopeTemplate = {
		id: string;
		name: string;
		description: string | null;
		isActive: boolean;
		categoryTemplates: CategoryTemplate[];
	};

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

	// Mobile detection - use md breakpoint (768px) for two-pane layout
	let windowWidth = $state(typeof window !== 'undefined' ? window.innerWidth : 768);
	let isDesktop = $derived(windowWidth >= 768);

	// Mobile view state
	type MobileView = 'list' | 'editor';
	let mobileView = $state<MobileView>('list');

	// Stores for refetching data after mutations
	let serviceScopeStore = $state(new GetScopeTemplatesStore());
	let projectScopeStore = $state(new GetProjectScopeTemplatesStore());

	// UI state
	let isLoading = $state(false);
	let error = $state('');
	let selectedServiceTemplateId = $state<string | null>(null);
	let selectedProjectTemplateId = $state<string | null>(null);

	// Expanded areas/categories
	let expandedServiceAreas = new SvelteSet<string>();
	let expandedProjectCategories = new SvelteSet<string>();

	// Edit modes
	let editingTemplateName = $state<string | null>(null);
	let editingAreaName = $state<string | null>(null);
	let editingTaskId = $state<string | null>(null);

	// New item state
	let newTemplateName = $state('');
	let newAreaName = $state('');
	let newTaskDescription = $state('');
	let showNewTemplateInput = $state(false);
	let showNewAreaInput = $state<string | null>(null);
	let showNewTaskInput = $state<string | null>(null);

	// JSON Import modal
	let showJsonImportModal = $state(false);
	let jsonImportText = $state('');
	let jsonImportReplace = $state(false);
	let jsonImportError = $state('');
	type JsonImportPayload = {
		name?: string;
		areas?: unknown[];
		categories?: unknown[];
	};
	let jsonImportParsed = $state<JsonImportPayload | null>(null);

	// JSON Export modal
	let showJsonExportModal = $state(false);
	let jsonExportText = $state('');
	let jsonExportCopied = $state(false);

	// Window resize handler
	$effect(() => {
		if (typeof window !== 'undefined') {
			const handleResize = () => {
				windowWidth = window.innerWidth;
			};
			window.addEventListener('resize', handleResize);
			return () => window.removeEventListener('resize', handleResize);
		}
	});

	// Derived data - use store data if available (after mutations refetch), otherwise use server data
	let serviceTemplates = $derived(
		(($serviceScopeStore.data?.scopeTemplates ?? data?.serviceScopes) as ScopeTemplate[]) ?? []
	);
	let projectTemplates = $derived(
		(($projectScopeStore.data?.projectScopeTemplates ??
			data?.projectScopes) as ProjectScopeTemplate[]) ?? []
	);

	let selectedServiceTemplate = $derived(
		serviceTemplates.find((t) => t.id === selectedServiceTemplateId) ?? null
	);
	let selectedProjectTemplate = $derived(
		projectTemplates.find((t) => t.id === selectedProjectTemplateId) ?? null
	);

	// Tab toggle functions (for mobile)
	function previousTab() {
		activeTab = activeTab === 'service' ? 'project' : 'service';
	}

	function nextTab() {
		activeTab = activeTab === 'service' ? 'project' : 'service';
	}

	// Template selection (toggle on desktop, always open on mobile)
	function selectServiceTemplate(id: string) {
		if (isDesktop && selectedServiceTemplateId === id) {
			// Toggle off on desktop
			selectedServiceTemplateId = null;
		} else {
			selectedServiceTemplateId = id;
			expandedServiceAreas.clear();
			if (!isDesktop) {
				mobileView = 'editor';
			}
		}
	}

	function selectProjectTemplate(id: string) {
		if (isDesktop && selectedProjectTemplateId === id) {
			// Toggle off on desktop
			selectedProjectTemplateId = null;
		} else {
			selectedProjectTemplateId = id;
			expandedProjectCategories.clear();
			if (!isDesktop) {
				mobileView = 'editor';
			}
		}
	}

	// Area/Category expansion
	function toggleServiceArea(areaId: string) {
		if (expandedServiceAreas.has(areaId)) {
			expandedServiceAreas.delete(areaId);
		} else {
			expandedServiceAreas.add(areaId);
		}
	}

	function toggleProjectCategory(categoryId: string) {
		if (expandedProjectCategories.has(categoryId)) {
			expandedProjectCategories.delete(categoryId);
		} else {
			expandedProjectCategories.add(categoryId);
		}
	}

	// CRUD Operations - Service Scope Templates
	async function handleCreateServiceTemplate() {
		if (!newTemplateName.trim()) return;
		try {
			const result = await createScopeTemplate({
				name: newTemplateName.trim(),
				description: '',
				isActive: true
			});
			await serviceScopeStore.fetch();
			selectedServiceTemplateId = result.id;
			newTemplateName = '';
			showNewTemplateInput = false;
		} catch (e) {
			error = e instanceof Error ? e.message : 'Failed to create template';
		}
	}

	async function handleUpdateServiceTemplate(id: string, name: string) {
		try {
			await updateScopeTemplate({ id, name });
			await serviceScopeStore.fetch();
			editingTemplateName = null;
		} catch (e) {
			error = e instanceof Error ? e.message : 'Failed to update template';
		}
	}

	async function handleUpdateServiceTemplateDescription(id: string, description: string) {
		try {
			await updateScopeTemplate({ id, description });
			await serviceScopeStore.fetch();
		} catch (e) {
			error = e instanceof Error ? e.message : 'Failed to update template description';
		}
	}

	async function handleDeleteServiceTemplate(id: string) {
		if (!confirm('Delete this template and all its areas/tasks?')) return;
		try {
			await deleteScopeTemplate(id);
			await serviceScopeStore.fetch();
			if (selectedServiceTemplateId === id) {
				selectedServiceTemplateId = null;
			}
		} catch (e) {
			error = e instanceof Error ? e.message : 'Failed to delete template';
		}
	}

	async function handleCreateServiceArea(templateId: string) {
		if (!newAreaName.trim()) return;
		try {
			await createAreaTemplate({
				scopeTemplateId: templateId,
				name: newAreaName.trim(),
				order: selectedServiceTemplate?.areaTemplates.length ?? 0
			});
			await serviceScopeStore.fetch();
			newAreaName = '';
			showNewAreaInput = null;
		} catch (e) {
			error = e instanceof Error ? e.message : 'Failed to create area';
		}
	}

	async function handleUpdateServiceArea(id: string, name: string) {
		try {
			await updateAreaTemplate({ id, name });
			await serviceScopeStore.fetch();
			editingAreaName = null;
		} catch (e) {
			error = e instanceof Error ? e.message : 'Failed to update area';
		}
	}

	async function handleDeleteServiceArea(id: string) {
		if (!confirm('Delete this area and all its tasks?')) return;
		try {
			await deleteAreaTemplate(id);
			await serviceScopeStore.fetch();
		} catch (e) {
			error = e instanceof Error ? e.message : 'Failed to delete area';
		}
	}

	async function handleCreateServiceTask(areaId: string) {
		if (!newTaskDescription.trim()) return;
		try {
			const area = selectedServiceTemplate?.areaTemplates.find((a) => a.id === areaId);
			await createTaskTemplate({
				areaTemplateId: areaId,
				description: newTaskDescription.trim(),
				checklistDescription: '',
				frequency: 'weekly',
				isConditional: false,
				order: area?.taskTemplates.length ?? 0,
				estimatedMinutes: null
			});
			await serviceScopeStore.fetch();
			newTaskDescription = '';
			showNewTaskInput = null;
		} catch (e) {
			error = e instanceof Error ? e.message : 'Failed to create task';
		}
	}

	async function handleDeleteServiceTask(id: string) {
		if (!confirm('Delete this task?')) return;
		try {
			await deleteTaskTemplate(id);
			await serviceScopeStore.fetch();
		} catch (e) {
			error = e instanceof Error ? e.message : 'Failed to delete task';
		}
	}

	async function handleUpdateServiceTask(
		taskId: string,
		updates: {
			description?: string;
			checklistDescription?: string;
			frequency?: string;
			estimatedMinutes?: number | null;
		}
	) {
		try {
			await updateTaskTemplate({
				id: taskId,
				...updates
			});
			await serviceScopeStore.fetch();
			editingTaskId = null;
		} catch (e) {
			error = e instanceof Error ? e.message : 'Failed to update task';
		}
	}

	async function handleMoveServiceAreaUp(areaId: string) {
		if (!selectedServiceTemplate) return;
		try {
			const areas = [...selectedServiceTemplate.areaTemplates].sort((a, b) => a.order - b.order);
			const index = areas.findIndex((a) => a.id === areaId);
			if (index <= 0) return; // Already at top or not found
			const currentArea = areas[index];
			const previousArea = areas[index - 1];
			const tempOrder = currentArea.order;
			await updateAreaTemplate({ id: currentArea.id, order: previousArea.order });
			await updateAreaTemplate({ id: previousArea.id, order: tempOrder });
			await serviceScopeStore.fetch();
		} catch (e) {
			error = e instanceof Error ? e.message : 'Failed to reorder area';
			await serviceScopeStore.fetch();
		}
	}

	async function handleMoveServiceAreaDown(areaId: string) {
		if (!selectedServiceTemplate) return;
		try {
			const areas = [...selectedServiceTemplate.areaTemplates].sort((a, b) => a.order - b.order);
			const index = areas.findIndex((a) => a.id === areaId);
			if (index === -1 || index >= areas.length - 1) return; // Already at bottom or not found
			const currentArea = areas[index];
			const nextArea = areas[index + 1];
			const tempOrder = currentArea.order;
			await updateAreaTemplate({ id: currentArea.id, order: nextArea.order });
			await updateAreaTemplate({ id: nextArea.id, order: tempOrder });
			await serviceScopeStore.fetch();
		} catch (e) {
			error = e instanceof Error ? e.message : 'Failed to reorder area';
			await serviceScopeStore.fetch();
		}
	}

	async function handleMoveServiceTaskUp(taskId: string, areaId: string) {
		if (!selectedServiceTemplate) return;
		try {
			const area = selectedServiceTemplate.areaTemplates.find((a) => a.id === areaId);
			if (!area) return;
			const tasks = [...area.taskTemplates].sort((a, b) => a.order - b.order);
			const index = tasks.findIndex((t) => t.id === taskId);
			if (index <= 0) return; // Already at top or not found
			const currentTask = tasks[index];
			const previousTask = tasks[index - 1];
			const tempOrder = currentTask.order;
			await updateTaskTemplate({ id: currentTask.id, order: previousTask.order });
			await updateTaskTemplate({ id: previousTask.id, order: tempOrder });
			await serviceScopeStore.fetch();
		} catch (e) {
			error = e instanceof Error ? e.message : 'Failed to reorder task';
			await serviceScopeStore.fetch();
		}
	}

	async function handleMoveServiceTaskDown(taskId: string, areaId: string) {
		if (!selectedServiceTemplate) return;
		try {
			const area = selectedServiceTemplate.areaTemplates.find((a) => a.id === areaId);
			if (!area) return;
			const tasks = [...area.taskTemplates].sort((a, b) => a.order - b.order);
			const index = tasks.findIndex((t) => t.id === taskId);
			if (index === -1 || index >= tasks.length - 1) return; // Already at bottom or not found
			const currentTask = tasks[index];
			const nextTask = tasks[index + 1];
			const tempOrder = currentTask.order;
			await updateTaskTemplate({ id: currentTask.id, order: nextTask.order });
			await updateTaskTemplate({ id: nextTask.id, order: tempOrder });
			await serviceScopeStore.fetch();
		} catch (e) {
			error = e instanceof Error ? e.message : 'Failed to reorder task';
			await serviceScopeStore.fetch();
		}
	}

	// CRUD Operations - Project Scope Templates
	async function handleCreateProjectTemplate() {
		if (!newTemplateName.trim()) return;
		try {
			const result = await createProjectScopeTemplate({
				name: newTemplateName.trim(),
				description: '',
				isActive: true
			});
			await projectScopeStore.fetch();
			selectedProjectTemplateId = result.id;
			newTemplateName = '';
			showNewTemplateInput = false;
		} catch (e) {
			error = e instanceof Error ? e.message : 'Failed to create template';
		}
	}

	async function handleUpdateProjectTemplate(id: string, name: string) {
		try {
			await updateProjectScopeTemplate({ id, name });
			await projectScopeStore.fetch();
			editingTemplateName = null;
		} catch (e) {
			error = e instanceof Error ? e.message : 'Failed to update template';
		}
	}

	async function handleUpdateProjectTemplateDescription(id: string, description: string) {
		try {
			await updateProjectScopeTemplate({ id, description });
			await projectScopeStore.fetch();
		} catch (e) {
			error = e instanceof Error ? e.message : 'Failed to update template description';
		}
	}

	async function handleDeleteProjectTemplate(id: string) {
		if (!confirm('Delete this template and all its categories/tasks?')) return;
		try {
			await deleteProjectScopeTemplate(id);
			await projectScopeStore.fetch();
			if (selectedProjectTemplateId === id) {
				selectedProjectTemplateId = null;
			}
		} catch (e) {
			error = e instanceof Error ? e.message : 'Failed to delete template';
		}
	}

	async function handleCreateProjectCategory(templateId: string) {
		if (!newAreaName.trim()) return;
		try {
			await createProjectAreaTemplate({
				scopeTemplateId: templateId,
				name: newAreaName.trim(),
				order: selectedProjectTemplate?.categoryTemplates.length ?? 0
			});
			await projectScopeStore.fetch();
			newAreaName = '';
			showNewAreaInput = null;
		} catch (e) {
			error = e instanceof Error ? e.message : 'Failed to create category';
		}
	}

	async function handleUpdateProjectCategory(id: string, name: string) {
		try {
			await updateProjectAreaTemplate({ id, name });
			await projectScopeStore.fetch();
			editingAreaName = null;
		} catch (e) {
			error = e instanceof Error ? e.message : 'Failed to update category';
		}
	}

	async function handleDeleteProjectCategory(id: string) {
		if (!confirm('Delete this category and all its tasks?')) return;
		try {
			await deleteProjectAreaTemplate(id);
			await projectScopeStore.fetch();
		} catch (e) {
			error = e instanceof Error ? e.message : 'Failed to delete category';
		}
	}

	async function handleCreateProjectTask(categoryId: string) {
		if (!newTaskDescription.trim()) return;
		try {
			const category = selectedProjectTemplate?.categoryTemplates.find((c) => c.id === categoryId);
			await createProjectTaskTemplate({
				areaTemplateId: categoryId,
				description: newTaskDescription.trim(),
				checklistDescription: '',
				order: category?.taskTemplates.length ?? 0,
				estimatedMinutes: null
			});
			await projectScopeStore.fetch();
			newTaskDescription = '';
			showNewTaskInput = null;
		} catch (e) {
			error = e instanceof Error ? e.message : 'Failed to create task';
		}
	}

	async function handleDeleteProjectTask(id: string) {
		if (!confirm('Delete this task?')) return;
		try {
			await deleteProjectTaskTemplate(id);
			await projectScopeStore.fetch();
		} catch (e) {
			error = e instanceof Error ? e.message : 'Failed to delete task';
		}
	}

	async function handleUpdateProjectTask(
		taskId: string,
		updates: {
			description?: string;
			checklistDescription?: string;
			estimatedMinutes?: number | null;
		}
	) {
		try {
			await updateProjectTaskTemplate({
				id: taskId,
				...updates
			});
			await projectScopeStore.fetch();
			editingTaskId = null;
		} catch (e) {
			error = e instanceof Error ? e.message : 'Failed to update task';
		}
	}

	async function handleMoveProjectCategoryUp(categoryId: string) {
		if (!selectedProjectTemplate) return;
		try {
			const categories = [...selectedProjectTemplate.categoryTemplates].sort(
				(a, b) => a.order - b.order
			);
			const index = categories.findIndex((c) => c.id === categoryId);
			if (index <= 0) return; // Already at top or not found
			const currentCategory = categories[index];
			const previousCategory = categories[index - 1];
			const tempOrder = currentCategory.order;
			await updateProjectAreaTemplate({ id: currentCategory.id, order: previousCategory.order });
			await updateProjectAreaTemplate({ id: previousCategory.id, order: tempOrder });
			await projectScopeStore.fetch();
		} catch (e) {
			error = e instanceof Error ? e.message : 'Failed to reorder category';
			await projectScopeStore.fetch();
		}
	}

	async function handleMoveProjectCategoryDown(categoryId: string) {
		if (!selectedProjectTemplate) return;
		try {
			const categories = [...selectedProjectTemplate.categoryTemplates].sort(
				(a, b) => a.order - b.order
			);
			const index = categories.findIndex((c) => c.id === categoryId);
			if (index === -1 || index >= categories.length - 1) return; // Already at bottom or not found
			const currentCategory = categories[index];
			const nextCategory = categories[index + 1];
			const tempOrder = currentCategory.order;
			await updateProjectAreaTemplate({ id: currentCategory.id, order: nextCategory.order });
			await updateProjectAreaTemplate({ id: nextCategory.id, order: tempOrder });
			await projectScopeStore.fetch();
		} catch (e) {
			error = e instanceof Error ? e.message : 'Failed to reorder category';
			await projectScopeStore.fetch();
		}
	}

	async function handleMoveProjectTaskUp(taskId: string, categoryId: string) {
		if (!selectedProjectTemplate) return;
		try {
			const category = selectedProjectTemplate.categoryTemplates.find((c) => c.id === categoryId);
			if (!category) return;
			const tasks = [...category.taskTemplates].sort((a, b) => a.order - b.order);
			const index = tasks.findIndex((t) => t.id === taskId);
			if (index <= 0) return; // Already at top or not found
			const currentTask = tasks[index];
			const previousTask = tasks[index - 1];
			const tempOrder = currentTask.order;
			await updateProjectTaskTemplate({ id: currentTask.id, order: previousTask.order });
			await updateProjectTaskTemplate({ id: previousTask.id, order: tempOrder });
			await projectScopeStore.fetch();
		} catch (e) {
			error = e instanceof Error ? e.message : 'Failed to reorder task';
			await projectScopeStore.fetch();
		}
	}

	async function handleMoveProjectTaskDown(taskId: string, categoryId: string) {
		if (!selectedProjectTemplate) return;
		try {
			const category = selectedProjectTemplate.categoryTemplates.find((c) => c.id === categoryId);
			if (!category) return;
			const tasks = [...category.taskTemplates].sort((a, b) => a.order - b.order);
			const index = tasks.findIndex((t) => t.id === taskId);
			if (index === -1 || index >= tasks.length - 1) return; // Already at bottom or not found
			const currentTask = tasks[index];
			const nextTask = tasks[index + 1];
			const tempOrder = currentTask.order;
			await updateProjectTaskTemplate({ id: currentTask.id, order: nextTask.order });
			await updateProjectTaskTemplate({ id: nextTask.id, order: tempOrder });
			await projectScopeStore.fetch();
		} catch (e) {
			error = e instanceof Error ? e.message : 'Failed to reorder task';
			await projectScopeStore.fetch();
		}
	}

	// JSON Import
	function openJsonImport() {
		showJsonImportModal = true;
		jsonImportText = '';
		jsonImportReplace = false;
		jsonImportError = '';
		jsonImportParsed = null;
	}

	function parseJsonImport() {
		try {
			jsonImportParsed = JSON.parse(jsonImportText);
			jsonImportError = '';
		} catch {
			jsonImportError = 'Invalid JSON format';
			jsonImportParsed = null;
		}
	}

	function handleJsonFileUpload(event: Event) {
		const input = event.target as HTMLInputElement;
		const file = input.files?.[0];
		if (!file) return;

		if (!file.name.endsWith('.json')) {
			jsonImportError = 'Please select a JSON file';
			return;
		}

		const reader = new FileReader();
		reader.onload = (e) => {
			jsonImportText = e.target?.result as string;
			parseJsonImport();
		};
		reader.onerror = () => {
			jsonImportError = 'Failed to read file';
		};
		reader.readAsText(file);

		// Reset input so the same file can be selected again
		input.value = '';
	}

	async function submitJsonImport() {
		if (!jsonImportParsed) return;
		try {
			if (activeTab === 'service') {
				await createScopeTemplateFromJson(jsonImportParsed, jsonImportReplace);
				await serviceScopeStore.fetch();
			} else {
				await createProjectScopeTemplateFromJson(jsonImportParsed, jsonImportReplace);
				await projectScopeStore.fetch();
			}
			showJsonImportModal = false;
		} catch (e) {
			jsonImportError = e instanceof Error ? e.message : 'Failed to import template';
		}
	}

	// JSON Export
	function openJsonExport() {
		const template =
			activeTab === 'service' ? selectedServiceTemplate : selectedProjectTemplate;
		if (!template) return;

		jsonExportCopied = false;

		if (activeTab === 'service' && selectedServiceTemplate) {
			// Export service scope template
			const exportData = {
				name: selectedServiceTemplate.name,
				description: selectedServiceTemplate.description || '',
				is_active: selectedServiceTemplate.isActive,
				areas: selectedServiceTemplate.areaTemplates.map((area) => ({
					name: area.name,
					order: area.order,
					tasks: area.taskTemplates.map((task) => ({
						description: task.description,
						checklist_description: task.checklistDescription || '',
						frequency: (task.frequency || 'weekly').toUpperCase(),
						is_conditional: false, // Always false as it's deprecated
						order: task.order,
						estimated_minutes: task.estimatedMinutes
					}))
				}))
			};
			jsonExportText = JSON.stringify(exportData, null, 2);
		} else if (activeTab === 'project' && selectedProjectTemplate) {
			// Export project scope template
			const exportData = {
				name: selectedProjectTemplate.name,
				description: selectedProjectTemplate.description || '',
				is_active: selectedProjectTemplate.isActive,
				categories: selectedProjectTemplate.categoryTemplates.map((category) => ({
					name: category.name,
					order: category.order,
					tasks: category.taskTemplates.map((task) => ({
						description: task.description,
						checklist_description: task.checklistDescription || '',
						order: task.order,
						estimated_minutes: task.estimatedMinutes
					}))
				}))
			};
			jsonExportText = JSON.stringify(exportData, null, 2);
		}

		showJsonExportModal = true;
	}

	async function copyJsonExport() {
		try {
			await navigator.clipboard.writeText(jsonExportText);
			jsonExportCopied = true;
			setTimeout(() => (jsonExportCopied = false), 2000);
		} catch {
			// Fallback for older browsers
			const textarea = document.createElement('textarea');
			textarea.value = jsonExportText;
			document.body.appendChild(textarea);
			textarea.select();
			document.execCommand('copy');
			document.body.removeChild(textarea);
			jsonExportCopied = true;
			setTimeout(() => (jsonExportCopied = false), 2000);
		}
	}

	function downloadJsonExport() {
		const template =
			activeTab === 'service' ? selectedServiceTemplate : selectedProjectTemplate;
		if (!template) return;

		const blob = new Blob([jsonExportText], { type: 'application/json' });
		const url = URL.createObjectURL(blob);
		const a = document.createElement('a');
		a.href = url;
		a.download = `${template.name.toLowerCase().replace(/\s+/g, '-')}-scope-template.json`;
		document.body.appendChild(a);
		a.click();
		document.body.removeChild(a);
		URL.revokeObjectURL(url);
	}
</script>

<svelte:window bind:innerWidth={windowWidth} />

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

<div class="flex h-[calc(100vh-7.5rem)] flex-col overflow-hidden bg-theme">
	<!-- Header -->
	<div class="border-b border-theme bg-theme-card px-4 py-4 shadow-sm md:px-6">
		<div class="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
			<div class="flex items-center gap-4">
				<a
					href="/admin"
					class="rounded-lg p-1 text-theme-muted hover:bg-black/5 hover:text-theme dark:hover:bg-white/10"
					aria-label="Go back"
				>
					<svg class="h-5 w-5" style="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>
				</a>
				<div>
					<h1 class="text-xl font-bold text-accent3-600 dark:text-accent3-400">Scope Templates</h1>
					<p class="text-sm text-theme-secondary">Manage service and project scope templates</p>
				</div>
			</div>

			<!-- Desktop Tab Toggle -->
			<div class="hidden items-center gap-4 md:flex">
				<div class="flex items-center rounded-lg border border-theme bg-theme p-1">
					<button
						onclick={() => (activeTab = 'service')}
						class="flex items-center gap-1.5 rounded-md px-4 py-2 text-sm font-medium transition-colors {activeTab ===
						'service'
							? 'bg-secondary-500/10 text-secondary-600 shadow-sm dark:text-secondary-400'
							: 'text-theme-muted hover:text-theme'}"
					>
						<svg class="h-4 w-4" style="fill: none" viewBox="0 0 24 24" stroke="currentColor">
							<path
								stroke-linecap="round"
								stroke-linejoin="round"
								stroke-width="2"
								d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4"
							/>
						</svg>
						Service Scopes
					</button>
					<button
						onclick={() => (activeTab = 'project')}
						class="flex items-center gap-1.5 rounded-md px-4 py-2 text-sm font-medium transition-colors {activeTab ===
						'project'
							? 'bg-accent-500/10 text-accent-600 shadow-sm dark:text-accent-400'
							: 'text-theme-muted hover:text-theme'}"
					>
						<svg class="h-4 w-4" style="fill: none" viewBox="0 0 24 24" stroke="currentColor">
							<path
								stroke-linecap="round"
								stroke-linejoin="round"
								stroke-width="2"
								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>
						Project Scopes
					</button>
				</div>

				<button
					onclick={openJsonImport}
					class="flex items-center gap-2 rounded-lg border border-theme interactive bg-theme px-3 py-2 text-sm font-medium text-theme"
				>
					<svg class="h-4 w-4" style="fill: none" viewBox="0 0 24 24" stroke="currentColor">
						<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>
					Import JSON
				</button>
				<button
					onclick={openJsonExport}
					disabled={activeTab === 'service' ? !selectedServiceTemplateId : !selectedProjectTemplateId}
					class="flex items-center gap-2 rounded-lg border border-theme interactive bg-theme px-3 py-2 text-sm font-medium text-theme disabled:cursor-not-allowed disabled:opacity-50"
				>
					<svg class="h-4 w-4" style="fill: none" viewBox="0 0 24 24" stroke="currentColor">
						<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>
					Export JSON
				</button>
			</div>
		</div>
	</div>

	<!-- Error Alert -->
	{#if error}
		<div class="mx-4 mt-4 alert-error">
			{error}
			<button onclick={() => (error = '')} class="ml-2 font-medium underline">Dismiss</button>
		</div>
	{/if}

	<!-- Mobile Tab Toggle -->
	<div class="flex items-center justify-center gap-3 border-b border-theme py-3 md:hidden">
		<button
			onclick={previousTab}
			aria-label="Previous tab"
			class="rounded-lg p-1 text-theme-muted transition-colors hover:bg-black/5 hover:text-theme dark:hover:bg-white/10"
		>
			<svg class="h-5 w-5" style="fill: none" viewBox="0 0 24 24" stroke="currentColor">
				<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
			</svg>
		</button>
		<div class="flex items-center gap-2">
			<span
				class="h-3 w-3 rounded-full {activeTab === 'service'
					? 'bg-secondary-500'
					: 'bg-accent-500'}"
			></span>
			<span
				class="text-lg font-semibold {activeTab === 'service'
					? 'text-secondary-600 dark:text-secondary-400'
					: 'text-accent-600 dark:text-accent-400'}"
			>
				{activeTab === 'service' ? 'Service Scopes' : 'Project Scopes'}
			</span>
			<span
				class="rounded-full px-2 py-0.5 text-xs font-semibold {activeTab === 'service'
					? 'bg-secondary-500 text-white'
					: 'bg-accent-500 text-white'}"
			>
				{activeTab === 'service' ? serviceTemplates.length : projectTemplates.length}
			</span>
		</div>
		<button
			onclick={nextTab}
			aria-label="Next tab"
			class="rounded-lg p-1 text-theme-muted transition-colors hover:bg-black/5 hover:text-theme dark:hover:bg-white/10"
		>
			<svg class="h-5 w-5" style="fill: none" viewBox="0 0 24 24" stroke="currentColor">
				<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
			</svg>
		</button>
	</div>

	<!-- Mobile Actions -->
	<div class="flex items-center justify-between border-b border-theme px-4 py-2 md:hidden">
		{#if mobileView === 'editor' && (selectedServiceTemplateId || selectedProjectTemplateId)}
			<button
				onclick={() => (mobileView = 'list')}
				class="flex items-center gap-1 text-sm font-medium text-secondary-600 dark:text-secondary-400"
			>
				<svg class="h-4 w-4" style="fill: none" viewBox="0 0 24 24" stroke="currentColor">
					<path
						stroke-linecap="round"
						stroke-linejoin="round"
						stroke-width="2"
						d="M15 19l-7-7 7-7"
					/>
				</svg>
				Templates
			</button>
		{:else}
			<span class="text-sm text-theme-muted">Select a template</span>
		{/if}
		<div class="flex items-center gap-2">
			<button
				onclick={openJsonImport}
				class="flex items-center gap-1 rounded-lg border border-theme px-2 py-1 text-xs font-medium text-theme"
			>
				<svg class="h-3 w-3" style="fill: none" viewBox="0 0 24 24" stroke="currentColor">
					<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>
				Import
			</button>
			<button
				onclick={openJsonExport}
				disabled={activeTab === 'service' ? !selectedServiceTemplateId : !selectedProjectTemplateId}
				class="flex items-center gap-1 rounded-lg border border-theme px-2 py-1 text-xs font-medium text-theme disabled:cursor-not-allowed disabled:opacity-50"
			>
				<svg class="h-3 w-3" style="fill: none" viewBox="0 0 24 24" stroke="currentColor">
					<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>
				Export
			</button>
		</div>
	</div>

	<!-- Main Content -->
	{#if isLoading}
		<div class="flex flex-1 items-center justify-center">
			<div class="flex flex-col items-center gap-4">
				<svg
					class="h-12 w-12 animate-spin text-secondary-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>
				<span class="text-theme-secondary">Loading templates...</span>
			</div>
		</div>
	{:else}
		<!-- Desktop: Two-pane layout -->
		<div class="hidden flex-1 overflow-hidden md:flex">
			<!-- Template List (Left Pane) -->
			<div class="flex w-56 shrink-0 flex-col border-r border-theme bg-theme-card lg:w-72">
				<div class="flex items-center justify-between border-b border-theme px-4 py-3">
					<h2 class="font-semibold text-theme">
						{activeTab === 'service' ? 'Service Templates' : 'Project Templates'}
					</h2>
					<button
						onclick={() => (showNewTemplateInput = true)}
						class="rounded-lg bg-secondary-500 p-1.5 text-white transition-colors hover:bg-secondary-600"
						aria-label="Add template"
					>
						<svg class="h-4 w-4" style="fill: none" viewBox="0 0 24 24" stroke="currentColor">
							<path
								stroke-linecap="round"
								stroke-linejoin="round"
								stroke-width="2"
								d="M12 6v6m0 0v6m0-6h6m-6 0H6"
							/>
						</svg>
					</button>
				</div>

				<TemplateList
					templates={activeTab === 'service' ? serviceTemplates : projectTemplates}
					selectedId={activeTab === 'service'
						? selectedServiceTemplateId
						: selectedProjectTemplateId}
					variant={activeTab}
					showNewInput={showNewTemplateInput}
					newName={newTemplateName}
					onSelect={(id) =>
						activeTab === 'service' ? selectServiceTemplate(id) : selectProjectTemplate(id)}
					onCreate={() =>
						activeTab === 'service' ? handleCreateServiceTemplate() : handleCreateProjectTemplate()}
					onShowNewInput={(show) => (showNewTemplateInput = show)}
					onNewNameChange={(name) => (newTemplateName = name)}
				/>
			</div>

			<!-- Template Editor (Right Pane) -->
			<div class="flex flex-1 flex-col overflow-hidden bg-theme">
				{#if activeTab === 'service' && selectedServiceTemplate}
					<TemplateEditor
						template={selectedServiceTemplate}
						variant="service"
						expandedAreas={expandedServiceAreas}
						{editingTemplateName}
						{editingAreaName}
						{editingTaskId}
						{showNewAreaInput}
						{showNewTaskInput}
						{newAreaName}
						{newTaskDescription}
						onToggleArea={toggleServiceArea}
						onStartEditTemplateName={() => (editingTemplateName = selectedServiceTemplate.id)}
						onCancelEditTemplateName={() => (editingTemplateName = null)}
						onUpdateTemplateName={(name) =>
							handleUpdateServiceTemplate(selectedServiceTemplate.id, name)}
						onUpdateTemplateDescription={(description) =>
							handleUpdateServiceTemplateDescription(selectedServiceTemplate.id, description)}
						onDeleteTemplate={() => handleDeleteServiceTemplate(selectedServiceTemplate.id)}
						onStartEditAreaName={(areaId) => (editingAreaName = areaId)}
						onCancelEditAreaName={() => (editingAreaName = null)}
						onUpdateAreaName={(areaId, name) => handleUpdateServiceArea(areaId, name)}
						onDeleteArea={handleDeleteServiceArea}
						onShowNewArea={() => (showNewAreaInput = selectedServiceTemplate.id)}
						onHideNewArea={() => (showNewAreaInput = null)}
						onNewAreaNameChange={(name) => (newAreaName = name)}
						onCreateArea={() => handleCreateServiceArea(selectedServiceTemplate.id)}
						onShowNewTask={(areaId) => (showNewTaskInput = areaId)}
						onHideNewTask={() => (showNewTaskInput = null)}
						onNewTaskDescriptionChange={(desc) => (newTaskDescription = desc)}
						onCreateTask={handleCreateServiceTask}
						onStartEditTask={(taskId) => (editingTaskId = taskId)}
						onCancelEditTask={() => (editingTaskId = null)}
						onUpdateTask={handleUpdateServiceTask}
						onDeleteTask={handleDeleteServiceTask}
						onMoveAreaUp={handleMoveServiceAreaUp}
						onMoveAreaDown={handleMoveServiceAreaDown}
						onMoveTaskUp={handleMoveServiceTaskUp}
						onMoveTaskDown={handleMoveServiceTaskDown}
					/>
				{:else if activeTab === 'project' && selectedProjectTemplate}
					<TemplateEditor
						template={selectedProjectTemplate}
						variant="project"
						expandedAreas={expandedProjectCategories}
						{editingTemplateName}
						{editingAreaName}
						{editingTaskId}
						{showNewAreaInput}
						{showNewTaskInput}
						{newAreaName}
						{newTaskDescription}
						onToggleArea={toggleProjectCategory}
						onStartEditTemplateName={() => (editingTemplateName = selectedProjectTemplate.id)}
						onCancelEditTemplateName={() => (editingTemplateName = null)}
						onUpdateTemplateName={(name) =>
							handleUpdateProjectTemplate(selectedProjectTemplate.id, name)}
						onUpdateTemplateDescription={(description) =>
							handleUpdateProjectTemplateDescription(selectedProjectTemplate.id, description)}
						onDeleteTemplate={() => handleDeleteProjectTemplate(selectedProjectTemplate.id)}
						onStartEditAreaName={(areaId) => (editingAreaName = areaId)}
						onCancelEditAreaName={() => (editingAreaName = null)}
						onUpdateAreaName={(areaId, name) => handleUpdateProjectCategory(areaId, name)}
						onDeleteArea={handleDeleteProjectCategory}
						onShowNewArea={() => (showNewAreaInput = selectedProjectTemplate.id)}
						onHideNewArea={() => (showNewAreaInput = null)}
						onNewAreaNameChange={(name) => (newAreaName = name)}
						onCreateArea={() => handleCreateProjectCategory(selectedProjectTemplate.id)}
						onShowNewTask={(areaId) => (showNewTaskInput = areaId)}
						onHideNewTask={() => (showNewTaskInput = null)}
						onNewTaskDescriptionChange={(desc) => (newTaskDescription = desc)}
						onCreateTask={handleCreateProjectTask}
						onStartEditTask={(taskId) => (editingTaskId = taskId)}
						onCancelEditTask={() => (editingTaskId = null)}
						onUpdateTask={handleUpdateProjectTask}
						onDeleteTask={handleDeleteProjectTask}
						onMoveAreaUp={handleMoveProjectCategoryUp}
						onMoveAreaDown={handleMoveProjectCategoryDown}
						onMoveTaskUp={handleMoveProjectTaskUp}
						onMoveTaskDown={handleMoveProjectTaskDown}
					/>
				{:else}
					<!-- No template selected -->
					<div class="flex flex-1 items-center justify-center">
						<div class="text-center text-theme-muted">
							<svg
								class="mx-auto mb-4 h-16 w-16"
								style="fill: none"
								viewBox="0 0 24 24"
								stroke="currentColor"
							>
								<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>
							<p class="text-lg font-medium">Select a template</p>
							<p class="mt-1 text-sm">
								Choose a template from the list, or click + to create a new one
							</p>
						</div>
					</div>
				{/if}
			</div>
		</div>

		<!-- Mobile: Single view switching -->
		<div class="flex flex-1 flex-col overflow-hidden md:hidden">
			{#if mobileView === 'list'}
				<!-- Mobile Template List -->
				<div class="flex-1 overflow-y-auto p-4">
					<!-- New Template Input (Mobile) -->
					{#if showNewTemplateInput}
						<div
							class="mb-4 rounded-lg border border-theme bg-theme-card p-3"
							transition:slide={{ duration: 150 }}
						>
							<input
								type="text"
								bind:value={newTemplateName}
								placeholder="Template name..."
								class="placeholder-theme-muted w-full rounded-lg border border-theme bg-theme px-3 py-2 text-sm text-theme focus:border-secondary-500 focus:outline-none"
							/>
							<div class="mt-2 flex justify-end gap-2">
								<button
									onclick={() => {
										showNewTemplateInput = false;
										newTemplateName = '';
									}}
									class="rounded px-3 py-1 text-sm text-theme-muted hover:text-theme"
								>
									Cancel
								</button>
								<button
									onclick={() =>
										activeTab === 'service'
											? handleCreateServiceTemplate()
											: handleCreateProjectTemplate()}
									class="rounded bg-secondary-500 px-3 py-1 text-sm text-white hover:bg-secondary-600"
								>
									Create
								</button>
							</div>
						</div>
					{:else}
						<button
							onclick={() => (showNewTemplateInput = true)}
							class="mb-4 flex w-full items-center justify-center gap-2 rounded-lg border border-dashed border-theme bg-theme-card p-3 text-sm text-theme-muted"
						>
							<svg class="h-4 w-4" style="fill: none" viewBox="0 0 24 24" stroke="currentColor">
								<path
									stroke-linecap="round"
									stroke-linejoin="round"
									stroke-width="2"
									d="M12 6v6m0 0v6m0-6h6m-6 0H6"
								/>
							</svg>
							New Template
						</button>
					{/if}

					{#if activeTab === 'service'}
						{#each serviceTemplates as template (template.id)}
							<button
								onclick={() => selectServiceTemplate(template.id)}
								class="mb-2 w-full rounded-lg border border-l-4 border-theme border-l-secondary-500/50 bg-theme-card p-4 text-left transition-colors hover:border-secondary-500"
							>
								<span class="flex items-center justify-between">
									<span class="font-medium text-theme">{template.name}</span>
									<svg
										class="h-4 w-4 text-secondary-500"
										style="fill: none"
										viewBox="0 0 24 24"
										stroke="currentColor"
									>
										<path
											stroke-linecap="round"
											stroke-linejoin="round"
											stroke-width="2"
											d="M9 5l7 7-7 7"
										/>
									</svg>
								</span>
								<span class="mt-1 block text-xs text-theme-muted">
									{template.areaTemplates.length} areas,
									{template.areaTemplates.reduce((sum, a) => sum + a.taskTemplates.length, 0)} tasks
								</span>
							</button>
						{/each}
						{#if serviceTemplates.length === 0 && !showNewTemplateInput}
							<div class="py-8 text-center text-theme-muted">
								<p>No service templates yet</p>
							</div>
						{/if}
					{:else}
						{#each projectTemplates as template (template.id)}
							<button
								onclick={() => selectProjectTemplate(template.id)}
								class="mb-2 w-full rounded-lg border border-l-4 border-theme border-l-accent-500/50 bg-theme-card p-4 text-left transition-colors hover:border-accent-500"
							>
								<span class="flex items-center justify-between">
									<span class="font-medium text-theme">{template.name}</span>
									<svg
										class="h-4 w-4 text-accent-500"
										style="fill: none"
										viewBox="0 0 24 24"
										stroke="currentColor"
									>
										<path
											stroke-linecap="round"
											stroke-linejoin="round"
											stroke-width="2"
											d="M9 5l7 7-7 7"
										/>
									</svg>
								</span>
								<span class="mt-1 block text-xs text-theme-muted">
									{template.categoryTemplates.length} categories,
									{template.categoryTemplates.reduce((sum, c) => sum + c.taskTemplates.length, 0)} tasks
								</span>
							</button>
						{/each}
						{#if projectTemplates.length === 0 && !showNewTemplateInput}
							<div class="py-8 text-center text-theme-muted">
								<p>No project templates yet</p>
							</div>
						{/if}
					{/if}
				</div>
			{:else}
				<!-- Mobile Template Editor -->
				<div class="flex-1 overflow-y-auto p-4">
					{#if activeTab === 'service' && selectedServiceTemplate}
						<TemplateEditor
							template={selectedServiceTemplate}
							variant="service"
							expandedAreas={expandedServiceAreas}
							{editingTemplateName}
							{editingAreaName}
							{editingTaskId}
							{showNewAreaInput}
							{showNewTaskInput}
							{newAreaName}
							{newTaskDescription}
							onToggleArea={toggleServiceArea}
							onStartEditTemplateName={() => (editingTemplateName = selectedServiceTemplate.id)}
							onCancelEditTemplateName={() => (editingTemplateName = null)}
							onUpdateTemplateName={(name) =>
								handleUpdateServiceTemplate(selectedServiceTemplate.id, name)}
							onUpdateTemplateDescription={(description) =>
								handleUpdateServiceTemplateDescription(selectedServiceTemplate.id, description)}
							onDeleteTemplate={() => handleDeleteServiceTemplate(selectedServiceTemplate.id)}
							onStartEditAreaName={(areaId) => (editingAreaName = areaId)}
							onCancelEditAreaName={() => (editingAreaName = null)}
							onUpdateAreaName={(areaId, name) => handleUpdateServiceArea(areaId, name)}
							onDeleteArea={handleDeleteServiceArea}
							onShowNewArea={() => (showNewAreaInput = selectedServiceTemplate.id)}
							onHideNewArea={() => (showNewAreaInput = null)}
							onNewAreaNameChange={(name) => (newAreaName = name)}
							onCreateArea={() => handleCreateServiceArea(selectedServiceTemplate.id)}
							onShowNewTask={(areaId) => (showNewTaskInput = areaId)}
							onHideNewTask={() => (showNewTaskInput = null)}
							onNewTaskDescriptionChange={(desc) => (newTaskDescription = desc)}
							onCreateTask={handleCreateServiceTask}
							onStartEditTask={(taskId) => (editingTaskId = taskId)}
							onCancelEditTask={() => (editingTaskId = null)}
							onUpdateTask={handleUpdateServiceTask}
							onDeleteTask={handleDeleteServiceTask}
							onMoveAreaUp={handleMoveServiceAreaUp}
							onMoveAreaDown={handleMoveServiceAreaDown}
							onMoveTaskUp={handleMoveServiceTaskUp}
							onMoveTaskDown={handleMoveServiceTaskDown}
						/>
					{:else if activeTab === 'project' && selectedProjectTemplate}
						<TemplateEditor
							template={selectedProjectTemplate}
							variant="project"
							expandedAreas={expandedProjectCategories}
							{editingTemplateName}
							{editingAreaName}
							{editingTaskId}
							{showNewAreaInput}
							{showNewTaskInput}
							{newAreaName}
							{newTaskDescription}
							onToggleArea={toggleProjectCategory}
							onStartEditTemplateName={() => (editingTemplateName = selectedProjectTemplate.id)}
							onCancelEditTemplateName={() => (editingTemplateName = null)}
							onUpdateTemplateName={(name) =>
								handleUpdateProjectTemplate(selectedProjectTemplate.id, name)}
							onUpdateTemplateDescription={(description) =>
								handleUpdateProjectTemplateDescription(selectedProjectTemplate.id, description)}
							onDeleteTemplate={() => handleDeleteProjectTemplate(selectedProjectTemplate.id)}
							onStartEditAreaName={(areaId) => (editingAreaName = areaId)}
							onCancelEditAreaName={() => (editingAreaName = null)}
							onUpdateAreaName={(areaId, name) => handleUpdateProjectCategory(areaId, name)}
							onDeleteArea={handleDeleteProjectCategory}
							onShowNewArea={() => (showNewAreaInput = selectedProjectTemplate.id)}
							onHideNewArea={() => (showNewAreaInput = null)}
							onNewAreaNameChange={(name) => (newAreaName = name)}
							onCreateArea={() => handleCreateProjectCategory(selectedProjectTemplate.id)}
							onShowNewTask={(areaId) => (showNewTaskInput = areaId)}
							onHideNewTask={() => (showNewTaskInput = null)}
							onNewTaskDescriptionChange={(desc) => (newTaskDescription = desc)}
							onCreateTask={handleCreateProjectTask}
							onStartEditTask={(taskId) => (editingTaskId = taskId)}
							onCancelEditTask={() => (editingTaskId = null)}
							onUpdateTask={handleUpdateProjectTask}
							onDeleteTask={handleDeleteProjectTask}
							onMoveAreaUp={handleMoveProjectCategoryUp}
							onMoveAreaDown={handleMoveProjectCategoryDown}
							onMoveTaskUp={handleMoveProjectTaskUp}
							onMoveTaskDown={handleMoveProjectTaskDown}
						/>
					{/if}
				</div>
			{/if}
		</div>
	{/if}
</div>

<!-- JSON Import Modal --><!-- JSON Import Modal -->
{#if showJsonImportModal}
	<!-- svelte-ignore a11y_click_events_have_key_events -->
	<!-- svelte-ignore a11y_interactive_supports_focus -->
	<div
		role="dialog"
		aria-modal="true"
		aria-labelledby="json-import-title"
		class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4"
		onclick={() => (showJsonImportModal = false)}
		onkeydown={(e) => {
			if (e.key === 'Escape') showJsonImportModal = false;
		}}
	>
		<!-- svelte-ignore a11y_click_events_have_key_events -->
		<!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
		<div
			role="document"
			class="w-full max-w-2xl rounded-xl bg-theme-card shadow-xl"
			onclick={(e) => e.stopPropagation()}
		>
			<div class="flex items-center justify-between border-b border-theme px-6 py-4">
				<h3 id="json-import-title" class="text-lg font-semibold text-theme">
					Import {activeTab === 'service' ? 'Service' : 'Project'} Scope Template
				</h3>
				<button
					onclick={() => (showJsonImportModal = false)}
					class="rounded p-1 text-theme-muted hover:text-theme"
					aria-label="Close"
				>
					<svg class="h-5 w-5" style="fill: none" viewBox="0 0 24 24" stroke="currentColor">
						<path
							stroke-linecap="round"
							stroke-linejoin="round"
							stroke-width="2"
							d="M6 18L18 6M6 6l12 12"
						/>
					</svg>
				</button>
			</div>

			<div class="p-6">
				<!-- File Upload -->
				<div class="mb-4">
					<label
						class="flex cursor-pointer flex-col items-center justify-center rounded-lg border-2 border-dashed border-theme bg-theme px-4 py-6 transition-colors hover:border-secondary-500 hover:bg-black/5 dark:hover:bg-white/5"
					>
						<svg class="mb-2 h-8 w-8 text-theme-muted" style="fill: none" viewBox="0 0 24 24" stroke="currentColor">
							<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 class="text-sm font-medium text-theme">Upload JSON file</span>
						<span class="mt-1 text-xs text-theme-muted">or paste JSON below</span>
						<input
							type="file"
							accept=".json,application/json"
							onchange={handleJsonFileUpload}
							class="hidden"
						/>
					</label>
				</div>

				<textarea
					bind:value={jsonImportText}
					oninput={parseJsonImport}
					placeholder="Paste JSON here..."
					class="placeholder-theme-muted h-48 w-full rounded-lg border border-theme bg-theme p-3 font-mono text-sm text-theme focus:border-secondary-500 focus:outline-none"
				></textarea>

				{#if jsonImportError}
					<div class="mt-2 text-sm text-danger">{jsonImportError}</div>
				{/if}

				{#if jsonImportParsed}
					<div class="mt-4 success-box">
						<div class="success-box-title">
							<svg class="h-4 w-4" style="fill: none" viewBox="0 0 24 24" stroke="currentColor">
								<path
									stroke-linecap="round"
									stroke-linejoin="round"
									stroke-width="2"
									d="M5 13l4 4L19 7"
								/>
							</svg>
							Valid JSON
						</div>
						<div class="success-box-text">
							Template: {jsonImportParsed.name ?? 'Unnamed'}
							{#if activeTab === 'service' && jsonImportParsed.areas}
								• {jsonImportParsed.areas.length} areas
							{:else if activeTab === 'project' && jsonImportParsed.categories}
								• {jsonImportParsed.categories.length} categories
							{/if}
						</div>
					</div>
				{/if}

				<div class="mt-4">
					<label class="flex items-center gap-2 text-sm text-theme">
						<input type="checkbox" bind:checked={jsonImportReplace} class="rounded border-theme" />
						Replace existing template with same name
					</label>
				</div>
			</div>

			<div class="flex justify-end gap-3 border-t border-theme px-6 py-4">
				<button
					onclick={() => (showJsonImportModal = false)}
					class="rounded-lg border border-theme interactive px-4 py-2 text-sm font-medium text-theme"
				>
					Cancel
				</button>
				<button
					onclick={submitJsonImport}
					disabled={!jsonImportParsed}
					class="rounded-lg bg-secondary-500 px-4 py-2 text-sm font-medium text-white hover:bg-secondary-600 disabled:opacity-50"
				>
					Import
				</button>
			</div>
		</div>
	</div>
{/if}

<!-- JSON Export Modal -->
{#if showJsonExportModal}
	<!-- svelte-ignore a11y_click_events_have_key_events -->
	<!-- svelte-ignore a11y_interactive_supports_focus -->
	<div
		role="dialog"
		aria-modal="true"
		aria-labelledby="json-export-title"
		class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4"
		onclick={() => (showJsonExportModal = false)}
		onkeydown={(e) => {
			if (e.key === 'Escape') showJsonExportModal = false;
		}}
	>
		<!-- svelte-ignore a11y_click_events_have_key_events -->
		<!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
		<div
			role="document"
			class="flex max-h-[90vh] w-full max-w-3xl flex-col rounded-xl bg-theme-card shadow-xl"
			onclick={(e) => e.stopPropagation()}
		>
			<div class="flex items-center justify-between border-b border-theme px-6 py-4">
				<h3 id="json-export-title" class="text-lg font-semibold text-theme">
					Export {activeTab === 'service' ? 'Service' : 'Project'} Scope Template
				</h3>
				<button
					onclick={() => (showJsonExportModal = false)}
					class="rounded p-1 text-theme-muted hover:text-theme"
					aria-label="Close"
				>
					<svg class="h-5 w-5" style="fill: none" viewBox="0 0 24 24" stroke="currentColor">
						<path
							stroke-linecap="round"
							stroke-linejoin="round"
							stroke-width="2"
							d="M6 18L18 6M6 6l12 12"
						/>
					</svg>
				</button>
			</div>

			<div class="flex-1 overflow-y-auto p-6">
				<div class="relative">
					<pre
						class="max-h-64 overflow-auto rounded-lg border border-theme bg-theme p-3 font-mono text-sm text-theme">{jsonExportText}</pre>
					<button
						onclick={copyJsonExport}
						class="absolute right-2 top-2 rounded-lg border border-theme bg-theme-card px-2 py-1 text-xs font-medium text-theme hover:bg-black/5 dark:hover:bg-white/10"
					>
						{jsonExportCopied ? 'Copied!' : 'Copy'}
					</button>
				</div>

				<!-- JSON Format Documentation -->
				<details class="mt-4">
					<summary class="cursor-pointer text-sm font-medium text-theme hover:text-secondary-600 dark:hover:text-secondary-400">
						JSON Format Reference
					</summary>
					<div class="mt-3 rounded-lg border border-theme bg-theme p-4 text-sm text-theme-secondary">
						{#if activeTab === 'service'}
							<p class="mb-3 font-medium text-theme">Service Scope Template Format:</p>
							<pre class="overflow-x-auto rounded bg-black/5 p-3 text-xs dark:bg-white/5">{`{
  "name": "Template Name",
  "description": "Optional description",
  "is_active": true,
  "areas": [
    {
      "name": "Area Name",
      "order": 1,
      "tasks": [
        {
          "description": "Task description (detailed)",
          "checklist_description": "Short checklist text",
          "frequency": "DAILY|WEEKLY|MONTHLY|QUARTERLY|TRIANNUAL|ANNUAL|AS_NEEDED",
          "is_conditional": false,
          "order": 1,
          "estimated_minutes": null
        }
      ]
    }
  ]
}`}</pre>
							<div class="mt-3 space-y-1 text-xs">
								<p><strong>Note:</strong> <code>is_conditional</code> is deprecated and should always be <code>false</code>.</p>
								<p><strong>Frequency values:</strong> DAILY, WEEKLY, MONTHLY, QUARTERLY, TRIANNUAL, ANNUAL, AS_NEEDED</p>
							</div>
						{:else}
							<p class="mb-3 font-medium text-theme">Project Scope Template Format:</p>
							<pre class="overflow-x-auto rounded bg-black/5 p-3 text-xs dark:bg-white/5">{`{
  "name": "Template Name",
  "description": "Optional description",
  "is_active": true,
  "categories": [
    {
      "name": "Category Name",
      "order": 10,
      "tasks": [
        {
          "description": "Task description (detailed)",
          "checklist_description": "Short checklist text",
          "order": 10,
          "estimated_minutes": null
        }
      ]
    }
  ]
}`}</pre>
							<div class="mt-3 space-y-1 text-xs">
								<p><strong>Note:</strong> Project scopes use <code>categories</code> instead of <code>areas</code>, and tasks do not have <code>frequency</code> or <code>is_conditional</code> fields.</p>
							</div>
						{/if}
					</div>
				</details>
			</div>

			<div class="flex justify-end gap-3 border-t border-theme px-6 py-4">
				<button
					onclick={() => (showJsonExportModal = false)}
					class="rounded-lg border border-theme interactive px-4 py-2 text-sm font-medium text-theme"
				>
					Close
				</button>
				<button
					onclick={downloadJsonExport}
					class="flex items-center gap-2 rounded-lg bg-secondary-500 px-4 py-2 text-sm font-medium text-white hover:bg-secondary-600"
				>
					<svg class="h-4 w-4" style="fill: none" viewBox="0 0 24 24" stroke="currentColor">
						<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>
					Download
				</button>
			</div>
		</div>
	</div>
{/if}
