<script lang="ts">
	// @ts-nocheck
	import { appController } from '$lib/app/controller';
	import { dismissIosInstallHint, dismissOfflineReady, promptInstall, pwaState } from '$lib/pwa';
	import { appState, unreadNotificationsCount } from '$lib/app/store';
	import { Alert, AlertAction, AlertDescription, AlertTitle } from '$lib/components/ui/alert/index.js';
	import { Avatar, AvatarFallback } from '$lib/components/ui/avatar/index.js';
	import { Badge } from '$lib/components/ui/badge/index.js';
	import { Button } from '$lib/components/ui/button/index.js';
	import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '$lib/components/ui/dialog/index.js';
	import { Separator } from '$lib/components/ui/separator/index.js';

	let { children, pageKey } = $props<{ children: () => unknown; pageKey: string }>();
	let recordingDialogOpen = $state(false);

	$effect(() => {
		appController.setPage(pageKey);
	});

	$effect(() => {
		recordingDialogOpen = $appState.recordingModal.open;
	});

	$effect(() => {
		if (!recordingDialogOpen && $appState.recordingModal.open) {
			appController.closeRecordingModal();
		}
	});

	const isHomePage = (page: string) => page === 'camera' || page === 'client';
	const isAuthenticated = () => Boolean($appState.session && $appState.device);
	const shouldReserveSidebar = () => $appState.loading && pageKey !== 'auth' && pageKey !== 'onboarding';
	const showSidebar = () => isAuthenticated() || shouldReserveSidebar();
	const showSidebarSkeleton = () => shouldReserveSidebar() && !isAuthenticated();
	const userName = () => $appState.session?.user?.name || 'Signed Out';
	const userEmail = () => $appState.session?.user?.email || 'Signed Out';
	const userInitial = () => ($appState.session?.user?.name?.[0] || '?').toUpperCase();
	const navVariant = (active: boolean) => (active ? 'secondary' : 'ghost');
	const toastTitle = (type: string) => (type ? `${type[0].toUpperCase()}${type.slice(1)}` : 'Notice');
	const reloadForUpdate = () => {
		window.location.reload();
	};
	const offlineTitle = () => ($appState.session ? 'Offline Shell Mode' : 'Offline');
	const offlineDescription = () =>
		$appState.session
			? 'Cached screens remain available, but sign-in refresh, live monitoring, camera control, and realtime updates need connectivity.'
			: 'You can open the cached shell, but sign-in and device setup need an internet connection.';
</script>

