'use client'
'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var _tslib = require('../../../../_virtual/_tslib.cjs');
var jsxRuntime = require('react/jsx-runtime');
var React = require('react');
var reactI18next = require('react-i18next');
var utils = require('@dynamic-labs/utils');
var walletConnectorCore = require('@dynamic-labs/wallet-connector-core');
require('../../components/Accordion/components/AccordionItem/AccordionItem.cjs');
var close = require('../../shared/assets/close.cjs');
var signCircle = require('../../shared/assets/sign-circle.cjs');
require('@dynamic-labs/iconic');
var ViewContext = require('../../context/ViewContext/ViewContext.cjs');
require('../../shared/logger.cjs');
require('@dynamic-labs/wallet-book');
require('../../utils/constants/colors.cjs');
require('../../utils/constants/values.cjs');
require('@dynamic-labs/sdk-api-core');
var usePreventPageScroll = require('../../shared/utils/hooks/usePreventPageScroll/usePreventPageScroll.cjs');
var index = require('../../shared/consts/index.cjs');
require('../../components/Alert/Alert.cjs');
var AnimatePresence = require('../../components/AnimatePresence/AnimatePresence.cjs');
var AppOriginTile = require('../../components/AppOriginTile/AppOriginTile.cjs');
require('../../context/AccessDeniedContext/AccessDeniedContext.cjs');
require('../../context/DynamicContext/DynamicContext.cjs');
require('../../store/state/loadingAndLifecycle/loadingAndLifecycle.cjs');
var dynamicEvents = require('../../events/dynamicEvents.cjs');
require('../../context/CaptchaContext/CaptchaContext.cjs');
require('../../context/ErrorContext/ErrorContext.cjs');
require('@dynamic-labs/multi-wallet');
require('react-international-phone');
require('../../store/state/nonce/nonce.cjs');
require('@dynamic-labs-sdk/client/core');
require('../../client/client.cjs');
require('@dynamic-labs-sdk/client');
require('../../config/ApiEndpoint.cjs');
require('@dynamic-labs/locale');
require('../../store/state/dynamicContextProps/dynamicContextProps.cjs');
require('../../store/state/primaryWalletId/primaryWalletId.cjs');
require('../../store/state/connectedWalletsInfo/connectedWalletsInfo.cjs');
require('../../context/AccountExistsContext/AccountExistsContext.cjs');
require('../../context/UserWalletsContext/UserWalletsContext.cjs');
require('../../store/state/authMode/authMode.cjs');
require('../../context/VerificationContext/VerificationContext.cjs');
require('react-dom');
require('../../utils/functions/compareChains/compareChains.cjs');
require('../../views/Passkey/utils/findPrimaryEmbeddedChain/findPrimaryEmbeddedChain.cjs');
require('../../context/ThemeContext/ThemeContext.cjs');
var useSmartWallets = require('../../utils/hooks/useSmartWallets/useSmartWallets.cjs');
require('../../utils/hooks/useUserUpdateRequest/useUpdateUser/userFieldsSchema.cjs');
var useMutation = require('../../utils/hooks/useMutation/useMutation.cjs');
var usePasskeyRecovery = require('../../utils/hooks/usePasskeyRecovery/usePasskeyRecovery.cjs');
require('bs58');
require('@dynamic-labs/types');
require('../../context/SocialRedirectContext/SocialRedirectContext.cjs');
require('../../context/LoadingContext/LoadingContext.cjs');
require('../../context/WalletContext/WalletContext.cjs');
var useIsTurnkeyWallet = require('../../utils/hooks/useIsTurnkeyWallet/useIsTurnkeyWallet.cjs');
require('../../utils/hooks/useEmbeddedWallet/useSecureEnclaveEmbeddedWallet/constants.cjs');
require('yup');
require('../../context/MockContext/MockContext.cjs');
require('../../views/CollectUserDataView/useFields.cjs');
require('../../context/FieldsStateContext/FieldsStateContext.cjs');
require('../../context/UserFieldEditorContext/UserFieldEditorContext.cjs');
require('@dynamic-labs/rpc-providers');
require('../../store/state/walletOptions/walletOptions.cjs');
var PoweredByDynamic = require('../../components/PoweredByDynamic/PoweredByDynamic.cjs');
require('../../context/FooterAnimationContext/index.cjs');
require('../../components/ShadowDOM/ShadowDOM.cjs');
require('../../components/Transition/ZoomTransition/ZoomTransition.cjs');
require('../../components/Transition/SlideInUpTransition/SlideInUpTransition.cjs');
require('../../components/Transition/OpacityTransition/OpacityTransition.cjs');
var VerticalDrawerTransition = require('../../components/Transition/VerticalDrawerTransition/VerticalDrawerTransition.cjs');
require('../../components/OverlayCardBase/OverlayCardTarget/OverlayCardTarget.cjs');
require('../../context/WalletGroupContext/WalletGroupContext.cjs');
require('../../widgets/DynamicWidget/components/DynamicWidgetHeader/DynamicWidgetHeader.cjs');
var Modal = require('../../components/Modal/Modal.cjs');
var ModalCard = require('../../components/ModalCard/ModalCard.cjs');
var Portal = require('../../components/Portal/Portal.cjs');
var IconWithSpinner = require('../../components/IconWithSpinner/IconWithSpinner.cjs');
var Icon = require('../../components/Icon/Icon.cjs');
var Typography = require('../../components/Typography/Typography.cjs');
require('../../widgets/DynamicWidget/context/DynamicWidgetContext.cjs');
var ErrorContainer = require('../../components/ErrorContainer/ErrorContainer.cjs');
var IconButton = require('../../components/IconButton/IconButton.cjs');
var ModalHeader = require('../../components/ModalHeader/ModalHeader.cjs');
var TypographyButton = require('../../components/TypographyButton/TypographyButton.cjs');
var getProperErrorMessage = require('./getProperErrorMessage.cjs');
require('../../components/MenuList/Dropdown/Dropdown.cjs');
require('formik');
require('../../utils/hooks/useSubdomainCheck/useSubdomainCheck.cjs');
require('../../store/state/sendBalances.cjs');
require('../../components/Input/Input.cjs');
require('../../components/OverlayCard/OverlayCard.cjs');
var useEffectOnce = require('../../utils/hooks/useEffectOnce/useEffectOnce.cjs');
require('../../views/TransactionConfirmationView/TransactionConfirmationView.cjs');
var PasskeyCreatedSuccessBanner = require('../../components/PasskeyCreatedSuccessBanner/PasskeyCreatedSuccessBanner.cjs');
var PasskeyContext = require('../../context/PasskeyContext/PasskeyContext.cjs');
require('../../widgets/DynamicWidget/components/PasskeyCard/PasskeyCard.cjs');
require('../../widgets/DynamicWidget/views/CryptoComOnramp/CryptoComOnramp.cjs');
require('../../context/OnrampContext/OnrampContext.cjs');
require('../../../index.cjs');
require('../../widgets/DynamicWidget/helpers/convertExchangeKeyAndProviderEnum.cjs');
require('qrcode');
require('../../widgets/DynamicWidget/views/ReceiveWalletFunds/ReceiveWalletFunds.cjs');
var NeedHelpSection = require('../../components/NeedHelpSection/NeedHelpSection.cjs');
require('../../context/IpConfigurationContext/IpConfigurationContext.cjs');
require('../../context/ConnectWithOtpContext/ConnectWithOtpContext.cjs');
require('../../widgets/DynamicBridgeWidget/views/WalletsView/components/SecondaryWallets/SecondaryWallets.cjs');
require('@hcaptcha/react-hcaptcha');
require('../../views/ExchangeWhitelistWarning/ExchangeWhitelistWarning.cjs');
require('../../context/ErrorContext/hooks/useErrorText/useErrorText.cjs');
require('../../views/MfaChooseDeviceView/useGetMfaOptions/useGetMfaOptions.cjs');
require('../../store/state/connectorsInitializing/connectorsInitializing.cjs');
require('../../store/state/tokenBalances.cjs');
require('../../store/state/multichainBalances.cjs');
require('../../shared/utils/functions/getInitialUrl/getInitialUrl.cjs');
var useInternalDynamicContext = require('../../context/DynamicContext/useDynamicContext/useInternalDynamicContext/useInternalDynamicContext.cjs');
require('../../components/InlineWidget/InlineWidget.cjs');
require('../../components/IsBrowser/IsBrowser.cjs');
require('../../components/Popper/Popper/Popper.cjs');
require('../../components/Popper/PopperContext/PopperContext.cjs');
var SignMessagePreview = require('../../components/SignMessagePreview/SignMessagePreview.cjs');

