<script lang="ts">
	import { goto } from '$app/navigation';
	import { page } from '$app/stores';
	import { onMount } from 'svelte';
	import { locale } from 'svelte-i18n';
	import { PillNavigation, QuickInputBar, ImmersiveModeToggle } from '@manacore/shared-ui';
	import {
		SplitPaneContainer,
		setSplitPanelContext,
		DEFAULT_APPS,
	} from '@manacore/shared-splitscreen';
	import type {
		PillNavItem,
		PillDropdownItem,
		QuickInputItem,
		CreatePreview,
	} from '@manacore/shared-ui';
	import { authStore } from '$lib/stores/auth.svelte';
	import { userSettings } from '$lib/stores/user-settings.svelte';
	import { todoSettings } from '$lib/stores/settings.svelte';
	import { projectsStore } from '$lib/stores/projects.svelte';
	import { labelsStore } from '$lib/stores/labels.svelte';
	import { tasksStore } from '$lib/stores/tasks.svelte';
	import { theme } from '$lib/stores/theme';
	import {
		isSidebarMode as sidebarModeStore,
		isNavCollapsed as collapsedStore,
		isToolbarCollapsed as toolbarCollapsedStore,
	} from '$lib/stores/navigation';
	import TodoToolbar from '$lib/components/TodoToolbar.svelte';
	import {
		THEME_DEFINITIONS,
		DEFAULT_THEME_VARIANTS,
		EXTENDED_THEME_VARIANTS,
	} from '@manacore/shared-theme';
	import type { ThemeVariant } from '@manacore/shared-theme';
	import { filterHiddenNavItems } from '@manacore/shared-theme';
	import { getLanguageDropdownItems, getCurrentLanguageLabel } from '@manacore/shared-i18n';
	import { getPillAppItems } from '@manacore/shared-branding';
	import { getTasks } from '$lib/api/tasks';
	import { parseTaskInput, resolveTaskIds, formatParsedTaskPreview } from '$lib/utils/task-parser';
	import AuthGateModal from '$lib/components/AuthGateModal.svelte';
	import { sessionTasksStore } from '$lib/stores/session-tasks.svelte';

	// App switcher items
	const appItems = getPillAppItems('todo');

	// Split-Panel Store für Split-Screen Feature
	const splitPanel = setSplitPanelContext('todo', DEFAULT_APPS);

	// Handler für Split-Screen Panel-Öffnung
	function handleOpenInPanel(appId: string, url: string) {
		splitPanel.openPanel(appId);
	}

	let { children } = $props();

	// QuickInputBar search - search tasks
	async function handleSearch(query: string): Promise<QuickInputItem[]> {
		if (!query.trim()) return [];

		try {
			const tasks = await getTasks({ search: query });
			return tasks.slice(0, 10).map((task) => ({
				id: task.id,
				title: task.title,
				subtitle: task.isCompleted
					? '✓ Erledigt'
					: task.dueDate
						? new Date(task.dueDate).toLocaleDateString('de-DE')
						: 'Kein Datum',
			}));
		} catch {
			return [];
		}
	}

	function handleSelect(item: QuickInputItem) {
		goto(`/task/${item.id}`);
	}

	// QuickInputBar create - parse input and show preview
	function handleParseCreate(query: string): CreatePreview | null {
		if (!query.trim()) return null;

		const parsed = parseTaskInput(query);
		const preview = formatParsedTaskPreview(parsed);

		return {
			title: `"${parsed.title}" erstellen`,
			subtitle: preview || 'Neue Aufgabe',
		};
	}

	// QuickInputBar create - actually create the task
	async function handleCreate(query: string): Promise<void> {
		if (!query.trim()) return;

		const parsed = parseTaskInput(query);
		const resolved = resolveTaskIds(parsed, projectsStore.projects, labelsStore.labels);

		await tasksStore.createTask({
			title: resolved.title,
			dueDate: resolved.dueDate,
			priority: resolved.priority,
			projectId: resolved.projectId,
			labelIds: resolved.labelIds,
		});
	}

	let isSidebarMode = $state(false);
	let isCollapsed = $state(false);
	let isToolbarCollapsed = $state(true);

	// Use theme store's isDark directly
	let isDark = $derived(theme.isDark);

	// Get pinned themes from user settings (extended themes only)
	let pinnedThemes = $derived<ThemeVariant[]>(
		(userSettings.theme?.pinnedThemes || []).filter((t): t is ThemeVariant =>
			EXTENDED_THEME_VARIANTS.includes(t as ThemeVariant)
		)
	);

	// Visible themes in PillNav: default + pinned extended
	let visibleThemes = $derived<ThemeVariant[]>([...DEFAULT_THEME_VARIANTS, ...pinnedThemes]);

	// Theme variant dropdown items
	let themeVariantItems = $derived<PillDropdownItem[]>([
		...visibleThemes.map((variant) => ({
			id: variant,
			label: THEME_DEFINITIONS[variant].label,
			icon: THEME_DEFINITIONS[variant].icon,
			onClick: () => theme.setVariant(variant),
			active: theme.variant === variant,
		})),
		{
			id: 'all-themes',
			label: 'Alle Themes',
			icon: 'palette',
			onClick: () => goto('/themes'),
			active: false,
		},
	]);

	// Current theme variant label
	let currentThemeVariantLabel = $derived(THEME_DEFINITIONS[theme.variant].label);

	// Language selector items
	let currentLocale = $derived($locale || 'de');
	function handleLocaleChange(newLocale: string) {
		locale.set(newLocale);
	}
	let languageItems = $derived(
		getLanguageDropdownItems(['de', 'en'], currentLocale, handleLocaleChange)
	);
	let currentLanguageLabel = $derived(getCurrentLanguageLabel(currentLocale));

	// User email for user dropdown
	let userEmail = $derived(authStore.user?.email || 'Menü');

	// Base navigation items for Todo
	const baseNavItems: PillNavItem[] = [
		{ href: '/', label: 'Aufgaben', icon: 'list' },
		{ href: '/kanban', label: 'Kanban', icon: 'columns' },
		{ href: '/statistics', label: 'Statistiken', icon: 'chart' },
		{ href: '/tags', label: 'Tags', icon: 'tag' },
		{ href: '/network', label: 'Netzwerk', icon: 'share-2' },
		{ href: '/settings', label: 'Einstellungen', icon: 'settings' },
		{ href: '/feedback', label: 'Feedback', icon: 'chat' },
	];

	// Navigation items (base items + dynamic label items in sidebar mode, filtered by visibility settings)
	const navItems = $derived.by(() => {
		// Start with base items, filter out hidden ones (with fallback for guest mode)
		let items = filterHiddenNavItems('todo', baseNavItems, userSettings.nav?.hiddenNavItems || {});

		// In sidebar mode, add tags as sub-items if available
		if (isSidebarMode && labelsStore.labels.length > 0) {
			const tagItems: PillNavItem[] = labelsStore.labels.slice(0, 5).map((label) => ({
				href: `/tag/${label.id}`,
				label: label.name,
				icon: 'tag',
			}));

			// Insert tag items after "Tags" nav item
			const tagsIndex = items.findIndex((i) => i.href === '/tags');
			if (tagsIndex !== -1 && tagItems.length > 0) {
				items = [...items];
				items.splice(tagsIndex + 1, 0, ...tagItems);
			}
		}
		return items;
	});

	// Navigation shortcuts (Ctrl+1-6) - use base items for consistent shortcuts
	const navRoutes = baseNavItems.map((item) => item.href);

	function handleKeydown(event: KeyboardEvent) {
		const target = event.target as HTMLElement;

		if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable) {
			return;
		}

		if ((event.ctrlKey || event.metaKey) && !event.shiftKey && !event.altKey) {
			const num = parseInt(event.key);
			if (num >= 1 && num <= navRoutes.length) {
				event.preventDefault();
				const route = navRoutes[num - 1];
				if (route) {
					goto(route);
				}
			}
		}

		// F = Toggle Immersive Mode (no modifier keys)
		if (
			(event.key === 'f' || event.key === 'F') &&
			!event.ctrlKey &&
			!event.metaKey &&
			!event.shiftKey &&
			!event.altKey
		) {
			event.preventDefault();
			todoSettings.toggleImmersiveMode();
		}
	}

	function handleModeChange(isSidebar: boolean) {
		isSidebarMode = isSidebar;
		sidebarModeStore.set(isSidebar);
		try {
			localStorage?.setItem('todo-nav-sidebar', String(isSidebar));
		} catch {
			// localStorage not available or quota exceeded
		}
	}

	function handleCollapsedChange(collapsed: boolean) {
		isCollapsed = collapsed;
		collapsedStore.set(collapsed);
		try {
			localStorage?.setItem('todo-nav-collapsed', String(collapsed));
		} catch {
			// localStorage not available or quota exceeded
		}
	}

	function handleToolbarCollapsedChange(collapsed: boolean) {
		isToolbarCollapsed = collapsed;
		toolbarCollapsedStore.set(collapsed);
		try {
			localStorage?.setItem('todo-toolbar-collapsed', String(collapsed));
		} catch {
			// localStorage not available or quota exceeded
		}
	}

	function handleToggleTheme() {
		theme.toggleMode();
	}

	function handleThemeModeChange(mode: 'light' | 'dark' | 'system') {
		theme.setMode(mode);
	}

	async function handleLogout() {
		await authStore.signOut();
		projectsStore.clear();
		labelsStore.clear();
		goto('/login');
	}

	// Auth gate modal state
	let showAuthGateModal = $state(false);
	let authGateAction = $state<'save' | 'sync' | 'feature'>('save');

	// Show auth gate modal (can be called from child components)
	function showAuthGate(action: 'save' | 'sync' | 'feature' = 'save') {
		authGateAction = action;
		showAuthGateModal = true;
	}

	// Session tasks indicator
	let sessionTaskCount = $derived(sessionTasksStore.count);

	onMount(async () => {
		// Initialize split-panel from URL/localStorage
		splitPanel.initialize();

		// Initialize todo settings
		todoSettings.initialize();

		// Initialize session tasks for guest mode
		sessionTasksStore.initialize();

		// Load projects (works in both guest and authenticated mode)
		await projectsStore.fetchProjects();

		// Only fetch labels and user settings if authenticated
		if (authStore.isAuthenticated) {
			await Promise.all([labelsStore.fetchLabels(), userSettings.load()]);

			// Check for session tasks to migrate after login
			if (tasksStore.hasSessionTasks) {
				const defaultProject = projectsStore.inboxProject;
				await tasksStore.migrateSessionTasks(defaultProject?.id);
			}

			// Redirect to start page if on root and a custom start page is set
			const currentPath = window.location.pathname;
			if (currentPath === '/' && userSettings.startPage && userSettings.startPage !== '/') {
				goto(userSettings.startPage, { replaceState: true });
			}
		}

		// Initialize sidebar mode from localStorage (with error handling for private browsing)
		try {
			const savedSidebar = localStorage?.getItem('todo-nav-sidebar');
			if (savedSidebar === 'true') {
				isSidebarMode = true;
				sidebarModeStore.set(true);
			}
		} catch {
			// localStorage not available (private browsing, quota exceeded, etc.)
		}

		// Initialize collapsed state from localStorage
		try {
			const savedCollapsed = localStorage?.getItem('todo-nav-collapsed');
			if (savedCollapsed === 'true') {
				isCollapsed = true;
				collapsedStore.set(true);
			}
		} catch {
			// localStorage not available
		}

		// Initialize toolbar collapsed state from localStorage
		try {
			const savedToolbarCollapsed = localStorage?.getItem('todo-toolbar-collapsed');
			if (savedToolbarCollapsed === 'false') {
				isToolbarCollapsed = false;
				toolbarCollapsedStore.set(false);
			}
		} catch {
			// localStorage not available
		}

		// Register Service Worker for PWA
		if ('serviceWorker' in navigator) {
			try {
				const registration = await navigator.serviceWorker.register('/sw.js', {
					scope: '/',
				});
				console.log('Todo PWA: Service Worker registered', registration.scope);

				// Check for updates
				registration.addEventListener('updatefound', () => {
					const newWorker = registration.installing;
					if (newWorker) {
						newWorker.addEventListener('statechange', () => {
							if (newWorker.state === 'installed' && navigator.serviceWorker.controller) {
								// New version available
								console.log('Todo PWA: New version available');
							}
						});
					}
				});
			} catch (error) {
				console.error('Todo PWA: Service Worker registration failed', error);
			}
		}
	});
