<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';

	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';
	};
</script>

<AppChrome pageKey="client">
	<section id="screen-home-client" class="mx-auto flex h-full max-w-7xl min-h-0 flex-col gap-8">
		<div class="flex justify-between items-center mb-4">
			<h2 class="text-2xl font-bold text-white tracking-tight">Client Dashboard</h2>
			<div class="flex gap-3">
				<Button
					id="linkCameraBtn"
					variant="outline"
					class="rounded-xl border-white/10 text-gray-300 shadow-none hover:bg-white/5 hover:text-white"
					onclick={() => appController.linkCamera()}
				>
					<svg data-icon="inline-start" xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
						<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
					</svg>
					Link Camera
				</Button>
				<Button
					id="refreshClientBtn"
					variant="ghost"
					size="icon"
					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()}
				>
					<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
						<path
							stroke-linecap="round"
							stroke-linejoin="round"
							stroke-width="2"
							d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"
						/>
					</svg>
				</Button>
			</div>
		</div>

		<Card class="glass-card mb-4 shrink-0 rounded-3xl border-white/10 bg-[#16161d]/80">
			<CardHeader>
				<CardTitle class="text-xs font-bold uppercase tracking-wider text-gray-400">Your Cameras</CardTitle>
			</CardHeader>
			<CardContent>
				{#if $appState.linkedCameras.length === 0}
					<Alert class="border-dashed border-white/10 bg-black/20 text-center">
						<AlertTitle class="justify-self-center text-sm text-gray-200">No cameras linked</AlertTitle>
						<AlertDescription class="justify-self-center text-sm 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-2">
						{#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"
								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-colors { $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">
												<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
													<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
													<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
												</svg>
												<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-500 transition-colors hover:text-gray-300">
												<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
													<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z" />
												</svg>
												<p class="text-[10px]">{isCameraLive(link.cameraDeviceId) ? 'Live Stream Active' : '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"
												>
													<span class="h-2 w-2 rounded-full shrink-0 {statusDotClass(link.cameraStatus)}"></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}
														>
															<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
																<circle cx="10" cy="4" r="1.6" />
																<circle cx="10" cy="10" r="1.6" />
																<circle cx="10" cy="16" r="1.6" />
															</svg>
														</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-8 xl:flex-row">
			<Card
				id="clientStreamViewerWrapper"
				class="glass-card min-w-0 flex-1 overflow-hidden rounded-3xl border-white/10 bg-[#16161d]/80 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-4">
					<div class="flex items-center justify-between gap-3">
						<div class="flex items-center gap-3">
							<span class="w-2 h-2 rounded-full bg-red-500 animate-[pulse_2s_ease-in-out_infinite] {isCameraLive($appState.activeCameraDeviceId) ? '' : 'hidden'}" id="clientLiveDot"></span>
							<CardTitle class="font-medium tracking-wide text-white" id="clientStreamViewerTitle">
								Live Feed: {activeCameraLabel()}
							</CardTitle>
						</div>
						<Button
						id="closeStreamViewerBtn"
						variant="ghost"
						size="icon-sm"
						class="text-gray-400 hover:text-white"
						aria-label="Close stream viewer"
						title="Close stream viewer"
						onclick={() => appController.closeStreamViewer()}
					>
							<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-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>
				</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>

					<Alert
						id="clientStreamPlaceholder"
						class="relative z-10 m-6 flex max-w-md flex-col items-center gap-4 border-white/10 bg-black/40 text-center {$appState.clientStreamMode === 'none' || $appState.clientStreamMode === 'connecting' || $appState.clientStreamMode === 'unavailable' ? '' : 'hidden'}"
					>
						<svg xmlns="http://www.w3.org/2000/svg" class="h-12 w-12 text-gray-700" fill="none" viewBox="0 0 24 24" stroke="currentColor">
							<path
								stroke-linecap="round"
								stroke-linejoin="round"
								stroke-width="2"
								d="M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z"
							></path>
						</svg>
						<AlertTitle class="justify-self-center text-sm text-gray-200">Stream unavailable</AlertTitle>
						<AlertDescription class="justify-self-center text-sm font-medium uppercase tracking-wide text-gray-500">
							{$appState.clientPlaceholderText}
						</AlertDescription>
					</Alert>
				</CardContent>
			</Card>

			<div class="flex shrink-0 flex-col gap-6 pr-2 xl:max-h-full xl:w-96 xl:overflow-y-auto">
				<Card class="glass-card flex-1 rounded-3xl border-white/10 bg-[#16161d]/80">
					<CardHeader>
						<CardTitle class="text-xs font-bold uppercase tracking-wider text-gray-400">Recent Recordings</CardTitle>
					</CardHeader>
					<CardContent>
						<ScrollArea class="max-h-[26rem] pr-3">
							<div id="recordingsList" class="space-y-3">
						{#if $appState.recordings.length === 0}
								<Alert class="border-white/10 bg-gray-900/30 text-center">
									<AlertTitle class="justify-self-center text-xs text-gray-200">No recordings found</AlertTitle>
									<AlertDescription class="justify-self-center text-xs text-gray-500">
										Captured clips will appear here when they are ready.
									</AlertDescription>
								</Alert>
						{:else}
							{#each $appState.recordings.slice(0, 5) as recording (recording.id)}
									<Card size="sm" class="border-white/5 bg-gray-900/40">
										<CardContent class="flex items-center justify-between gap-4 px-3 py-3">
											<div class="flex flex-col">
												<span class="text-xs font-medium text-gray-300">{new Date(recording.createdAt).toLocaleString()}</span>
												<span class="text-[10px] text-gray-500">
													{recording.durationSeconds != null ? `${recording.durationSeconds}s duration` : 'Duration pending'} · {recording.status ?? 'unknown'}
												</span>
											</div>
											<Button
												variant="outline"
												size="xs"
												class="border-white/10 text-gray-400"
												disabled={recording.status !== 'ready'}
												onclick={() => appController.openRecording(recording.id)}
											>
												View
											</Button>
										</CardContent>
									</Card>
							{/each}
						{/if}
							</div>
						</ScrollArea>
					</CardContent>
				</Card>
			</div>
		</div>
	</section>
</AppChrome>
