'use client'
import { __awaiter } from '../../../../_virtual/_tslib.js';
import { jsxs, Fragment, jsx } from 'react/jsx-runtime';
import { useState, useRef, useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { EmbeddedWalletVersionEnum } from '@dynamic-labs/sdk-api-core';
import { isSessionKeyCompatibleWallet } from '@dynamic-labs/wallet-connector-core';
import '@dynamic-labs-sdk/client/core';
import '../../client/client.js';
import '@dynamic-labs-sdk/client';
import '../../config/ApiEndpoint.js';
import '@dynamic-labs/iconic';
import { ReactComponent as SvgCheck } from '../../shared/assets/check.js';
import { ReactComponent as SvgSignInWithEmail } from '../../shared/assets/sign-in-with-email.js';
import { useViewContext } from '../../context/ViewContext/ViewContext.js';
import { logger } from '../../shared/logger.js';
import '@dynamic-labs/wallet-book';
import '@dynamic-labs/utils';
import '../../utils/constants/colors.js';
import '../../utils/constants/values.js';
import '../../shared/consts/index.js';
import { findEmbeddedWalletFromVerifiedCredentials } from '../../utils/functions/findEmbeddedWalletFromVerifiedCredentials/findEmbeddedWalletFromVerifiedCredentials.js';
import '@dynamic-labs/multi-wallet';
import 'react-international-phone';
import { shortenEmail } from '../../shared/utils/functions/shortenEmail/shortenEmail.js';
import '../../store/state/nonce/nonce.js';
import { isTurnkeyEnabled } from '../../utils/functions/isTurnkeyEnabled/isTurnkeyEnabled.js';
import { updatePrimaryWalletId } from '../../utils/functions/updatePrimaryWalletId/updatePrimaryWalletId.js';
import '../../store/state/connectedWalletsInfo/connectedWalletsInfo.js';
import '../../store/state/dynamicContextProps/dynamicContextProps.js';
import '../../store/state/primaryWalletId/primaryWalletId.js';
import { generateClientSessionKeys } from '../../utils/functions/clientSessionKeys/getClientSessionKeys.js';
import { signInWithEmailVerification, retryEmailVerification } from '../../data/api/email/email.js';
import '@dynamic-labs/locale';
import { dynamicEvents } from '../../events/dynamicEvents.js';
import { storeTokenAndUser } from '../../client/extension/storeTokenAndUser/storeTokenAndUser.js';
import { convertSdkUserToUserProfile } from '../../client/extension/user/convertSdkUserToUserProfile/convertSdkUserToUserProfile.js';
import { classNames } from '../../utils/functions/classNames/classNames.js';
import '../../components/Accordion/components/AccordionItem/AccordionItem.js';
import '../../components/Alert/Alert.js';
import '../../context/DynamicContext/DynamicContext.js';
import '../../store/state/loadingAndLifecycle/loadingAndLifecycle.js';
import '../../store/state/authMode/authMode.js';
import { useInternalDynamicContext } from '../../context/DynamicContext/useDynamicContext/useInternalDynamicContext/useInternalDynamicContext.js';
import '../../context/CaptchaContext/CaptchaContext.js';
import { useErrorContext } from '../../context/ErrorContext/ErrorContext.js';
import '../../context/AccessDeniedContext/AccessDeniedContext.js';
import '../../context/AccountExistsContext/AccountExistsContext.js';
import '../../context/UserWalletsContext/UserWalletsContext.js';
import { useOtpVerificationRequest } from '../../utils/hooks/authenticationHooks/useOtpVerificationRequest/useOtpVerificationRequest.js';
import 'react-dom';
import '../../utils/functions/compareChains/compareChains.js';
import { findPrimaryEmbeddedChain } from '../Passkey/utils/findPrimaryEmbeddedChain/findPrimaryEmbeddedChain.js';
import { useEmbeddedWalletSessionKeys } from '../../utils/hooks/useEmbeddedWalletSessionKeys/useEmbeddedWalletSessionKeys.js';
import '../../context/ThemeContext/ThemeContext.js';
import { useSmartWallets } from '../../utils/hooks/useSmartWallets/useSmartWallets.js';
import { useVerification } from '../../context/VerificationContext/VerificationContext.js';
import '../../utils/hooks/useUserUpdateRequest/useUpdateUser/userFieldsSchema.js';
import { useOnUnmount } from '../../utils/hooks/useOnUnmount/useOnUnmount.js';
import { usePasskeyRecovery } from '../../utils/hooks/usePasskeyRecovery/usePasskeyRecovery.js';
import 'bs58';
import '@dynamic-labs/types';
import '../../context/SocialRedirectContext/SocialRedirectContext.js';
import { useUserAuth } from '../../utils/hooks/useUserAuth/useUserAuth.js';
import 'yup';
import '../../context/MockContext/MockContext.js';
import '../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 { Typography } from '../../components/Typography/Typography.js';
import '../../context/FooterAnimationContext/index.js';
import { useIsTurnkeyWallet } from '../../utils/hooks/useIsTurnkeyWallet/useIsTurnkeyWallet.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 '../../components/OverlayCardBase/OverlayCardTarget/OverlayCardTarget.js';
import '../../context/WalletGroupContext/WalletGroupContext.js';
import '../../widgets/DynamicWidget/components/DynamicWidgetHeader/DynamicWidgetHeader.js';
import 'react-focus-lock';
import { IconWithSpinner } from '../../components/IconWithSpinner/IconWithSpinner.js';
import { Icon } from '../../components/Icon/Icon.js';
import { useLoadingContext } from '../../context/LoadingContext/LoadingContext.js';
import '../../context/WalletContext/WalletContext.js';
import '../../widgets/DynamicWidget/context/DynamicWidgetContext.js';
import { ErrorContainer } from '../../components/ErrorContainer/ErrorContainer.js';
import '../../components/IconButton/IconButton.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 '../TransactionConfirmationView/TransactionConfirmationView.js';
import '../../components/PasskeyCreatedSuccessBanner/PasskeyCreatedSuccessBanner.js';
import '../../context/PasskeyContext/PasskeyContext.js';
import '../../widgets/DynamicWidget/components/PasskeyCard/PasskeyCard.js';
import '../../utils/hooks/useEmbeddedWallet/useSecureEnclaveEmbeddedWallet/constants.js';
import '../../widgets/DynamicWidget/views/CryptoComOnramp/CryptoComOnramp.js';
import '../../context/OnrampContext/OnrampContext.js';
import '../../../index.js';
import '../../widgets/DynamicWidget/helpers/convertExchangeKeyAndProviderEnum.js';
import { TextButton } from '../../components/TextButton/TextButton.js';
import 'qrcode';
import '../../widgets/DynamicWidget/views/ReceiveWalletFunds/ReceiveWalletFunds.js';
import { IconWithStatus } from '../../components/IconWithStatus/IconWithStatus.js';
import '../../context/IpConfigurationContext/IpConfigurationContext.js';
import '../../context/ConnectWithOtpContext/ConnectWithOtpContext.js';
import { useConnectWithOtp } from '../../context/ConnectWithOtpContext/useConnectWithOtp.js';
import '../../widgets/DynamicBridgeWidget/views/WalletsView/components/SecondaryWallets/SecondaryWallets.js';
import '@hcaptcha/react-hcaptcha';
import { PinField } from '../../components/PinField/PinField.js';
import { RetrySendVerificationCodeSection } from '../../components/RetrySendVerificationCodeSection/RetrySendVerificationCodeSection.js';
import '../ExchangeWhitelistWarning/ExchangeWhitelistWarning.js';
import '../../context/ErrorContext/hooks/useErrorText/useErrorText.js';
import '../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 '../../components/InlineWidget/InlineWidget.js';
import '../../components/IsBrowser/IsBrowser.js';
import '../../components/Popper/Popper/Popper.js';
import '../../components/Popper/PopperContext/PopperContext.js';

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();
    const { pushView, clearStackAndPushInitialView } = useViewContext();
    const { error, setError, setErrorMessage } = useErrorContext();
    const { loading, setLoading } = useLoadingContext();
    const [showRetryButton, setShowRetryButton] = useState(_showRetryButton);
    const [showTransferMessage, setShowTransferMessage] = useState(_showTransferMessage);
    const { getEOAWallet } = useSmartWallets();
    // Use a state to ensure UI is updated, but also a ref to access in effect cleanup
    const [isValidated, _setIsValidated] = useState(false);
    const isValidatedRef = useRef(isValidated);
    const setIsValidated = (value) => {
        _setIsValidated(value);
        isValidatedRef.current = value;
    };
    const { displayedDestination: email, verificationUUID, setVerificationUUID, } = useVerification();
    const { t } = useTranslation();
    const { addRecoveryEmail } = usePasskeyRecovery();
    const { isTurnkeyWallet, hasTurnkeyVerifiedCredentialAuthenticator, hasRecoveryEmail, } = useIsTurnkeyWallet();
    const isTurnkeyProviderEnabled = isTurnkeyEnabled(projectSettings);
    const { initAuth, completeAuth, cancelAuth } = useUserAuth({
        authMethod: 'email',
    });
    const { verifyOneTimePassword, retryOneTimePassword } = useConnectWithOtp();
    const { generateSessionKey, shouldRegisterSessionKeysOnSignin } = useEmbeddedWalletSessionKeys({
        environmentId,
        projectSettings,
    });
    // When true, causes the component to call emailVerificationX callback on unmount
    const callCallbackOnUnmount = useRef(true);
    useOnUnmount(() => {
        if (!callCallbackOnUnmount.current)
            return;
        const emailString = email !== null && email !== void 0 ? email : '';
        dynamicEvents.emit('emailVerificationResult', isValidatedRef.current, emailString);
        if (!isValidatedRef.current)
            dynamicEvents.emit('authFailure', { email: emailString, option: emailString, type: 'email' }, 'user-cancelled');
        if (!email)
            logger.warn("WARNING: emitted emailVerificationResult with incomplete params because useVerification's displayedDestination was undefined");
    });
    const { verifyOtp } = useOtpVerificationRequest();
    const completeSignInFlow = useCallback((updateUserProfileResponse) => __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(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 && isSessionKeyCompatibleWallet(primaryWallet)) ||
                (eoaWallet && 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) ===
                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(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(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(embeddedWalletVerifiedCredential.id);
                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 = useCallback((verificationToken) => __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 },
                // 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: () => __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;
                    }
                    yield generateClientSessionKeys();
                    return signInWithEmailVerification({
                        environmentId,
                        sessionPublicKey,
                        verificationToken,
                        verificationUUID,
                    });
                }),
            });
        }
        // Verify flow (still depends on verificationUUID)
        if (!verificationUUID) {
            return cancelAuth();
        }
        return completeAuth({
            completeSignInFlow: (updateUserResponse) => __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, isEmailRecoveryFlow },
            updateJwtFunction: () => __awaiter(void 0, void 0, void 0, function* () { return verifyOtp(verificationToken, 'email', verificationUUID); }),
        });
    }), [
        setError,
        setLoading,
        verificationUUID,
        user,
        userWithMissingInfo,
        completeAuth,
        email,
        isEmailRecoveryFlow,
        cancelAuth,
        initAuth,
        environmentId,
        completeSignInFlow,
        verifyOtp,
        verifyOneTimePassword,
        generateSessionKey,
        shouldRegisterSessionKeysOnSignin,
    ]);
    const handleRetry = () => __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) {
                yield retryOneTimePassword();
                setVerificationUUID(undefined);
                setError(undefined);
                return;
            }
            const { verificationUUID: newVerificationUUID } = yield retryEmailVerification({
                email,
                environmentId,
                verificationUUID,
            });
            setVerificationUUID(newVerificationUUID);
            setError(undefined);
        }
        catch (error) {
            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 = useMemo(() => {
        const EmailIcon = (props) => (jsx(Icon, { color: 'brand-primary', children: jsx(SvgSignInWithEmail, Object.assign({}, props)) }));
        return EmailIcon;
    }, []);
    return (jsxs(Fragment, { children: [error && (jsx(ErrorContainer, { withIcon: false, className: 'email-verification__error-message', children: error })), jsxs("div", { className: classNames('email-verification__container', {
                    'email-verification__container--error': Boolean(error),
                }), children: [showTransferMessage && (jsx("div", { className: 'email-verification__transfer-message', copykey: 'dyn_otp_verification.email.complete', children: t('dyn_otp_verification.email.complete') })), isValidated ? (jsx("div", { className: 'email-verification__icon-container', children: jsx(IconWithStatus, { containerClassName: 'email-verification__icon--verified', Icon: EmailIcon, iconSize: 64, InnerIcon: SvgCheck }) })) : (jsx(IconWithSpinner, { Icon: EmailIcon, iconSize: 96, isSpinning: true, className: 'email-verification__icon-with-spinner' })), jsxs("div", { className: 'email-verification__copy-text-container', children: [jsx(Typography, { variant: 'body_normal', weight: 'regular', color: 'secondary', copykey: 'dyn_otp_verification.description', children: t('dyn_otp_verification.description') }), jsx(Typography, { variant: 'body_normal', weight: 'bold', color: 'secondary', children: shortenEmail(email) })] }), jsx(PinField, { initialValue: Array(6).fill(''), isLoading: loading, handleComplete: handleEmailVerification, isValidated: isValidated, inputMode: 'numeric', pattern: '[0-9]*', hasError: Boolean(error), onChange: () => setError(undefined) }), showRetryButton && (jsx(RetrySendVerificationCodeSection, { className: 'email-verification__retry-container', retryHandler: handleRetry, secondsToRetry: SECONDS_TO_RETRY })), (user || userWithMissingInfo) && !isEmailRecoveryFlow && (jsx(TextButton, { className: 'email-verification__log-out', onClick: handleLogOut, copykey: 'dyn_otp_verification.log_out_button', children: t('dyn_otp_verification.log_out_button') }))] })] }));
};

export { EmailVerification };
