// File: src/hooks/useInactivityTimeout.js
// Hook to auto-logout users after a period of inactivity

import { useEffect, useRef } from "react";
import { useNavigate } from "react-router";

/**
 * Hook that monitors user activity and redirects to logout after inactivity timeout
 * @param {number} timeout - Timeout in milliseconds (default: 15 minutes)
 * @param {boolean} enabled - Whether the timeout is enabled (default: true)
 */
export const useInactivityTimeout = (timeout = 15 * 60 * 1000, enabled = true) => {
  const navigate = useNavigate();
  const timeoutIdRef = useRef(null);
  const lastActivityRef = useRef(Date.now());

  useEffect(() => {
    if (!enabled) return;

    const resetTimeout = () => {
      // Clear existing timeout
      if (timeoutIdRef.current) {
        clearTimeout(timeoutIdRef.current);
      }

      // Update last activity time
      lastActivityRef.current = Date.now();

      // Set new timeout
      timeoutIdRef.current = setTimeout(() => {
        if (import.meta.env.DEV) {
          console.log("[useInactivityTimeout] Inactivity timeout reached, logging out");
        }
        navigate("/logout");
      }, timeout);
    };

    // Events that indicate user activity
    const activityEvents = [
      "mousedown",
      "mousemove",
      "keypress",
      "scroll",
      "touchstart",
      "click",
    ];

    // Throttle activity detection to avoid excessive timeout resets
    let throttleTimer = null;
    const handleActivity = () => {
      if (!throttleTimer) {
        throttleTimer = setTimeout(() => {
          resetTimeout();
          throttleTimer = null;
        }, 1000); // Throttle to once per second
      }
    };

    // Add event listeners
    activityEvents.forEach((event) => {
      window.addEventListener(event, handleActivity, { passive: true });
    });

    // Initialize timeout
    resetTimeout();

    // Cleanup
    return () => {
      if (timeoutIdRef.current) {
        clearTimeout(timeoutIdRef.current);
      }
      if (throttleTimer) {
        clearTimeout(throttleTimer);
      }
      activityEvents.forEach((event) => {
        window.removeEventListener(event, handleActivity);
      });
    };
  }, [timeout, enabled, navigate]);
};
