/**
 * Module-level user-activity tracker.
 *
 * Fires two custom window events:
 *   dt:inactive — user has been idle for INACTIVE_TIMEOUT_MS
 *   dt:active   — user returned after being idle
 *
 * Uses a singleton pattern so startActivityTracking() is safe to call
 * multiple times — only one set of event listeners is ever registered.
 *
 * Consumers call usePauseOnInactivity() to react to these events with
 * zero extra re-renders on the tracker side.
 */

const INACTIVE_TIMEOUT_MS = 10 * 60 * 1000; // 10 minutes

const ACTIVITY_EVENTS = ["mousemove", "mousedown", "keydown", "touchstart", "scroll"] as const;

let timer: ReturnType<typeof setTimeout> | null = null;
let currentlyInactive = false;
let started = false;

function markActive() {
  if (currentlyInactive) {
    currentlyInactive = false;
    window.dispatchEvent(new Event("dt:active"));
  }
  scheduleInactive();
}

function scheduleInactive() {
  if (timer) clearTimeout(timer);
  timer = setTimeout(() => {
    currentlyInactive = true;
    window.dispatchEvent(new Event("dt:inactive"));
  }, INACTIVE_TIMEOUT_MS);
}

export function startActivityTracking(): () => void {
  if (started || typeof window === "undefined") return () => { };
  started = true;

  ACTIVITY_EVENTS.forEach((ev) =>
    window.addEventListener(ev, markActive, { passive: true }),
  );

  // Treat returning to a visible tab as activity
  document.addEventListener("visibilitychange", () => {
    if (!document.hidden) markActive();
  });

  scheduleInactive();

  return () => {
    ACTIVITY_EVENTS.forEach((ev) => window.removeEventListener(ev, markActive));
    if (timer) clearTimeout(timer);
    started = false;
  };
}
