'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');
var client = require('../../../client/client.cjs');
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');
require('../../../context/ViewContext/ViewContext.cjs');
require('../../../shared/logger.cjs');
require('@dynamic-labs/wallet-book');
require('../../constants/colors.cjs');
require('../../constants/values.cjs');
require('../../../shared/consts/index.cjs');
require('../../../events/dynamicEvents.cjs');
require('../../../context/CaptchaContext/CaptchaContext.cjs');
require('../../../context/ErrorContext/ErrorContext.cjs');
var errors = require('../../constants/errors.cjs');
require('@dynamic-labs/multi-wallet');
require('react-international-phone');
require('../../../store/state/nonce/nonce.cjs');
var isTurnkeyEnabled = require('../../functions/isTurnkeyEnabled/isTurnkeyEnabled.cjs');
var hasEmbeddedWallet = require('../../functions/hasEmbeddedWallet/hasEmbeddedWallet.cjs');
var updatePrimaryWalletId = require('../../functions/updatePrimaryWalletId/updatePrimaryWalletId.cjs');
require('../../../store/state/connectedWalletsInfo/connectedWalletsInfo.cjs');
require('../../../store/state/dynamicContextProps/dynamicContextProps.cjs');
var primaryWalletId = require('../../../store/state/primaryWalletId/primaryWalletId.cjs');
require('@dynamic-labs-sdk/client/core');
require('@dynamic-labs-sdk/client');
require('../../../config/ApiEndpoint.cjs');
require('@dynamic-labs/locale');
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');
require('../../functions/compareChains/compareChains.cjs');
require('../../../views/Passkey/utils/findPrimaryEmbeddedChain/findPrimaryEmbeddedChain.cjs');
require('../../../context/ThemeContext/ThemeContext.cjs');
require('../useUserUpdateRequest/useUpdateUser/userFieldsSchema.cjs');
var useIsTurnkeyWallet = require('../useIsTurnkeyWallet/useIsTurnkeyWallet.cjs');
require('bs58');
require('@dynamic-labs/types');
require('../../../context/SocialRedirectContext/SocialRedirectContext.cjs');
require('../../../context/LoadingContext/LoadingContext.cjs');
var WalletContext = require('../../../context/WalletContext/WalletContext.cjs');
var findPrimaryWalletVCForUser = require('../../functions/findPrimaryWalletVCForUser/findPrimaryWalletVCForUser.cjs');
var useSecureEnclaveEmbeddedWallet = require('./useSecureEnclaveEmbeddedWallet/useSecureEnclaveEmbeddedWallet.cjs');
require('./useSecureEnclaveEmbeddedWallet/constants.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('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
/**
 * @returns {
 *  createEmbeddedWallet, - creates Dynamic embedded wallet according to the settings
 *  createOrRestoreSession, - creates or restores session for the embedded wallet
 *  createPasskey, - creates passkey for the embedded wallet
 *  getPasskeys, - gets passkeys for the embedded wallet
 *  isLoadingEmbeddedWallet, - loading state of the embedded wallet
 *  isSessionActive, - checks if the session is active for the embedded wallet
 *  revealWalletKey, - reveals the private key or recovery phrase for the embedded wallet
 *  sendOneTimeCode, - sends one time code for the embedded wallet
 *  userHasEmbeddedWallet, - checks if the user has an embedded wallet
 * }
 */
const useEmbeddedWallet = () => {
    const { user, projectSettings } = useInternalDynamicContext.useInternalDynamicContext();
    const { isTurnkeyWallet } = useIsTurnkeyWallet.useIsTurnkeyWallet();
    const { createEmbeddedWallet: createTurnkeyEmbeddedWallet, createEmbeddedWalletAccount, createOrRestoreSession, createPasskey, revealEmbeddedWalletKey: revealTurnkeyEmbeddedWalletKey, getPasskeys, isSessionActive, sendOneTimeCode, getWalletVersion: getTurnkeyWalletVersion, } = useSecureEnclaveEmbeddedWallet.useSecureEnclaveEmbeddedWallet();
    const { isLoadingEmbeddedWallet } = WalletContext.useWalletContext();
    const userHasEmbeddedWallet = React.useCallback(() => hasEmbeddedWallet.hasEmbeddedWallet(user), [user]);
    const getWalletVersion = React.useCallback(() => {
        if (!user) {
            throw new utils.DynamicError(errors.USER_NOT_LOGGED_IN);
        }
        if (!userHasEmbeddedWallet()) {
            throw new utils.DynamicError('Embedded wallet not found');
        }
        if (isTurnkeyWallet) {
            return getTurnkeyWalletVersion();
        }
        return undefined;
    }, [getTurnkeyWalletVersion, isTurnkeyWallet, user, userHasEmbeddedWallet]);
    /**
     * Creates Dynamic embedded wallet according to the settings
     * @param chains - array of chains to create the wallet for
     * @param options - options for the wallet creation
     * @returns Promise<Wallet | undefined> - created wallet object
     */
    const createEmbeddedWallet = React.useCallback((chains, options) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        const wallet = yield createTurnkeyEmbeddedWallet(chains, options);
        return wallet;
    }), [createTurnkeyEmbeddedWallet]);
    /**
     * Reveals the private key or recovery phrase for the embedded wallet
     * @param options - options for revealing the wallet key
     * @returns Promise<boolean> - true if the key was revealed successfully
     */
    const revealWalletKey = (options) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        if (!user) {
            throw new utils.DynamicError(errors.USER_NOT_LOGGED_IN);
        }
        if (!userHasEmbeddedWallet()) {
            throw new utils.DynamicError('Embedded wallet not found');
        }
        return revealTurnkeyEmbeddedWalletKey(options);
    });
    const shouldPromptForKeyExport = React.useCallback(() => { var _a; return Boolean((_a = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.sdk.embeddedWallets) === null || _a === void 0 ? void 0 : _a.promptForKeyExport); }, [projectSettings]);
    const embeddedWalletSettingVersion = React.useCallback(() => { var _a; return (_a = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.sdk.embeddedWallets) === null || _a === void 0 ? void 0 : _a.defaultWalletVersion; }, [projectSettings]);
    const findPrimaryWalletVCForUserCallback = React.useCallback((user) => findPrimaryWalletVCForUser.findPrimaryWalletVCForUser(user, projectSettings, true), [projectSettings]);
    const shouldAutoCreateEmbeddedWallet = React.useCallback(() => {
        var _a, _b;
        const hasEmbeddedWalletProviderEnabled = isTurnkeyEnabled.isTurnkeyEnabled(projectSettings);
        const { user } = client.getDynamicClient();
        const hasPrimaryWallet = primaryWalletId.getPrimaryWalletId();
        // If V3 wallets are enabled, never create V1/V2 wallets - they should be handled by WAAS flow
        if (embeddedWalletSettingVersion() === sdkApiCore.EmbeddedWalletVersionEnum.V3) {
            const primaryWalletVC = findPrimaryWalletVCForUserCallback(user);
            if (primaryWalletVC && !hasPrimaryWallet) {
                updatePrimaryWalletId.updatePrimaryWalletId(primaryWalletVC.id);
            }
            return false;
        }
        if (!hasEmbeddedWalletProviderEnabled || hasPrimaryWallet) {
            return false;
        }
        // Turnkey and WAAS specific rules
        if (user) {
            const primaryWalletVC = findPrimaryWalletVCForUserCallback(user);
            if (primaryWalletVC) {
                updatePrimaryWalletId.updatePrimaryWalletId(primaryWalletVC.id);
                return false;
            }
        }
        if (isTurnkeyEnabled.isTurnkeyEnabled(projectSettings) &&
            !((_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.automaticEmbeddedWalletCreation)) {
            return false;
        }
        return true;
    }, [
        projectSettings,
        embeddedWalletSettingVersion,
        findPrimaryWalletVCForUserCallback,
    ]);
    return {
        createEmbeddedWallet,
        createEmbeddedWalletAccount,
        createOrRestoreSession,
        createPasskey,
        embeddedWalletSettingVersion,
        getPasskeys,
        getWalletVersion,
        isLoadingEmbeddedWallet,
        isSessionActive,
        revealWalletKey,
        sendOneTimeCode,
        shouldAutoCreateEmbeddedWallet,
        shouldPromptForKeyExport,
        userHasEmbeddedWallet,
    };
};

exports.useEmbeddedWallet = useEmbeddedWallet;
