import { useEffect } from "react";
import { useBlocker } from "react-router-dom";

export function useUnsavedChanges(active: boolean) {
  const blocker = useBlocker(active);

  useEffect(() => {
    if (!active) return;
    const handler = (e: BeforeUnloadEvent) => {
      e.preventDefault();
      e.returnValue = "";
    };
    window.addEventListener("beforeunload", handler);
    return () => window.removeEventListener("beforeunload", handler);
  }, [active]);

  return blocker;
}
