import { useEffect } from 'react';

/**
 * Adds a browser beforeunload warning when the form has unsaved changes.
 * Use in admin mutation forms alongside Inertia's useForm isDirty state.
 */
export function useBeforeUnload(isDirty: boolean) {
  useEffect(() => {
    if (!isDirty) return;
    const handler = (e: BeforeUnloadEvent) => {
      e.preventDefault();
      e.returnValue = '';
    };
    window.addEventListener('beforeunload', handler);
    return () => window.removeEventListener('beforeunload', handler);
  }, [isDirty]);
}
