<script lang="ts">
	// @ts-nocheck
	import AppChrome from '$lib/sim/ui/AppChrome.svelte';
	import { appController } from '$lib/app/controller';
	import { appState } from '$lib/app/store';
	import { Alert, AlertDescription, AlertTitle } from '$lib/components/ui/alert/index.js';
	import { Badge } from '$lib/components/ui/badge/index.js';
	import { Button } from '$lib/components/ui/button/index.js';
	import { Card, CardContent, CardHeader, CardTitle } from '$lib/components/ui/card/index.js';
	import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '$lib/components/ui/dropdown-menu/index.js';
	import { ScrollArea } from '$lib/components/ui/scroll-area/index.js';
	import {
		Plus,
		RefreshCw,
		Monitor,
		Eye,
		Video,
		VideoOff,
		MoreVertical,
		X,
		History,
		Activity,
		ShieldCheck,
		Clock
	} from '@lucide/svelte';

	let clientVideoElement: HTMLVideoElement | null = null;

	$effect(() => {
		appController.setClientVideoElement(clientVideoElement);
	});

	const statusDotClass = (status: string) =>
		status?.toLowerCase() === 'online' ? 'bg-green-500' : 'bg-gray-600';

	const isCameraLive = (cameraDeviceId: string) => {
		const sessionId = $appState.cameraSessions?.[cameraDeviceId];
		if (!sessionId) return false;
		return $appState.connectedStreamSessionIds.includes(sessionId);
	};

	const activeCameraLabel = () => {
		const linked = $appState.linkedCameras.find((camera) => camera.cameraDeviceId === $appState.activeCameraDeviceId);
		return linked?.cameraName || linked?.cameraDeviceId || 'Live Feed Viewer';
	};

	const activeStreamSessionId = () => {
		if ($appState.activeStreamSessionId) {
			return $appState.activeStreamSessionId;
		}
		if (!$appState.activeCameraDeviceId) {
			return null;
		}
		return $appState.cameraSessions?.[$appState.activeCameraDeviceId] ?? null;
	};

	const activeStreamDiagnostics = () => {
		const streamSessionId = activeStreamSessionId();
		if (!streamSessionId) {
			return null;
		}
		return $appState.streamDiagnostics?.[streamSessionId] ?? null;
	};

	const diagnosticLevelClass = (level: string) => {
		if (level === 'error') return 'border-red-500/20 bg-red-500/10 text-red-200';
		if (level === 'success') return 'border-emerald-500/20 bg-emerald-500/10 text-emerald-200';
		return 'border-white/10 bg-white/5 text-gray-300';
	};
</script>

