// The only JavaScript in the app: tick the live work timer and the visible POC reset countdown.
// Everything else is plain HTML + htmx.
(function () {
  var workInterval = null;
  var resetInterval = null;
  var reloadingForReset = false;

  function pad(n) { return (n < 10 ? "0" : "") + n; }

  function tickWorkTimer() {
    var el = document.getElementById("clock");
    if (!el || !el.dataset.start) {
      if (workInterval) { clearInterval(workInterval); workInterval = null; }
      return;
    }
    var start = new Date(el.dataset.start).getTime();
    var diff = Math.max(0, Math.floor((Date.now() - start) / 1000));
    var h = Math.floor(diff / 3600);
    var m = Math.floor((diff % 3600) / 60);
    var s = diff % 60;
    el.textContent = pad(h) + ":" + pad(m) + ":" + pad(s);
  }

  function formatReset(seconds) {
    var m = Math.floor(seconds / 60);
    var s = seconds % 60;
    return pad(m) + ":" + pad(s);
  }

  function tickResetCountdown() {
    var el = document.getElementById("reset-countdown");
    if (!el || !el.dataset.resetAt) {
      if (resetInterval) { clearInterval(resetInterval); resetInterval = null; }
      return;
    }

    var resetAt = new Date(el.dataset.resetAt).getTime();
    var remaining = Math.ceil((resetAt - Date.now()) / 1000);
    if (remaining <= 0) {
      el.textContent = "resetting…";
      document.body.classList.add("reset-imminent");
      if (!reloadingForReset) {
        reloadingForReset = true;
        window.setTimeout(function () { window.location.reload(); }, 1500);
      }
      return;
    }

    el.textContent = formatReset(remaining);
    document.body.classList.toggle("reset-imminent", remaining <= 30);
  }

  function restartWorkTimer() {
    if (workInterval) clearInterval(workInterval);
    tickWorkTimer();
    workInterval = setInterval(tickWorkTimer, 1000);
  }

  function startResetCountdown() {
    if (resetInterval) clearInterval(resetInterval);
    tickResetCountdown();
    resetInterval = setInterval(tickResetCountdown, 1000);
  }

  document.addEventListener("DOMContentLoaded", function () {
    restartWorkTimer();
    startResetCountdown();
  });

  // Re-evaluate the work timer after htmx swaps the working area in/out.
  document.body.addEventListener("htmx:afterSettle", restartWorkTimer);
})();
