<script lang="ts">
	import type { PageData } from './$types';
	import { invalidateAll } from '$app/navigation';
	import { ContentContainer } from '$lib/components/layout';
	import { PageHeader, SectionHeader } from '$lib/components/admin';
	import { DeleteModal, ScheduleListModal, ScopeListModal } from '$lib/components/modals';
	import { FormDrawer } from '$lib/components/drawers';
	import { AreaForm, LocationForm, ScheduleForm, ScopeForm, TaskForm } from '$lib/components/forms';
	import { formatDate } from '$lib/utils/date';
	import { client } from '$lib/graphql/client';
	import {
		DELETE_SCHEDULE,
		DELETE_SERVICE_SCOPE,
		DELETE_SCOPE_AREA,
		DELETE_SCOPE_TASK,
		UPDATE_SCOPE_AREA,
		UPDATE_SCOPE_TASK
	} from '$lib/graphql/mutations/location';

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

	let account = $derived(data.account);
	let location = $derived(data.location);

	// If there's only one location and it has no name, call it "Primary Service Address"
	let locationDisplayName = $derived(
		location.name ||
			(account.addresses.length === 1 ? 'Primary Service Address' : 'Service Location')
	);

	// Check if this is a project-only service (hides Schedule and Scope sections)
	let isProjectOnly = $derived(
		location.notes?.toLowerCase().includes('project service only') ?? false
	);

	// Get active labor rate
	let activeLabor = $derived(location.labor?.find((l) => l.isActive) ?? null);

	// Get active schedule
	let activeSchedule = $derived(location.schedules?.find((s) => s.isActive) ?? null);

	// Compute past and future schedules for history/future modals
	let today = $derived(new Date().toISOString().split('T')[0]);
	let pastSchedules = $derived(
		(location.schedules ?? [])
			.filter((s) => !s.isActive && s.endDate && s.endDate < today)
			.sort((a, b) => (b.endDate ?? '').localeCompare(a.endDate ?? ''))
	);
	let futureSchedules = $derived(
		(location.schedules ?? [])
			.filter((s) => !s.isActive && s.startDate && s.startDate > today)
			.sort((a, b) => (a.startDate ?? '').localeCompare(b.startDate ?? ''))
	);
	let hasPastSchedules = $derived(pastSchedules.length > 0);
	let hasFutureSchedules = $derived(futureSchedules.length > 0);

	// Schedule history/future modal state
	let scheduleModalOpen = $state(false);
	let scheduleModalType = $state<'past' | 'future'>('past');

	function openScheduleModal(type: 'past' | 'future') {
		scheduleModalType = type;
		scheduleModalOpen = true;
	}

	function closeScheduleModal() {
		scheduleModalOpen = false;
	}

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

	// Get inactive (previous) scopes
	let inactiveScopes = $derived((location.scopes ?? []).filter((s) => !s.isActive));
	let hasInactiveScopes = $derived(inactiveScopes.length > 0);

	// Scope history modal state
	let scopeModalOpen = $state(false);

	function openScopeModal() {
		scopeModalOpen = true;
	}

	function closeScopeModal() {
		scopeModalOpen = false;
	}

	function formatCurrency(amount: string): string {
		return new Intl.NumberFormat('en-US', {
			style: 'currency',
			currency: 'USD'
		}).format(parseFloat(amount));
	}

	function isScheduledDay(day: string): boolean {
		if (!activeSchedule) return false;
		switch (day) {
			case 'monday':
				return activeSchedule.monday;
			case 'tuesday':
				return activeSchedule.tuesday;
			case 'wednesday':
				return activeSchedule.wednesday;
			case 'thursday':
				return activeSchedule.thursday;
			case 'friday':
				return activeSchedule.friday;
			case 'saturday':
				return activeSchedule.saturday;
			case 'sunday':
				return activeSchedule.sunday;
			default:
				return false;
		}
	}

	function formatScheduleDays(schedule: typeof activeSchedule): string {
		if (!schedule) return '';
		const days: string[] = [];
		if (schedule.monday) days.push('Mon');
		if (schedule.tuesday) days.push('Tue');
		if (schedule.wednesday) days.push('Wed');
		if (schedule.thursday) days.push('Thu');
		if (schedule.friday) days.push('Fri');
		if (schedule.saturday) days.push('Sat');
		if (schedule.sunday) days.push('Sun');
		if (schedule.weekendService) days.push('Weekends');
		return days.join(', ') || 'No days selected';
	}

	// Drawer state
	type DrawerType = 'location' | 'schedule' | 'scope' | 'area' | 'task' | null;
	let drawerOpen = $state(false);
	let drawerType = $state<DrawerType>(null);
	let drawerMode = $state<'add' | 'edit'>('add');

	// For area/task editing, track the selected item
	let selectedArea =
		$state<
			typeof activeScope extends null
				? null
				: NonNullable<typeof activeScope>['areas'][number] | null
		>(null);
	let selectedTask = $state<{ task: any; areaId: string } | null>(null);

	function openDrawer(type: DrawerType, mode: 'add' | 'edit' = 'add') {
		drawerType = type;
		drawerMode = mode;
		drawerOpen = true;
	}

	function openAreaDrawer(area?: typeof selectedArea) {
		selectedArea = area ?? null;
		drawerType = 'area';
		drawerMode = area ? 'edit' : 'add';
		drawerOpen = true;
	}

	function openTaskDrawer(areaId: string, task?: any) {
		selectedTask = task ? { task, areaId } : { task: null, areaId };
		drawerType = 'task';
		drawerMode = task ? 'edit' : 'add';
		drawerOpen = true;
	}

	function closeDrawer() {
		drawerOpen = false;
		drawerType = null;
		selectedArea = null;
		selectedTask = null;
	}

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

	// Drawer title helper
	let drawerTitle = $derived(() => {
		if (!drawerType) return '';
		const typeNames: Record<string, string> = {
			location: 'Location',
			schedule: 'Schedule',
			scope: 'Scope',
			area: 'Area',
			task: 'Task'
		};
		return `${drawerMode === 'add' ? 'Add' : 'Edit'} ${typeNames[drawerType]}`;
	});

	// Delete modal state
	type DeleteType = 'location' | 'schedule' | 'scope' | 'area' | 'task' | null;
	let deleteModalOpen = $state(false);
	let deleteType = $state<DeleteType>(null);
	let deleteLoading = $state(false);
	let deleteTargetId = $state<string | null>(null);
	let deleteTargetName = $state<string>('');

	function openDeleteModal(type: DeleteType, id?: string, name?: string) {
		deleteType = type;
		deleteTargetId = id ?? null;
		deleteTargetName = name ?? '';
		deleteModalOpen = true;
	}

	function closeDeleteModal() {
		deleteModalOpen = false;
		deleteType = null;
		deleteTargetId = null;
		deleteTargetName = '';
	}

	// Delete modal message helper
	let deleteMessage = $derived(() => {
		switch (deleteType) {
			case 'location':
				return 'Are you sure you want to delete this service location? This action cannot be undone.';
			case 'schedule':
				return 'Are you sure you want to delete this schedule?';
			case 'scope':
				return 'Are you sure you want to delete this scope? All areas and tasks will also be removed.';
			case 'area':
				return `Are you sure you want to delete "${deleteTargetName}"? All tasks in this area will also be removed.`;
			case 'task':
				return `Are you sure you want to delete "${deleteTargetName}"?`;
			default:
				return '';
		}
	});

	let deleteTitle = $derived(() => {
		const titles: Record<string, string> = {
			location: 'Delete Location',
			schedule: 'Delete Schedule',
			scope: 'Delete Scope',
			area: 'Delete Area',
			task: 'Delete Task'
		};
		return deleteType ? titles[deleteType] : '';
	});

	async function confirmDelete() {
		deleteLoading = true;
		try {
			switch (deleteType) {
				case 'schedule':
					if (activeSchedule) {
						await client.mutate({
							mutation: DELETE_SCHEDULE,
							variables: { id: activeSchedule.id }
						});
					}
					break;
				case 'scope':
					if (activeScope) {
						await client.mutate({
							mutation: DELETE_SERVICE_SCOPE,
							variables: { id: activeScope.id }
						});
					}
					break;
				case 'area':
					if (deleteTargetId) {
						await client.mutate({
							mutation: DELETE_SCOPE_AREA,
							variables: { id: deleteTargetId }
						});
					}
					break;
				case 'task':
					if (deleteTargetId) {
						await client.mutate({
							mutation: DELETE_SCOPE_TASK,
							variables: { id: deleteTargetId }
						});
					}
					break;
				case 'location':
					// TODO: Wire up location delete when backend is ready
					// await client.mutate({ mutation: DELETE_LOCATION, variables: { id: location.id } });
					// goto(`/admin/accounts/${account.id}`);
					break;
			}
			closeDeleteModal();
			await invalidateAll();
		} catch (err) {
			console.error('Delete failed:', err);
		} finally {
			deleteLoading = false;
		}
	}

	// Reorder functions (increment by 5 to leave room for insertions)
	const ORDER_INCREMENT = 5;

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

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

