<template>
  {{ string_repr }}
</template>

<script setup lang="ts">
import { Duration } from "luxon";
import { onBeforeUnmount, onMounted, ref } from "vue";

const props = withDefaults(
  defineProps<{
    until: number;
    tick_time?: number;
  }>(),
  { tick_time: 200 },
);

let interval_id: number | undefined;
const string_repr = ref("");

onMounted(() => {
  function tick(): void {
    const distance_ms = props.until - Date.now();

    if (distance_ms <= 0) {
      string_repr.value = "Jetzt!";
      return;
    }

    const distance = Duration.fromMillis(distance_ms);
    const d_days = distance.shiftTo("day").mapUnits(Math.floor);
    const d_hms = distance.minus(d_days).shiftTo("hour", "minute", "second");

    if (d_days.days > 0) {
      string_repr.value = d_days.toHuman() + " ";
    } else {
      string_repr.value = "";
    }
    string_repr.value += d_hms.toFormat("hh:mm:ss");
  }

  tick();
  interval_id = window.setInterval(tick, props.tick_time);
});

onBeforeUnmount(() => {
  window.clearInterval(interval_id);
});
</script>
