<script lang="ts">
	import { onMount, untrack } from 'svelte';
	import { quickLinks } from '$lib/quick-links.svelte';
	import { invalidateAll } from '$app/navigation';
	import StationAlertCard from '$lib/components/ui/station-board/StationAlertCard.svelte';

	import { formatUkDateTime, formatUkTime } from '$lib/utils/time';
	import StaffServicesTable from '$lib/components/ui/station-board/StaffServicesTable.svelte';
	import LiveIndicator from '$lib/components/ui/LiveIndicator.svelte';

	let { data } = $props();
	let now = $state(new Date());
	let live = $state(false);

	// Handle auto-refreshing & Wake-lock
	$effect(() => {
		let intervalId: number | undefined;
		let wakeLock: WakeLockSentinel | null = null;

		const requestWakeLock = async () => {
			if ('wakeLock' in navigator && !wakeLock) {
				try {
					wakeLock = await navigator.wakeLock.request('screen');
					console.log("Wake lock obtained");
				} catch (error) {
					console.warn("Wake lock request rejected: ", error);
				} 
			}
		};

		const releaseWakeLock = async () => {
			if (wakeLock) {
				try {
					await wakeLock.release();
					console.log("Wake lock released");
				} catch (error) {
					console.error("Wake lock release failed: ", error);
				}
				wakeLock = null;
			}
		};

		const startPolling = async () => {
			await requestWakeLock();
			if (intervalId) return;
			intervalId = window.setInterval(async () => {
				try {
					console.log("Invalidating data")
					await invalidateAll();
				} catch (error) {
					console.error("Background data fetch failed: ", error)
					live = false;
				}
			}, 60100);
			live = true;
			console.log("Polling started")
		};

		const stopPolling = async () => {
			if (intervalId) {
				window.clearInterval(intervalId);
				intervalId = undefined;
				console.log("Polling ended")
			}
			await releaseWakeLock();
		};

		const handleVisibilityChange = () => {
			if (document.hidden) {
				stopPolling();
			} else {
				startPolling();
			}
		};

		if (!document.hidden) {
			startPolling();
		}

		document.addEventListener('visibilitychange', handleVisibilityChange);

		return () => {
			stopPolling();
			document.removeEventListener('visibilitychange', handleVisibilityChange);
		};
	})

	onMount(() => {
		const interval = setInterval(() => {
			now = new Date();
		}, 1000);

		return () => clearInterval(interval);
	});

	const currentBoardId = $derived(
        data.BoardLocation ? (data.BoardLocation.c ?? data.BoardLocation.t) : null
    );

	// Update 'QuickLinks' when currentBoardId changes
$effect(() => {
        if (currentBoardId) {
            // Keep the execution and logs inside untrack to isolate dependencies completely
            untrack(() => {
                quickLinks.recordVisit(currentBoardId);
                console.log(`QuickLink visit recorded: ${JSON.stringify(data.BoardLocation)}`);
            });
        }
    });

	// Wake Lock API Handling
	// Load Data Invalidation Handling
	// Refresh countdown logic
</script>
<section class="board-wrapper">
	<div class="time-data">
		<span class="time-loaded">Updated: {formatUkDateTime(data.boardData.producedAt, true)}</span>
		<span class="time-now">{formatUkTime(now, true)}</span>
	</div>
	{#if data.boardData.data.m?.length}
		<StationAlertCard messages={data.boardData.data.m} />
	{/if}
	{#if live}
		<div class="live-indicator">
			<LiveIndicator />
		</div>
	{/if}
	{#if data.boardData.data.s?.length}
		<div class="service-list-wrapper">
			<StaffServicesTable services={data.boardData.data.s} />
		</div>
	{/if}
</section>

<style>
	.board-wrapper {
		display: flex;
		height: calc(100dvh - var(--nav-height) - var(--header-height));
		flex-direction: column;
		align-items: center;
		width: 100%;
		margin: 0 auto;
		overflow: hidden;
		gap: 0;
	}

	.time-data {
		display: flex;
		justify-content: space-between;
		align-items: center;
		width: 90%;
		max-width: 700px;
		margin: 10px auto;
		font-family: 'URW Gothic', sans-serif;
	}

	.time-loaded,
	.time-now {
		font-variant-numeric: tabular-nums;
	}

	.time-loaded {
		font-size: 0.9rem;
	}

	.time-now {
		font-weight: 600;
		font-size: 1rem;
	}

	.live-indicator {
		margin: 0.25rem auto;
	}

	.service-list-wrapper {
		flex: 1;
		overflow-y: auto;
		height: calc(100dvh - 60px);
		width: 97%;
		max-width: 700px;
		margin-bottom: 5px;
	}
</style>
