/**
 * Block browser leave + in-app navigation when the editor is dirty.
 */
import { useEffect } from '@wordpress/element';
import {
	defaultLeaveMessage,
	setUnsavedChangesBlocker,
} from '../unsavedChanges';

/**
 * @param {boolean} isDirty Whether the form has unsaved edits.
 */
export default function useUnsavedChanges( isDirty ) {
	useEffect( () => {
		const onBeforeUnload = ( event ) => {
			if ( ! isDirty ) {
				return;
			}
			event.preventDefault();
			event.returnValue = '';
		};

		window.addEventListener( 'beforeunload', onBeforeUnload );

		setUnsavedChangesBlocker( () => {
			if ( ! isDirty ) {
				return true;
			}
			return window.confirm( defaultLeaveMessage() );
		} );

		return () => {
			window.removeEventListener( 'beforeunload', onBeforeUnload );
			setUnsavedChangesBlocker( null );
		};
	}, [ isDirty ] );
}