<div data-sim-page={pageKey} class="flex h-full w-full">
	<div id="toast-container" class="fixed top-4 right-4 z-50 flex w-[22rem] flex-col gap-3">
		{#each $appState.toasts as toast (toast.id)}
			<Alert
				variant={toast.type === 'error' ? 'destructive' : 'default'}
				class="glass-card border-white/10 bg-background/95 shadow-lg"
			>
				<AlertTitle class="text-xs">{toastTitle(toast.type)}</AlertTitle>
				<AlertDescription class="pr-8 text-xs text-gray-300">{toast.message}</AlertDescription>
				<AlertAction>
					<Button
						variant="ghost"
						size="icon-xs"
						class="text-gray-400 hover:text-white"
						onclick={() => appController.removeToast(toast.id)}
					>
						<svg data-icon="inline-start" xmlns="http://www.w3.org/2000/svg" class="size-3.5" 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>
						<span class="sr-only">Dismiss notification</span>
					</Button>
				</AlertAction>
			</Alert>
		{/each}

		{#if $pwaState.installAvailable}
			<Alert class="glass-card border-white/10 bg-background/95 shadow-lg">
				<AlertTitle class="text-xs">Install App</AlertTitle>
				<AlertDescription class="pr-8 text-xs text-gray-300">
					Add PhoneCam to your home screen for a more native dashboard experience.
				</AlertDescription>
				<AlertAction>
					<Button
						variant="outline"
						size="sm"
						class="border-white/10 text-gray-200"
						disabled={$pwaState.installing}
						onclick={() => void promptInstall()}
					>
						{$pwaState.installing ? 'Installing...' : 'Install'}
					</Button>
				</AlertAction>
			</Alert>
		{/if}

		{#if $pwaState.showIosInstallHint}
			<Alert class="glass-card border-white/10 bg-background/95 shadow-lg">
				<AlertTitle class="text-xs">Install on iPhone</AlertTitle>
				<AlertDescription class="pr-8 text-xs text-gray-300">
					In Safari, tap the Share button, then choose “Add to Home Screen” to install PhoneCam.
				</AlertDescription>
				<AlertAction>
					<Button variant="ghost" size="sm" class="text-gray-300" onclick={dismissIosInstallHint}>
						Got it
					</Button>
				</AlertAction>
			</Alert>
		{/if}

		{#if $pwaState.updateAvailable}
			<Alert class="glass-card border-blue-500/20 bg-background/95 shadow-lg">
				<AlertTitle class="text-xs">Update Ready</AlertTitle>
				<AlertDescription class="pr-8 text-xs text-gray-300">
					A newer version of PhoneCam is ready. Reload to use the latest app shell.
				</AlertDescription>
				<AlertAction>
					<Button variant="outline" size="sm" class="border-blue-500/30 text-gray-200" onclick={reloadForUpdate}>
						Reload
					</Button>
				</AlertAction>
			</Alert>
		{/if}

		{#if $pwaState.offlineReady}
			<Alert class="glass-card border-emerald-500/20 bg-background/95 shadow-lg">
				<AlertTitle class="text-xs">Offline Shell Ready</AlertTitle>
				<AlertDescription class="pr-8 text-xs text-gray-300">
					The app shell is now cached for quicker relaunches, but live camera features still need connectivity.
				</AlertDescription>
				<AlertAction>
					<Button variant="ghost" size="sm" class="text-gray-300" onclick={dismissOfflineReady}>
						Dismiss
					</Button>
				</AlertAction>
			</Alert>
		{/if}
	</div>

	<aside
		id="bottomNav"
		class="w-20 lg:w-72 glass-panel border-r border-white/5 flex-col justify-between h-full {showSidebar() ? 'flex' : 'hidden'}"
	>
		{#if showSidebarSkeleton()}
			<div class="p-4 lg:p-6">
				<div class="flex items-center justify-center gap-3 lg:justify-start">
					<div class="size-10 rounded-full bg-white/8 animate-pulse"></div>
					<div class="hidden min-w-0 flex-1 flex-col gap-2 lg:flex">
						<div class="h-3 w-28 rounded-full bg-white/8 animate-pulse"></div>
						<div class="h-2.5 w-36 rounded-full bg-white/6 animate-pulse"></div>
					</div>
				</div>
				<div class="mt-3 flex items-center justify-center lg:justify-start">
					<div class="h-6 w-24 rounded-full bg-white/8 animate-pulse"></div>
				</div>
			</div>
			<Separator class="bg-white/5" />
			<nav class="flex flex-1 flex-col gap-2 py-6 px-3">
				{#each Array(3) as _, index (index)}
					<div class="h-12 w-full rounded-xl bg-white/6 animate-pulse"></div>
				{/each}
			</nav>
		{:else}
			<div class="p-4 lg:p-6">
				<div id="authStatusBadge" class="flex items-center justify-center lg:justify-start gap-3 text-sm text-gray-300">
					<Avatar size="lg" class="bg-gray-800/80 text-xs font-bold text-white">
						<AvatarFallback>{userInitial()}</AvatarFallback>
					</Avatar>
					<div class="hidden lg:block min-w-0">
						<p class="font-semibold text-white truncate" title={userEmail()}>{userName()}</p>
						<p class="text-xs text-gray-500 truncate" title={userEmail()}>{userEmail()}</p>
					</div>
				</div>
				<div id="connectionStatus" class="mt-3 flex items-center justify-center lg:justify-start gap-2">
					<Badge
						variant={$appState.socketConnected ? 'secondary' : 'destructive'}
						class="gap-2 rounded-full px-2.5 py-1 text-[11px] uppercase tracking-wide"
					>
						<span class="status-dot {$appState.socketConnected ? 'status-online' : 'status-offline'} transition-colors duration-300"></span>
						{$appState.socketConnected ? 'ONLINE' : 'OFFLINE'}
					</Badge>
				</div>
			</div>
			<Separator class="bg-white/5" />

			<nav class="flex flex-1 flex-col gap-2 py-6 px-3">
				<Button
					variant={navVariant(isHomePage($appState.page))}
					class="nav-btn h-12 w-full justify-center gap-3 rounded-xl border border-transparent text-gray-400 hover:text-white lg:justify-start"
					onclick={() => appController.navigate('home')}
				>
					<svg
						xmlns="http://www.w3.org/2000/svg"
						data-icon="inline-start"
						class="h-5 w-5 shrink-0"
						fill="none"
						viewBox="0 0 24 24"
						stroke="currentColor"
					>
						<path
							stroke-linecap="round"
							stroke-linejoin="round"
							stroke-width="2"
							d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6"
						/>
					</svg>
					<span class="font-medium hidden lg:block text-sm">Dashboard</span>
				</Button>

				<Button
					variant={navVariant($appState.page === 'activity')}
					class="nav-btn relative h-12 w-full justify-center gap-3 rounded-xl border border-transparent text-gray-400 hover:text-white lg:justify-start"
					onclick={() => appController.navigate('activity')}
				>
					<svg
						xmlns="http://www.w3.org/2000/svg"
						data-icon="inline-start"
						class="h-5 w-5 shrink-0"
						fill="none"
						viewBox="0 0 24 24"
						stroke="currentColor"
					>
						<path
							stroke-linecap="round"
							stroke-linejoin="round"
							stroke-width="2"
							d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9"
						/>
					</svg>
					<span class="font-medium hidden lg:block text-sm">Activity Feed</span>
					{#if $unreadNotificationsCount > 0}
						<Badge
							id="notificationDot"
							variant="destructive"
							class="absolute top-2.5 right-2 size-2 rounded-full p-0 lg:hidden"
						/>
						<Badge
							variant="destructive"
							class="ml-auto hidden min-w-5 items-center justify-center rounded-full px-1.5 text-[10px] lg:inline-flex"
						>
							{$unreadNotificationsCount}
						</Badge>
					{/if}
				</Button>

				<Button
					variant={navVariant($appState.page === 'settings')}
					class="nav-btn h-12 w-full justify-center gap-3 rounded-xl border border-transparent text-gray-400 hover:text-white lg:justify-start"
					onclick={() => appController.navigate('settings')}
				>
					<svg
						xmlns="http://www.w3.org/2000/svg"
						data-icon="inline-start"
						class="h-5 w-5 shrink-0"
						fill="none"
						viewBox="0 0 24 24"
						stroke="currentColor"
					>
						<path
							stroke-linecap="round"
							stroke-linejoin="round"
							stroke-width="2"
							d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"
						/>
						<path
							stroke-linecap="round"
							stroke-linejoin="round"
							stroke-width="2"
							d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"
						/>
					</svg>
					<span class="font-medium hidden lg:block text-sm">Settings</span>
				</Button>
			</nav>
		{/if}
	</aside>

	<main class="flex-1 flex flex-col h-full overflow-hidden relative">
		{#if $pwaState.isOffline}
			<div class="px-4 pt-4 md:px-8 md:pt-6 lg:px-10">
				<Alert class="glass-card border-amber-500/20 bg-[#141418]/95 shadow-lg">
					<AlertTitle class="text-xs uppercase tracking-wide text-amber-300">{offlineTitle()}</AlertTitle>
					<AlertDescription class="text-xs text-gray-300">
						{offlineDescription()}
					</AlertDescription>
				</Alert>
			</div>
		{/if}
		<div class="flex-1 overflow-y-auto p-4 md:p-8 lg:p-10 relative">
			{@render children()}
		</div>
	</main>
</div>

<Dialog bind:open={recordingDialogOpen}>
	<DialogContent
		id="recordingModal"
		showCloseButton={false}
		class="glass-card max-w-5xl border-white/10 bg-[#101014]/95 p-0 shadow-2xl sm:max-w-5xl"
	>
		<DialogHeader class="gap-3 px-6 pt-6">
			<div class="flex items-center justify-between gap-4">
				<div class="min-w-0">
					<DialogTitle id="recordingModalTitle" class="truncate text-lg font-semibold text-white tracking-wide">
						{$appState.recordingModal.title}
					</DialogTitle>
					<DialogDescription class="sr-only">Playback of the selected recording.</DialogDescription>
				</div>
				<Button
					id="recordingModalCloseBtn"
					variant="ghost"
					size="icon-sm"
					class="text-gray-400 hover:text-white"
					aria-label="Close recording modal"
					title="Close recording modal"
					onclick={() => appController.closeRecordingModal()}
				>
					<svg data-icon="inline-start" xmlns="http://www.w3.org/2000/svg" class="size-4" 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>
		</DialogHeader>
		<div class="px-6 pb-6">
			<div class="min-h-0 overflow-hidden rounded-2xl border border-white/5 bg-black shadow-inner">
				<video id="recordingModalVideo" class="h-full w-full object-contain" src={$appState.recordingModal.url} controls playsinline>
					<track kind="captions" />
				</video>
			</div>
		</div>
	</DialogContent>
</Dialog>
