"use client";

import { useEffect } from "react";

/**
 * Attach the browser’s native leave-site prompt while `enabled` is true.
 *
 * Modern browsers ignore custom copy; this only blocks accidental tab or
 * window close. No-ops during SSR and when `enabled` is false so clean
 * sessions never register a listener.
 *
 * @param enabled Whether unsaved work would be lost on unload.
 *
 * @example
 * useBeforeUnloadGuard(isWizardSessionDirty());
 */
export function useBeforeUnloadGuard(enabled: boolean): void {
  useEffect(() => {
    if (!enabled || typeof window === "undefined") {
      return;
    }

    const onBeforeUnload = (event: BeforeUnloadEvent) => {
      event.preventDefault();
      event.returnValue = "";
    };

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