<script lang="ts">
  interface Props {
    target: Date;
    compact?: boolean;
    pastMessage?: string;
  }

  let {
    target,
    compact = false,
    pastMessage = "The big day is here!",
  }: Props = $props();

  let now = $state(Date.now());

  $effect(() => {
    const id = setInterval(() => (now = Date.now()), 1000);
    return () => clearInterval(id);
  });

  const diffMs = $derived(Math.max(0, target.getTime() - now));
  const isPast = $derived(diffMs <= 0);

  const days = $derived(Math.floor(diffMs / 86_400_000));
  const hours = $derived(Math.floor((diffMs % 86_400_000) / 3_600_000));
  const minutes = $derived(Math.floor((diffMs % 3_600_000) / 60_000));
  const seconds = $derived(Math.floor((diffMs % 60_000) / 1000));

  const units = $derived([
    { label: "days", value: days },
    { label: "hours", value: hours },
    { label: "minutes", value: minutes },
    { label: "seconds", value: seconds },
  ]);
</script>

{#if isPast}
  <p
    class={compact
      ? "text-lg font-medium sm:text-xl  sm:text-md"
      : "text-surface-50 text-2xl  sm:text-md font-medium"}
  >
    {pastMessage}
  </p>
{:else if compact}
  <div class="flex items-baseline gap-2 z-10" role="timer" aria-live="polite">
    {#each units as unit, i (unit.label)}
      {#if i > 0}<span class="text-secondary-300/60">·</span>{/if}
      <span class="font-semibold tabular-nums text-md md:text-3xl"
        >{unit.value}</span
      >
      <span class="text-secondary-100/80 text-md md:text-3xl">{unit.label}</span
      >
    {/each}
  </div>
{:else}
  <div class="flex gap-4 sm:gap-8" role="timer" aria-live="polite">
    {#each units as unit (unit.label)}
      <div class="flex flex-col items-center">
        <span
          class="text-secondary-400 text-4xl font-bold tabular-nums sm:text-6xl"
        >
          {String(unit.value).padStart(2, "0")}
        </span>
        <span
          class="text-surface-200 text-base tracking-wide uppercase sm:text-lg"
          >{unit.label}</span
        >
      </div>
    {/each}
  </div>
{/if}
