'use client'
'use strict';

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

var _tslib = require('../../../../../_virtual/_tslib.cjs');
var React = require('react');
var reactInternationalPhone = require('react-international-phone');
require('../../../context/DynamicContext/DynamicContext.cjs');
require('../../../store/state/loadingAndLifecycle/loadingAndLifecycle.cjs');
require('@dynamic-labs/iconic');
require('@dynamic-labs/wallet-connector-core');
require('react/jsx-runtime');
require('../../../context/ViewContext/ViewContext.cjs');
var logger = require('../../../shared/logger.cjs');
require('@dynamic-labs/wallet-book');
require('@dynamic-labs/utils');
require('../../../utils/constants/colors.cjs');
require('../../../utils/constants/values.cjs');
require('@dynamic-labs/sdk-api-core');
require('../../../shared/consts/index.cjs');
var dynamicEvents = require('../../../events/dynamicEvents.cjs');
require('../../../context/CaptchaContext/CaptchaContext.cjs');
require('../../../context/ErrorContext/ErrorContext.cjs');
require('@dynamic-labs/multi-wallet');
require('../../../store/state/nonce/nonce.cjs');
require('@dynamic-labs-sdk/client/core');
require('../../../client/client.cjs');
require('@dynamic-labs-sdk/client');
require('../../../config/ApiEndpoint.cjs');
var sms = require('../../../data/api/sms/sms.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 useOtpVerificationRequest = require('../../../utils/hooks/authenticationHooks/useOtpVerificationRequest/useOtpVerificationRequest.cjs');
require('react-dom');
require('../../../utils/functions/compareChains/compareChains.cjs');
require('../../Passkey/utils/findPrimaryEmbeddedChain/findPrimaryEmbeddedChain.cjs');
var useEmbeddedWalletSessionKeys = require('../../../utils/hooks/useEmbeddedWalletSessionKeys/useEmbeddedWalletSessionKeys.cjs');
require('../../../context/ThemeContext/ThemeContext.cjs');
var VerificationContext = require('../../../context/VerificationContext/VerificationContext.cjs');
require('../../../utils/hooks/useUserUpdateRequest/useUpdateUser/userFieldsSchema.cjs');
var useMutation = require('../../../utils/hooks/useMutation/useMutation.cjs');
var useOnUnmount = require('../../../utils/hooks/useOnUnmount/useOnUnmount.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');
require('react-i18next');
require('../../../components/Accordion/components/AccordionItem/AccordionItem.cjs');
require('../../../components/Alert/Alert.cjs');
require('../../../context/WalletContext/WalletContext.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('../../../utils/hooks/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('../../../context/LoadingContext/LoadingContext.cjs');
require('../../../widgets/DynamicWidget/context/DynamicWidgetContext.cjs');
require('../../../widgets/DynamicWidget/helpers/convertExchangeKeyAndProviderEnum.cjs');
require('../../ExchangeWhitelistWarning/ExchangeWhitelistWarning.cjs');
require('../../../context/ErrorContext/hooks/useErrorText/useErrorText.cjs');
require('../../../context/FooterAnimationContext/index.cjs');
require('@dynamic-labs/locale');
require('../../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('../../TransactionConfirmationView/TransactionConfirmationView.cjs');
require('../../../widgets/DynamicWidget/components/PasskeyCard/PasskeyCard.cjs');
require('../../../utils/hooks/useEmbeddedWallet/useSecureEnclaveEmbeddedWallet/constants.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 useSmsVerification = (type) => {
    const { verificationUUID, displayedDestination: formattedPhone, retryData, } = VerificationContext.useVerification();
    const { environmentId, user, userWithMissingInfo, projectSettings } = useInternalDynamicContext.useInternalDynamicContext();
    const [error, setError] = React.useState();
    const { verifyOtp } = useOtpVerificationRequest.useOtpVerificationRequest();
    const { generateSessionKey, shouldRegisterSessionKeysOnSignin } = useEmbeddedWalletSessionKeys.useEmbeddedWalletSessionKeys({
        environmentId,
        projectSettings,
    });
    const { initAuth, completeAuth, cancelAuth } = useUserAuth.useUserAuth({
        authMethod: 'sms',
    });
    /** Whether verification was successfully performed */
    const isValidatedRef = React.useRef(false);
    useOnUnmount.useOnUnmount(() => {
        const phone = retryData !== null && retryData !== void 0 ? retryData : {
            dialCode: '',
            iso2: '',
            phone: '',
        };
        if (!retryData)
            logger.logger.warn('WARNING: emitted smsVerificationResult with incomplete params because retryData was undefined');
        dynamicEvents.dynamicEvents.emit('smsVerificationResult', isValidatedRef.current, phone);
        if (!isValidatedRef.current)
            dynamicEvents.dynamicEvents.emit('authFailure', { option: phone, phone, type: 'sms' }, 'user-cancelled');
    });
    const retryOneTimePassword = () => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        setError(undefined);
        if (!verificationUUID || !retryData) {
            yield cancelAuth();
            return;
        }
        sms.retrySmsVerification({
            environmentId,
            isoCountryCode: retryData.iso2,
            phoneCountryCode: retryData.dialCode,
            phoneNumber: reactInternationalPhone.removeDialCode({
                dialCode: retryData.dialCode,
                phone: retryData.phone,
            }),
            verificationUUID,
        });
    });
    const submitOtpForVerification = React.useCallback((verificationToken) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        if (!verificationUUID || (!user && !userWithMissingInfo)) {
            yield cancelAuth();
            return;
        }
        yield completeAuth({
            onValidUpdatedJwt: () => (isValidatedRef.current = true),
            updateJwtFunction: () => _tslib.__awaiter(void 0, void 0, void 0, function* () { return verifyOtp(verificationToken, 'sms', verificationUUID); }),
        });
    }), [
        cancelAuth,
        completeAuth,
        user,
        userWithMissingInfo,
        verificationUUID,
        verifyOtp,
    ]);
    const submitOtpForLogin = React.useCallback((verificationToken) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        if (!verificationUUID) {
            yield cancelAuth();
            return;
        }
        yield initAuth({
            onError: (error) => setError(error),
            onVerifySuccess: () => {
                isValidatedRef.current = true;
            },
            options: { phone: retryData },
            showSuccessMessage: true,
            verifyFunction: () => _tslib.__awaiter(void 0, void 0, void 0, function* () {
                let sessionPublicKey = undefined;
                if (shouldRegisterSessionKeysOnSignin()) {
                    const keypair = yield generateSessionKey();
                    sessionPublicKey = keypair.publicKey;
                }
                return sms.signInWithSmsVerification({
                    environmentId,
                    sessionPublicKey,
                    verificationToken,
                    verificationUUID,
                });
            }),
        });
    }), [
        verificationUUID,
        initAuth,
        retryData,
        cancelAuth,
        environmentId,
        generateSessionKey,
        shouldRegisterSessionKeysOnSignin,
    ]);
    const { isLoading, mutate: onSubmit } = useMutation.useMutation(type === 'login' ? submitOtpForLogin : submitOtpForVerification, {
        onFailure: (error) => {
            setError(error);
        },
    });
    return {
        error,
        formattedPhone: formattedPhone !== null && formattedPhone !== void 0 ? formattedPhone : '',
        isLoading,
        isValid: isValidatedRef.current,
        onSubmit,
        retryOneTimePassword,
        setError,
    };
};

exports.useSmsVerification = useSmsVerification;
