import { useCallback, useEffect, useRef } from 'react';

/**
 * Hook a callback into page unload
 *
 * The callback will fire once on `beforeunload` or `pagehide`, whichever comes first.
 */
export default function usePageUnload(
  callback?: ((e: Event) => void) | null,
  options?: { capture?: boolean; enabled?: boolean }
) {
  const { capture, enabled = true } = options || {};

  const callbackRef = useRef(callback);
  useEffect(() => {
    callbackRef.current = callback;
  }, [callback]);

  const hasFired = useRef(false);
  const reset = useCallback(() => {
    hasFired.current = false;
  }, []);

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

    hasFired.current = false;

    const opts = capture != null ? { capture } : undefined;

    const handleUnload = (e: Event) => {
      if (!hasFired.current) {
        hasFired.current = true;
        callbackRef.current?.(e);
      }
    };

    window.addEventListener('beforeunload', handleUnload, opts);
    window.addEventListener('pagehide', handleUnload, opts);

    return () => {
      window.removeEventListener('beforeunload', handleUnload, opts);
      window.removeEventListener('pagehide', handleUnload, opts);
    };
  }, [enabled, capture]);

  return [reset];
}
