'use client';
import { jsxDEV as _jsxDEV } from "react/jsx-dev-runtime";
import React, { useCallback } from 'react';
import { useForm, useFormModified } from '../../forms/Form/index.js';
import { useAuth } from '../../providers/Auth/index.js';
import { useTranslation } from '../../providers/Translation/index.js';
import { ConfirmationModal } from '../ConfirmationModal/index.js';
import { useModal } from '../Modal/index.js';
import { usePreventLeave } from './usePreventLeave.js';
const leaveWithoutSavingModalSlug = 'leave-without-saving';
export const LeaveWithoutSaving = ({ disablePreventLeave = false, onConfirm, onPrevent })=>{
    const modalSlug = leaveWithoutSavingModalSlug;
    const { closeModal, openModal } = useModal();
    const modified = useFormModified();
    const { isValid } = useForm();
    const { user } = useAuth();
    const [hasAccepted, setHasAccepted] = React.useState(false);
    const prevent = !disablePreventLeave && Boolean((modified || !isValid) && user);
    const handlePrevent = useCallback(()=>{
        const activeHref = document.activeElement?.href || null;
        if (onPrevent) {
            onPrevent(activeHref);
        }
        openModal(modalSlug);
    }, [
        openModal,
        onPrevent,
        modalSlug
    ]);
    const handleAccept = useCallback(()=>{
        closeModal(modalSlug);
    }, [
        closeModal,
        modalSlug
    ]);
    usePreventLeave({
        hasAccepted,
        onAccept: handleAccept,
        onPrevent: handlePrevent,
        prevent
    });
    const onCancel = useCallback(()=>{
        closeModal(modalSlug);
    }, [
        closeModal,
        modalSlug
    ]);
    const handleConfirm = useCallback(async ()=>{
        if (onConfirm) {
            try {
                await onConfirm();
            } catch (err) {
                // eslint-disable-next-line no-console
                console.error('Error in LeaveWithoutSaving onConfirm:', err);
            }
        }
        setHasAccepted(true);
    }, [
        onConfirm
    ]);
    return /*#__PURE__*/ _jsxDEV(LeaveWithoutSavingModal, {
        modalSlug: modalSlug,
        onCancel: onCancel,
        onConfirm: handleConfirm
    }, void 0, false, {
        fileName: "src/elements/LeaveWithoutSaving/index.tsx",
        lineNumber: 67,
        columnNumber: 5
    }, this);
};
export const LeaveWithoutSavingModal = ({ modalSlug, onCancel, onConfirm })=>{
    const { t } = useTranslation();
    return /*#__PURE__*/ _jsxDEV(ConfirmationModal, {
        body: t('general:changesNotSaved'),
        cancelLabel: t('general:stayOnThisPage'),
        confirmLabel: t('general:leaveAnyway'),
        heading: t('general:leaveWithoutSaving'),
        modalSlug: modalSlug,
        onCancel: onCancel,
        onConfirm: onConfirm
    }, void 0, false, {
        fileName: "src/elements/LeaveWithoutSaving/index.tsx",
        lineNumber: 83,
        columnNumber: 5
    }, this);
};

//# sourceMappingURL=index.js.map