import { useState, useEffect } from 'react';

/**
 * Hook to detect tab visibility using the Page Visibility API
 * @returns boolean - true when page is visible, false when hidden
 */
export const usePageVisibility = (): boolean => {
  const [isVisible, setIsVisible] = useState<boolean>(() =>
    typeof document !== 'undefined' ? !document.hidden : true
  );

  useEffect(() => {
    const handleVisibilityChange = () => {
      setIsVisible(!document.hidden);
    };

    document.addEventListener('visibilitychange', handleVisibilityChange);

    return () => {
      document.removeEventListener('visibilitychange', handleVisibilityChange);
    };
  }, []);

  return isVisible;
};
