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

const SignMessageConfirmationModal = ({ message, handler, onReject, onSignMessage, hideModal }) => {
    usePreventPageScroll(true);
    const didConfirmRef = useRef(false);
    const [show, setShow] = useState(true);
    const { initPasskeyRecoveryProcess, shouldInitRecovery } = usePasskeyRecovery();
    const { isTurnkeyWallet } = useIsTurnkeyWallet();
    const { setShowAuthFlow, primaryWallet, user } = useInternalDynamicContext();
    const { pushView } = useViewContext();
    const { userNeedsCrossDomainPasskey } = usePasskeyContext();
    const { t } = useTranslation();
    const { getEOAWallet } = useSmartWallets();
    const eoaWallet = primaryWallet && getEOAWallet(primaryWallet);
    const handleOnReject = useCallback(() => {
        didConfirmRef.current = false;
        setShow(false);
    }, [setShow]);
    const { isLoading, mutate: confirm, data: signedMessage, error: signMessageError, } = useMutation(() => handler(message), {
        onSuccess: () => {
            didConfirmRef.current = true;
            setShow(false);
        },
    });
    const errorText = useMemo(() => {
        if (!signMessageError) {
            return undefined;
        }
        if (signMessageError instanceof DynamicError) {
            return signMessageError.message;
        }
        try {
            return getProperErrorMessage(signMessageError, user);
        }
        catch (e) {
            if (e instanceof AccessBlockedError) {
                pushView('access-blocked');
            }
            return;
        }
    }, [signMessageError, pushView, user]);
    const handleOnModalUnmount = useCallback(() => {
        if (signedMessage) {
            return onSignMessage(signedMessage);
        }
        onReject(signMessageError || new UserRejectedRequestError());
    }, [signedMessage, onSignMessage, onReject, signMessageError]);
    const handleMessageSign = (signWithoutModal) => __awaiter(void 0, void 0, void 0, function* () {
        const isSessionKeyCompatible = (primaryWallet && isSessionKeyCompatibleWallet(primaryWallet)) ||
            (eoaWallet && 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.once('passkeyRecoveryCompleted', () => {
                confirm();
            });
            return;
        }
        confirm();
    });
    useEffectOnce(() => {
        if (hideModal) {
            handleMessageSign(true);
        }
    });
    const closeButton = (jsx(IconButton, { type: 'button', onClick: handleOnReject, "data-testid": 'close', disabled: isLoading, children: jsx(SvgClose, {}) }));
    return hideModal ? null : (jsx(Portal, { handleClose: handleOnReject, isShown: show, zIndex: authModalZIndex, withBackdrop: true, elementId: 'dynamic-sign-message', transitionEvents: {
            onUnmount: handleOnModalUnmount,
        }, children: jsx(Modal, { children: jsxs(ModalCard, { children: [jsx(ModalHeader, { trailing: closeButton, alignContent: 'bottom', children: jsx(IconWithSpinner, { Icon: (props) => (jsx(Icon, { color: 'brand-primary', children: jsx(SvgSignCircle, Object.assign({}, props)) })), iconSize: 64, isSpinning: true }) }), jsx(PasskeyCreatedSuccessBanner, {}), jsxs("div", { className: 'sign-message-confirmation__body', children: [jsx(Typography, { variant: 'title', color: 'primary', className: 'sign-message-confirmation__title', copykey: 'dyn_sign_message.title', children: t('dyn_sign_message.title') }), jsx(AppOriginTile, {}), jsx(Typography, { variant: 'body_normal', color: 'secondary', className: 'sign-message-confirmation__warning', copykey: 'dyn_sign_message.warning', children: t('dyn_sign_message.warning') }), jsx(AnimatePresence, { animationComponent: jsx(VerticalDrawerTransition, {}), children: signMessageError && (jsx("div", { className: 'sign-message-confirmation__error', children: jsx(ErrorContainer, { children: errorText }) })) }), jsxs("div", { className: 'sign-message-confirmation__message-container-wrapper', children: [jsx(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') }), jsx("div", { className: 'sign-message-confirmation__message-container', children: jsx("div", { className: 'sign-message-confirmation__message', children: jsx(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') }) }) })] }), jsxs("div", { className: 'sign-message-confirmation__actions', children: [jsx(TypographyButton, { buttonVariant: 'secondary', onClick: handleOnReject, expanded: true, buttonPadding: 'large', disabled: isLoading, copykey: 'dyn_sign_message.cancel_button', children: t('dyn_sign_message.cancel_button') }), jsx(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') })] }), jsx(NeedHelpSection, {}), jsx(PoweredByDynamic, {})] })] }) }) }));
};

export { SignMessageConfirmationModal };
