'use client'
'use strict';

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

var _tslib = require('../../../../../_virtual/_tslib.cjs');
var React = require('react');
var sdkApiCore = require('@dynamic-labs/sdk-api-core');
var walletConnectorCore = require('@dynamic-labs/wallet-connector-core');
require('../../../context/DynamicContext/DynamicContext.cjs');
require('../../../store/state/loadingAndLifecycle/loadingAndLifecycle.cjs');
require('@dynamic-labs/iconic');
require('react/jsx-runtime');
var ViewContext = require('../../../context/ViewContext/ViewContext.cjs');
var logger = require('../../../shared/logger.cjs');
require('@dynamic-labs/wallet-book');
require('@dynamic-labs/utils');
require('../../constants/colors.cjs');
require('../../constants/values.cjs');
require('../../../shared/consts/index.cjs');
var dynamicEvents = require('../../../events/dynamicEvents.cjs');
require('../../../context/CaptchaContext/CaptchaContext.cjs');
require('../../../context/ErrorContext/ErrorContext.cjs');
var errors = require('../../constants/errors.cjs');
require('@dynamic-labs/multi-wallet');
require('react-international-phone');
require('../../../store/state/nonce/nonce.cjs');
var isTurnkeyEnabled = require('../../functions/isTurnkeyEnabled/isTurnkeyEnabled.cjs');
var getEnabledEmbeddedWalletsAuthenticators = require('../../functions/getEnabledEmbeddedWalletsAuthenticators/getEnabledEmbeddedWalletsAuthenticators.cjs');
var hasEmbeddedWallet = require('../../functions/hasEmbeddedWallet/hasEmbeddedWallet.cjs');
var getEmbeddedWalletSessionExpiration = require('../../functions/getEmbeddedWalletSessionExpiration/getEmbeddedWalletSessionExpiration.cjs');
require('@dynamic-labs-sdk/client/core');
require('../../../client/client.cjs');
require('@dynamic-labs-sdk/client');
require('../../../config/ApiEndpoint.cjs');
require('@dynamic-labs/locale');
var user = require('../../../data/api/user/user.cjs');
require('../../../store/state/dynamicContextProps/dynamicContextProps.cjs');
require('../../../store/state/primaryWalletId/primaryWalletId.cjs');
require('../../../store/state/connectedWalletsInfo/connectedWalletsInfo.cjs');
require('../../../context/AccessDeniedContext/AccessDeniedContext.cjs');
require('../../../context/AccountExistsContext/AccountExistsContext.cjs');
require('../../../context/UserWalletsContext/UserWalletsContext.cjs');
require('../../../store/state/authMode/authMode.cjs');
var VerificationContext = require('../../../context/VerificationContext/VerificationContext.cjs');
require('react-dom');
var useElementById = require('../useElementById/useElementById.cjs');
require('../../functions/compareChains/compareChains.cjs');
require('../../../views/Passkey/utils/findPrimaryEmbeddedChain/findPrimaryEmbeddedChain.cjs');
require('../../../context/ThemeContext/ThemeContext.cjs');
var useSmartWallets = require('../useSmartWallets/useSmartWallets.cjs');
require('../useUserUpdateRequest/useUpdateUser/userFieldsSchema.cjs');
var constants = require('../../../views/Passkey/PasskeyRecovery/constants.cjs');
var passkeyRecovery = require('../../../views/Passkey/utils/passkeyRecovery/passkeyRecovery.cjs');
var useInitEmbeddedWalletAuthMethod = require('../useInitEmbeddedWalletAuthMethod/useInitEmbeddedWalletAuthMethod.cjs');
var useIsTurnkeyWallet = require('../useIsTurnkeyWallet/useIsTurnkeyWallet.cjs');
require('bs58');
require('@dynamic-labs/types');
require('../../../context/SocialRedirectContext/SocialRedirectContext.cjs');
require('../../../context/LoadingContext/LoadingContext.cjs');
require('../../../context/WalletContext/WalletContext.cjs');
require('../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');
require('react-i18next');
require('../../../components/Accordion/components/AccordionItem/AccordionItem.cjs');
require('../../../components/Alert/Alert.cjs');
require('../../../components/ShadowDOM/ShadowDOM.cjs');
require('../../../components/IconButton/IconButton.cjs');
require('../../../components/InlineWidget/InlineWidget.cjs');
require('../../../components/Input/Input.cjs');
require('../../../components/IsBrowser/IsBrowser.cjs');
require('../../../components/MenuList/Dropdown/Dropdown.cjs');
require('../../../components/OverlayCard/OverlayCard.cjs');
require('../../../components/Transition/ZoomTransition/ZoomTransition.cjs');
require('../../../components/Transition/SlideInUpTransition/SlideInUpTransition.cjs');
require('../../../components/Transition/OpacityTransition/OpacityTransition.cjs');
require('../../../components/PasskeyCreatedSuccessBanner/PasskeyCreatedSuccessBanner.cjs');
require('../../../components/Popper/Popper/Popper.cjs');
require('../../../components/Popper/PopperContext/PopperContext.cjs');
require('react-focus-lock');
require('qrcode');
require('formik');
require('../useSubdomainCheck/useSubdomainCheck.cjs');
require('../../../context/WalletGroupContext/WalletGroupContext.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('../../../widgets/DynamicWidget/context/DynamicWidgetContext.cjs');
require('../../../widgets/DynamicWidget/helpers/convertExchangeKeyAndProviderEnum.cjs');
require('../../../views/ExchangeWhitelistWarning/ExchangeWhitelistWarning.cjs');
require('../../../context/ErrorContext/hooks/useErrorText/useErrorText.cjs');
require('../../../context/FooterAnimationContext/index.cjs');
require('../../../views/MfaChooseDeviceView/useGetMfaOptions/useGetMfaOptions.cjs');
require('../../../context/PasskeyContext/PasskeyContext.cjs');
require('../../../context/OnrampContext/OnrampContext.cjs');
require('../../../store/state/sendBalances.cjs');
require('../../../store/state/connectorsInitializing/connectorsInitializing.cjs');
require('../../../components/OverlayCardBase/OverlayCardTarget/OverlayCardTarget.cjs');
require('../../../widgets/DynamicWidget/components/DynamicWidgetHeader/DynamicWidgetHeader.cjs');
require('../../../views/TransactionConfirmationView/TransactionConfirmationView.cjs');
require('../../../widgets/DynamicWidget/components/PasskeyCard/PasskeyCard.cjs');
require('../../../widgets/DynamicWidget/views/CryptoComOnramp/CryptoComOnramp.cjs');
require('../../../../index.cjs');
require('../../../widgets/DynamicWidget/views/ReceiveWalletFunds/ReceiveWalletFunds.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');

// Hook exposed to customers and used internally to trigger passkey recovery
const usePasskeyRecovery = () => {
    var _a, _b, _c;
    const { environmentId, primaryWallet, projectSettings, setShowAuthFlow, user: user$1, } = useInternalDynamicContext.useInternalDynamicContext();
    const { createRootElement } = useElementById.useElementById();
    const iframeContainerRef = createRootElement(constants.iframeContainerId);
    const { isTurnkeyWalletWithoutAuthenticator, hasRecoveryEmail } = useIsTurnkeyWallet.useIsTurnkeyWallet();
    const { initAuthMethod } = useInitEmbeddedWalletAuthMethod.useInitEmbeddedWalletAuthMethod();
    const { setDisplayedDestination: setEmailForVerification, setVerificationUUID, } = VerificationContext.useVerification();
    const { getEOAWallet } = useSmartWallets.useSmartWallets();
    const { pushView } = ViewContext.useViewContext();
    const wallet = (_a = (primaryWallet && getEOAWallet(primaryWallet))) !== null && _a !== void 0 ? _a : primaryWallet;
    const isSessionRestored = React.useCallback(() => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        var _d, _e;
        if (!((_d = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.sdk.embeddedWallets) === null || _d === void 0 ? void 0 : _d.sessionKeyDuration) ||
            !passkeyRecovery.canRestoreEmbeddedWalletSession((_e = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.sdk.embeddedWallets) === null || _e === void 0 ? void 0 : _e.sessionKeyDuration)) {
            return false;
        }
        const sessionExpiration = getEmbeddedWalletSessionExpiration.getEmbeddedWalletSessionExpiration(projectSettings.sdk.embeddedWallets.sessionKeyDuration);
        try {
            return yield passkeyRecovery.restoreEmbeddedWalletSession({
                iframeContainer: iframeContainerRef.current,
                iframeElementId: constants.iframeElementId,
                sessionExpiration,
                user: user$1,
                wallet: primaryWallet,
            });
        }
        catch (err) {
            logger.logger.error('Failed to restore embedded wallet', err);
        }
        return false;
    }), [
        user$1,
        iframeContainerRef,
        primaryWallet,
        (_c = (_b = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.sdk) === null || _b === void 0 ? void 0 : _b.embeddedWallets) === null || _c === void 0 ? void 0 : _c.sessionKeyDuration,
    ]);
    const shouldInitRecovery = React.useCallback(() => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        if (!wallet || !walletConnectorCore.isPasskeyWalletConnector(wallet.connector)) {
            return false;
        }
        const turnkeyRecoveryHandler = wallet.connector.getAuthenticatorHandler();
        // user has passkey authenticator set up OR
        // email auth - session is still up, so no need to recover
        if (!isTurnkeyWalletWithoutAuthenticator ||
            turnkeyRecoveryHandler.isSessionActive() ||
            (yield isSessionRestored())) {
            return false;
        }
        return true;
    }), [wallet, isTurnkeyWalletWithoutAuthenticator, isSessionRestored]);
    const initPasskeyRecoveryProcess = React.useCallback((authenticatorType, currentAction) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        var _f;
        const validateRecoveryRequest = () => {
            if (!user$1) {
                throw new Error(errors.USER_NOT_LOGGED_IN);
            }
            if (!isTurnkeyEnabled.isTurnkeyEnabled(projectSettings)) {
                throw new Error('Dynamic embedded wallet is not enabled. Go to the dashboard and make sure to have both Dynamic embedded wallet and at least one EVM network enabled. Also, check if EthereumWalletConnectors is in the  DynamicContextProvider > settings > walletConnectors.');
            }
            if (!hasEmbeddedWallet.hasEmbeddedWallet(user$1)) {
                throw new Error('Dynamic embedded wallet not found');
            }
            if (wallet && !walletConnectorCore.isPasskeyWalletConnector(wallet.connector)) {
                throw new Error('Dynamic embedded wallet not found.');
            }
        };
        validateRecoveryRequest();
        const turnkeyRecoveryHandler = (wallet === null || wallet === void 0 ? void 0 : wallet.connector).getAuthenticatorHandler();
        // email auth - session is still up, so create passkey authenticator usign the same session
        if (authenticatorType === 'passkey' &&
            turnkeyRecoveryHandler.isSessionActive()) {
            yield passkeyRecovery.addNewPasskeyAuthenticator({
                environmentId,
                user: user$1,
                wallet: wallet,
            });
            setShowAuthFlow(false);
            // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
            return wallet;
        }
        const supportedAuthenticators = getEnabledEmbeddedWalletsAuthenticators.getEnabledEmbeddedWalletsAuthenticators((_f = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.sdk.embeddedWallets) === null || _f === void 0 ? void 0 : _f.supportedSecurityMethods);
        const supportedAuthenticatorMethods = supportedAuthenticators
            ? Object.keys(supportedAuthenticators)
            : [];
        if (!hasRecoveryEmail) {
            pushView('passkey-recovery-add-email', { shouldInitRecovery: true });
            setShowAuthFlow(true, {
                ignoreIfIsEmbeddedWidget: false,
                performMultiWalletChecks: false,
            });
        }
        else if (!authenticatorType &&
            supportedAuthenticatorMethods.length > 1) {
            pushView('embedded-wallet-auth-choice', { currentAction });
            setShowAuthFlow(true, {
                ignoreIfIsEmbeddedWidget: false,
                performMultiWalletChecks: false,
            });
        }
        else {
            const [authType] = supportedAuthenticatorMethods;
            // since we're forcing the authenticator type = 'email' during transactions when no passkey is configured,
            // we need to make sure it's supported.
            // Otherwise, we'll use the first supported authenticator type from the list
            if (authenticatorType &&
                !supportedAuthenticatorMethods.includes(authenticatorType)) {
                authenticatorType = authType;
            }
            yield initAuthMethod({
                authenticatorType: authenticatorType || authType,
                currentAction,
                iframeContainer: iframeContainerRef.current,
            });
        }
        return new Promise((resolve, reject) => {
            dynamicEvents.dynamicEvents.once('passkeyRecoveryCompleted', (wallet) => resolve(wallet));
            dynamicEvents.dynamicEvents.once('passkeyRecoveryFailed', (error) => reject(error));
        });
    }), [
        wallet,
        projectSettings,
        hasRecoveryEmail,
        environmentId,
        user$1,
        setShowAuthFlow,
        pushView,
        initAuthMethod,
        iframeContainerRef,
    ]);
    const addRecoveryEmail = (emailInput) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        try {
            let updatedUser = user$1;
            // TODO - This seems wrong what if the user has a different email.
            // As well it does not verify the the email is verified
            if (!(user$1 === null || user$1 === void 0 ? void 0 : user$1.email)) {
                updatedUser = yield updateUserProfile(emailInput);
            }
            yield passkeyRecovery.addEmailRecovery({
                environmentId,
                user: updatedUser,
                wallet: primaryWallet,
            });
            dynamicEvents.dynamicEvents.emit('embeddedWalletRecoveryEmailCompleted', '');
        }
        catch (err) {
            logger.logger.error('Failed to add recovery email', err);
            dynamicEvents.dynamicEvents.emit('embeddedWalletRecoveryEmailFailed', err);
        }
    });
    const updateUserProfile = (emailInput) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        try {
            const { nextView, emailVerification, userProfile } = yield user.updateUserProfileFields(environmentId, {
                email: emailInput,
            });
            if (nextView === sdkApiCore.NextViewEnum.Done) {
                return userProfile;
            }
            pushView('verify-email', { isEmailRecoveryFlow: true });
            setEmailForVerification(emailInput);
            setVerificationUUID(emailVerification === null || emailVerification === void 0 ? void 0 : emailVerification.verificationUUID);
            return new Promise((resolve, reject) => {
                // TODO - This is not the latest user, it is the not verified user
                dynamicEvents.dynamicEvents.once('emailVerificationResult', (wasSuccessful) => {
                    if (wasSuccessful) {
                        resolve(userProfile);
                    }
                    reject('Failed to verify email');
                });
            });
        }
        catch (err) {
            logger.logger.error('Failed to update user email', err);
            throw err;
        }
    });
    return {
        addRecoveryEmail,
        initPasskeyRecoveryProcess,
        shouldInitRecovery,
    };
};

exports.usePasskeyRecovery = usePasskeyRecovery;
