<script lang="ts">
	import { onMount, onDestroy } from "svelte";

	let timeUntilNext = $state("");
	let newVerseReady = $state(false);
	let intervalId: number | null = null;
	let targetTime = 0;

	function initTarget() {
		const target = new Date();
		target.setHours(0, 0, 0, 0);
		if (Date.now() >= target.getTime()) {
			target.setDate(target.getDate() + 1);
		}
		targetTime = target.getTime();
	}

	function updateTimer() {
		const diff = targetTime - Date.now();

		if (diff <= 0) {
			newVerseReady = true;
			timeUntilNext = "";
			if (intervalId) {
				clearInterval(intervalId);
				intervalId = null;
			}
			return;
		}

		const hours = Math.floor(diff / (1000 * 60 * 60));
		const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
		const seconds = Math.floor((diff % (1000 * 60)) / 1000);

		timeUntilNext = `${hours.toString().padStart(2, "0")}h ${minutes
			.toString()
			.padStart(2, "0")}m ${seconds.toString().padStart(2, "0")}s`;
	}

	onMount(() => {
		initTarget();
		updateTimer();
		intervalId = window.setInterval(updateTimer, 1000);
	});

	onDestroy(() => {
		if (intervalId) {
			clearInterval(intervalId);
		}
	});
</script>

<div class="w-full flex flex-col flex-1">
	<div
		class="flex flex-col items-center justify-center bg-white/50 backdrop-blur-sm px-8 py-4 rounded-2xl border border-white/50 shadow-sm w-full flex-1"
	>
		{#if newVerseReady}
			<p
				class="text-xs uppercase tracking-[0.2em] text-gray-500 font-bold mb-2"
			>
				Next Verse In
			</p>
			<p class="text-4xl font-triodion font-black text-gray-800">Now</p>
			<p
				class="text-xs uppercase tracking-[0.2em] text-gray-500 font-bold mt-2"
			>
				(refresh page to see the new verse)
			</p>
		{:else}
			<p
				class="text-xs uppercase tracking-[0.2em] text-gray-500 font-bold mb-2"
			>
				Next Verse In
			</p>
			<p
				class="text-4xl font-triodion font-black text-gray-800 tabular-nums"
			>
				{timeUntilNext}
			</p>
		{/if}
	</div>
</div>
