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

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

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

let interval_id: number | null = null;
let string_repr = "";

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

  if (distance_ms <= 0) {
    string_repr = "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 = d_days.toHuman() + " ";
  } else {
    string_repr = "";
  }
  string_repr += d_hms.toFormat("hh:mm:ss");
}

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

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