'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');
require('../../utils/constants/values.cjs');
require('@dynamic-labs/utils');
require('@dynamic-labs/multi-wallet');
require('react-international-phone');
require('../../utils/constants/colors.cjs');
require('@dynamic-labs/iconic');
require('@dynamic-labs/wallet-connector-core');
require('../ViewContext/ViewContext.cjs');
require('../../shared/logger.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');
require('@dynamic-labs-sdk/client/core');
require('../../client/client.cjs');
require('@dynamic-labs-sdk/client');
require('../../config/ApiEndpoint.cjs');
require('@dynamic-labs/locale');
require('../../store/state/dynamicContextProps/dynamicContextProps.cjs');
require('../../store/state/primaryWalletId/primaryWalletId.cjs');
require('../../store/state/connectedWalletsInfo/connectedWalletsInfo.cjs');
require('../DynamicContext/DynamicContext.cjs');
require('../../store/state/loadingAndLifecycle/loadingAndLifecycle.cjs');
require('../../store/state/authMode/authMode.cjs');
var useInternalDynamicContext = require('../DynamicContext/useDynamicContext/useInternalDynamicContext/useInternalDynamicContext.cjs');
var CaptchaContext = require('../CaptchaContext/CaptchaContext.cjs');
require('../ErrorContext/ErrorContext.cjs');
require('../AccessDeniedContext/AccessDeniedContext.cjs');
require('../AccountExistsContext/AccountExistsContext.cjs');
require('../UserWalletsContext/UserWalletsContext.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('../IpConfigurationContext/IpConfigurationContext.cjs');
var ConnectWithOtpContext = require('./ConnectWithOtpContext.cjs');
var createEmailHandler = require('./utils/createEmailHandler.cjs');
var createSmsHandler = require('./utils/createSmsHandler.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('../ErrorContext/hooks/useErrorText/useErrorText.cjs');
require('../FooterAnimationContext/index.cjs');
require('../../views/MfaChooseDeviceView/useGetMfaOptions/useGetMfaOptions.cjs');
require('../PasskeyContext/PasskeyContext.cjs');
require('../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');

const { Provider } = ConnectWithOtpContext.ConnectWithOtpContext;
const ConnectWithOtpProvider = ({ children }) => {
    const { environmentId, projectSettings, setCallback, setShowAuthFlow } = useInternalDynamicContext.useInternalDynamicContext();
    const { engageCaptcha } = CaptchaContext.useCaptchaContext();
    const embeddedWalletSessionKeys = useEmbeddedWalletSessionKeys.useEmbeddedWalletSessionKeys({
        environmentId,
        projectSettings,
    });
    const lastVerificationHandlerRef = React.useRef(null);
    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) => {
        var _a;
        if (!((_a = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.security.hCaptcha) === null || _a === void 0 ? void 0 : _a.enabled)) {
            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');
        }
        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');
        }
        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;
        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);
        }
        // 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;