</script>

<svelte:window onkeydown={handleKeydown} />

<SplitPaneContainer>
	<div class="layout-container">
		<!-- Guest Mode Banner -->
		{#if !authStore.isAuthenticated}
			<div
				class="guest-banner bg-primary/10 border-primary/20 fixed top-0 right-0 left-0 z-50 flex items-center justify-between border-b px-4 py-2"
			>
				<div class="flex items-center gap-2 text-sm">
					<svg class="text-primary h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
						<path
							stroke-linecap="round"
							stroke-linejoin="round"
							stroke-width="2"
							d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
						/>
					</svg>
					<span class="text-foreground">
						<strong>Gast-Modus</strong>
						{#if sessionTaskCount > 0}
							- {sessionTaskCount}
							{sessionTaskCount === 1 ? 'Aufgabe' : 'Aufgaben'} lokal gespeichert
						{:else}
							- Aufgaben werden nur in diesem Tab gespeichert
						{/if}
					</span>
				</div>
				<button
					onclick={() => showAuthGate('sync')}
					class="bg-primary text-primary-foreground hover:bg-primary/90 rounded-md px-3 py-1 text-sm font-medium transition-colors"
				>
					Anmelden
				</button>
			</div>
		{/if}
		<!-- UI Elements (hidden in immersive mode) -->
		{#if !todoSettings.immersiveModeEnabled}
			<PillNavigation
				items={navItems}
				currentPath={$page.url.pathname}
				appName="Todo"
				homeRoute="/"
				onToggleTheme={handleToggleTheme}
				{isDark}
				{isSidebarMode}
				onModeChange={handleModeChange}
				{isCollapsed}
				onCollapsedChange={handleCollapsedChange}
				desktopPosition={userSettings.nav?.desktopPosition || 'bottom'}
				showThemeToggle={true}
				showThemeVariants={true}
				{themeVariantItems}
				{currentThemeVariantLabel}
				themeMode={theme.mode}
				onThemeModeChange={handleThemeModeChange}
				showLanguageSwitcher={true}
				{languageItems}
				{currentLanguageLabel}
				showLogout={authStore.isAuthenticated}
				onLogout={handleLogout}
				loginHref="/login"
				primaryColor="#8b5cf6"
				showAppSwitcher={true}
				{appItems}
				{userEmail}
				settingsHref="/settings"
				manaHref="/mana"
				profileHref="/profile"
				allAppsHref="/apps"
				onOpenInPanel={handleOpenInPanel}
			/>

			<!-- Global Quick Input Bar -->
			<QuickInputBar
				onSearch={handleSearch}
				onSelect={handleSelect}
				placeholder="Neue Aufgabe oder suchen..."
				emptyText="Keine Aufgaben gefunden"
				searchingText="Suche..."
				onCreate={handleCreate}
				onParseCreate={handleParseCreate}
				createText="Erstellen"
				appIcon="todo"
				hasFabRight={true}
				bottomOffset={isToolbarCollapsed ? '70px' : '140px'}
			/>

			<!-- Todo Toolbar (ExpandableToolbar FAB) -->
			<TodoToolbar
				{isSidebarMode}
				isCollapsed={isToolbarCollapsed}
				onCollapsedChange={handleToolbarCollapsedChange}
				onModeChange={handleModeChange}
				bottomOffset="70px"
			/>
		{/if}

		<!-- Immersive Mode Toggle (always visible) -->
		<ImmersiveModeToggle
			isImmersive={todoSettings.immersiveModeEnabled}
			onToggle={() => todoSettings.toggleImmersiveMode()}
		/>

		<main
			class="main-content bg-background"
			class:sidebar-mode={isSidebarMode && !isCollapsed}
			class:floating-mode={!isSidebarMode && !isCollapsed}
			class:immersive={todoSettings.immersiveModeEnabled}
		>
			<div
				class="content-wrapper"
				class:full-width={$page.url.pathname === '/kanban'}
				class:immersive={todoSettings.immersiveModeEnabled}
			>
				{@render children()}
			</div>
		</main>
	</div>
</SplitPaneContainer>

<!-- Auth Gate Modal -->
<AuthGateModal
	visible={showAuthGateModal}
	onClose={() => (showAuthGateModal = false)}
	action={authGateAction}
/>

<style>
	/* Guest banner styling */
	.guest-banner {
		height: 40px;
		min-height: 40px;
	}

	/* Offset content when guest banner is visible */
	.layout-container:has(.guest-banner) .main-content.floating-mode {
		padding-top: calc(70px + 40px);
	}
	.layout-container {
		display: flex;
		flex-direction: column;
		min-height: 100vh;
	}

	.main-content {
		transition: all 300ms ease;
		position: relative;
		/* Space for QuickInputBar at bottom */
		padding-bottom: calc(80px + env(safe-area-inset-bottom));
	}

	.main-content.floating-mode {
		padding-top: 70px;
	}

	.main-content.sidebar-mode {
		padding-left: 180px;
	}

	/* Immersive mode - fullscreen, no padding */
	.main-content.immersive {
		padding: 0 !important;
		height: 100vh;
		width: 100vw;
	}

	.content-wrapper.immersive {
		padding: 0;
		max-width: none;
		height: 100%;
	}

	.content-wrapper {
		max-width: 900px;
		margin-left: auto;
		margin-right: auto;
		padding: 1rem;
	}

	.content-wrapper.full-width {
		max-width: none;
		padding-left: 0;
		padding-right: 0;
	}

	@media (min-width: 640px) {
		.content-wrapper {
			padding: 1.5rem;
		}
		.content-wrapper.full-width {
			padding-left: 0;
			padding-right: 0;
		}
	}

	@media (min-width: 1024px) {
		.content-wrapper {
			padding: 2rem;
		}
		.content-wrapper.full-width {
			padding-left: 0;
			padding-right: 0;
		}
	}

	/* Mobile: More space for QuickInputBar + PillNav */
	@media (max-width: 768px) {
		.main-content {
			padding-bottom: calc(150px + env(safe-area-inset-bottom));
		}
	}
</style>
