import { useRef, useEffect } from "react"; import { Modal, Text, Button, Group, Stack } from "@mantine/core"; import { useNavigationGuard } from "@app/contexts/NavigationContext"; import { useTranslation } from "react-i18next"; import ArrowBackIcon from "@mui/icons-material/ArrowBack"; import DeleteOutlineIcon from "@mui/icons-material/DeleteOutline"; import CheckCircleOutlineIcon from "@mui/icons-material/CheckCircleOutline"; import { Z_INDEX_TOAST } from "@app/styles/zIndex"; const NavigationWarningModal = () => { const { t } = useTranslation(); const { showNavigationWarning, hasUnsavedChanges, pendingNavigation, cancelNavigation, setHasUnsavedChanges, navigationWarningHandlersRef, } = useNavigationGuard(); // Store pendingNavigation in a ref so async handlers always have the latest, // not a stale closure captured before an await. const pendingNavigationRef = useRef(pendingNavigation); useEffect(() => { pendingNavigationRef.current = pendingNavigation; }, [pendingNavigation]); const handleKeepWorking = () => { cancelNavigation(); }; const finishAndNavigate = () => { const nav = pendingNavigationRef.current; setHasUnsavedChanges(false); cancelNavigation(); if (nav) { nav(); } }; const handleDiscardChanges = async () => { const handlers = navigationWarningHandlersRef.current; if (handlers?.onDiscardAndContinue) { await handlers.onDiscardAndContinue(); } finishAndNavigate(); }; const handleApplyAndContinue = async () => { const handlers = navigationWarningHandlersRef.current; if (handlers?.onApplyAndContinue) { await handlers.onApplyAndContinue(); } finishAndNavigate(); }; const handleExportAndContinue = async () => { const handlers = navigationWarningHandlersRef.current; if (handlers?.onExportAndContinue) { await handlers.onExportAndContinue(); } finishAndNavigate(); }; // Read handler availability at render time for button visibility const handlers = navigationWarningHandlersRef.current; const hasApply = !!handlers?.onApplyAndContinue; const hasExport = !!handlers?.onExportAndContinue; const BUTTON_WIDTH = "12rem"; // Only show modal if there are unsaved changes AND there's an actual pending navigation if (!hasUnsavedChanges || !pendingNavigation) { return null; } return ( {t("unsavedChanges", "You have unsaved changes to your PDF.")} {t("areYouSure", "Are you sure you want to leave?")} {/* Desktop layout: 2 groups side by side */} {hasApply && ( )} {hasExport && ( )} {/* Mobile layout: centered stack of 4 buttons */} {hasApply && ( )} {hasExport && ( )} ); }; export default NavigationWarningModal;