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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
<script lang="ts">
	import { T } from "@threlte/core";
	import { interactivity } from "@threlte/extras";
	import {
		VideoTexture,
		CanvasTexture,
		LinearFilter,
		RGBAFormat,
		Shape,
		Path,
		ExtrudeGeometry,
		BoxGeometry
	} from "three";
	import { onMount } from "svelte";
	import type { VideoInstance } from "$lib/elements/video/VideoManager.svelte";
	import { videoManager } from "$lib/elements/video/VideoManager.svelte";

	// Props interface
	interface Props {
		// Video instance (required)
		videoInstance: VideoInstance;

		// Workspace ID (required for API calls)
		workspaceId: string;

		// TV dimensions
		width?: number;
		height?: number;
		depth?: number;
		frameThickness?: number;
		cornerRadius?: number;

		// Video props - now optional since we use the connection system
		videoSrc?: string;
		loadingDelay?: number;

		// Style props
		frameColor?: string;
		frameActiveColor?: string;
		frameMetalness?: number;
		frameRoughness?: number;
		frameEnvMapIntensity?: number;
		fallbackColor?: string;

		// Loading props
		showLoading?: boolean;
		loadingText?: string;
		loadingEmoji?: string;

		// Stream management props
		lazyLoad?: boolean;
	}

	// Props with defaults
	let {
		videoInstance,
		workspaceId,

		width = 4,
		height = 2.25,
		depth = 0.1,
		frameThickness = 0.2,
		cornerRadius = 0.15,

		videoSrc = "/video.mp4", // Fallback if no stream
		loadingDelay = 1000, // Reduced delay for real streams

		frameColor = "#374151",
		frameActiveColor = "#FFD700",
		frameMetalness = 0.05,
		frameRoughness = 0.4,
		frameEnvMapIntensity = 0.3,
		fallbackColor = "#FFD700",

		showLoading = true,
		loadingText = "Hover to load video...",
		loadingEmoji = "📺",

		lazyLoad = true
	}: Props = $props();

	let isPlayingLocked = $state(false);
	let isHovered = $state(false);

	// Video setup
	let videoElement: HTMLVideoElement | null = $state(null);
	let videoTexture: VideoTexture | null = $state(null);
	let loadingTexture: CanvasTexture | null = $state(null);
	let videoLoaded = $state(false);
	let isLoading = $state(false);

	// Function to create loading texture with text
	const createLoadingTexture = (text: string, backgroundColor: string = fallbackColor) => {
		const canvas = document.createElement("canvas");
		const ctx = canvas.getContext("2d")!;

		// Set canvas size (should match video aspect ratio)
		canvas.width = 512;
		canvas.height = 288; // 16:9 aspect ratio

		// Fill background
		ctx.fillStyle = backgroundColor;
		ctx.fillRect(0, 0, canvas.width, canvas.height);

		// Setup text styling
		ctx.fillStyle = "#FFFFFF";
		ctx.textAlign = "center";
		ctx.textBaseline = "middle";
		ctx.font = "bold 32px Arial, sans-serif";

		// Add text shadow for better readability
		ctx.shadowColor = "rgba(0, 0, 0, 0.7)";
		ctx.shadowBlur = 4;
		ctx.shadowOffsetX = 2;
		ctx.shadowOffsetY = 2;

		// Draw the loading text
		ctx.fillText(text, canvas.width / 2, canvas.height / 2);

		// Draw emoji if provided
		if (loadingEmoji) {
			ctx.font = "bold 48px Arial, sans-serif";
			ctx.shadowColor = "transparent";
			ctx.fillText(loadingEmoji, canvas.width / 2, canvas.height / 2 - 60);
		}

		// Create and return Three.js texture
		const texture = new CanvasTexture(canvas);
		texture.minFilter = LinearFilter;
		texture.magFilter = LinearFilter;
		texture.needsUpdate = true;

		return texture;
	};

	// Function to setup video element
	const setupVideo = (stream?: MediaStream) => {
		// Create video element
		videoElement = document.createElement("video");
		videoElement.loop = true;
		videoElement.muted = true; // Required for autoplay
		videoElement.playsInline = true;
		videoElement.crossOrigin = "anonymous";

		if (stream) {
			// Use live stream
			videoElement.srcObject = stream;
		} else {
			// Fallback to static video
			videoElement.src = videoSrc;
		}

		// Create video texture
		if (!videoTexture) {
			videoTexture = new VideoTexture(videoElement);
			videoTexture.minFilter = LinearFilter;
			videoTexture.magFilter = LinearFilter;
			videoTexture.format = RGBAFormat;
			videoTexture.flipY = true; // Fix the flipped video
			videoTexture.needsUpdate = true;

			videoElement.addEventListener("loadeddata", () => {
				videoLoaded = true;
				isLoading = false;
			});

			videoElement.addEventListener("canplay", () => {
				videoElement?.play().catch(console.error);
			});

			videoElement.addEventListener("error", (e) => {
				console.error("Video error:", e);
				isLoading = false;
			});

			if (stream) {
				// For streams, try to play immediately
				videoElement.play().catch(console.error);
				// Mark as loaded faster for live streams
				setTimeout(() => {
					if (!videoLoaded) {
						videoLoaded = true;
						isLoading = false;
					}
				}, 500);
			} else {
				videoElement.load();
			}
		}
	};

	// Function to cleanup video
	const cleanupVideo = () => {
		if (videoElement) {
			videoElement.pause();
			if (videoElement.srcObject) {
				videoElement.srcObject = null;
			}
			if (videoElement.src) {
				videoElement.removeAttribute("src");
				videoElement.load(); // This clears any pending loads
			}
			videoElement = null;
		}
		if (videoTexture) {
			videoTexture.dispose();
			videoTexture = null;
		}
		if (loadingTexture) {
			loadingTexture.dispose();
			loadingTexture = null;
		}
		videoLoaded = false;
		isLoading = false;
	};

	// Create loading texture on mount
	onMount(() => {
		loadingTexture = createLoadingTexture(loadingText);
	});

	let shouldPlay = $derived(isPlayingLocked || isHovered);

	// Watch for hover state changes
	$effect(() => {
		if (shouldPlay) {
			// Start loading video when hovered
			isLoading = true;

			// Create a loading texture for the loading state if not already created
			if (!loadingTexture) {
				loadingTexture = createLoadingTexture("Loading...");
			}

			// Cache status values to prevent reactive loops
			const canActivate =
				lazyLoad &&
				(videoInstance.input.connectionState === "prepared" ||
					videoInstance.input.connectionState === "paused");
			const hasPreparedRoom = videoInstance.input.preparedRoomId !== null;

			// Add a small delay to avoid loading on quick hovers
			const timeoutId = setTimeout(async () => {
				if (shouldPlay) {
					// Double check we're still hovered
					// Handle lazy loading: activate prepared/paused remote streams
					if (canActivate && hasPreparedRoom) {
						try {
							const result = await videoManager.activateRemoteStream(videoInstance.id, workspaceId);
							if (!result.success) {
								console.error("Failed to activate remote stream:", result.error);
								isLoading = false;
								return;
							}
						} catch (error) {
							console.error("Error activating remote stream:", error);
							isLoading = false;
							return;
						}
					}

					const stream = videoInstance.currentStream;
					setupVideo(stream || undefined);
				}
			}, loadingDelay);

			return () => {
				clearTimeout(timeoutId);
			};
		} else {
			// Handle cleanup when not hovered
			// Cleanup video rendering
			cleanupVideo();

			// Cache status values to prevent reactive loops
			const canPause =
				lazyLoad &&
				videoInstance.input.connectionState === "connected" &&
				videoInstance.input.connectionPolicy === "lazy";

			// Only pause remote streams with lazy policy (not persistent connections)
			if (canPause) {
				try {
					videoManager.pauseRemoteStream(videoInstance.id);
				} catch (error) {
					console.error("Error pausing remote stream:", error);
				}
			}
		}
	});

	// Watch for stream changes when video is active (hovered) - simplified to prevent loops
	let lastStreamRef: MediaStream | null = null;
	$effect(() => {
		if (!shouldPlay || !videoElement) {
			lastStreamRef = null;
			return;
		}

		const currentStream = videoInstance.currentStream;

		// Only update if the stream reference has actually changed
		if (currentStream !== lastStreamRef) {
			lastStreamRef = currentStream;

			// Gracefully stop current video
			try {
				videoElement.pause();

				// Clear sources
				if (videoElement.srcObject) {
					videoElement.srcObject = null;
				}
				if (videoElement.src) {
					videoElement.removeAttribute("src");
					videoElement.load(); // This clears any pending loads
				}
			} catch (error) {
				console.warn("Error stopping previous video:", error);
			}

			// Dispose current texture
			if (videoTexture) {
				videoTexture.dispose();
				videoTexture = null;
			}

			// Create/update loading texture for the loading state
			if (loadingTexture) {
				loadingTexture.dispose();
			}
			loadingTexture = createLoadingTexture("Loading...");

			// Reset state
			videoLoaded = false;
			isLoading = true;

			// Small delay to ensure cleanup is complete
			setTimeout(() => {
				if (shouldPlay && currentStream === lastStreamRef) {
					// Make sure we're still hovered and stream hasn't changed
					setupVideo(currentStream || undefined);
				}
			}, 50);
		}
	});

	// Create the TV frame geometry (outer rounded rectangle)
	function createTVFrame(
		tvWidth: number,
		tvHeight: number,
		tvDepth: number,
		tvFrameThickness: number,
		tvCornerRadius: number
	) {
		const shape = new Shape();
		const x = -tvWidth / 2;
		const y = -tvHeight / 2;
		const w = tvWidth;
		const h = tvHeight;
		const radius = tvCornerRadius;

		shape.moveTo(x, y + radius);
		shape.lineTo(x, y + h - radius);
		shape.quadraticCurveTo(x, y + h, x + radius, y + h);
		shape.lineTo(x + w - radius, y + h);
		shape.quadraticCurveTo(x + w, y + h, x + w, y + h - radius);
		shape.lineTo(x + w, y + radius);
		shape.quadraticCurveTo(x + w, y, x + w - radius, y);
		shape.lineTo(x + radius, y);
		shape.quadraticCurveTo(x, y, x, y + radius);

		// Create hole for screen (inner rectangle)
		const hole = new Path();
		const hx = x + tvFrameThickness;
		const hy = y + tvFrameThickness;
		const hwidth = w - tvFrameThickness * 2;
		const hheight = h - tvFrameThickness * 2;
		const hradius = tvCornerRadius * 0.5;

		hole.moveTo(hx, hy + hradius);
		hole.lineTo(hx, hy + hheight - hradius);
		hole.quadraticCurveTo(hx, hy + hheight, hx + hradius, hy + hheight);
		hole.lineTo(hx + hwidth - hradius, hy + hheight);
		hole.quadraticCurveTo(hx + hwidth, hy + hheight, hx + hwidth, hy + hheight - hradius);
		hole.lineTo(hx + hwidth, hy + hradius);
		hole.quadraticCurveTo(hx + hwidth, hy, hx + hwidth - hradius, hy);
		hole.lineTo(hx + hradius, hy);
		hole.quadraticCurveTo(hx, hy, hx, hy + hradius);

		shape.holes.push(hole);

		return new ExtrudeGeometry(shape, {
			depth: tvDepth,
			bevelEnabled: true,
			bevelThickness: 0.02,
			bevelSize: 0.02,
			bevelSegments: 8
		});
	}

	// Create the screen (video display area)
	function createScreen(tvWidth: number, tvHeight: number, tvFrameThickness: number) {
		const w = tvWidth - tvFrameThickness * 2;
		const h = tvHeight - tvFrameThickness * 2;

		// Create a very thin box for the screen area (only visible from front)
		return new BoxGeometry(w, h, 0.02);
	}

	const frameGeometry = createTVFrame(width, height, depth, frameThickness, cornerRadius);
	const screenGeometry = createScreen(width, height, frameThickness);

	interactivity();
