import { useEffect } from "react";
import { useTranslation } from "react-i18next";

const useUnsavedChangesWarning = (unsavedChanges: boolean) => {
  const [t] = useTranslation();
  useEffect(() => {
    const handleBeforeUnload = (event: BeforeUnloadEvent) => {
      if (unsavedChanges) {
        // Prevent default action and stop the event
        event.preventDefault();
        // Optionally set returnValue to an empty string
        event.returnValue = "";
      }
    };

const handleNavigation = (event: Event) => {
      // const target = event.target as HTMLElement;

  if (unsavedChanges   ) {
      const leave = window.confirm(t("validation.You have unsaved changes! Are you sure you want to leave?"));

    if (leave) return ;

    event.stopPropagation();
    event.preventDefault();
  }
};

    window.addEventListener("beforeunload", handleBeforeUnload);

    // Intercept link clicks (example for <a> elements)
      // document.addEventListener("click", handleNavigation);
    document.querySelectorAll(".link").forEach((link) => {
      link.addEventListener("click", handleNavigation);
    });

    return () => {
      window.removeEventListener("beforeunload", handleBeforeUnload);
    document.querySelectorAll(".link").forEach((link) => {
      link.removeEventListener("click", handleNavigation);
    });
      // Clean up event listeners
      document.removeEventListener("click", handleNavigation);

    };
  }, [unsavedChanges]);
};

export default useUnsavedChangesWarning;
