'use client'
'use strict';

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

var _tslib = require('../../../../../_virtual/_tslib.cjs');
var React = require('react');
var client = require('@dynamic-labs-sdk/client');
var sdkApiCore = require('@dynamic-labs/sdk-api-core');
var utils = require('@dynamic-labs/utils');
require('@dynamic-labs-sdk/client/core');
require('../../../client/client.cjs');
require('../../../config/ApiEndpoint.cjs');
var values = require('../../constants/values.cjs');
require('@dynamic-labs/multi-wallet');
require('react-international-phone');
require('../../constants/colors.cjs');
require('@dynamic-labs/iconic');
require('@dynamic-labs/wallet-connector-core');
require('react/jsx-runtime');
var ViewContext = require('../../../context/ViewContext/ViewContext.cjs');
var logger = require('../../../shared/logger.cjs');
require('@dynamic-labs/wallet-book');
var hasPendingMfaAction = require('../../../shared/utils/functions/hasPendingMfaAction/hasPendingMfaAction.cjs');
require('../../../shared/consts/index.cjs');
require('../../../store/state/nonce/nonce.cjs');
require('@dynamic-labs/locale');
require('../../../store/state/dynamicContextProps/dynamicContextProps.cjs');
require('../../../store/state/primaryWalletId/primaryWalletId.cjs');
require('../../../store/state/connectedWalletsInfo/connectedWalletsInfo.cjs');
var getClientSessionKeys = require('../../functions/clientSessionKeys/getClientSessionKeys.cjs');
require('../../../events/dynamicEvents.cjs');
var storeTokenAndUser = require('../../../client/extension/storeTokenAndUser/storeTokenAndUser.cjs');
var AccessDeniedContext = require('../../../context/AccessDeniedContext/AccessDeniedContext.cjs');
var AccountExistsContext = require('../../../context/AccountExistsContext/AccountExistsContext.cjs');
require('../../../context/DynamicContext/DynamicContext.cjs');
require('../../../store/state/loadingAndLifecycle/loadingAndLifecycle.cjs');
require('../../../context/CaptchaContext/CaptchaContext.cjs');
var ErrorContext = require('../../../context/ErrorContext/ErrorContext.cjs');
require('../../../context/UserWalletsContext/UserWalletsContext.cjs');
require('../../../store/state/authMode/authMode.cjs');
require('../../../context/VerificationContext/VerificationContext.cjs');
require('react-dom');
require('../../functions/compareChains/compareChains.cjs');
require('../../../views/Passkey/utils/findPrimaryEmbeddedChain/findPrimaryEmbeddedChain.cjs');
require('../../../context/ThemeContext/ThemeContext.cjs');
require('../useUserUpdateRequest/useUpdateUser/userFieldsSchema.cjs');
require('bs58');
require('@dynamic-labs/types');
require('../../../context/SocialRedirectContext/SocialRedirectContext.cjs');
var LoadingContext = require('../../../context/LoadingContext/LoadingContext.cjs');
var useEmbeddedWallet = require('../useEmbeddedWallet/useEmbeddedWallet.cjs');
require('../../../context/WalletContext/WalletContext.cjs');
require('../useEmbeddedWallet/useSecureEnclaveEmbeddedWallet/constants.cjs');
var useHandleAuthenticatedUser = require('../useHandleAuthenticatedUser/useHandleAuthenticatedUser.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');

