'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');
var utils = require('@dynamic-labs/utils');
require('../../../context/DynamicContext/useDynamicContext/useDynamicContext.cjs');
var useInternalDynamicContext = require('../../../context/DynamicContext/useDynamicContext/useInternalDynamicContext/useInternalDynamicContext.cjs');
var dynamicEvents = require('../../../events/dynamicEvents.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('../../constants/colors.cjs');
require('../../constants/values.cjs');
require('../../../shared/consts/index.cjs');
var createEmbeddedWalletRequest = require('../../../views/Passkey/utils/createEmbeddedWalletRequest/createEmbeddedWalletRequest.cjs');
var findPasskeyEmailWalletConnector = require('../../../views/Passkey/utils/findPasskeyEmailWalletConnector/findPasskeyEmailWalletConnector.cjs');
var smartWallet = require('../useWalletConnectors/utils/smartWallet/smartWallet.cjs');
var findPrimaryEmbeddedChain = require('../../../views/Passkey/utils/findPrimaryEmbeddedChain/findPrimaryEmbeddedChain.cjs');
var errors = require('../../constants/errors.cjs');
var useEmbeddedWalletSessionKeys = require('../useEmbeddedWalletSessionKeys/useEmbeddedWalletSessionKeys.cjs');
require('@dynamic-labs/multi-wallet');
require('react-international-phone');
require('../../../store/state/nonce/nonce.cjs');
require('@dynamic-labs-wallet/browser-wallet-client');
require('@dynamic-labs-sdk/client/core');
require('eventemitter3');
require('@dynamic-labs-sdk/client');
require('../../../config/ApiEndpoint.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/locale');
require('../../functions/getWaasAddressTypeLabel/getWaasAddressTypeLabel.cjs');

const getEmbeddedChain = (chainName) => {
    if (chainName === 'SOL')
        return sdkApiCore.EmbeddedWalletChainEnum.Sol;
    if (chainName === 'BTC')
        return sdkApiCore.EmbeddedWalletChainEnum.Btc;
    return sdkApiCore.EmbeddedWalletChainEnum.Evm;
};
// This hook needs to be async that's why it's not using useMutation
const useCreateDynamicEmbeddedWalletMutation = () => {
    var _a, _b;
    const { user, setShowAuthFlow, projectSettings, environmentId } = useInternalDynamicContext.useInternalDynamicContext();
    const [isLoading, setIsLoading] = React.useState(false);
    const [error, setError] = React.useState();
    const { getSessionPublicKey, shouldRegisterSessionKeysOnSignin } = useEmbeddedWalletSessionKeys.useEmbeddedWalletSessionKeys({
        environmentId,
        projectSettings,
    });
    const chainConfigurations = (_b = (_a = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.sdk) === null || _a === void 0 ? void 0 : _a.embeddedWallets) === null || _b === void 0 ? void 0 : _b.chainConfigurations;
    const primaryEmbeddedChain = findPrimaryEmbeddedChain.findPrimaryEmbeddedChain(projectSettings);
    const embeddedChains = React.useMemo(() => (chainConfigurations || [])
        .filter((chain) => chain.enabled)
        .map((c) => getEmbeddedChain(c.name)), [chainConfigurations]);
    const createDynamicEmbeddedWalletMutation = React.useCallback((_c) => _tslib.__awaiter(void 0, [_c], void 0, function* ({ environmentId, walletConnectorOptions, withAuthenticator, options, chains, }) {
        var _d, _e;
        setIsLoading(true);
        if (!user) {
            throw new utils.DynamicError(errors.USER_NOT_LOGGED_IN, 'user_not_logged_in');
        }
        let sessionPublicKey;
        // get the session public key that was created in the login/signup flow
        if (shouldRegisterSessionKeysOnSignin()) {
            sessionPublicKey = getSessionPublicKey();
        }
        try {
            const { embeddedWalletVerifiedCredential, updatedUser, walletConnector, } = yield createEmbeddedWalletRequest.createEmbeddedWalletRequest({
                chains: chains !== null && chains !== void 0 ? chains : embeddedChains,
                environmentId,
                sessionPublicKey,
                user,
                walletConnector: findPasskeyEmailWalletConnector.findPasskeyEmailWalletConnector(walletConnectorOptions, primaryEmbeddedChain),
                webAuthnAttestation: options === null || options === void 0 ? void 0 : options.webAuthnAttestation,
                withAuthenticator,
            });
            const turnkeyVerifiedCredentials = (_d = updatedUser.verifiedCredentials) === null || _d === void 0 ? void 0 : _d.find(({ walletName }) => walletName === null || walletName === void 0 ? void 0 : walletName.startsWith('turnkey'));
            /** It's not authenticated if it's a turnkey wallet that still hasn't created a passkey */
            const isAuthenticated = Boolean((_e = turnkeyVerifiedCredentials === null || turnkeyVerifiedCredentials === void 0 ? void 0 : turnkeyVerifiedCredentials.walletProperties) === null || _e === void 0 ? void 0 : _e.isAuthenticatorAttached);
            const embeddedWallet = walletConnector.createWallet({
                address: (yield walletConnector.getAddress()) || '',
                chain: walletConnector.connectedChain,
                connector: walletConnector,
                id: embeddedWalletVerifiedCredential.id,
                isAuthenticated,
                key: embeddedWalletVerifiedCredential.walletName || walletConnector.key,
            });
            const smartWallet$1 = smartWallet.findSmartWallet(embeddedWalletVerifiedCredential, updatedUser.verifiedCredentials);
            if (!smartWallet$1) {
                updatePrimaryWalletId.updatePrimaryWalletId(embeddedWalletVerifiedCredential.id);
            }
            else {
                yield smartWallet.initializeSmartWallet({
                    account: smartWallet$1,
                    primaryWalletId: smartWallet$1.id,
                    verifiedCredentials: updatedUser.verifiedCredentials,
                    walletConnectorOptions,
                });
                updatePrimaryWalletId.updatePrimaryWalletId(smartWallet$1.id);
            }
            dynamicEvents.dynamicEvents.emit('embeddedWalletCreated', embeddedWallet, turnkeyVerifiedCredentials, updatedUser);
            setShowAuthFlow(false, { performMultiWalletChecks: false });
        }
        catch (err) {
            logger.logger.error('Failed to create embedded wallet', err);
            setError(err);
            dynamicEvents.dynamicEvents.emit('embeddedWalletFailed', err);
        }
        finally {
            setIsLoading(false);
        }
    }), [
        embeddedChains,
        primaryEmbeddedChain,
        setShowAuthFlow,
        user,
        getSessionPublicKey,
        shouldRegisterSessionKeysOnSignin,
    ]);
    return {
        createDynamicEmbeddedWalletMutation,
        error,
        isLoading,
    };
};

exports.getEmbeddedChain = getEmbeddedChain;
exports.useCreateDynamicEmbeddedWalletMutation = useCreateDynamicEmbeddedWalletMutation;
