'use client'
import { __awaiter } from '../../../../_virtual/_tslib.js';
import { jsx } from 'react/jsx-runtime';
import { useRef } from 'react';
import { ProviderEnum } from '@dynamic-labs/sdk-api-core';
import { dynamicEvents } from '../../events/dynamicEvents.js';
import '../../utils/constants/values.js';
import '@dynamic-labs/utils';
import '@dynamic-labs/multi-wallet';
import 'react-international-phone';
import '../../utils/constants/colors.js';
import '@dynamic-labs/iconic';
import '@dynamic-labs/wallet-connector-core';
import '../ViewContext/ViewContext.js';
import '../../shared/logger.js';
import '@dynamic-labs/wallet-book';
import '../../shared/consts/index.js';
import '../../store/state/nonce/nonce.js';
import { isProviderEnabled } from '../../utils/functions/isProviderEnabled/isProviderEnabled.js';
import { isEmailValid } from '../../utils/functions/isEmailValid/isEmailValid.js';
import '@dynamic-labs-sdk/client/core';
import '../../client/client.js';
import '@dynamic-labs-sdk/client';
import '../../config/ApiEndpoint.js';
import '@dynamic-labs/locale';
import '../../store/state/dynamicContextProps/dynamicContextProps.js';
import '../../store/state/primaryWalletId/primaryWalletId.js';
import '../../store/state/connectedWalletsInfo/connectedWalletsInfo.js';
import '../DynamicContext/DynamicContext.js';
import '../../store/state/loadingAndLifecycle/loadingAndLifecycle.js';
import '../../store/state/authMode/authMode.js';
import { useInternalDynamicContext } from '../DynamicContext/useDynamicContext/useInternalDynamicContext/useInternalDynamicContext.js';
import { useCaptchaContext } from '../CaptchaContext/CaptchaContext.js';
import '../ErrorContext/ErrorContext.js';
import '../AccessDeniedContext/AccessDeniedContext.js';
import '../AccountExistsContext/AccountExistsContext.js';
import '../UserWalletsContext/UserWalletsContext.js';
import '../VerificationContext/VerificationContext.js';
import 'react-dom';
import '../../utils/functions/compareChains/compareChains.js';
import '../../views/Passkey/utils/findPrimaryEmbeddedChain/findPrimaryEmbeddedChain.js';
import { useEmbeddedWalletSessionKeys } from '../../utils/hooks/useEmbeddedWalletSessionKeys/useEmbeddedWalletSessionKeys.js';
import '../ThemeContext/ThemeContext.js';
import '../../utils/hooks/useUserUpdateRequest/useUpdateUser/userFieldsSchema.js';
import 'bs58';
import '@dynamic-labs/types';
import '../SocialRedirectContext/SocialRedirectContext.js';
import '../LoadingContext/LoadingContext.js';
import '../WalletContext/WalletContext.js';
import '../../utils/hooks/useEmbeddedWallet/useSecureEnclaveEmbeddedWallet/constants.js';
import 'yup';
import '../MockContext/MockContext.js';
import '../../views/CollectUserDataView/useFields.js';
import '../FieldsStateContext/FieldsStateContext.js';
import '../UserFieldEditorContext/UserFieldEditorContext.js';
import '@dynamic-labs/rpc-providers';
import '../../store/state/walletOptions/walletOptions.js';
import 'react-i18next';
import '../../components/Accordion/components/AccordionItem/AccordionItem.js';
import '../../components/Alert/Alert.js';
import '../../components/ShadowDOM/ShadowDOM.js';
import '../../components/IconButton/IconButton.js';
import '../../components/InlineWidget/InlineWidget.js';
import '../../components/Input/Input.js';
import '../../components/IsBrowser/IsBrowser.js';
import '../../components/MenuList/Dropdown/Dropdown.js';
import '../../components/OverlayCard/OverlayCard.js';
import '../../components/Transition/ZoomTransition/ZoomTransition.js';
import '../../components/Transition/SlideInUpTransition/SlideInUpTransition.js';
import '../../components/Transition/OpacityTransition/OpacityTransition.js';
import '../../components/PasskeyCreatedSuccessBanner/PasskeyCreatedSuccessBanner.js';
import '../../components/Popper/Popper/Popper.js';
import '../../components/Popper/PopperContext/PopperContext.js';
import 'react-focus-lock';
import 'qrcode';
import 'formik';
import '../../utils/hooks/useSubdomainCheck/useSubdomainCheck.js';
import '../WalletGroupContext/WalletGroupContext.js';
import '../IpConfigurationContext/IpConfigurationContext.js';
import { ConnectWithOtpContext } from './ConnectWithOtpContext.js';
import { createEmailHandler } from './utils/createEmailHandler.js';
import { createSmsHandler } from './utils/createSmsHandler.js';
import '../../widgets/DynamicBridgeWidget/views/WalletsView/components/SecondaryWallets/SecondaryWallets.js';
import '@hcaptcha/react-hcaptcha';
import '../../widgets/DynamicWidget/context/DynamicWidgetContext.js';
import '../../widgets/DynamicWidget/helpers/convertExchangeKeyAndProviderEnum.js';
import '../../views/ExchangeWhitelistWarning/ExchangeWhitelistWarning.js';
import '../ErrorContext/hooks/useErrorText/useErrorText.js';
import '../FooterAnimationContext/index.js';
import '../../views/MfaChooseDeviceView/useGetMfaOptions/useGetMfaOptions.js';
import '../PasskeyContext/PasskeyContext.js';
import '../OnrampContext/OnrampContext.js';
import '../../store/state/sendBalances.js';
import '../../store/state/connectorsInitializing/connectorsInitializing.js';
import '../../components/OverlayCardBase/OverlayCardTarget/OverlayCardTarget.js';
import '../../widgets/DynamicWidget/components/DynamicWidgetHeader/DynamicWidgetHeader.js';
import '../../views/TransactionConfirmationView/TransactionConfirmationView.js';
import '../../widgets/DynamicWidget/components/PasskeyCard/PasskeyCard.js';
import '../../widgets/DynamicWidget/views/CryptoComOnramp/CryptoComOnramp.js';
import '../../../index.js';
import '../../widgets/DynamicWidget/views/ReceiveWalletFunds/ReceiveWalletFunds.js';
import '../../store/state/tokenBalances.js';
import '../../store/state/multichainBalances.js';
import '../../shared/utils/functions/getInitialUrl/getInitialUrl.js';

