/**
 * Hook that tracks whether the current page is visible to the user.
 *
 * Returns true when the page is active and visible, false when the user has switched
 * to another tab, window, or minimized the browser.
 *
 * Uses the Document.hidden API with the `visibilitychange` event.
 * See: https://developer.mozilla.org/en-US/docs/Web/API/Document/visibilitychange_event
 */
import { useEffect, useState } from "react";

/**
 * Track whether the page is currently visible to the user.
 *
 * @returns True if the page is visible, false if hidden
 */
export function usePageVisibility(): boolean {
  const [isVisible, setIsVisible] = useState(!document.hidden);

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

    document.addEventListener("visibilitychange", handleVisibilityChange);
    return (): void => {
      document.removeEventListener("visibilitychange", handleVisibilityChange);
    };
  }, []);

  return isVisible;
}
