'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 sdkApiCore = require('@dynamic-labs/sdk-api-core');
var walletConnectorCore = require('@dynamic-labs/wallet-connector-core');
require('@dynamic-labs-sdk/client/core');
require('../../client/client.cjs');
require('@dynamic-labs-sdk/client');
require('../../config/ApiEndpoint.cjs');
var findEmbeddedWalletFromVerifiedCredentials = require('../../utils/functions/findEmbeddedWalletFromVerifiedCredentials/findEmbeddedWalletFromVerifiedCredentials.cjs');
require('@dynamic-labs/utils');
require('../../utils/constants/values.cjs');
require('@dynamic-labs/multi-wallet');
require('react-international-phone');
require('../../utils/constants/colors.cjs');
var shortenEmail = require('../../shared/utils/functions/shortenEmail/shortenEmail.cjs');
require('@dynamic-labs/iconic');
var check = require('../../shared/assets/check.cjs');
var signInWithEmail = require('../../shared/assets/sign-in-with-email.cjs');
var ViewContext = require('../../context/ViewContext/ViewContext.cjs');
var logger = require('../../shared/logger.cjs');
require('@dynamic-labs/wallet-book');
require('../../shared/consts/index.cjs');
require('../../store/state/nonce/nonce.cjs');
var isTurnkeyEnabled = require('../../utils/functions/isTurnkeyEnabled/isTurnkeyEnabled.cjs');
var updatePrimaryWalletId = require('../../utils/functions/updatePrimaryWalletId/updatePrimaryWalletId.cjs');
require('../../store/state/connectedWalletsInfo/connectedWalletsInfo.cjs');
require('../../store/state/dynamicContextProps/dynamicContextProps.cjs');
require('../../store/state/primaryWalletId/primaryWalletId.cjs');
var email = require('../../data/api/email/email.cjs');
require('@dynamic-labs/locale');
var dynamicEvents = require('../../events/dynamicEvents.cjs');
var storeTokenAndUser = require('../../client/extension/storeTokenAndUser/storeTokenAndUser.cjs');
var convertSdkUserToUserProfile = require('../../client/extension/user/convertSdkUserToUserProfile/convertSdkUserToUserProfile.cjs');
var classNames = require('../../utils/functions/classNames/classNames.cjs');
require('../../components/Accordion/components/AccordionItem/AccordionItem.cjs');
require('../../components/Alert/Alert.cjs');
require('../../context/DynamicContext/DynamicContext.cjs');
require('../../store/state/loadingAndLifecycle/loadingAndLifecycle.cjs');
require('../../store/state/authMode/authMode.cjs');
var useInternalDynamicContext = require('../../context/DynamicContext/useDynamicContext/useInternalDynamicContext/useInternalDynamicContext.cjs');
require('../../context/CaptchaContext/CaptchaContext.cjs');
var ErrorContext = require('../../context/ErrorContext/ErrorContext.cjs');
require('../../context/AccessDeniedContext/AccessDeniedContext.cjs');
require('../../context/AccountExistsContext/AccountExistsContext.cjs');
require('../../context/UserWalletsContext/UserWalletsContext.cjs');
var useOtpVerificationRequest = require('../../utils/hooks/authenticationHooks/useOtpVerificationRequest/useOtpVerificationRequest.cjs');
require('react-dom');
require('../../utils/functions/compareChains/compareChains.cjs');
var findPrimaryEmbeddedChain = require('../Passkey/utils/findPrimaryEmbeddedChain/findPrimaryEmbeddedChain.cjs');
var useEmbeddedWalletSessionKeys = require('../../utils/hooks/useEmbeddedWalletSessionKeys/useEmbeddedWalletSessionKeys.cjs');
require('../../context/ThemeContext/ThemeContext.cjs');
var useSmartWallets = require('../../utils/hooks/useSmartWallets/useSmartWallets.cjs');
var VerificationContext = require('../../context/VerificationContext/VerificationContext.cjs');
require('../../utils/hooks/useUserUpdateRequest/useUpdateUser/userFieldsSchema.cjs');
var useOnUnmount = require('../../utils/hooks/useOnUnmount/useOnUnmount.cjs');
var usePasskeyRecovery = require('../../utils/hooks/usePasskeyRecovery/usePasskeyRecovery.cjs');
require('bs58');
require('@dynamic-labs/types');
require('../../context/SocialRedirectContext/SocialRedirectContext.cjs');
var useUserAuth = require('../../utils/hooks/useUserAuth/useUserAuth.cjs');
require('yup');
require('../../context/MockContext/MockContext.cjs');
require('../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 Typography = require('../../components/Typography/Typography.cjs');
require('../../context/FooterAnimationContext/index.cjs');
var useIsTurnkeyWallet = require('../../utils/hooks/useIsTurnkeyWallet/useIsTurnkeyWallet.cjs');
require('../../components/ShadowDOM/ShadowDOM.cjs');
require('../../components/Transition/ZoomTransition/ZoomTransition.cjs');
require('../../components/Transition/SlideInUpTransition/SlideInUpTransition.cjs');
require('../../components/Transition/OpacityTransition/OpacityTransition.cjs');
require('../../components/OverlayCardBase/OverlayCardTarget/OverlayCardTarget.cjs');
require('../../context/WalletGroupContext/WalletGroupContext.cjs');
require('../../widgets/DynamicWidget/components/DynamicWidgetHeader/DynamicWidgetHeader.cjs');
require('react-focus-lock');
var IconWithSpinner = require('../../components/IconWithSpinner/IconWithSpinner.cjs');
var Icon = require('../../components/Icon/Icon.cjs');
var LoadingContext = require('../../context/LoadingContext/LoadingContext.cjs');
require('../../context/WalletContext/WalletContext.cjs');
require('../../widgets/DynamicWidget/context/DynamicWidgetContext.cjs');
var ErrorContainer = require('../../components/ErrorContainer/ErrorContainer.cjs');
require('../../components/IconButton/IconButton.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');
require('../TransactionConfirmationView/TransactionConfirmationView.cjs');
require('../../components/PasskeyCreatedSuccessBanner/PasskeyCreatedSuccessBanner.cjs');
require('../../context/PasskeyContext/PasskeyContext.cjs');
require('../../widgets/DynamicWidget/components/PasskeyCard/PasskeyCard.cjs');
require('../../utils/hooks/useEmbeddedWallet/useSecureEnclaveEmbeddedWallet/constants.cjs');
require('../../widgets/DynamicWidget/views/CryptoComOnramp/CryptoComOnramp.cjs');
require('../../context/OnrampContext/OnrampContext.cjs');
require('../../../index.cjs');
require('../../widgets/DynamicWidget/helpers/convertExchangeKeyAndProviderEnum.cjs');
var TextButton = require('../../components/TextButton/TextButton.cjs');
require('qrcode');
require('../../widgets/DynamicWidget/views/ReceiveWalletFunds/ReceiveWalletFunds.cjs');
var IconWithStatus = require('../../components/IconWithStatus/IconWithStatus.cjs');
require('../../context/IpConfigurationContext/IpConfigurationContext.cjs');
require('../../context/ConnectWithOtpContext/ConnectWithOtpContext.cjs');
var useConnectWithOtp = require('../../context/ConnectWithOtpContext/useConnectWithOtp.cjs');
require('../../widgets/DynamicBridgeWidget/views/WalletsView/components/SecondaryWallets/SecondaryWallets.cjs');
require('@hcaptcha/react-hcaptcha');
var PinField = require('../../components/PinField/PinField.cjs');
var RetrySendVerificationCodeSection = require('../../components/RetrySendVerificationCodeSection/RetrySendVerificationCodeSection.cjs');
require('../ExchangeWhitelistWarning/ExchangeWhitelistWarning.cjs');
require('../../context/ErrorContext/hooks/useErrorText/useErrorText.cjs');
require('../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');
require('../../components/InlineWidget/InlineWidget.cjs');
require('../../components/IsBrowser/IsBrowser.cjs');
require('../../components/Popper/Popper/Popper.cjs');
require('../../components/Popper/PopperContext/PopperContext.cjs');

const SECONDS_TO_RETRY = 15;
const EmailVerification = ({ isEmailRecoveryFlow = false, showRetryButton: _showRetryButton = true, showTransferMessage: _showTransferMessage = false, }) => {
    var _a, _b, _c, _d;
    const { environmentId, handleLogOut, setShowAuthFlow, projectSettings, user, userWithMissingInfo, walletConnectorOptions, primaryWallet, } = useInternalDynamicContext.useInternalDynamicContext();
    const { pushView, clearStackAndPushInitialView } = ViewContext.useViewContext();
    const { error, setError, setErrorMessage } = ErrorContext.useErrorContext();
    const { loading, setLoading } = LoadingContext.useLoadingContext();
    const [showRetryButton, setShowRetryButton] = React.useState(_showRetryButton);
    const [showTransferMessage, setShowTransferMessage] = React.useState(_showTransferMessage);
    const { getEOAWallet } = useSmartWallets.useSmartWallets();
    // Use a state to ensure UI is updated, but also a ref to access in effect cleanup
    const [isValidated, _setIsValidated] = React.useState(false);
    const isValidatedRef = React.useRef(isValidated);
    const setIsValidated = (value) => {
        _setIsValidated(value);
        isValidatedRef.current = value;
    };
    const { displayedDestination: email$1, verificationUUID, setVerificationUUID, } = VerificationContext.useVerification();
    const { t } = reactI18next.useTranslation();
    const { addRecoveryEmail } = usePasskeyRecovery.usePasskeyRecovery();
    const { isTurnkeyWallet, hasTurnkeyVerifiedCredentialAuthenticator, hasRecoveryEmail, } = useIsTurnkeyWallet.useIsTurnkeyWallet();
    const isTurnkeyProviderEnabled = isTurnkeyEnabled.isTurnkeyEnabled(projectSettings);
    const { initAuth, completeAuth, cancelAuth } = useUserAuth.useUserAuth({
        authMethod: 'email',
    });
    const { verifyOneTimePassword, retryOneTimePassword } = useConnectWithOtp.useConnectWithOtp();
    const { generateSessionKey, shouldRegisterSessionKeysOnSignin } = useEmbeddedWalletSessionKeys.useEmbeddedWalletSessionKeys({
        environmentId,
        projectSettings,
    });
    // When true, causes the component to call emailVerificationX callback on unmount
    const callCallbackOnUnmount = React.useRef(true);
    useOnUnmount.useOnUnmount(() => {
        if (!callCallbackOnUnmount.current)
            return;
        const emailString = email$1 !== null && email$1 !== void 0 ? email$1 : '';
        dynamicEvents.dynamicEvents.emit('emailVerificationResult', isValidatedRef.current, emailString);
        if (!isValidatedRef.current)
            dynamicEvents.dynamicEvents.emit('authFailure', { email: emailString, option: emailString, type: 'email' }, 'user-cancelled');
        if (!email$1)
            logger.logger.warn("WARNING: emitted emailVerificationResult with incomplete params because useVerification's displayedDestination was undefined");
    });
    const { verifyOtp } = useOtpVerificationRequest.useOtpVerificationRequest();
    const completeSignInFlow = React.useCallback((updateUserProfileResponse) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        var _e, _f, _g, _h, _j, _k, _l, _m;
        if (updateUserProfileResponse.nextView === 'verified-and-transferred') {
            setShowTransferMessage === null || setShowTransferMessage === void 0 ? void 0 : setShowTransferMessage(true);
        }
        if (isEmailRecoveryFlow) {
            pushView('passkey-recovery-add-email', {
                canSkipAddingEmail: false,
                isFromEmailVerification: true,
            });
            return true;
        }
        if (!isTurnkeyWallet) {
            return false;
        }
        // If the user has a turnkey embedded wallet and no recovery email, add the email as a recovery email
        // This logic should run even if the turnkey provider is not enabled anymore
        // (e.g. user created the wallet and then the settings were disalbed)
        if (hasTurnkeyVerifiedCredentialAuthenticator &&
            !hasRecoveryEmail &&
            ((_e = updateUserProfileResponse === null || updateUserProfileResponse === void 0 ? void 0 : updateUserProfileResponse.user) === null || _e === void 0 ? void 0 : _e.email)) {
            storeTokenAndUser.storeTokenAndUser(updateUserProfileResponse);
            yield addRecoveryEmail(updateUserProfileResponse.user.email);
            setShowAuthFlow(false);
            return true;
        }
        // The logic below is needed when we capture an email after a user
        // authenticated with Sms/Twitter etc And we need to capture and email.
        if (isTurnkeyProviderEnabled) {
            const isAutomaticWalletCreation = (_g = (_f = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.sdk) === null || _f === void 0 ? void 0 : _f.embeddedWallets) === null || _g === void 0 ? void 0 : _g.automaticEmbeddedWalletCreation;
            const eoaWallet = primaryWallet && getEOAWallet(primaryWallet);
            const isSessionKeyCompatible = (primaryWallet && walletConnectorCore.isSessionKeyCompatibleWallet(primaryWallet)) ||
                (eoaWallet && walletConnectorCore.isSessionKeyCompatibleWallet(eoaWallet));
            const usingV3Wallets = Boolean(((_j = (_h = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.sdk) === null || _h === void 0 ? void 0 : _h.embeddedWallets) === null || _j === void 0 ? void 0 : _j.defaultWalletVersion) ===
                sdkApiCore.EmbeddedWalletVersionEnum.V3);
            const isUsingPregeneratedWallets = Boolean(!usingV3Wallets &&
                isAutomaticWalletCreation &&
                (!((_l = (_k = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.sdk) === null || _k === void 0 ? void 0 : _k.embeddedWallets) === null || _l === void 0 ? void 0 : _l.forceAuthenticatorAtSignup) ||
                    isSessionKeyCompatible));
            if (isUsingPregeneratedWallets) {
                const primaryChain = findPrimaryEmbeddedChain.findPrimaryEmbeddedChain(projectSettings);
                // Pregenerated wallet was created during an
                // additional email validation step as part of onboarding
                // cannot rely on newUser JWT field here due to session being counted twice
                // when authentication happens followed by a separate email kyc step
                const embeddedWalletVerifiedCredential = findEmbeddedWalletFromVerifiedCredentials.findEmbeddedWalletFromVerifiedCredentials(convertSdkUserToUserProfile.convertSdkUserToUserProfile(updateUserProfileResponse.user), [primaryChain]);
                if (!embeddedWalletVerifiedCredential) {
                    throw new Error('Could not find an embedded wallet');
                }
                const walletOption = walletConnectorOptions === null || walletConnectorOptions === void 0 ? void 0 : walletConnectorOptions.find((option) => option.key === embeddedWalletVerifiedCredential.walletName);
                if (!(walletOption === null || walletOption === void 0 ? void 0 : walletOption.walletConnector)) {
                    throw new Error('Could not find connector for embedded wallet');
                }
                const wallet = walletOption.walletConnector.createWallet({
                    address: embeddedWalletVerifiedCredential.address || '',
                    chain: walletOption.walletConnector.connectedChain,
                    connector: walletOption.walletConnector,
                    id: embeddedWalletVerifiedCredential.id,
                    isAuthenticated: false,
                    key: (_m = embeddedWalletVerifiedCredential.walletName) !== null && _m !== void 0 ? _m : '',
                });
                updatePrimaryWalletId.updatePrimaryWalletId(embeddedWalletVerifiedCredential.id);
                dynamicEvents.dynamicEvents.emit('embeddedWalletCreated', wallet, embeddedWalletVerifiedCredential, user);
            }
            if (isUsingPregeneratedWallets || !isAutomaticWalletCreation) {
                setShowAuthFlow(false);
                return true;
            }
        }
        return false;
    }), [
        isEmailRecoveryFlow,
        isTurnkeyWallet,
        hasTurnkeyVerifiedCredentialAuthenticator,
        hasRecoveryEmail,
        isTurnkeyProviderEnabled,
        pushView,
        addRecoveryEmail,
        setShowAuthFlow,
        (_b = (_a = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.sdk) === null || _a === void 0 ? void 0 : _a.embeddedWallets) === null || _b === void 0 ? void 0 : _b.automaticEmbeddedWalletCreation,
        (_d = (_c = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.sdk) === null || _c === void 0 ? void 0 : _c.embeddedWallets) === null || _d === void 0 ? void 0 : _d.forceAuthenticatorAtSignup,
        primaryWallet,
        getEOAWallet,
        walletConnectorOptions,
        user,
    ]);
    const handleEmailVerification = React.useCallback((verificationToken) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        setError(undefined);
        setLoading(true);
        // Sign in flow
        if (!user && !userWithMissingInfo) {
            return initAuth({
                onVerifySuccess: () => setIsValidated(true),
                options: { email: email$1 },
                // TODO: revisit why the success state is not shown when true
                // currently setting it to true will delay the otp step but not show the success state
                showSuccessMessage: false,
                verifyFunction: () => _tslib.__awaiter(void 0, void 0, void 0, function* () {
                    if (!verificationUUID) {
                        // Try the new headless login flow that doesn't require a verificationUUID
                        return verifyOneTimePassword(verificationToken, {
                            // Skip setting the user auth token because it can trigger view re-renders
                            skipSetUserAndAuthToken: true,
                        });
                    }
                    let sessionPublicKey = undefined;
                    if (shouldRegisterSessionKeysOnSignin()) {
                        const keypair = yield generateSessionKey();
                        sessionPublicKey = keypair.publicKey;
                    }
                    return email.signInWithEmailVerification({
                        environmentId,
                        sessionPublicKey,
                        verificationToken,
                        verificationUUID,
                    });
                }),
            });
        }
        // Verify flow (still depends on verificationUUID)
        if (!verificationUUID) {
            return cancelAuth();
        }
        return completeAuth({
            completeSignInFlow: (updateUserResponse) => _tslib.__awaiter(void 0, void 0, void 0, function* () { return completeSignInFlow(updateUserResponse); }),
            onValidUpdatedJwt: () => {
                // This causes emaiLVerificationSuccess to be raised, so it should be set as soon
                // as verification doesn't fail. Don't move it below
                setIsValidated(true);
            },
            options: { email: email$1, isEmailRecoveryFlow },
            updateJwtFunction: () => _tslib.__awaiter(void 0, void 0, void 0, function* () { return verifyOtp(verificationToken, 'email', verificationUUID); }),
        });
    }), [
        setError,
        setLoading,
        verificationUUID,
        user,
        userWithMissingInfo,
        completeAuth,
        email$1,
        isEmailRecoveryFlow,
        cancelAuth,
        initAuth,
        environmentId,
        completeSignInFlow,
        verifyOtp,
        verifyOneTimePassword,
        generateSessionKey,
        shouldRegisterSessionKeysOnSignin,
    ]);
    const handleRetry = () => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        try {
            setLoading(true);
            // Try the new headless login flow that doesn't need useVerification()
            if (!verificationUUID || !email$1) {
                yield retryOneTimePassword();
                setVerificationUUID(undefined);
                setError(undefined);
                return;
            }
            const { verificationUUID: newVerificationUUID } = yield email.retryEmailVerification({
                email: email$1,
                environmentId,
                verificationUUID,
            });
            setVerificationUUID(newVerificationUUID);
            setError(undefined);
        }
        catch (error) {
            logger.logger.debug(error);
            setErrorMessage(error.code);
            if (error.code === 'too_many_email_verification_attempts') {
                setShowRetryButton(false);
            }
            if (error.code === 'invalid_email_verification') {
                clearStackAndPushInitialView();
            }
        }
        finally {
            setLoading(false);
        }
    });
    const EmailIcon = React.useMemo(() => {
        const EmailIcon = (props) => (jsxRuntime.jsx(Icon.Icon, { color: 'brand-primary', children: jsxRuntime.jsx(signInWithEmail.ReactComponent, Object.assign({}, props)) }));
        return EmailIcon;
    }, []);
    return (jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [error && (jsxRuntime.jsx(ErrorContainer.ErrorContainer, { withIcon: false, className: 'email-verification__error-message', children: error })), jsxRuntime.jsxs("div", { className: classNames.classNames('email-verification__container', {
                    'email-verification__container--error': Boolean(error),
                }), children: [showTransferMessage && (jsxRuntime.jsx("div", { className: 'email-verification__transfer-message', copykey: 'dyn_otp_verification.email.complete', children: t('dyn_otp_verification.email.complete') })), isValidated ? (jsxRuntime.jsx("div", { className: 'email-verification__icon-container', children: jsxRuntime.jsx(IconWithStatus.IconWithStatus, { containerClassName: 'email-verification__icon--verified', Icon: EmailIcon, iconSize: 64, InnerIcon: check.ReactComponent }) })) : (jsxRuntime.jsx(IconWithSpinner.IconWithSpinner, { Icon: EmailIcon, iconSize: 96, isSpinning: true, className: 'email-verification__icon-with-spinner' })), jsxRuntime.jsxs("div", { className: 'email-verification__copy-text-container', children: [jsxRuntime.jsx(Typography.Typography, { variant: 'body_normal', weight: 'regular', color: 'secondary', copykey: 'dyn_otp_verification.description', children: t('dyn_otp_verification.description') }), jsxRuntime.jsx(Typography.Typography, { variant: 'body_normal', weight: 'bold', color: 'secondary', children: shortenEmail.shortenEmail(email$1) })] }), jsxRuntime.jsx(PinField.PinField, { initialValue: Array(6).fill(''), isLoading: loading, handleComplete: handleEmailVerification, isValidated: isValidated, inputMode: 'numeric', pattern: '[0-9]*', hasError: Boolean(error), onChange: () => setError(undefined) }), showRetryButton && (jsxRuntime.jsx(RetrySendVerificationCodeSection.RetrySendVerificationCodeSection, { className: 'email-verification__retry-container', retryHandler: handleRetry, secondsToRetry: SECONDS_TO_RETRY })), (user || userWithMissingInfo) && !isEmailRecoveryFlow && (jsxRuntime.jsx(TextButton.TextButton, { className: 'email-verification__log-out', onClick: handleLogOut, copykey: 'dyn_otp_verification.log_out_button', children: t('dyn_otp_verification.log_out_button') }))] })] }));
};

exports.EmailVerification = EmailVerification;
