import { useEffect, useState } from 'react';

export function useIdle() {
  const [isIdle, setIsIdle] = useState(false);

  useEffect(() => {
    let timeoutId: NodeJS.Timeout;

    const handleUserActivity = () => {
      setIsIdle(false);
      clearTimeout(timeoutId);
      timeoutId = setTimeout(() => setIsIdle(true), 600000);
    };

    const events = [
      'mousedown',
      'mousemove',
      'keydown',
      'scroll',
      'touchstart',
    ];
    events.forEach((event) =>
      document.addEventListener(event, handleUserActivity),
    );

    handleUserActivity();

    return () => {
      events.forEach((event) =>
        document.removeEventListener(event, handleUserActivity),
      );
      clearTimeout(timeoutId);
    };
  }, []);

  console.log('re-render');

  return isIdle;
}