const sleepToShowSuccessMessage = () => utils.sleep(1500);
const useUserAuth = ({ authMethod, }) => {
    const { handleLogOut, setShowAuthFlow, setCallback, setMultiWalletWidgetState, walletConnectorOptions, } = useInternalDynamicContext.useInternalDynamicContext();
    const { setDeniedOauthUsername, setDeniedOauthProvider } = AccessDeniedContext.useAccessDeniedContext();
    const { view, pushView, clearStackAndPushInitialView } = ViewContext.useViewContext();
    const { setLoading } = LoadingContext.useLoadingContext();
    const { setErrorMessage, setError } = ErrorContext.useErrorContext();
    const { setExistentAccountData } = AccountExistsContext.useAccountExistsContext();
    const handleAuthenticatedUser = useHandleAuthenticatedUser.useHandleAuthenticatedUser();
    const { shouldAutoCreateEmbeddedWallet, shouldPromptForKeyExport, embeddedWalletSettingVersion, } = useEmbeddedWallet.useEmbeddedWallet();
    const isVerifyResponse = (response) => response.user;
    const handleWaasInitialization = React.useCallback((verifiedUser) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        const sessionSignatureResult = yield getClientSessionKeys.getClientSessionSignature({
            sessionId: verifiedUser === null || verifiedUser === void 0 ? void 0 : verifiedUser.sessionId,
        });
        const dynamicWaasConnectors = walletConnectorOptions.filter((walletOption) => walletOption.walletConnector.key === 'dynamicwaas');
        dynamicWaasConnectors.forEach((walletOption) => {
            var _a;
            const walletAddress = (_a = verifiedUser.verifiedCredentials.find((credential) => {
                var _a;
                return values.VerifiedCredentialNameToChainEnum[(_a = credential.chain) !== null && _a !== void 0 ? _a : ''] ===
                    walletOption.walletConnector.connectedChain;
            })) === null || _a === void 0 ? void 0 : _a.address;
            if (walletAddress) {
                // Create the waas iframe
                walletOption.walletConnector
                    .getWaasWalletClient()
                    .then((client) => {
                    // Restore the wallet keyshare to the iframe
                    client
                        .getWallet({
                        accountAddress: walletAddress,
                        signedSessionId: sessionSignatureResult.sessionSignature,
                        walletOperation: 'SIGN_MESSAGE',
                    })
                        .catch((error) => {
                        logger.logger.error('Error restoring wallet keyshare', {
                            error,
                            sessionId: verifiedUser.sessionId,
                            userId: verifiedUser.userId,
                            walletAddress,
                        });
                    });
                })
                    .catch((error) => {
                    logger.logger.error('Error initializing waas wallet client', {
                        error,
                        sessionId: verifiedUser.sessionId,
                        userId: verifiedUser.userId,
                        walletAddress,
                    });
                });
            }
        });
    }), [walletConnectorOptions]);
    const cancelAuth = React.useCallback(() => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        logger.logger.debug('cancelAuth', { authMethod });
        yield handleLogOut();
        clearStackAndPushInitialView();
    }), [authMethod, clearStackAndPushInitialView, handleLogOut]);
    const handleAuthError = React.useCallback((error, { options = {}, onError, }) => {
        var _a;
        if (error instanceof client.MfaInvalidOtpError ||
            error instanceof client.MfaRateLimitedError) {
            throw error;
        }
        // these get caught in onboarding form and handled there
        if (error instanceof utils.EmailAlreadyExistsError ||
            error instanceof utils.CustomFieldNotUniqueError ||
            error instanceof utils.UsernameAlreadyExistsError ||
            error instanceof utils.TooManyEmailVerificationsError ||
            error instanceof utils.InvalidPhoneNumberError)
            throw error;
        if (error instanceof utils.NoAccessError) {
            setDeniedOauthProvider(error === null || error === void 0 ? void 0 : error.socialProvider);
            setDeniedOauthUsername((_a = error === null || error === void 0 ? void 0 : error.socialUsername) !== null && _a !== void 0 ? _a : '');
            pushView('no-access');
            return;
        }
        if (error instanceof utils.AccountExistsError) {
            setExistentAccountData(error.errorPayload);
            pushView('account-exists');
            return;
        }
        if (error instanceof utils.SandboxMaximumThresholdReachedError ||
            error instanceof client.SandboxMaximumThresholdReachedError) {
            pushView('sandbox-maximum-threshold-reached');
            return;
        }
        // Handle the case where the user has already an account with the email
        if (error instanceof utils.UserHasAccountWithEmailError) {
            pushView('merge-user-accounts-with-same-email', {
                returnToView: 'isEmailRecoveryFlow' in options && options.isEmailRecoveryFlow
                    ? 'passkey-recovery-add-email'
                    : undefined,
            });
            return;
        }
        if (onError) {
            onError === null || onError === void 0 ? void 0 : onError(error);
            return;
        }
        if (error.code) {
            setErrorMessage(error.code);
        }
        else {
            setError(error.message);
        }
    }, [
        pushView,
        setDeniedOauthProvider,
        setDeniedOauthUsername,
        setError,
        setErrorMessage,
        setExistentAccountData,
    ]);
    const initAuth = React.useCallback((_a) => _tslib.__awaiter(void 0, [_a], void 0, function* ({ isSignIn = true, verifyFunction, onVerifySuccess, onSettled, onError, showSuccessMessage = false, skipDefaultErrorHandling = false, }) {
        var _b;
        logger.logger.debug('initAuth', { authMethod, isSignIn });
        try {
            // TODO: change this logic to const verifiedUser = await verifyFunction();
            // once all verify functions are updated to return UserProfile instead of VerifyResponse
            const verifyResponse = yield verifyFunction();
            if (!verifyResponse) {
                yield cancelAuth();
                throw new utils.DynamicError('No user returned from verify function');
            }
            let verifiedUser;
            if (isVerifyResponse(verifyResponse)) {
                verifiedUser = storeTokenAndUser.storeTokenAndUser(verifyResponse);
            }
            else {
                verifiedUser = verifyResponse;
            }
            onVerifySuccess === null || onVerifySuccess === void 0 ? void 0 : onVerifySuccess(verifiedUser);
            walletConnectorOptions.forEach((walletOption) => {
                walletOption.walletConnector.setVerifiedCredentials(verifiedUser.verifiedCredentials);
            });
            if (hasPendingMfaAction.hasPendingMfaAction(verifiedUser)) {
                // handled in SyncAuthFlow
                return;
            }
            if (isSignIn && ((_b = verifiedUser.missingFields) === null || _b === void 0 ? void 0 : _b.length)) {
                //onboarding will be handled in the onboarding flow
                return;
            }
            setMultiWalletWidgetState('idle');
            yield handleAuthenticatedUser(verifiedUser);
            // we should only close auth flow if no wallet is going to be created or there is no key export
            // otherwise there will be a glitch with auth flow closing and then reopening for passkeys or export
            const shouldCreateWallet = shouldAutoCreateEmbeddedWallet();
            // only support export prompt on v2 and higher
            const shouldPromptExport = shouldPromptForKeyExport();
            if (showSuccessMessage) {
                // this timeout is set to make sure that the user will see success message
                yield sleepToShowSuccessMessage();
            }
            if (isSignIn) {
                setCallback('authSuccess');
                const hasWaasWallets = verifiedUser.verifiedCredentials.some((vc) => vc.walletProvider === sdkApiCore.WalletProviderEnum.EmbeddedWallet &&
                    vc.walletName === 'dynamicwaas');
                if (hasWaasWallets) {
                    // Eagerly initialize waas wallets
                    yield handleWaasInitialization(verifiedUser);
                }
            }
            const walletVersion = embeddedWalletSettingVersion();
            if (walletVersion === sdkApiCore.EmbeddedWalletVersionEnum.V1 &&
                shouldCreateWallet) {
                setShowAuthFlow(true);
            }
            else if (!shouldCreateWallet || !shouldPromptExport) {
                setShowAuthFlow(false);
            }
            onSettled === null || onSettled === void 0 ? void 0 : onSettled();
        }
        catch (error) {
            logger.logger.debug(error);
            if (skipDefaultErrorHandling) {
                onError === null || onError === void 0 ? void 0 : onError(error);
                return;
            }
            handleAuthError(error, { onError });
        }
        finally {
            setLoading(false);
            onSettled === null || onSettled === void 0 ? void 0 : onSettled();
        }
    }), [
        authMethod,
        cancelAuth,
        embeddedWalletSettingVersion,
        handleAuthError,
        handleAuthenticatedUser,
        handleWaasInitialization,
        setCallback,
        setLoading,
        setMultiWalletWidgetState,
        setShowAuthFlow,
        shouldAutoCreateEmbeddedWallet,
        shouldPromptForKeyExport,
        walletConnectorOptions,
    ]);
    const handleVerifyMissingFields = React.useCallback((_c) => _tslib.__awaiter(void 0, [_c], void 0, function* ({ missingFields, isEmailVerificationRequired, isSmsVerificationRequired, }) {
        if (isEmailVerificationRequired &&
            missingFields.find((field) => field.name === 'email')) {
            pushView('verify-email');
            return;
        }
        if (isSmsVerificationRequired &&
            missingFields.find((field) => field.name === 'phoneNumber')) {
            pushView('verify-sms');
            return;
        }
        pushView(view.type);
    }), [pushView, view === null || view === void 0 ? void 0 : view.type]);
    const completeAuth = React.useCallback((_d) => _tslib.__awaiter(void 0, [_d], void 0, function* ({ completeSignInFlow, updateJwtFunction, onValidUpdatedJwt, options = {}, }) {
        logger.logger.debug('completeAuth', { authMethod });
        try {
            const { updateUserProfileResponse, isSmsVerificationRequired, isEmailVerificationRequired, missingFields, } = yield updateJwtFunction();
            onValidUpdatedJwt === null || onValidUpdatedJwt === void 0 ? void 0 : onValidUpdatedJwt();
            const updatedUser = storeTokenAndUser.storeTokenAndUser({
                expiresAt: updateUserProfileResponse.expiresAt,
                jwt: updateUserProfileResponse.jwt,
                minifiedJwt: updateUserProfileResponse.minifiedJwt,
                user: updateUserProfileResponse.user,
            });
            if (missingFields.length > 0) {
                yield handleVerifyMissingFields({
                    isEmailVerificationRequired,
                    isSmsVerificationRequired,
                    missingFields,
                });
                return;
            }
            yield handleAuthenticatedUser(updatedUser);
            setCallback('authSuccess');
            if (completeSignInFlow) {
                const shouldReturn = yield completeSignInFlow(updateUserProfileResponse);
                if (shouldReturn) {
                    return;
                }
            }
            // we should only close auth flow if no wallet is going to be created,
            // otherwise there will be a glitch with auth flow closing and then reopening for passkeys
            const shouldCreateWallet = shouldAutoCreateEmbeddedWallet();
            if (!shouldCreateWallet &&
                updatedUser.mfaBackupCodeAcknowledgement !==
                    sdkApiCore.MfaBackupCodeAcknowledgement.Pending) {
                setShowAuthFlow(false);
            }
        }
        catch (error) {
            logger.logger.debug(error);
            handleAuthError(error, { options });
        }
        finally {
            setLoading(false);
        }
    }), [
        authMethod,
        handleAuthError,
        handleAuthenticatedUser,
        handleVerifyMissingFields,
        setCallback,
        setLoading,
        setShowAuthFlow,
        shouldAutoCreateEmbeddedWallet,
    ]);
    return {
        cancelAuth,
        completeAuth,
        handleAuthError,
        initAuth,
    };
};

exports.useUserAuth = useUserAuth;
