import { useEffect } from 'react';

/**
 * Prevent accidental tab/window closure while a long-running operation
 * is in progress. Shows the browser's native "Leave site?" confirmation.
 *
 * @param {boolean} active — true while the operation is running
 */
export function useBeforeUnload(active) {
  useEffect(() => {
    if (!active) return;

    const handler = (e) => {
      e.preventDefault();
      // Legacy browsers require returnValue to be set
      e.returnValue = '';
    };

    window.addEventListener('beforeunload', handler);
    return () => window.removeEventListener('beforeunload', handler);
  }, [active]);
}
