'use client'
'use strict';

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

var _tslib = require('../../../../../../../_virtual/_tslib.cjs');
var React = require('react');
var sdkApiCore = require('@dynamic-labs/sdk-api-core');
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');
var ViewContext = require('../../../../../context/ViewContext/ViewContext.cjs');
var logger = require('../../../../../shared/logger.cjs');
require('@dynamic-labs/wallet-book');
require('@dynamic-labs/utils');
require('../../../../constants/colors.cjs');
require('../../../../constants/values.cjs');
require('../../../../../shared/consts/index.cjs');
var dynamicEvents = require('../../../../../events/dynamicEvents.cjs');
require('../../../../../context/CaptchaContext/CaptchaContext.cjs');
require('../../../../../context/ErrorContext/ErrorContext.cjs');
var findEmbeddedWalletFromVerifiedCredentials = require('../../../../functions/findEmbeddedWalletFromVerifiedCredentials/findEmbeddedWalletFromVerifiedCredentials.cjs');
var findTurnkeyWallet = require('../../../../functions/findTurnkeyWallet/findTurnkeyWallet.cjs');
require('@dynamic-labs/multi-wallet');
require('react-international-phone');
var getUserWalletsFromVerifiedCredentials = require('../../../../functions/getUserWalletsFromVerifiedCredentials/getUserWalletsFromVerifiedCredentials.cjs');
require('../../../../../store/state/nonce/nonce.cjs');
var getUserVerifiedCredentialType = require('../../../../functions/getUserVerifiedCredentialType/getUserVerifiedCredentialType.cjs');
var updatePrimaryWalletId = require('../../../../functions/updatePrimaryWalletId/updatePrimaryWalletId.cjs');
require('../../../../../store/state/connectedWalletsInfo/connectedWalletsInfo.cjs');
require('../../../../../store/state/dynamicContextProps/dynamicContextProps.cjs');
require('../../../../../store/state/primaryWalletId/primaryWalletId.cjs');
require('@dynamic-labs-sdk/client/core');
require('../../../../../client/client.cjs');
require('@dynamic-labs-sdk/client');
require('../../../../../config/ApiEndpoint.cjs');
require('@dynamic-labs/locale');
var errors = require('../../../../constants/errors.cjs');
require('../../../../../context/AccessDeniedContext/AccessDeniedContext.cjs');
require('../../../../../context/AccountExistsContext/AccountExistsContext.cjs');
require('../../../../../context/UserWalletsContext/UserWalletsContext.cjs');
require('../../../../../store/state/authMode/authMode.cjs');
require('../../../../../context/VerificationContext/VerificationContext.cjs');
require('react-dom');
var useCreateDynamicEmbeddedWalletMutation = require('../../../useCreateDynamicEmbeddedWalletMutation/useCreateDynamicEmbeddedWalletMutation.cjs');
require('../../../../../context/ThemeContext/ThemeContext.cjs');
var useSmartWallets = require('../../../useSmartWallets/useSmartWallets.cjs');
require('../../../useUserUpdateRequest/useUpdateUser/userFieldsSchema.cjs');
require('bs58');
require('@dynamic-labs/types');
require('../../../../../context/SocialRedirectContext/SocialRedirectContext.cjs');
require('../../../../../context/LoadingContext/LoadingContext.cjs');
require('../../../../../context/WalletContext/WalletContext.cjs');
var findPrimaryEmbeddedChain = require('../../../../../views/Passkey/utils/findPrimaryEmbeddedChain/findPrimaryEmbeddedChain.cjs');
require('../constants.cjs');
var findPasskeyEmailWalletConnector = require('../../../../../views/Passkey/utils/findPasskeyEmailWalletConnector/findPasskeyEmailWalletConnector.cjs');
var smartWallet = require('../../../useWalletConnectors/utils/smartWallet/smartWallet.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('../../../../functions/compareChains/compareChains.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');

// Hook exposed to customers and used internally to trigger embedded wallet creation
const useTurnkey = () => {
    const { projectSettings, walletConnectorOptions, setShowAuthFlow, environmentId, user, primaryWallet, } = useInternalDynamicContext.useInternalDynamicContext();
    const { pushView } = ViewContext.useViewContext();
    const { createDynamicEmbeddedWalletMutation } = useCreateDynamicEmbeddedWalletMutation.useCreateDynamicEmbeddedWalletMutation();
    const { getEOAWallet } = useSmartWallets.useSmartWallets();
    const startHeadlessEmbeddedWalletCreationFlow = React.useCallback((chains, options) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        return new Promise((resolve, reject) => {
            // register the event listeners before calling create embedded wallet
            // as the event might fire before the listeners are registered.
            dynamicEvents.dynamicEvents.once('embeddedWalletCreated', (wallet) => {
                resolve(wallet);
            });
            dynamicEvents.dynamicEvents.once('embeddedWalletFailed', (error) => reject(error));
            createDynamicEmbeddedWalletMutation({
                chains,
                environmentId,
                options,
                walletConnectorOptions,
                withAuthenticator: false,
            })
                .then(() => {
                setShowAuthFlow(false, { performMultiWalletChecks: false }); // close email otp pin modal
            })
                .catch((error) => {
                reject(error);
            });
        });
    }), [
        createDynamicEmbeddedWalletMutation,
        environmentId,
        walletConnectorOptions,
        setShowAuthFlow,
    ]);
    const startPasskeyEmbeddedWalletCreationFlow = React.useCallback((chains) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        setShowAuthFlow(true, {
            ignoreIfIsEmbeddedWidget: false,
            performMultiWalletChecks: false,
        });
        pushView('passkey-intro', { chains });
        return new Promise((resolve, reject) => {
            dynamicEvents.dynamicEvents.once('embeddedWalletCreated', (wallet) => resolve(wallet));
            dynamicEvents.dynamicEvents.once('embeddedWalletFailed', (error) => {
                // when creating a passkey, if user cancels the passkey modal more than once
                // it will throw this DOMException, but we don't want to let user to have access
                // to the app before they've a passkey correctly setup
                if (error instanceof DOMException &&
                    error.name === 'NotAllowedError') {
                    logger.logger.error('User cancelled the passkey creation.', error);
                    return;
                }
                reject(error);
            });
        });
    }), [setShowAuthFlow, pushView]);
    const returnEmbeddedWallet = React.useCallback((embeddedWalletVerifiedCredential) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        var _a, _b;
        const { chain } = embeddedWalletVerifiedCredential;
        const turnkeyWallet = findTurnkeyWallet.findTurnkeyWalletByChain(walletConnectorOptions, chain);
        let newPrimaryWalletId = null;
        // if user already has embedded wallet, set it as primary wallet
        if (user) {
            (_a = turnkeyWallet === null || turnkeyWallet === void 0 ? void 0 : turnkeyWallet.walletConnector) === null || _a === void 0 ? void 0 : _a.setVerifiedCredentials(user.verifiedCredentials);
            const smartWallet$1 = smartWallet.findSmartWallet(embeddedWalletVerifiedCredential, user.verifiedCredentials);
            if (smartWallet$1) {
                yield smartWallet.initializeSmartWallet({
                    account: smartWallet$1,
                    primaryWalletId: smartWallet$1.id,
                    verifiedCredentials: user.verifiedCredentials,
                    walletConnectorOptions,
                });
                newPrimaryWalletId = smartWallet$1.id;
            }
            else {
                newPrimaryWalletId = embeddedWalletVerifiedCredential.id;
            }
        }
        if (newPrimaryWalletId) {
            updatePrimaryWalletId.updatePrimaryWalletId(newPrimaryWalletId);
        }
        /** It's not authenticated if it still hasn't created a passkey */
        const isAuthenticated = Boolean((_b = embeddedWalletVerifiedCredential.walletProperties) === null || _b === void 0 ? void 0 : _b.isAuthenticatorAttached);
        if (!(turnkeyWallet === null || turnkeyWallet === void 0 ? void 0 : turnkeyWallet.walletConnector)) {
            throw new Error('Could not find the embedded wallet connector');
        }
        const connector = turnkeyWallet.walletConnector;
        const passkeyWallet = connector.createWallet({
            address: (yield connector.getAddress()) || '',
            chain: connector.connectedChain,
            connector,
            id: embeddedWalletVerifiedCredential.id,
            isAuthenticated,
            key: embeddedWalletVerifiedCredential.walletName || connector.key || '',
        });
        return Promise.resolve(passkeyWallet);
    }), [walletConnectorOptions, user]);
    const createTurnkeyWallet = React.useCallback((chains, options) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        var _c, _d, _e, _f, _g, _h;
        if (!user) {
            throw new Error(errors.USER_NOT_LOGGED_IN);
        }
        const isManualMode = ((_c = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.sdk.embeddedWallets) === null || _c === void 0 ? void 0 : _c.automaticEmbeddedWalletCreation) === false;
        const shouldCreateV2WalletsByDefault = ((_d = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.sdk.embeddedWallets) === null || _d === void 0 ? void 0 : _d.defaultWalletVersion) ===
            sdkApiCore.EmbeddedWalletVersionEnum.V2;
        const primaryChain = findPrimaryEmbeddedChain.findPrimaryEmbeddedChain(projectSettings);
        // if embedded wallet already exists
        // get the one with the primary chain if `chains` is undefined
        const embeddedWalletVerifiedCredential = findEmbeddedWalletFromVerifiedCredentials.findEmbeddedWalletFromVerifiedCredentials(user, chains !== null && chains !== void 0 ? chains : [primaryChain]);
        const userWalletsCredentials = getUserWalletsFromVerifiedCredentials.getUserWalletsFromVerifiedCredentials(user);
        // If the user doesn't have a wallet, or if the customer is in Manual
        // Mode, we should attempt to create a new wallet. Note that if in manual
        // mode, the check for the existance of an embedded wallet was arbitrarily
        // added as a safeguard given the pre-existing condition we're overriding.
        if (!(userWalletsCredentials === null || userWalletsCredentials === void 0 ? void 0 : userWalletsCredentials.length) ||
            (!embeddedWalletVerifiedCredential && isManualMode)) {
            const hasEmailVC = getUserVerifiedCredentialType.getUserVerifiedCredentialType(user, sdkApiCore.JwtVerifiedCredentialFormatEnum.Email);
            if ((!((_e = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.sdk.embeddedWallets) === null || _e === void 0 ? void 0 : _e.forceAuthenticatorAtSignup) &&
                hasEmailVC) ||
                (options === null || options === void 0 ? void 0 : options.webAuthnAttestation) ||
                shouldCreateV2WalletsByDefault) {
                // create embedded wallet fully headless
                return startHeadlessEmbeddedWalletCreationFlow(chains, options);
            }
            else {
                // show the passkey view to create an embedded wallet
                return startPasskeyEmbeddedWalletCreationFlow(chains);
            }
        }
        else {
            // the pregenerated wallet must have been created at this point in the
            // backend if this called as part of a new user sign up.
            if (embeddedWalletVerifiedCredential &&
                user.newUser &&
                ((_f = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.sdk.embeddedWallets) === null || _f === void 0 ? void 0 : _f.automaticEmbeddedWalletCreation)) {
                const walletConnector = findPasskeyEmailWalletConnector.findPasskeyEmailWalletConnector(walletConnectorOptions, primaryChain);
                if (!walletConnector) {
                    throw new Error('Could not find the embedded wallet connector');
                }
                const wallet = walletConnector.createWallet({
                    address: (yield walletConnector.getAddress()) || '',
                    chain: walletConnector.connectedChain,
                    connector: walletConnector,
                    id: embeddedWalletVerifiedCredential.id,
                    isAuthenticated: Boolean((_g = embeddedWalletVerifiedCredential === null || embeddedWalletVerifiedCredential === void 0 ? void 0 : embeddedWalletVerifiedCredential.walletProperties) === null || _g === void 0 ? void 0 : _g.isAuthenticatorAttached),
                    key: (_h = embeddedWalletVerifiedCredential.walletName) !== null && _h !== void 0 ? _h : walletConnector.key,
                });
                updatePrimaryWalletId.updatePrimaryWalletId(embeddedWalletVerifiedCredential.id);
                dynamicEvents.dynamicEvents.emit('embeddedWalletCreated', wallet, embeddedWalletVerifiedCredential, user);
            }
        }
        setShowAuthFlow(false, { performMultiWalletChecks: false });
        // if user logged in with MM for example, just continue the flow
        if (!embeddedWalletVerifiedCredential) {
            throw new Error('Primary wallet is not an embedded wallet');
        }
        // if user already has embedded wallet, returns it
        return returnEmbeddedWallet(embeddedWalletVerifiedCredential);
    }), [
        user,
        projectSettings,
        primaryWallet,
        getEOAWallet,
        setShowAuthFlow,
        returnEmbeddedWallet,
        startHeadlessEmbeddedWalletCreationFlow,
        startPasskeyEmbeddedWalletCreationFlow,
        walletConnectorOptions,
    ]);
    return {
        createTurnkeyWallet,
    };
};

exports.useTurnkey = useTurnkey;
