<script lang="ts">
	import { onMount } from 'svelte';
	import { m } from '$lib/paraglide/messages';

	let time = $state(0);
	let fps = 0;
	let start = 0;
	let displayFps = $state('?');
	let fpsInterval: NodeJS.Timeout | undefined;

	const times: number[] = [];
	function refreshLoop() {
		const now = performance.now();
		time = Math.floor(now - start);
		while (times.length > 0 && times[0] <= now - 1000) {
			times.shift();
		}
		times.push(now);
		fps = times.length;
		window.requestAnimationFrame(refreshLoop);
	}

	function restart() {
		displayFps = '?';
		times.length = 0;
		start = performance.now();
		clearInterval(fpsInterval);
		fpsInterval = setInterval(() => {
			displayFps = fps.toString();
		}, 1000);
	}

	onMount(() => {
		refreshLoop();
		restart();
	});
</script>

<h2><i class="ti ti-alarm"></i> {m.timer_title()}</h2>
<div class="display">
	<div class="time">{time}</div>
	<div class="fps">{displayFps} {m.timer_fps()}</div>
</div>
<button onclick={restart}>{m.timer_restart()}</button>

<style>
	div,
	button {
		text-align: center;
		margin-bottom: 1rem;
		user-select: none;
		line-height: 1;
	}

	.display {
		flex-grow: 1;
		display: flex;
		flex-direction: column;
		justify-content: center;
		font-variant-numeric: tabular-nums;
	}

	.time {
		font-size: 12rem;
	}

	.fps {
		font-size: 4rem;
	}

	button {
		align-self: center;
		font-size: 2rem;
	}
</style>
