<script lang="ts">
	import { onMount, untrack } from 'svelte';
	import { quickLinks } from '$lib/quick-links.svelte';
	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';
	let { data } = $props();
	let now = $state(new Date());

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

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

	// Update 'QuickLinks'
	$effect(() => {
		if (data.BoardLocation) {
			const id = data.BoardLocation?.c ?? data.BoardLocation?.t;
			if (id) {
				// Untrack, as we do not need to handle changes to quickLinks - this is WRITE_ONLY
				untrack(() => {
					quickLinks.recordVisit(id);
					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 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;
	}

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