<svelte:head>
	<title
		>{location?.name || 'Service Location'} - {account?.name ?? 'Account'} - Admin - Nexus</title
	>
</svelte:head>

<div class="py-8">
	<ContentContainer maxWidth="4xl">
		{#if location && account}
			<PageHeader
				title={locationDisplayName}
				colorScheme="primary"
				backHref="/admin/accounts/{account.id}"
				invalidateOnBack
			>
				<span class="text-sm font-normal text-theme-secondary">{account.name}</span>
				{#if location.isPrimary}
					<span class="badge-primary">Primary</span>
				{/if}
			</PageHeader>

			<div class="space-y-6">
				<!-- Location Information -->
				<section
					class="overflow-hidden rounded-xl border border-primary-500/20 bg-theme-card shadow-theme-md"
				>
					<div
						class="border-b border-primary-500/20 bg-linear-to-r from-primary-500/10 to-transparent px-5 py-3"
					>
						<SectionHeader
							title="Location Details"
							buttonText="Edit"
							buttonIcon="edit"
							onButtonClick={() => openDrawer('location', 'edit')}
						/>
					</div>
					<div class="grid grid-cols-1 gap-6 px-5 py-5 sm:grid-cols-2">
						<div>
							<p class="detail-label">Location Name</p>
							<p class="text-theme">{locationDisplayName}</p>
						</div>
						<div>
							<p class="detail-label">Status</p>
							{#if location.isActive}
								<span class="badge-success">Active</span>
							{:else}
								<span class="badge-neutral">Inactive</span>
							{/if}
						</div>
						<div>
							<p class="detail-label">Account</p>
							<a
								href="/admin/accounts/{account.id}"
								class="text-primary-500 hover:text-primary-600"
							>
								{account.name} &rarr;
							</a>
						</div>
						<div>
							<p class="detail-label">Labor Paid</p>
							{#if activeLabor}
								<p class="text-theme">{formatCurrency(activeLabor.amount)}</p>
								<p class="text-sm text-theme-secondary">
									Since {formatDate(activeLabor.startDate)}
								</p>
							{:else}
								<p class="text-theme-muted">Not set</p>
							{/if}
						</div>
						<div class="sm:col-span-2">
							<p class="detail-label">Address</p>
							<p class="text-theme">
								{location.streetAddress}, {location.city}, {location.state}
								{location.zipCode}
							</p>
						</div>
						{#if location.notes}
							<div class="sm:col-span-2">
								<p class="detail-label">Notes</p>
								<p class="text-theme">{location.notes}</p>
							</div>
						{/if}
					</div>
				</section>

				{#if !isProjectOnly}
					<!-- Schedule -->
					<section
						class="overflow-hidden rounded-xl border border-primary-500/20 bg-theme-card shadow-theme-md"
					>
						<div
							class="border-b border-primary-500/20 bg-linear-to-r from-primary-500/10 to-transparent px-5 py-3"
						>
							<SectionHeader
								title="Schedule"
								buttonText={activeSchedule ? 'Edit' : 'Add'}
								buttonIcon={activeSchedule ? 'edit' : 'plus'}
								onButtonClick={() => openDrawer('schedule', activeSchedule ? 'edit' : 'add')}
							/>
						</div>
						<div class="px-5 py-5">
							{#if activeSchedule}
								<div class="space-y-4">
									<h3 class="font-medium text-theme">
										{activeSchedule.name || 'Service Schedule'}
									</h3>
									<!-- Visual day blocks -->
									<div>
										<p class="detail-label mb-2">Service Days</p>
										<div class="flex gap-1">
											<!-- Weekday blocks -->
											{#each [{ key: 'monday', short: 'M', full: 'Monday' }, { key: 'tuesday', short: 'T', full: 'Tuesday' }, { key: 'wednesday', short: 'W', full: 'Wednesday' }, { key: 'thursday', short: 'Th', full: 'Thursday' }] as day}
												<div
													class="flex h-9 w-10 items-center justify-center rounded-md text-sm font-medium
														transition-colors sm:w-auto sm:px-3
														{isScheduledDay(day.key) ? 'bg-primary-500 text-white' : 'bg-theme-secondary/50 text-theme-muted'}"
												>
													<span class="sm:hidden">{day.short}</span>
													<span class="hidden sm:inline">{day.full}</span>
												</div>
											{/each}
											<!-- Weekend: combined block when weekendService is true -->
											{#if activeSchedule.weekendService}
												<div
													class="flex h-9 w-14 items-center justify-center rounded-md bg-primary-500 text-sm
														font-medium text-white transition-colors sm:w-auto sm:px-3"
												>
													<span class="sm:hidden">Wknd*</span>
													<span class="hidden sm:inline">Weekend*</span>
												</div>
											{:else}
												<!-- No weekend flag: show individual F/Sa/Su -->
												{#each [{ key: 'friday', short: 'F', full: 'Friday' }, { key: 'saturday', short: 'Sa', full: 'Saturday' }, { key: 'sunday', short: 'Su', full: 'Sunday' }] as day}
													<div
														class="flex h-9 w-10 items-center justify-center rounded-md text-sm font-medium
															transition-colors sm:w-auto sm:px-3
															{isScheduledDay(day.key) ? 'bg-primary-500 text-white' : 'bg-theme-secondary/50 text-theme-muted'}"
													>
														<span class="sm:hidden">{day.short}</span>
														<span class="hidden sm:inline">{day.full}</span>
													</div>
												{/each}
											{/if}
										</div>
										{#if activeSchedule.weekendService}
											<p class="mt-1 text-xs text-theme-muted">
												*Service can be completed anytime Fri–Sun
											</p>
										{/if}
									</div>
									{#if activeSchedule.startDate}
										<p class="text-sm text-theme-secondary">
											{#if activeSchedule.endDate}
												{formatDate(activeSchedule.startDate)} – {formatDate(
													activeSchedule.endDate
												)}
											{:else}
												Since {formatDate(activeSchedule.startDate)}
											{/if}
										</p>
									{/if}
									{#if activeSchedule.scheduleException}
										<div>
											<p class="detail-label">Exceptions</p>
											<p class="text-theme-secondary">{activeSchedule.scheduleException}</p>
										</div>
									{/if}
									<!-- Past/Future schedule togglers and Add button -->
									<div class="flex flex-wrap items-center gap-3 border-t border-theme pt-4">
										{#if hasPastSchedules}
											<button
												type="button"
												onclick={() => openScheduleModal('past')}
												class="flex items-center gap-1.5 text-sm text-theme-muted hover:text-theme"
											>
												<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 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"
													/>
												</svg>
												Previous ({pastSchedules.length})
											</button>
										{/if}
										{#if hasFutureSchedules}
											<button
												type="button"
												onclick={() => openScheduleModal('future')}
												class="flex items-center gap-1.5 text-sm text-theme-muted hover:text-theme"
											>
												<svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
													<path
														stroke-linecap="round"
														stroke-linejoin="round"
														stroke-width="2"
														d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"
													/>
												</svg>
												Upcoming ({futureSchedules.length})
											</button>
										{/if}
										<button
											type="button"
											onclick={() => openDrawer('schedule', 'add')}
											class="flex items-center gap-1.5 text-sm text-primary-600 hover:text-primary-700 dark:text-primary-400 dark:hover:text-primary-300"
										>
											<svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
												<path
													stroke-linecap="round"
													stroke-linejoin="round"
													stroke-width="2"
													d="M12 4v16m8-8H4"
												/>
											</svg>
											Add Schedule
										</button>
									</div>
									<div class="pt-2">
										<button
											type="button"
											onclick={() => openDeleteModal('schedule')}
											class="text-sm text-error-600 hover:text-error-700 dark:text-error-400 dark:hover:text-error-300"
										>
											Delete Schedule
										</button>
									</div>
								</div>
							{:else}
								<p class="py-6 text-center text-theme-muted">No schedule configured yet.</p>
							{/if}
						</div>
					</section>

					<!-- Scope -->
					<section
						class="overflow-hidden rounded-xl border border-primary-500/20 bg-theme-card shadow-theme-md"
					>
						<div
							class="border-b border-primary-500/20 bg-linear-to-r from-primary-500/10 to-transparent px-5 py-3"
						>
							<SectionHeader
								title="Scope"
								buttonText={activeScope ? 'Edit' : 'Add'}
								buttonIcon={activeScope ? 'edit' : 'plus'}
								onButtonClick={() => openDrawer('scope', activeScope ? 'edit' : 'add')}
							/>
						</div>
						<div class="px-5 py-5">
							{#if activeScope}
								<div class="space-y-4">
									<h3 class="font-medium text-theme">{activeScope.name || 'Service Scope'}</h3>
									{#if activeScope.description}
										<p class="text-theme-secondary">{activeScope.description}</p>
									{/if}
									{#each activeScope.areas as area (area.id)}
										<details class="group bg-theme-secondary/30 rounded-lg border border-theme">
											<summary
												class="flex cursor-pointer items-center justify-between p-4 select-none"
											>
												<span class="flex items-center gap-2">
													<svg
														class="h-4 w-4 text-theme-muted transition-transform group-open:rotate-90"
														fill="none"
														stroke="currentColor"
														viewBox="0 0 24 24"
													>
														<path
															stroke-linecap="round"
															stroke-linejoin="round"
															stroke-width="2"
															d="M9 5l7 7-7 7"
														/>
													</svg>
													<span class="font-medium text-theme">{area.name}</span>
													<span class="text-xs text-theme-muted"
														>({area.tasks.length} task{area.tasks.length === 1 ? '' : 's'})</span
													>
												</span>
												<span class="flex items-center gap-1">
													<!-- Order/reorder - hidden on mobile -->
													<span class="hidden items-center gap-1 sm:flex">
														<span class="mr-2 text-xs text-theme-muted">#{area.order}</span>
														<button
															type="button"
															onclick={(e) => {
																e.preventDefault();
																reorderArea(area.id, area.order, 'up');
															}}
															class="hover:bg-theme-secondary/50 rounded p-1 text-theme-muted hover:text-theme"
															title="Move up"
														>
															<svg
																class="h-4 w-4"
																fill="none"
																stroke="currentColor"
																viewBox="0 0 24 24"
															>
																<path
																	stroke-linecap="round"
																	stroke-linejoin="round"
																	stroke-width="2"
																	d="M5 15l7-7 7 7"
																/>
															</svg>
														</button>
														<button
															type="button"
															onclick={(e) => {
																e.preventDefault();
																reorderArea(area.id, area.order, 'down');
															}}
															class="hover:bg-theme-secondary/50 rounded p-1 text-theme-muted hover:text-theme"
															title="Move down"
														>
															<svg
																class="h-4 w-4"
																fill="none"
																stroke="currentColor"
																viewBox="0 0 24 24"
															>
																<path
																	stroke-linecap="round"
																	stroke-linejoin="round"
																	stroke-width="2"
																	d="M19 9l-7 7-7-7"
																/>
															</svg>
														</button>
														<span class="text-theme-muted/30 mx-1 hidden group-open:inline">|</span>
													</span>
													<!-- Edit/Delete - show on expand -->
													<span class="hidden items-center gap-2 group-open:flex">
														<button
															type="button"
															onclick={(e) => {
																e.preventDefault();
																openAreaDrawer(area);
															}}
															class="text-xs text-primary-600 hover:text-primary-700 dark:text-primary-400 dark:hover:text-primary-300"
														>
															Edit
														</button>
														<button
															type="button"
															onclick={(e) => {
																e.preventDefault();
																openDeleteModal('area', area.id, area.name);
															}}
															class="text-xs text-error-600 hover:text-error-700 dark:text-error-400 dark:hover:text-error-300"
														>
															Delete
														</button>
													</span>
												</span>
											</summary>
											<div class="border-t border-theme px-4 pb-4">
												{#if area.tasks.length > 0}
													<ul class="divide-theme-muted/20 mt-3 divide-y">
														{#each area.tasks as task (task.id)}
															<li>
																<details class="group/task">
																	<summary
																		class="hover:bg-theme-secondary/30 -mx-2 flex cursor-pointer items-start justify-between gap-3 rounded px-2 py-2 select-none"
																	>
																		<span class="flex min-w-0 items-start gap-2">
																			<svg
																				class="mt-0.5 h-4 w-4 shrink-0 text-theme-muted transition-transform group-open/task:rotate-90"
																				fill="none"
																				stroke="currentColor"
																				viewBox="0 0 24 24"
																			>
																				<path
																					stroke-linecap="round"
																					stroke-linejoin="round"
																					stroke-width="2"
																					d="M9 5l7 7-7 7"
																				/>
																			</svg>
																			<span class="min-w-0">
																				<span class="text-sm text-theme"
																					>{task.scopeDescription}</span
																				>
																				<span class="mt-0.5 flex items-center gap-2">
																					{#if task.frequency !== 'DAILY'}
																						<span class="badge-neutral text-xs"
																							>{task.frequency}</span
																						>
																					{/if}
																					{#if task.estimatedMinutes}
																						<span class="text-xs text-theme-muted"
																							>{task.estimatedMinutes} min</span
																						>
																					{/if}
																				</span>
																			</span>
																		</span>
																		<span class="flex shrink-0 items-center gap-1">
																			<!-- Order/reorder - hidden on mobile -->
																			<span class="hidden items-center gap-1 sm:flex">
																				<span class="mr-1 text-xs text-theme-muted"
																					>#{task.order}</span
																				>
																				<button
																					type="button"
																					onclick={(e) => {
																						e.preventDefault();
																						e.stopPropagation();
																						reorderTask(task.id, task.order, 'up');
																					}}
																					class="hover:bg-theme-secondary/50 rounded p-0.5 text-theme-muted hover:text-theme"
																					title="Move up"
																				>
																					<svg
																						class="h-3.5 w-3.5"
																						fill="none"
																						stroke="currentColor"
																						viewBox="0 0 24 24"
																					>
																						<path
																							stroke-linecap="round"
																							stroke-linejoin="round"
																							stroke-width="2"
																							d="M5 15l7-7 7 7"
																						/>
																					</svg>
																				</button>
																				<button
																					type="button"
																					onclick={(e) => {
																						e.preventDefault();
																						e.stopPropagation();
																						reorderTask(task.id, task.order, 'down');
																					}}
																					class="hover:bg-theme-secondary/50 rounded p-0.5 text-theme-muted hover:text-theme"
																					title="Move down"
																				>
																					<svg
																						class="h-3.5 w-3.5"
																						fill="none"
																						stroke="currentColor"
																						viewBox="0 0 24 24"
																					>
																						<path
																							stroke-linecap="round"
																							stroke-linejoin="round"
																							stroke-width="2"
																							d="M19 9l-7 7-7-7"
																						/>
																					</svg>
																				</button>
																				<span
																					class="text-theme-muted/30 mx-0.5 hidden group-open/task:inline"
																					>|</span
																				>
																			</span>
																			<!-- Edit/Delete - show on expand -->
																			<span class="hidden items-center gap-2 group-open/task:flex">
																				<button
																					type="button"
																					onclick={(e) => {
																						e.preventDefault();
																						openTaskDrawer(area.id, task);
																					}}
																					class="text-xs text-primary-600 hover:text-primary-700 dark:text-primary-400 dark:hover:text-primary-300"
																				>
																					Edit
																				</button>
																				<button
																					type="button"
																					onclick={(e) => {
																						e.preventDefault();
																						openDeleteModal('task', task.id, task.scopeDescription);
																					}}
																					class="text-xs text-error-600 hover:text-error-700 dark:text-error-400 dark:hover:text-error-300"
																				>
																					Delete
																				</button>
																			</span>
																		</span>
																	</summary>
																	<div class="ml-4 space-y-2 pb-2 text-sm sm:ml-6">
																		<div class="flex flex-col sm:flex-row sm:gap-6">
																			<span
																				class="shrink-0 text-xs text-theme-muted sm:w-24 sm:text-sm"
																				>Checklist:</span
																			>
																			<span class="text-theme-secondary"
																				>{task.checklistDescription || '—'}</span
																			>
																		</div>
																		<div class="flex flex-col sm:flex-row sm:gap-6">
																			<span
																				class="shrink-0 text-xs text-theme-muted sm:w-24 sm:text-sm"
																				>Instructions:</span
																			>
																			<span class="text-theme-secondary"
																				>{task.sessionDescription || '—'}</span
																			>
																		</div>
																	</div>
																</details>
															</li>
														{/each}
													</ul>
												{/if}
												<button
													type="button"
													onclick={() => openTaskDrawer(area.id)}
													class="mt-3 text-xs text-primary-600 hover:text-primary-700 dark:text-primary-400 dark:hover:text-primary-300"
												>
													+ Add Task
												</button>
											</div>
										</details>
									{/each}
									<!-- Add Area button -->
									<button
										type="button"
										onclick={() => openAreaDrawer()}
										class="border-theme-muted/50 w-full rounded-lg border-2 border-dashed py-3 text-sm text-theme-muted transition-colors hover:border-primary-500/50 hover:text-primary-600 dark:hover:text-primary-400"
									>
										+ Add Area
									</button>
									<!-- Previous scopes toggler and Add Scope button -->
									<div class="flex flex-wrap items-center gap-3 border-t border-theme pt-4">
										{#if hasInactiveScopes}
											<button
												type="button"
												onclick={openScopeModal}
												class="flex items-center gap-1.5 text-sm text-theme-muted hover:text-theme"
											>
												<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 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"
													/>
												</svg>
												Previous ({inactiveScopes.length})
											</button>
										{/if}
										<button
											type="button"
											onclick={() => openDrawer('scope', 'add')}
											class="flex items-center gap-1.5 text-sm text-primary-600 hover:text-primary-700 dark:text-primary-400 dark:hover:text-primary-300"
										>
											<svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
												<path
													stroke-linecap="round"
													stroke-linejoin="round"
													stroke-width="2"
													d="M12 4v16m8-8H4"
												/>
											</svg>
											New Scope
										</button>
									</div>
									<div class="pt-2">
										<button
											type="button"
											onclick={() => openDeleteModal('scope')}
											class="text-sm text-error-600 hover:text-error-700 dark:text-error-400 dark:hover:text-error-300"
										>
											Delete Scope
										</button>
									</div>
								</div>
							{:else}
								<p class="py-6 text-center text-theme-muted">No scope defined yet.</p>
							{/if}
						</div>
					</section>
				{/if}

				<!-- Danger Zone -->
				<details
					class="group overflow-hidden rounded-xl border border-error-500/30 bg-error-50/50 shadow-theme dark:bg-error-950/20"
				>
					<summary
						class="flex cursor-pointer items-center justify-between bg-linear-to-r from-error-500/10 to-transparent px-5 py-3 select-none"
					>
						<span class="text-lg font-semibold text-error-700 dark:text-error-400">Danger Zone</span
						>
						<svg
							class="h-5 w-5 text-error-500 transition-transform group-open:rotate-180"
							fill="none"
							stroke="currentColor"
							viewBox="0 0 24 24"
						>
							<path
								stroke-linecap="round"
								stroke-linejoin="round"
								stroke-width="2"
								d="M19 9l-7 7-7-7"
							/>
						</svg>
					</summary>
					<div class="space-y-4 border-t border-error-500/20 px-5 py-5">
						<p class="text-sm text-error-600 dark:text-error-300">
							Deleting this location will remove it from the account. This action cannot be undone.
						</p>
						<button type="button" class="btn-danger" onclick={() => openDeleteModal('location')}>
							Delete Location
						</button>
					</div>
				</details>
			</div>

			<!-- Form Drawer -->
			<FormDrawer open={drawerOpen} title={drawerTitle()} onClose={closeDrawer}>
				{#if drawerType === 'location'}
					<LocationForm
						{location}
						{activeLabor}
						onSuccess={handleFormSuccess}
						onCancel={closeDrawer}
					/>
				{:else if drawerType === 'schedule'}
					<ScheduleForm
						schedule={drawerMode === 'edit' ? activeSchedule : null}
						accountAddressId={location.id}
						existingSchedules={location.schedules ?? []}
						onSuccess={handleFormSuccess}
						onCancel={closeDrawer}
					/>
				{:else if drawerType === 'scope'}
					<ScopeForm
						scope={drawerMode === 'edit' ? activeScope : null}
						accountId={account.id}
						accountAddressId={location.id}
						onSuccess={handleFormSuccess}
						onCancel={closeDrawer}
					/>
				{:else if drawerType === 'area' && activeScope}
					<AreaForm
						area={selectedArea}
						scopeId={activeScope.id}
						onSuccess={handleFormSuccess}
						onCancel={closeDrawer}
					/>
				{:else if drawerType === 'task' && selectedTask}
					<TaskForm
						task={selectedTask.task}
						areaId={selectedTask.areaId}
						onSuccess={handleFormSuccess}
						onCancel={closeDrawer}
					/>
				{/if}
			</FormDrawer>

			<!-- Delete Modal -->
			<DeleteModal
				open={deleteModalOpen}
				title={deleteTitle()}
				message={deleteMessage()}
				requireConfirmation={deleteType === 'location'}
				loading={deleteLoading}
				onConfirm={confirmDelete}
				onCancel={closeDeleteModal}
			/>

			<!-- Schedule History/Future Modal -->
			<ScheduleListModal
				open={scheduleModalOpen}
				title={scheduleModalType === 'past' ? 'Previous Schedules' : 'Upcoming Schedules'}
				schedules={scheduleModalType === 'past' ? pastSchedules : futureSchedules}
				onClose={closeScheduleModal}
			/>

			<!-- Scope History Modal -->
			<ScopeListModal
				open={scopeModalOpen}
				title="Previous Scopes"
				scopes={inactiveScopes}
				onClose={closeScopeModal}
			/>
		{:else}
			<div class="empty-state">
				<svg class="empty-state-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
					<path
						stroke-linecap="round"
						stroke-linejoin="round"
						stroke-width="1.5"
						d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
					/>
				</svg>
				<h2 class="empty-state-title">Location not found</h2>
				<p class="empty-state-text">
					The service location you're looking for doesn't exist or has been deleted.
				</p>
				<a href="/admin/accounts" class="mt-4 btn-primary">Back to Accounts</a>
			</div>
		{/if}
	</ContentContainer>
</div>
