import {useEffect} from "@wordpress/element";

export default function useUnsavedChangesWarning(unsavedChanges) {
    useEffect(() => {
        const handleBeforeUnload = (e) => {
            // Skip warning if programmatic refresh is in progress
            if (window.lbaicSkipUnsavedChangesWarning) {
                return;
            }

            if (unsavedChanges) {
                e.preventDefault();
                e.returnValue = ''; // Required for Chrome
            }
        };

        window.addEventListener("beforeunload", handleBeforeUnload);
        return () => {
            window.removeEventListener("beforeunload", handleBeforeUnload)
        };
    }, [unsavedChanges]);
}