<script lang="ts">
	// @ts-nocheck
	import '../app.css';
	import { onMount } from 'svelte';
	import favicon from '$lib/assets/favicon.svg';
	import { appController } from '$lib/app/controller';
	import {
		clearInstallPrompt,
		setInstallPrompt,
		setOfflineReady,
		setOnlineStatus,
		setUpdateAvailable,
		syncInstallHelpState
	} from '$lib/pwa';

	let { children } = $props();

	onMount(() => {
		const registerServiceWorker = async () => {
			if (!import.meta.env.PROD || !('serviceWorker' in navigator)) {
				return;
			}

			try {
				const registration = await navigator.serviceWorker.register('/sw.js');

				const handleInstallingWorker = (worker) => {
					if (!worker) {
						return;
					}

					worker.addEventListener('statechange', () => {
						if (worker.state !== 'installed') {
							return;
						}

						if (navigator.serviceWorker.controller) {
							setUpdateAvailable(true);
							return;
						}

						setOfflineReady(true);
					});
				};

				if (registration.waiting) {
					setUpdateAvailable(true);
				}

				handleInstallingWorker(registration.installing);
				registration.addEventListener('updatefound', () => {
					handleInstallingWorker(registration.installing);
				});
			} catch (error) {
				console.error('Service worker registration failed', error);
			}
		};

		void registerServiceWorker();

		const handleBeforeInstallPrompt = (event) => {
			event.preventDefault();
			setInstallPrompt(event);
			syncInstallHelpState();
		};

		const handleAppInstalled = () => {
			clearInstallPrompt();
			syncInstallHelpState();
		};

		const handleOnline = () => {
			setOnlineStatus(true);
		};

		const handleOffline = () => {
			setOnlineStatus(false);
		};

		setOnlineStatus(navigator.onLine);
		syncInstallHelpState();

		window.addEventListener('beforeinstallprompt', handleBeforeInstallPrompt);
		window.addEventListener('appinstalled', handleAppInstalled);
		window.addEventListener('online', handleOnline);
		window.addEventListener('offline', handleOffline);

		void appController.init();

		return () => {
			window.removeEventListener('beforeinstallprompt', handleBeforeInstallPrompt);
			window.removeEventListener('appinstalled', handleAppInstalled);
			window.removeEventListener('online', handleOnline);
			window.removeEventListener('offline', handleOffline);
			void appController.destroy();
		};
	});
</script>

<svelte:head>
	<title>PhoneCam Web Dashboard</title>
	<link rel="icon" href={favicon} />
</svelte:head>
{@render children()}
