<script lang="ts">
	import {
		createAssignServicesStore,
		type EnrichedService,
		type TabType,
		type ViewMode
	} from '$lib/stores/assignServices.svelte';
	import AssignColumn from '$lib/components/admin/services/assign/AssignColumn.svelte';
	import AssignServiceGroup from '$lib/components/admin/services/assign/AssignServiceGroup.svelte';
	import GenerateServicesModal from '$lib/components/admin/services/GenerateServicesModal.svelte';
	import DeleteConfirmModal from '$lib/components/admin/DeleteConfirmModal.svelte';
	import IconSpinner from '$lib/components/icons/IconSpinner.svelte';
	import type { PageData } from './$types';

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

	// Create store instance
	const store = createAssignServicesStore();

	// View mode options
	const viewModes: ViewMode[] = ['date', 'week', 'account'];

	// Layout data from parent
	let accountLookup = $derived(data.accountLookup);
	let teamProfiles = $derived(data.team?.data?.teamProfiles ?? []);
	let accounts = $derived(data.accounts?.data?.accounts ?? []);

	// Generate modal state
	let showGenerateModal = $state(false);

	// Initialize store with external data
	$effect(() => {
		store.init(accountLookup, teamProfiles);
	});

	// Fetch services on mount and when month changes
	$effect(() => {
		void store.currentMonth;
		store.fetchServices();
	});

	// Reset expanded groups when view mode changes
	$effect(() => {
		void store.viewMode;
		store.resetExpandedGroups();
	});

	// Close dropdowns on window click
	function handleWindowClick() {
		store.closeAllDropdowns();
	}

	// Mobile tab helpers
	function getTabColor(tab: TabType): { dot: string; text: string; badge: string } {
		switch (tab) {
			case 'unassigned':
				return {
					dot: 'bg-red-500',
					text: 'text-red-600 dark:text-red-400',
					badge: 'bg-red-500 text-white'
				};
			case 'readyToAssign':
				return {
					dot: 'bg-yellow-500',
					text: 'text-yellow-600 dark:text-yellow-400',
					badge: 'bg-yellow-500 text-white'
				};
			case 'assigned':
				return {
					dot: 'bg-green-500',
					text: 'text-green-600 dark:text-green-400',
					badge: 'bg-green-500 text-white'
				};
		}
	}

	let activeTabColor = $derived(getTabColor(store.activeTab));

	function getTabLabel(tab: TabType): string {
		switch (tab) {
			case 'unassigned':
				return 'Unassigned';
			case 'readyToAssign':
				return 'Ready';
			case 'assigned':
				return 'Assigned';
		}
	}

	function getTabCount(tab: TabType): number {
		switch (tab) {
			case 'unassigned':
				return store.categorizedServices.unassigned.length;
			case 'readyToAssign':
				return store.categorizedServices.readyToAssign.length;
			case 'assigned':
				return store.categorizedServices.assigned.length;
		}
	}

	function getMobileGroupedServices(): Map<string, EnrichedService[]> {
		switch (store.activeTab) {
			case 'unassigned':
				return store.groupedUnassigned;
			case 'readyToAssign':
				return store.groupedReadyToAssign;
			case 'assigned':
				return store.groupedAssigned;
		}
	}

	function getMobileExpandedGroups() {
		switch (store.activeTab) {
			case 'unassigned':
				return store.expandedUnassigned;
			case 'readyToAssign':
				return store.expandedReadyToAssign;
			case 'assigned':
				return store.expandedAssigned;
		}
	}

	function getMobileEmptyMessage(): string {
		switch (store.activeTab) {
			case 'unassigned':
				return 'No unassigned services';
			case 'readyToAssign':
				return 'No services ready to assign';
			case 'assigned':
				return 'No assigned services';
		}
	}

	function getMobileEmptyIcon(): string {
		switch (store.activeTab) {
			case 'unassigned':
			case 'assigned':
				return 'M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z';
			case 'readyToAssign':
				return 'M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z';
		}
	}

	function getMobileSelectedServices() {
		switch (store.activeTab) {
			case 'unassigned':
				return store.selectedUnassigned;
			case 'readyToAssign':
				return store.selectedReadyToAssign;
			case 'assigned':
				return store.selectedAssigned;
		}
	}

	function getMobileBulkAction(): () => void {
		switch (store.activeTab) {
			case 'unassigned':
				return store.bulkAddDispatch;
			case 'readyToAssign':
				return store.bulkAddTeamMember;
			case 'assigned':
				return store.bulkRemoveNonDispatch;
		}
	}

	function getMobileBulkActionLabel(): string {
		switch (store.activeTab) {
			case 'unassigned':
				return 'Add Dispatch';
			case 'readyToAssign':
				return 'Assign';
			case 'assigned':
				return 'Remove Team';
		}
	}

	function getMobileBulkActionDisabled(): boolean {
		if (store.isBulkOperating) return true;
		const selected = getMobileSelectedServices();
		if (selected.size === 0) return true;
		return store.activeTab === 'readyToAssign' && !store.bulkSelectedTeamMember;
	}

	let mobileHasSelection = $derived(getMobileSelectedServices().size > 0);
	let mobileAllSelected = $derived(
		getTabCount(store.activeTab) > 0 &&
			getMobileSelectedServices().size === getTabCount(store.activeTab)
	);

	function getMobileSelectedTeamMemberName(): string {
		if (!store.bulkSelectedTeamMember) return 'Select...';
		const member = store.nonAdminTeamMembers.find((m) => {
			const parts = atob(m.id).split(':');
			return parts[1] === store.bulkSelectedTeamMember;
		});
		return member?.fullName ?? 'Unknown';
	}