</script>

<T.Group
	onclick={() => (isPlayingLocked = !isPlayingLocked)}
	onpointerenter={() => (isHovered = true)}
	onpointerleave={() => (isHovered = false)}
>
	<!-- TV Frame -->
	<T.Mesh geometry={frameGeometry}>
		<T.MeshStandardMaterial
			color={shouldPlay ? frameActiveColor : frameColor}
			metalness={frameMetalness}
			roughness={frameRoughness}
			envMapIntensity={frameEnvMapIntensity}
		/>
	</T.Mesh>

	<T.Mesh geometry={screenGeometry} position.z={depth / 2 - 0.01}>
		{#if videoLoaded && videoTexture}
			<T.MeshBasicMaterial map={videoTexture} />
		{:else if loadingTexture}
			<T.MeshBasicMaterial map={loadingTexture} />
		{:else}
			<T.MeshBasicMaterial color={fallbackColor} />
		{/if}
	</T.Mesh>

	<!-- Loading/Hover State Overlay -->
	{#if showLoading && (!isHovered || isLoading)}
		<T.MeshBasicMaterial color={fallbackColor} />
	{/if}

	<!-- Video Screen -->
	<!-- <T.Mesh position.z={depth / 2 - 0.01} scale={[2, 2, 2]} position.y={0.5}>

		{#if videoLoaded && videoTexture}
			{#if videoSrc}
				<T.MeshBasicMaterial map={videoTexture} />
				<Root>
					<Container >
						<Video bind:element={videoElement} autoplay muted width={100} height={100} />
						<Text text={videoElement?.src} />
					</Container>
				</Root>
			{:else}
				<T.MeshBasicMaterial color={fallbackColor} />
			{/if}
		{:else}
			<T.MeshBasicMaterial color={fallbackColor} />
		{/if}
	</T.Mesh> -->
</T.Group>