const SignMessageConfirmationModal = ({ message, handler, onReject, onSignMessage, hideModal }) => {
    usePreventPageScroll.usePreventPageScroll(true);
    const didConfirmRef = React.useRef(false);
    const [show, setShow] = React.useState(true);
    const { initPasskeyRecoveryProcess, shouldInitRecovery } = usePasskeyRecovery.usePasskeyRecovery();
    const { isTurnkeyWallet } = useIsTurnkeyWallet.useIsTurnkeyWallet();
    const { setShowAuthFlow, primaryWallet, user } = useInternalDynamicContext.useInternalDynamicContext();
    const { pushView } = ViewContext.useViewContext();
    const { userNeedsCrossDomainPasskey } = PasskeyContext.usePasskeyContext();
    const { t } = reactI18next.useTranslation();
    const { getEOAWallet } = useSmartWallets.useSmartWallets();
    const eoaWallet = primaryWallet && getEOAWallet(primaryWallet);
    const handleOnReject = React.useCallback(() => {
        didConfirmRef.current = false;
        setShow(false);
    }, [setShow]);
    const { isLoading, mutate: confirm, data: signedMessage, error: signMessageError, } = useMutation.useMutation(() => handler(message), {
        onSuccess: () => {
            didConfirmRef.current = true;
            setShow(false);
        },
    });
    const errorText = React.useMemo(() => {
        if (!signMessageError) {
            return undefined;
        }
        if (signMessageError instanceof utils.DynamicError) {
            return signMessageError.message;
        }
        try {
            return getProperErrorMessage.getProperErrorMessage(signMessageError, user);
        }
        catch (e) {
            if (e instanceof utils.AccessBlockedError) {
                pushView('access-blocked');
            }
            return;
        }
    }, [signMessageError, pushView, user]);
    const handleOnModalUnmount = React.useCallback(() => {
        if (signedMessage) {
            return onSignMessage(signedMessage);
        }
        onReject(signMessageError || new utils.UserRejectedRequestError());
    }, [signedMessage, onSignMessage, onReject, signMessageError]);
    const handleMessageSign = (signWithoutModal) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        const isSessionKeyCompatible = (primaryWallet && walletConnectorCore.isSessionKeyCompatibleWallet(primaryWallet)) ||
            (eoaWallet && walletConnectorCore.isSessionKeyCompatibleWallet(eoaWallet));
        if ((yield shouldInitRecovery()) && !isSessionKeyCompatible) {
            yield initPasskeyRecoveryProcess('email', {
                type: 'signMessage',
            });
        }
        if (signWithoutModal === true) {
            onSignMessage('callHandlerOutsideModal');
            return;
        }
        if (isSessionKeyCompatible) {
            confirm();
            return;
        }
        if (isTurnkeyWallet && userNeedsCrossDomainPasskey) {
            pushView('passkey-new-domain-detected');
            setShowAuthFlow(true, {
                ignoreIfIsEmbeddedWidget: false,
                performMultiWalletChecks: false,
            });
            dynamicEvents.dynamicEvents.once('passkeyRecoveryCompleted', () => {
                confirm();
            });
            return;
        }
        confirm();
    });
    useEffectOnce.useEffectOnce(() => {
        if (hideModal) {
            handleMessageSign(true);
        }
    });
    const closeButton = (jsxRuntime.jsx(IconButton.IconButton, { type: 'button', onClick: handleOnReject, "data-testid": 'close', disabled: isLoading, children: jsxRuntime.jsx(close.ReactComponent, {}) }));
    return hideModal ? null : (jsxRuntime.jsx(Portal.Portal, { handleClose: handleOnReject, isShown: show, zIndex: index.authModalZIndex, withBackdrop: true, elementId: 'dynamic-sign-message', transitionEvents: {
            onUnmount: handleOnModalUnmount,
        }, children: jsxRuntime.jsx(Modal.Modal, { children: jsxRuntime.jsxs(ModalCard.ModalCard, { children: [jsxRuntime.jsx(ModalHeader.ModalHeader, { trailing: closeButton, alignContent: 'bottom', children: jsxRuntime.jsx(IconWithSpinner.IconWithSpinner, { Icon: (props) => (jsxRuntime.jsx(Icon.Icon, { color: 'brand-primary', children: jsxRuntime.jsx(signCircle.ReactComponent, Object.assign({}, props)) })), iconSize: 64, isSpinning: true }) }), jsxRuntime.jsx(PasskeyCreatedSuccessBanner.PasskeyCreatedSuccessBanner, {}), jsxRuntime.jsxs("div", { className: 'sign-message-confirmation__body', children: [jsxRuntime.jsx(Typography.Typography, { variant: 'title', color: 'primary', className: 'sign-message-confirmation__title', copykey: 'dyn_sign_message.title', children: t('dyn_sign_message.title') }), jsxRuntime.jsx(AppOriginTile.AppOriginTile, {}), jsxRuntime.jsx(Typography.Typography, { variant: 'body_normal', color: 'secondary', className: 'sign-message-confirmation__warning', copykey: 'dyn_sign_message.warning', children: t('dyn_sign_message.warning') }), jsxRuntime.jsx(AnimatePresence.AnimatePresence, { animationComponent: jsxRuntime.jsx(VerticalDrawerTransition.VerticalDrawerTransition, {}), children: signMessageError && (jsxRuntime.jsx("div", { className: 'sign-message-confirmation__error', children: jsxRuntime.jsx(ErrorContainer.ErrorContainer, { children: errorText }) })) }), jsxRuntime.jsxs("div", { className: 'sign-message-confirmation__message-container-wrapper', children: [jsxRuntime.jsx(Typography.Typography, { variant: 'body_normal', color: 'primary', weight: 'bold', className: 'sign-message-confirmation__message-container-label', copykey: 'dyn_sign_message.message_label', children: t('dyn_sign_message.message_label') }), jsxRuntime.jsx("div", { className: 'sign-message-confirmation__message-container', children: jsxRuntime.jsx("div", { className: 'sign-message-confirmation__message', children: jsxRuntime.jsx(SignMessagePreview.SignMessagePreview
                                            // strip if entire message is a quote and replace escaped newlines
                                            , { 
                                                // strip if entire message is a quote and replace escaped newlines
                                                message: message
                                                    .toString()
                                                    .replace(/^"(.*)"$/, '$1')
                                                    .replace(/\\n/g, '\n') }) }) })] }), jsxRuntime.jsxs("div", { className: 'sign-message-confirmation__actions', children: [jsxRuntime.jsx(TypographyButton.TypographyButton, { buttonVariant: 'secondary', onClick: handleOnReject, expanded: true, buttonPadding: 'large', disabled: isLoading, copykey: 'dyn_sign_message.cancel_button', children: t('dyn_sign_message.cancel_button') }), jsxRuntime.jsx(TypographyButton.TypographyButton, { buttonVariant: 'primary', buttonPadding: 'large', onClick: handleMessageSign, expanded: true, loading: isLoading, copykey: 'dyn_sign_message.sign_button', dataTestId: 'sign-button', children: t('dyn_sign_message.sign_button') })] }), jsxRuntime.jsx(NeedHelpSection.NeedHelpSection, {}), jsxRuntime.jsx(PoweredByDynamic.PoweredByDynamic, {})] })] }) }) }));
};

exports.SignMessageConfirmationModal = SignMessageConfirmationModal;
