'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 sdkApiCore = require('@dynamic-labs/sdk-api-core');
var dynamicEvents = require('../../events/dynamicEvents.cjs');
var dynamicContextProps = require('../../store/state/dynamicContextProps/dynamicContextProps.cjs');
require('../../utils/constants/values.cjs');
require('@dynamic-labs/utils');
require('@dynamic-labs/multi-wallet');
require('../../shared/logger.cjs');
require('react-international-phone');
require('../../utils/constants/colors.cjs');
require('@dynamic-labs/iconic');
require('@dynamic-labs/wallet-connector-core');
require('../ViewContext/ViewContext.cjs');
require('@dynamic-labs/wallet-book');
require('../../shared/consts/index.cjs');
require('../../store/state/nonce/nonce.cjs');
var isProviderEnabled = require('../../utils/functions/isProviderEnabled/isProviderEnabled.cjs');
var isEmailValid = require('../../utils/functions/isEmailValid/isEmailValid.cjs');
var preconnectDynamicWaasIframe = require('../../utils/functions/preconnectDynamicWaasIframe/preconnectDynamicWaasIframe.cjs');
require('@dynamic-labs-sdk/client/core');
require('eventemitter3');
require('@dynamic-labs-sdk/client');
require('../../config/ApiEndpoint.cjs');
require('@dynamic-labs/locale');
require('../../store/state/primaryWalletId/primaryWalletId.cjs');
require('../../store/state/connectedWalletsInfo/connectedWalletsInfo.cjs');
require('../../utils/functions/getWaasAddressTypeLabel/getWaasAddressTypeLabel.cjs');
require('../DynamicContext/useDynamicContext/useDynamicContext.cjs');
var useInternalDynamicContext = require('../DynamicContext/useDynamicContext/useInternalDynamicContext/useInternalDynamicContext.cjs');
var CaptchaContext = require('../CaptchaContext/CaptchaContext.cjs');
var captcha = require('../../utils/captcha.cjs');
require('../ErrorContext/ErrorContext.cjs');
require('../AccessDeniedContext/AccessDeniedContext.cjs');
require('../AccountExistsContext/AccountExistsContext.cjs');
require('../UserWalletsContext/UserWalletsContext.cjs');
require('../../store/state/authMode/authMode.cjs');
require('../../store/state/loadingAndLifecycle/loadingAndLifecycle.cjs');
require('../VerificationContext/VerificationContext.cjs');
require('react-dom');
require('../../utils/functions/compareChains/compareChains.cjs');
require('../../views/Passkey/utils/findPrimaryEmbeddedChain/findPrimaryEmbeddedChain.cjs');
var useEmbeddedWalletSessionKeys = require('../../utils/hooks/useEmbeddedWalletSessionKeys/useEmbeddedWalletSessionKeys.cjs');
require('../ThemeContext/ThemeContext.cjs');
require('../../utils/hooks/useUserUpdateRequest/useUpdateUser/userFieldsSchema.cjs');
require('bs58');
require('@dynamic-labs/types');
require('../SocialRedirectContext/SocialRedirectContext.cjs');
require('../LoadingContext/LoadingContext.cjs');
require('../WalletContext/WalletContext.cjs');
require('../../utils/hooks/useEmbeddedWallet/useSecureEnclaveEmbeddedWallet/constants.cjs');
require('yup');
require('../MockContext/MockContext.cjs');
require('../../views/CollectUserDataView/useFields.cjs');
require('../FieldsStateContext/FieldsStateContext.cjs');
require('../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('../../utils/hooks/useSubdomainCheck/useSubdomainCheck.cjs');
require('../WalletGroupContext/WalletGroupContext.cjs');
require('../../widgets/DynamicWidget/context/DynamicWidgetContext.cjs');
require('../../utils/hooks/useGetMfaToken/useGetMfaToken.cjs');
require('../../utils/hooks/useWalletBackup/useWalletBackup.cjs');
require('../../utils/hooks/useWalletBackup/BackupError.cjs');
require('../../utils/hooks/useWalletBackup/types.cjs');
require('../../utils/hooks/useWalletBackup/cloudProviders.cjs');
require('@hcaptcha/react-hcaptcha');
require('@marsidev/react-turnstile');
require('../IpConfigurationContext/IpConfigurationContext.cjs');
var ConnectWithOtpContext = require('./ConnectWithOtpContext.cjs');
var useRestoreOtpVerificationState = require('./hooks/useRestoreOtpVerificationState/useRestoreOtpVerificationState.cjs');
var createEmailHandler = require('./utils/createEmailHandler.cjs');
var createSmsHandler = require('./utils/createSmsHandler.cjs');
var otpVerificationStorage = require('./utils/otpVerificationStorage/otpVerificationStorage.cjs');
require('../../widgets/DynamicBridgeWidget/views/WalletsView/components/SecondaryWallets/SecondaryWallets.cjs');
require('../../widgets/DynamicWidget/helpers/convertExchangeKeyAndProviderEnum.cjs');
require('../../views/ExchangeWhitelistWarning/ExchangeWhitelistWarning.cjs');
require('../ErrorContext/hooks/useErrorText/useErrorText.cjs');
require('../FooterAnimationContext/index.cjs');
require('../../views/MfaChooseDeviceView/useGetMfaOptions/useGetMfaOptions.cjs');
require('../PasskeyContext/PasskeyContext.cjs');
require('../OnrampContext/OnrampContext.cjs');
require('../../utils/hooks/useWalletDelegation/DelegationError.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/ManagePasskeysMfaWidgetView/ManagePasskeysMfaWidgetView.cjs');
require('../../widgets/DynamicWidget/views/ManageTotpMfaWidgetView/ManageTotpMfaWidgetView.cjs');
require('../../widgets/DynamicWidget/views/ReceiveWalletFunds/ReceiveWalletFunds.cjs');
require('../../store/state/tokenBalances.cjs');
require('../../store/state/multichainBalances.cjs');
require('@dynamic-labs/store');
require('../../shared/utils/functions/getInitialUrl/getInitialUrl.cjs');

const { Provider } = ConnectWithOtpContext.ConnectWithOtpContext;
const ConnectWithOtpProvider = ({ children }) => {
    const { environmentId, projectSettings, setCallback, setShowAuthFlow } = useInternalDynamicContext.useInternalDynamicContext();
    const { engageCaptcha } = CaptchaContext.useCaptchaContext();
    const apiBaseUrl = dynamicContextProps.useApiBaseUrl();
    const embeddedWalletSessionKeys = useEmbeddedWalletSessionKeys.useEmbeddedWalletSessionKeys({
        environmentId,
        projectSettings,
    });
    const lastVerificationHandlerRef = React.useRef(null);
    useRestoreOtpVerificationState.useRestoreOtpVerificationState({
        embeddedWalletSessionKeys,
        environmentId,
        handlerRef: lastVerificationHandlerRef,
    });
    const providers = (projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.providers) || [];
    const mapProvider = {
        [sdkApiCore.ProviderEnum.Dynamic]: {
            enabled: isProviderEnabled.isProviderEnabled(providers, sdkApiCore.ProviderEnum.Dynamic),
            handler: createEmailHandler.createEmailHandler(environmentId, embeddedWalletSessionKeys),
        },
    };
    const engageCaptchaIfNeeded = (type) => new Promise((resolve) => {
        if (!captcha.isCaptchaEnabled(projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.security)) {
            resolve(undefined);
            return;
        }
        setShowAuthFlow(true, {
            initializeWalletConnect: false,
            performMultiWalletChecks: false,
        });
        engageCaptcha({
            authMethod: type,
            onCaptchaSuccess: (captchaToken) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
                resolve(captchaToken);
                setShowAuthFlow(false);
            }),
        });
    });
    const connectWithEmail = (email_1, ...args_1) => _tslib.__awaiter(void 0, [email_1, ...args_1], void 0, function* (email, options = {}) {
        var _a;
        if (!isEmailValid.isEmailValid(email)) {
            throw new Error('Email is not valid');
        }
        // Warm the embedded-wallet iframe connection at auth-flow start
        preconnectDynamicWaasIframe.preconnectDynamicWaasIframe({ apiBaseUrl, projectSettings });
        const effectiveEmailProvider = 'dynamic';
        if (!mapProvider[effectiveEmailProvider].enabled) {
            throw new Error('Email provider is not enabled');
        }
        const captchaToken = (_a = options.captchaToken) !== null && _a !== void 0 ? _a : (yield engageCaptchaIfNeeded('email'));
        const verificationHandler = yield mapProvider[effectiveEmailProvider].handler(email, captchaToken);
        lastVerificationHandlerRef.current = verificationHandler;
    });
    const connectWithSms = (phone_1, ...args_2) => _tslib.__awaiter(void 0, [phone_1, ...args_2], void 0, function* (phone, options = {}) {
        var _b;
        if (!isProviderEnabled.isProviderEnabled(providers, sdkApiCore.ProviderEnum.Sms)) {
            throw new Error('SMS provider is not enabled');
        }
        preconnectDynamicWaasIframe.preconnectDynamicWaasIframe({ apiBaseUrl, projectSettings });
        const handler = createSmsHandler.createSmsHandler(environmentId, embeddedWalletSessionKeys);
        const captchaToken = (_b = options.captchaToken) !== null && _b !== void 0 ? _b : (yield engageCaptchaIfNeeded('phone'));
        const verificationHandler = yield handler(phone, captchaToken);
        lastVerificationHandlerRef.current = verificationHandler;
    });
    const verifyOneTimePassword = (oneTimePassword, options) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        if (!lastVerificationHandlerRef.current) {
            throw new Error('Verification has not started, use connectWithEmail or connectWithSms before verifying');
        }
        const { type, verify } = lastVerificationHandlerRef.current;
        // Re-warm before verification — OTP entry can outlive the ~10s socket
        preconnectDynamicWaasIframe.preconnectDynamicWaasIframe({ apiBaseUrl, projectSettings });
        const { destination, response, verified } = yield verify(oneTimePassword, options);
        if (type === 'sms') {
            dynamicEvents.dynamicEvents.emit('smsVerificationResult', verified, destination);
        }
        else {
            //EMAIL
            dynamicEvents.dynamicEvents.emit('emailVerificationResult', verified, destination);
        }
        otpVerificationStorage.clearOtpVerificationState();
        // Avoid calling authSuccess if we're only verifying
        if (!(options === null || options === void 0 ? void 0 : options.skipSetUserAndAuthToken)) {
            setCallback('authSuccess');
        }
        return response;
    });
    const retryOneTimePassword = () => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        if (!lastVerificationHandlerRef.current) {
            throw new Error('Verification has not started, use connectWithEmail or connectWithSms before verifying');
        }
        if (!lastVerificationHandlerRef.current.retry) {
            throw new Error('Re-send is not supported');
        }
        return lastVerificationHandlerRef.current.retry();
    });
    return (jsxRuntime.jsx(Provider, { value: {
            connectWithEmail,
            connectWithSms,
            retryOneTimePassword,
            verifyOneTimePassword,
        }, children: children }));
};

exports.ConnectWithOtpProvider = ConnectWithOtpProvider;
