/* eslint-disable react-hooks/exhaustive-deps */
import { useEffect } from 'react';

interface WindowFocusProps {
  onFocus?: () => void;
  onBlur?: () => void;
  args?: any[];
}

export const useWindowFocusChange = ({ onFocus, onBlur, ...args }: WindowFocusProps) => {
  const dependencies: any[] = [];
  if (Array.isArray(args)) {
    dependencies.push(...args);
  }
  const handleEvent = () => {
    if (document.hidden) {
      // the page is hidden
      onBlur?.();
    } else {
      // the page is visible
      onFocus?.();
    }
  };
  useEffect(() => {
    window.document.addEventListener('visibilitychange', handleEvent);
    return () => window.document.removeEventListener('visibilitychange', handleEvent);
  }, [onFocus, onBlur, ...dependencies]);
};