<AppChrome pageKey="client">
	<section id="screen-home-client" class="mx-auto flex h-full max-w-7xl min-h-0 flex-col gap-6">
		<div class="flex justify-between items-center px-1">
			<h2 class="text-2xl font-bold text-white tracking-tight">Client Dashboard</h2>
			<div class="flex gap-2">
				<Button
					id="linkCameraBtn"
					variant="outline"
					size="sm"
					class="rounded-xl border-white/10 text-gray-300 shadow-none hover:bg-white/5 hover:text-white"
					onclick={() => appController.linkCamera()}
				>
					<Plus class="h-4 w-4 mr-1.5" />
					Link Camera
				</Button>
				<Button
					id="refreshClientBtn"
					variant="ghost"
					size="icon-sm"
					class="rounded-xl border border-white/5 bg-white/5 hover:bg-white/10"
					aria-label="Refresh linked cameras"
					title="Refresh linked cameras"
					onclick={() => appController.refreshClientData()}
				>
					<RefreshCw class="h-4 w-4" />
				</Button>
			</div>
		</div>

		<Card variant="glass" class="mb-2 shrink-0 rounded-3xl">
			<CardHeader class="pb-3 flex flex-row items-center gap-2">
				<Monitor class="size-3.5 text-gray-500" />
				<CardTitle class="text-[10px] font-bold uppercase tracking-widest text-gray-500">Your Cameras</CardTitle>
			</CardHeader>
			<CardContent>
				{#if $appState.linkedCameras.length === 0}
					<Alert variant="default" class="border-dashed border-white/10 bg-black/20 text-center py-8">
						<AlertTitle class="text-sm text-gray-200">No cameras linked</AlertTitle>
						<AlertDescription class="text-xs text-gray-500">
							Link a camera to start viewing live feeds and recordings.
						</AlertDescription>
					</Alert>
				{:else}
					<ScrollArea class="w-full whitespace-nowrap" orientation="horizontal">
						<div id="linkedCamerasList" class="flex gap-4 pb-3">
						{#each $appState.linkedCameras as link (link.id)}
							<div
								role="button"
								tabindex="0"
								class="min-w-[240px] max-w-[240px] flex-shrink-0 cursor-pointer text-left group"
								onclick={(event) => {
									if ((event.target as HTMLElement).closest('[data-menu-trigger]')) return;
									appController.selectCamera(link.cameraDeviceId);
								}}
								onkeydown={(event) => {
									if (event.key === 'Enter' || event.key === ' ') appController.selectCamera(link.cameraDeviceId);
								}}
							>
								<Card
									size="sm"
									class="overflow-hidden rounded-xl border transition-all duration-300 { $appState.activeCameraDeviceId === link.cameraDeviceId ? 'border-blue-500/50 bg-blue-950/20' : 'border-white/5 bg-gray-900/60 hover:border-blue-500/30' }"
								>
									<div class="relative aspect-video overflow-hidden border-b border-white/5 bg-black/40">
										{#if $appState.activeCameraDeviceId === link.cameraDeviceId}
											<div class="absolute inset-0 flex flex-col items-center justify-center gap-2 bg-blue-500/10 text-blue-400">
												<Eye class="h-6 w-6" />
												<Badge variant="secondary" class="rounded-full px-2 text-[10px] uppercase tracking-wider">
													Viewing
												</Badge>
											</div>
										{:else}
											<div class="absolute inset-0 flex flex-col items-center justify-center gap-2 text-gray-600 transition-colors group-hover:text-gray-400">
												<Video class="h-6 w-6" />
												<p class="text-[10px] font-medium tracking-wide">{isCameraLive(link.cameraDeviceId) ? 'LIVE' : 'CLICK TO VIEW'}</p>
											</div>
										{/if}
									</div>
									<CardContent class="px-3 py-3">
										<div class="flex items-start justify-between gap-2">
											<div class="min-w-0 flex-1 space-y-2">
												<p class="truncate text-xs font-bold text-gray-200" title={link.cameraName || link.cameraDeviceId}>
													{link.cameraName || link.cameraDeviceId}
												</p>
												<Badge
													variant={link.cameraStatus?.toLowerCase() === 'online' ? 'secondary' : 'outline'}
													class="gap-1.5 rounded-full px-2 capitalize text-[10px]"
												>
													<span class="h-1.5 w-1.5 rounded-full shrink-0 {statusDotClass(link.cameraStatus)} shadow-[0_0_4px_rgba(16,185,129,0.4)]"></span>
													{link.cameraStatus || 'offline'}
												</Badge>
											</div>
											<DropdownMenu>
												<DropdownMenuTrigger>
													{#snippet child({ props })}
														<Button
															data-menu-trigger
															variant="ghost"
															size="icon-xs"
															class="text-gray-400 hover:text-white"
															{...props}
														>
															<MoreVertical class="h-3.5 w-3.5" />
														</Button>
													{/snippet}
												</DropdownMenuTrigger>
												<DropdownMenuContent align="end" class="w-28">
													<DropdownMenuItem
														onclick={(event) => {
															event.stopPropagation();
															appController.renameLinkedCamera(link.cameraDeviceId);
														}}
													>
														Rename
													</DropdownMenuItem>
													<DropdownMenuItem
														variant="destructive"
														onclick={(event) => {
															event.stopPropagation();
															appController.deleteLinkedCamera(link.id);
														}}
													>
														Delete
													</DropdownMenuItem>
												</DropdownMenuContent>
											</DropdownMenu>
										</div>
									</CardContent>
								</Card>
							</div>
						{/each}
						</div>
					</ScrollArea>
				{/if}
			</CardContent>
		</Card>

		<div class="flex flex-1 min-h-0 flex-col gap-6 xl:flex-row">
			<Card
				id="clientStreamViewerWrapper"
				variant="glass"
				class="min-w-0 flex-1 overflow-hidden shadow-xl {$appState.activeCameraDeviceId ? 'flex min-h-[400px] flex-col xl:min-h-0' : 'hidden'}"
			>
				<CardHeader class="border-b border-white/5 bg-black/20 px-5 py-3">
					<div class="flex items-center justify-between gap-3">
						<div class="flex items-center gap-3">
							{#if isCameraLive($appState.activeCameraDeviceId)}
								<span class="w-2 h-2 rounded-full bg-red-500 animate-[pulse_2s_ease-in-out_infinite]" id="clientLiveDot"></span>
							{/if}
							<CardTitle class="text-sm font-semibold tracking-wide text-white" id="clientStreamViewerTitle">
								{activeCameraLabel()}
							</CardTitle>
						</div>
						<Button
						id="closeStreamViewerBtn"
						variant="ghost"
						size="icon-xs"
						class="text-gray-400 hover:text-white"
						aria-label="Close stream viewer"
						title="Close stream viewer"
						onclick={() => appController.closeStreamViewer()}
					>
							<X class="h-4 w-4" />
						</Button>
					</div>
				</CardHeader>

				<CardContent id="clientStreamContainer" class="relative flex min-h-[320px] flex-1 items-center justify-center overflow-hidden bg-black p-0">
					<video
						id="clientStreamVideo"
						class="absolute inset-0 h-full w-full object-contain {$appState.clientStreamMode === 'video' ? '' : 'hidden'}"
						autoplay
						muted
						playsinline
						bind:this={clientVideoElement}
					></video>

					<div
						id="clientStreamPlaceholder"
						class="relative z-10 m-6 flex max-w-sm flex-col items-center gap-4 text-center {$appState.clientStreamMode === 'none' || $appState.clientStreamMode === 'connecting' || $appState.clientStreamMode === 'unavailable' ? '' : 'hidden'}"
					>
						<div class="p-5 rounded-full bg-white/5 mb-2">
							<VideoOff class="h-10 w-10 text-gray-600" />
						</div>
						<p class="text-base font-semibold text-white">Stream unavailable</p>
						<p class="text-xs font-bold uppercase tracking-widest text-gray-500">
							{$appState.clientPlaceholderText}
						</p>
					</div>
				</CardContent>

				{#if activeStreamDiagnostics()}
					<div class="border-t border-white/5 bg-black/20 px-5 py-4">
						<div class="flex flex-wrap items-center gap-2 text-[10px] font-bold uppercase tracking-widest text-gray-500">
							<Activity class="size-3 text-blue-500" />
							<span>Diagnostics</span>
							<Badge variant="outline" class="border-white/5 text-[9px] text-gray-500 px-1.5 font-mono">
								{activeStreamSessionId()?.slice(0, 8)}
							</Badge>
							{#if isCameraLive($appState.activeCameraDeviceId)}
								<Badge variant="secondary" class="rounded-full px-2 text-[9px] font-bold uppercase tracking-widest">Peer connected</Badge>
							{/if}
						</div>
						<div class="mt-4 grid gap-2">
							{#each activeStreamDiagnostics().entries.slice(0, 4) as entry (entry.id)}
								<div class="rounded-xl border px-3 py-2 {diagnosticLevelClass(entry.level)} transition-colors">
									<div class="flex items-center justify-between gap-3">
										<span class="text-[10px] font-bold uppercase tracking-wider">{entry.stage}</span>
										<span class="text-[9px] font-medium opacity-50">{new Date(entry.createdAt).toLocaleTimeString()}</span>
									</div>
									<p class="mt-1 text-xs text-current opacity-90">{entry.message}</p>
								</div>
							{/each}
						</div>
					</div>
				{/if}
			</Card>

			<div class="flex shrink-0 flex-col gap-6 pr-2 xl:max-h-full xl:w-96 xl:overflow-y-auto">
				<Card variant="glass" class="flex-1 rounded-3xl">
					<CardHeader class="pb-3 flex flex-row items-center gap-2">
						<History class="size-3.5 text-gray-500" />
						<CardTitle class="text-[10px] font-bold uppercase tracking-widest text-gray-400">Recent Clips</CardTitle>
					</CardHeader>
					<CardContent>
						<ScrollArea class="max-h-[30rem] pr-3">
							<div id="recordingsList" class="space-y-3">
						{#if $appState.recordings.length === 0}
								<Alert variant="default" class="border-dashed border-white/10 bg-gray-900/30 text-center py-6">
									<AlertTitle class="text-xs text-gray-200">No recordings found</AlertTitle>
									<AlertDescription class="text-[10px] text-gray-500">
										Captured clips will appear here.
									</AlertDescription>
								</Alert>
						{:else}
							{#each $appState.recordings.slice(0, 8) as recording (recording.id)}
									<Card size="sm" class="border-white/5 bg-white/5 hover:bg-white/10 transition-colors">
										<CardContent class="flex items-center justify-between gap-4 px-3 py-3">
											<div class="flex flex-col gap-1">
												<div class="flex items-center gap-1.5">
													<Clock class="size-3 text-gray-500" />
													<span class="text-xs font-semibold text-gray-300">{new Date(recording.createdAt).toLocaleTimeString()}</span>
												</div>
												<span class="text-[9px] font-bold uppercase tracking-widest text-gray-500">
													{recording.status ?? 'unknown'} · {recording.durationSeconds != null ? `${recording.durationSeconds}s` : '--'}
												</span>
											</div>
											<Button
												variant="outline"
												size="xs"
												class="h-7 rounded-lg border-white/10 text-xs font-bold text-gray-400 hover:text-white"
												disabled={recording.status !== 'ready'}
												onclick={() => appController.openRecording(recording.id)}
											>
												View
											</Button>
										</CardContent>
									</Card>
							{/each}
						{/if}
							</div>
						</ScrollArea>
					</CardContent>
				</Card>
			</div>
		</div>
	</section>
</AppChrome>
