"use client";

import { useEffect, useRef } from "react";

/**
 * Subscribe to the global inactivity signal.
 * When the user has been idle for 10 minutes, calls setPaused(true).
 * When the user returns, calls setPaused(false).
 *
 * Uses a ref so the effect never needs to re-register even if the
 * caller's setPaused identity changes between renders.
 */
export function usePauseOnInactivity(setPaused: (paused: boolean) => void) {
  const setPausedRef = useRef(setPaused);
  setPausedRef.current = setPaused;

  useEffect(() => {
    const onInactive = () => setPausedRef.current(true);
    const onActive = () => setPausedRef.current(false);

    window.addEventListener("dt:inactive", onInactive);
    window.addEventListener("dt:active", onActive);

    return () => {
      window.removeEventListener("dt:inactive", onInactive);
      window.removeEventListener("dt:active", onActive);
    };
  }, []); // registers once — ref handles identity changes
}