const { Provider } = ConnectWithOtpContext;
const ConnectWithOtpProvider = ({ children }) => {
    const { environmentId, projectSettings, setCallback, setShowAuthFlow } = useInternalDynamicContext();
    const { engageCaptcha } = useCaptchaContext();
    const embeddedWalletSessionKeys = useEmbeddedWalletSessionKeys({
        environmentId,
        projectSettings,
    });
    const lastVerificationHandlerRef = useRef(null);
    const providers = (projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.providers) || [];
    const mapProvider = {
        [ProviderEnum.Dynamic]: {
            enabled: isProviderEnabled(providers, ProviderEnum.Dynamic),
            handler: 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) => __awaiter(void 0, void 0, void 0, function* () {
                resolve(captchaToken);
                setShowAuthFlow(false);
            }),
        });
    });
    const connectWithEmail = (email_1, ...args_1) => __awaiter(void 0, [email_1, ...args_1], void 0, function* (email, options = {}) {
        var _a;
        if (!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) => __awaiter(void 0, [phone_1, ...args_2], void 0, function* (phone, options = {}) {
        var _b;
        if (!isProviderEnabled(providers, ProviderEnum.Sms)) {
            throw new Error('SMS provider is not enabled');
        }
        const handler = 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) => __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.emit('smsVerificationResult', verified, destination);
        }
        else {
            //EMAIL
            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 = () => __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 (jsx(Provider, { value: {
            connectWithEmail,
            connectWithSms,
            retryOneTimePassword,
            verifyOneTimePassword,
        }, children: children }));
};

export { ConnectWithOtpProvider };
