// SPDX-FileCopyrightText: 2026 Andrew Oberstar <andrew@ajoberstar.org>
// SPDX-License-Identifier: AGPL-3.0-only

(function () {
  const TIMEOUT = 15000;
  const ENABLED_KEY = "quixote-import-refresh";
  const SCROLL_KEY = "quixote-import-scroll-y";

  let enabled = sessionStorage.getItem(ENABLED_KEY) === "true";
  const checkbox = document.getElementById("auto-refresh");
  checkbox.checked = enabled;

  function reload() {
    sessionStorage.setItem(SCROLL_KEY, window.scrollY.toString());
    location.reload();
  }

  let timer = null;

  function pauseTimer() {
    clearTimeout(timer);
  }

  function resetTimer() {
    pauseTimer();
    if (enabled) {
      timer = setTimeout(reload, TIMEOUT);
    }
  }

  // initialize
  resetTimer();

  ["click", "keydown", "touchstart", "input", "change"].forEach((type) => {
    document.addEventListener(type, resetTimer);
  });

  checkbox.addEventListener("change", () => {
    enabled = checkbox.checked;
    sessionStorage.setItem(ENABLED_KEY, String(enabled));
    if (enabled) {
      resetTimer();
    } else {
      pauseTimer();
    }
  });

  // Pause on submit so a slow POST isn't interrupted by a reload.
  document.addEventListener("submit", pauseTimer);

  const saved = sessionStorage.getItem(SCROLL_KEY);
  if (saved !== null) {
    window.scrollTo(0, parseInt(saved, 10));
    sessionStorage.removeItem(SCROLL_KEY);
  }
})();