</script>

<svelte:window onclick={handleWindowClick} />

<svelte:head>
	<title>Bulk Assign - Services - Admin - Nexus</title>
</svelte:head>

<div class="flex h-screen flex-col overflow-hidden bg-theme">
	<!-- Header -->
	<div class="border-b border-theme bg-theme-card px-4 py-4 shadow-sm lg:px-6">
		<!-- Page Title Row -->
		<div class="flex items-center gap-4">
			<a
				href="/admin/services"
				class="rounded-lg border border-theme interactive bg-theme px-3 py-1.5 text-sm font-medium text-theme"
			>
				Back
			</a>
			<div class="min-w-0 flex-1">
				<h1 class="text-xl font-bold text-secondary-600 dark:text-secondary-400">Bulk Assign</h1>
				<p class="text-sm text-theme-secondary">Assign team members to scheduled services</p>
			</div>
			<!-- Desktop: Month Navigation -->
			<div class="hidden items-center gap-2 lg:flex">
				<button
					onclick={store.previousMonth}
					aria-label="Previous month"
					class="rounded-lg border border-theme interactive bg-theme p-2 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="M15 19l-7-7 7-7"
						/>
					</svg>
				</button>
				<span class="min-w-[140px] text-center text-lg font-semibold text-theme">
					{store.monthDisplay}
				</span>
				<button
					onclick={store.nextMonth}
					aria-label="Next month"
					class="rounded-lg border border-theme interactive bg-theme p-2 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 5l7 7-7 7"
						/>
					</svg>
				</button>
				<button
					onclick={store.goToCurrentMonth}
					class="rounded-lg border border-theme interactive bg-theme px-3 py-1.5 text-sm font-medium text-theme"
				>
					Now
				</button>
			</div>
		</div>

		<!-- Controls Row (Generate + View Mode) -->
		<div class="mt-4 flex items-center justify-between gap-3">
			<button
				onclick={() => (showGenerateModal = true)}
				class="flex items-center gap-2 rounded-lg border border-theme interactive bg-theme px-3 py-1.5 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="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>
				<span>Generate</span>
			</button>
			<div class="flex items-center rounded-lg border border-theme bg-theme p-1">
				{#each viewModes as mode (mode)}
					<button
						onclick={() => store.setViewMode(mode)}
						class="flex items-center gap-1.5 rounded-md px-2 py-1.5 text-sm font-medium transition-colors lg:px-3 {store.viewMode ===
						mode
							? 'bg-theme-card text-theme shadow-sm'
							: 'text-theme-muted hover:text-theme'}"
					>
						<svg class="h-4 w-4" style="fill: none" viewBox="0 0 24 24" stroke="currentColor">
							{#if mode === 'date'}
								<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"
								/>
							{:else if mode === 'week'}
								<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"
								/>
							{:else}
								<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"
								/>
							{/if}
						</svg>
						<span class="hidden capitalize sm:inline">{mode}</span>
					</button>
				{/each}
			</div>
		</div>

		<!-- Mobile Month Navigation -->
		<div class="mt-4 flex items-center justify-between lg:hidden">
			<button
				onclick={store.previousMonth}
				aria-label="Previous month"
				class="rounded-lg border border-theme bg-theme p-2 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="M15 19l-7-7 7-7"
					/>
				</svg>
			</button>
			<div class="flex items-center gap-2">
				<span class="text-lg font-semibold text-theme">{store.monthDisplay}</span>
				<button
					onclick={store.goToCurrentMonth}
					class="rounded-lg border border-theme interactive bg-theme px-2 py-1 text-xs font-medium text-theme"
				>
					Now
				</button>
			</div>
			<button
				onclick={store.nextMonth}
				aria-label="Next month"
				class="rounded-lg border border-theme bg-theme p-2 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="M9 5l7 7-7 7" />
				</svg>
			</button>
		</div>
	</div>

	<!-- Error Alert -->
	{#if store.error}
		<div class="mx-4 mt-4 alert-error lg:mx-6">
			{store.error}
			<button onclick={store.clearError} 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 lg:hidden">
		<button
			onclick={store.previousTab}
			aria-label="Previous tab"
			class="rounded-lg interactive p-1 text-theme-muted hover:text-theme"
		>
			<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 {activeTabColor.dot}"></span>
			<span class="text-lg font-semibold {activeTabColor.text}">{getTabLabel(store.activeTab)}</span
			>
			<span class="rounded-full px-2 py-0.5 text-xs font-semibold {activeTabColor.badge}">
				{getTabCount(store.activeTab)}
			</span>
		</div>
		<button
			onclick={store.nextTab}
			aria-label="Next tab"
			class="rounded-lg interactive p-1 text-theme-muted hover:text-theme"
		>
			<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 Bulk Action Bar -->
	{#if getTabCount(store.activeTab) > 0}
		<div class="border-b border-theme bg-theme-card px-4 py-2 lg:hidden">
			<div class="flex items-center justify-between gap-2">
				<!-- Select All / Clear -->
				<div class="flex items-center gap-2">
					<button
						onclick={() =>
							mobileAllSelected
								? store.clearColumnSelection(store.activeTab)
								: store.selectAllInColumn(store.activeTab)}
						class="flex items-center gap-1.5 rounded interactive px-2 py-1 text-xs font-medium {mobileHasSelection
							? 'text-primary-600 dark:text-primary-400'
							: 'text-theme-muted'}"
					>
						<svg
							class="h-4 w-4"
							style="fill: none"
							viewBox="0 0 24 24"
							stroke="currentColor"
							stroke-width="2"
						>
							{#if mobileAllSelected}
								<path
									stroke-linecap="round"
									stroke-linejoin="round"
									d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"
								/>
							{:else if mobileHasSelection}
								<path
									stroke-linecap="round"
									stroke-linejoin="round"
									d="M15 12H9m12 0a9 9 0 11-18 0 9 9 0 0118 0z"
								/>
							{:else}
								<circle cx="12" cy="12" r="9" />
							{/if}
						</svg>
						{#if mobileHasSelection}
							<span>{getMobileSelectedServices().size} selected</span>
						{:else}
							<span>Select all</span>
						{/if}
					</button>
					{#if mobileHasSelection}
						<button
							onclick={() => store.clearColumnSelection(store.activeTab)}
							class="text-xs text-theme-muted hover:text-theme"
						>
							Clear
						</button>
					{/if}
				</div>

				<!-- Bulk Action -->
				{#if mobileHasSelection}
					<div class="flex items-center gap-2">
						{#if store.activeTab === 'readyToAssign'}
							<!-- Team member dropdown for bulk assignment -->
							<div class="relative">
								<button
									onclick={(e) => {
										e.stopPropagation();
										store.toggleBulkTeamMemberDropdown();
									}}
									class="flex items-center gap-1 rounded border border-theme interactive bg-theme px-2 py-1 text-xs font-medium text-theme"
								>
									<span class="max-w-[80px] truncate">{getMobileSelectedTeamMemberName()}</span>
									<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="M19 9l-7 7-7-7"
										/>
									</svg>
								</button>
								{#if store.showBulkTeamMemberDropdown}
									<!-- svelte-ignore a11y_click_events_have_key_events -->
									<div
										role="menu"
										tabindex="-1"
										onclick={(e) => e.stopPropagation()}
										class="absolute top-full right-0 z-30 mt-1 max-h-48 w-48 overflow-y-auto rounded-lg border border-theme bg-theme-card py-1 shadow-lg"
									>
										{#each store.nonAdminTeamMembers as member (member.id)}
											{@const memberPk = atob(member.id).split(':')[1]}
											<button
												onclick={() => {
													store.setBulkSelectedTeamMember(memberPk);
													store.toggleBulkTeamMemberDropdown();
												}}
												class="block w-full interactive px-3 py-2 text-left text-sm text-theme {store.bulkSelectedTeamMember ===
												memberPk
													? 'bg-primary-50 dark:bg-primary-900/20'
													: ''}"
											>
												{member.fullName}
											</button>
										{/each}
									</div>
								{/if}
							</div>
						{/if}
						<button
							onclick={getMobileBulkAction()}
							disabled={getMobileBulkActionDisabled()}
							class="flex items-center gap-1 rounded bg-primary-600 px-2 py-1 text-xs font-medium text-white transition-colors hover:bg-primary-700 disabled:cursor-not-allowed disabled:opacity-50"
						>
							{#if store.isBulkOperating}
								<IconSpinner class="h-3 w-3" />
							{:else}
								<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="M9 5l7 7-7 7"
									/>
								</svg>
							{/if}
							{getMobileBulkActionLabel()}
						</button>
					</div>
				{/if}
			</div>
		</div>
	{/if}

	<!-- Main Content -->
	{#if store.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 services...</span>
			</div>
		</div>
	{:else}
		<!-- Desktop: Three columns -->
		<div class="hidden flex-1 gap-5 overflow-hidden p-5 lg:flex">
			<AssignColumn
				column="unassigned"
				services={store.categorizedServices.unassigned}
				groupedServices={store.groupedUnassigned}
				expandedGroups={store.expandedUnassigned}
				updatingServices={store.updatingServices}
				openTeamMemberDropdown={store.openTeamMemberDropdown}
				editingDateServiceId={store.editingDateServiceId}
				selectedServices={store.selectedUnassigned}
				isBulkOperating={store.isBulkOperating}
				onToggleGroup={(groupKey) => store.toggleGroup('unassigned', groupKey)}
				getTeamMemberNames={store.getTeamMemberNames}
				getNonDispatchTeamMemberNames={store.getNonDispatchTeamMemberNames}
				getAvailableTeamMembers={store.getAvailableTeamMembers}
				getStagedTeamMemberDetails={store.getStagedTeamMemberDetails}
				hasStagedMembers={store.hasStagedMembers}
				onAddDispatch={store.addDispatchToService}
				onRemoveDispatch={store.removeDispatchFromService}
				onSubmitStaged={store.submitStagedTeamMembers}
				onRemoveNonDispatch={store.removeNonDispatchMembers}
				onStageTeamMember={store.stageTeamMember}
				onUnstageTeamMember={store.unstageTeamMember}
				onToggleDropdown={store.setOpenTeamMemberDropdown}
				onToggleSelection={(id) => store.toggleServiceSelection('unassigned', id)}
				onSelectAll={() => store.selectAllInColumn('unassigned')}
				onClearSelection={() => store.clearColumnSelection('unassigned')}
				onBulkAction={store.bulkAddDispatch}
				onUpdateDate={store.updateServiceDate}
				onDeleteService={store.promptDeleteService}
				onStartEditDate={store.startEditDate}
				onCancelEditDate={store.cancelEditDate}
			/>
			<AssignColumn
				column="readyToAssign"
				services={store.categorizedServices.readyToAssign}
				groupedServices={store.groupedReadyToAssign}
				expandedGroups={store.expandedReadyToAssign}
				updatingServices={store.updatingServices}
				openTeamMemberDropdown={store.openTeamMemberDropdown}
				selectedServices={store.selectedReadyToAssign}
				isBulkOperating={store.isBulkOperating}
				nonAdminTeamMembers={store.nonAdminTeamMembers}
				bulkSelectedTeamMember={store.bulkSelectedTeamMember}
				showBulkTeamMemberDropdown={store.showBulkTeamMemberDropdown}
				onToggleGroup={(groupKey) => store.toggleGroup('readyToAssign', groupKey)}
				getTeamMemberNames={store.getTeamMemberNames}
				getNonDispatchTeamMemberNames={store.getNonDispatchTeamMemberNames}
				getAvailableTeamMembers={store.getAvailableTeamMembers}
				getStagedTeamMemberDetails={store.getStagedTeamMemberDetails}
				hasStagedMembers={store.hasStagedMembers}
				onAddDispatch={store.addDispatchToService}
				onRemoveDispatch={store.removeDispatchFromService}
				onSubmitStaged={store.submitStagedTeamMembers}
				onRemoveNonDispatch={store.removeNonDispatchMembers}
				onStageTeamMember={store.stageTeamMember}
				onUnstageTeamMember={store.unstageTeamMember}
				onToggleDropdown={store.setOpenTeamMemberDropdown}
				onToggleSelection={(id) => store.toggleServiceSelection('readyToAssign', id)}
				onSelectAll={() => store.selectAllInColumn('readyToAssign')}
				onClearSelection={() => store.clearColumnSelection('readyToAssign')}
				onBulkAction={store.bulkAddTeamMember}
				onBulkTeamMemberSelect={store.setBulkSelectedTeamMember}
				onToggleBulkTeamMemberDropdown={store.toggleBulkTeamMemberDropdown}
			/>
			<AssignColumn
				column="assigned"
				services={store.categorizedServices.assigned}
				groupedServices={store.groupedAssigned}
				expandedGroups={store.expandedAssigned}
				updatingServices={store.updatingServices}
				openTeamMemberDropdown={store.openTeamMemberDropdown}
				selectedServices={store.selectedAssigned}
				isBulkOperating={store.isBulkOperating}
				onToggleGroup={(groupKey) => store.toggleGroup('assigned', groupKey)}
				getTeamMemberNames={store.getTeamMemberNames}
				getNonDispatchTeamMemberNames={store.getNonDispatchTeamMemberNames}
				getAvailableTeamMembers={store.getAvailableTeamMembers}
				getStagedTeamMemberDetails={store.getStagedTeamMemberDetails}
				hasStagedMembers={store.hasStagedMembers}
				onAddDispatch={store.addDispatchToService}
				onRemoveDispatch={store.removeDispatchFromService}
				onSubmitStaged={store.submitStagedTeamMembers}
				onRemoveNonDispatch={store.removeNonDispatchMembers}
				onStageTeamMember={store.stageTeamMember}
				onUnstageTeamMember={store.unstageTeamMember}
				onToggleDropdown={store.setOpenTeamMemberDropdown}
				onToggleSelection={(id) => store.toggleServiceSelection('assigned', id)}
				onSelectAll={() => store.selectAllInColumn('assigned')}
				onClearSelection={() => store.clearColumnSelection('assigned')}
				onBulkAction={store.bulkRemoveNonDispatch}
			/>
		</div>

		<!-- Mobile: Single column based on active tab -->
		<div class="flex-1 overflow-y-auto p-4 lg:hidden">
			{#each [...getMobileGroupedServices().entries()] as [groupKey, groupServices] (groupKey)}
				<div class="mb-2">
					<AssignServiceGroup
						{groupKey}
						services={groupServices}
						column={store.activeTab}
						isExpanded={getMobileExpandedGroups().has(groupKey)}
						updatingServices={store.updatingServices}
						openTeamMemberDropdown={store.openTeamMemberDropdown}
						editingDateServiceId={store.activeTab === 'unassigned'
							? store.editingDateServiceId
							: null}
						selectedServices={getMobileSelectedServices()}
						onToggle={() => store.toggleGroup(store.activeTab, groupKey)}
						getTeamMemberNames={store.getTeamMemberNames}
						getNonDispatchTeamMemberNames={store.getNonDispatchTeamMemberNames}
						getAvailableTeamMembers={store.getAvailableTeamMembers}
						getStagedTeamMemberDetails={store.getStagedTeamMemberDetails}
						hasStagedMembers={store.hasStagedMembers}
						onAddDispatch={store.addDispatchToService}
						onRemoveDispatch={store.removeDispatchFromService}
						onSubmitStaged={store.submitStagedTeamMembers}
						onRemoveNonDispatch={store.removeNonDispatchMembers}
						onStageTeamMember={store.stageTeamMember}
						onUnstageTeamMember={store.unstageTeamMember}
						onToggleDropdown={store.setOpenTeamMemberDropdown}
						onToggleSelection={(id) => store.toggleServiceSelection(store.activeTab, id)}
						onUpdateDate={store.activeTab === 'unassigned' ? store.updateServiceDate : undefined}
						onDeleteService={store.activeTab === 'unassigned'
							? store.promptDeleteService
							: undefined}
						onStartEditDate={store.activeTab === 'unassigned' ? store.startEditDate : undefined}
						onCancelEditDate={store.activeTab === 'unassigned' ? store.cancelEditDate : undefined}
					/>
				</div>
			{/each}
			{#if getTabCount(store.activeTab) === 0}
				<div class="py-12 text-center text-theme-muted">
					<svg
						class="mx-auto mb-3 h-12 w-12"
						style="fill: none"
						viewBox="0 0 24 24"
						stroke="currentColor"
					>
						<path
							stroke-linecap="round"
							stroke-linejoin="round"
							stroke-width="1.5"
							d={getMobileEmptyIcon()}
						/>
					</svg>
					{getMobileEmptyMessage()}
				</div>
			{/if}
		</div>
	{/if}
</div>

<GenerateServicesModal
	bind:open={showGenerateModal}
	{accounts}
	initialMonth={store.currentMonth.getMonth() + 1}
	initialYear={store.currentMonth.getFullYear()}
	onClose={() => (showGenerateModal = false)}
	onSuccess={async () => {
		await store.fetchServices();
	}}
/>

<DeleteConfirmModal
	bind:open={store.showDeleteModal}
	title="Delete Service"
	message={store.serviceToDelete
		? `Are you sure you want to delete the service for "${store.serviceToDelete.accountName}" on ${new Date(store.serviceToDelete.date + 'T00:00:00').toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}? This action cannot be undone.`
		: 'Are you sure you want to delete this service?'}
	onconfirm={store.confirmDeleteService}
	oncancel={store.cancelDeleteService}
	loading={store.isDeleting}
/>
