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

  let timeUntilNext = $state("");
  let intervalId: number | null = null;

  function calculateTimeUntilFivePM(): string {
    const now = new Date();
    const target = new Date(now);

    // Set target to 5:00 PM today
    target.setHours(17, 0, 0, 0);

    // If it's already past 5:00 PM, set target to tomorrow 5:00 PM
    if (now.getTime() >= target.getTime()) {
      target.setDate(target.getDate() + 1);
    }

    const diff = target.getTime() - now.getTime();

    if (diff <= 0) {
      return "00:00:00";
    }

    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);

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

  function calculateTimeUntilMidnight(): string {
    const now = new Date();
    const target = new Date(now);

    // Set target to midnight today
    target.setHours(0, 0, 0, 0);

    // If it's already past midnight, set target to tomorrow midnight
    if (now.getTime() >= target.getTime()) {
      target.setDate(target.getDate() + 1);
    }

    const diff = target.getTime() - now.getTime();

    if (diff <= 0) {
      return "00:00:00";
    }

    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);

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

  function updateTimer() {
    timeUntilNext = calculateTimeUntilMidnight();
  }

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

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

<div class="w-full">
  <div
    class="flex flex-col items-center bg-white/50 backdrop-blur-sm px-8 py-4 rounded-2xl border border-white/50 shadow-sm w-full"
  >
    <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>
  </div>
</div>
