import { computed, onUnmounted, ref } from "vue";

/** Client-side countdown timer → decimal hours via `consumeHours()` */
export function useHoursTimer() {
  const running = ref(false);
  const elapsedSeconds = ref(0);
  let startedAtMs = /** @type {number | null} */ (null);
  let intervalId = /** @type {ReturnType<typeof setInterval> | null} */ (null);

  function tick() {
    if (startedAtMs == null) {
      return;
    }

    elapsedSeconds.value = Math.floor((Date.now() - startedAtMs) / 1000);
  }

  function start() {
    if (running.value) {
      return;
    }

    running.value = true;
    startedAtMs = Date.now();
    intervalId = setInterval(tick, 333);
    tick();
  }

  /** Cancel without returning hours */
  function reset() {
    if (intervalId != null) {
      clearInterval(intervalId);
      intervalId = null;
    }

    startedAtMs = null;
    running.value = false;
    elapsedSeconds.value = 0;
  }

  /** @returns {number} decimal hours accumulated */
  function stopAndDrainHours() {
    if (!running.value || startedAtMs == null) {
      return 0;
    }

    tick();
    const hours = elapsedSeconds.value / 3600;
    reset();

    return Math.round(hours * 100) / 100;
  }

  const displayHm = computed(() => {
    const s = elapsedSeconds.value;
    const hh = Math.floor(s / 3600);
    const mm = Math.floor((s % 3600) / 60);

    return `${hh}:${String(mm).padStart(2, "0")}`;
  });

  onUnmounted(() => {
    reset();
  });

  return {
    running,
    elapsedSeconds,
    displayHm,
    start,
    reset,
    stopAndDrainHours,
  };
}
