'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 reactI18next = require('react-i18next');
var iconic = require('@dynamic-labs/iconic');
var logger = require('@dynamic-labs/logger');
var utils = require('@dynamic-labs/utils');
var walletBook = require('@dynamic-labs/wallet-book');
var walletConnectorCore = require('@dynamic-labs/wallet-connector-core');
var locale = require('@dynamic-labs/locale');
var app = require('../../app.cjs');
require('@dynamic-labs-sdk/client/core');
require('@dynamic-labs/sdk-api-core');
require('../../client/client.cjs');
require('@dynamic-labs-sdk/client');
var useInitializeSdkClient = require('../../client/extension/hooks/useInitializeSdkClient/useInitializeSdkClient.cjs');
var values = require('../../utils/constants/values.cjs');
require('@dynamic-labs/multi-wallet');
require('react-international-phone');
var localStorage = require('../../utils/constants/localStorage.cjs');
require('../../utils/constants/colors.cjs');
var ViewContext = require('../ViewContext/ViewContext.cjs');
var logger$1 = require('../../shared/logger.cjs');
var useLocalStorage = require('../../shared/utils/hooks/useLocalStorage/useLocalStorage.cjs');
var usePrefetch = require('../../shared/utils/hooks/usePrefetch/usePrefetch.cjs');
require('../../shared/consts/index.cjs');
var nonce = require('../../store/state/nonce/nonce.cjs');
var ApiEndpoint = require('../../config/ApiEndpoint.cjs');
var settings = require('../../data/api/settings/settings.cjs');
var dynamicContextProps = require('../../store/state/dynamicContextProps/dynamicContextProps.cjs');
var primaryWalletId = require('../../store/state/primaryWalletId/primaryWalletId.cjs');
var connectedWalletsInfo = require('../../store/state/connectedWalletsInfo/connectedWalletsInfo.cjs');
var getMissingChains = require('../../utils/functions/getMissingChains/getMissingChains.cjs');
var dynamicEvents = require('../../events/dynamicEvents.cjs');
var useOnboardingCompleteUser = require('../../client/extension/user/useOnboardingCompleteUser/useOnboardingCompleteUser.cjs');
var useUser = require('../../client/extension/user/useUser/useUser.cjs');
var useProjectSettings = require('../../client/extension/projectSettings/useProjectSettings/useProjectSettings.cjs');
var useRefetchProjectSettings = require('../../client/extension/projectSettings/useRefetchProjectSettings/useRefetchProjectSettings.cjs');
require('../../components/Accordion/components/AccordionItem/AccordionItem.cjs');
require('../../components/Alert/Alert.cjs');
require('../../store/state/loadingAndLifecycle/loadingAndLifecycle.cjs');
var authMode = require('../../store/state/authMode/authMode.cjs');
var CaptchaContext = require('../CaptchaContext/CaptchaContext.cjs');
var ErrorContext = require('../ErrorContext/ErrorContext.cjs');
var AccessDeniedContext = require('../AccessDeniedContext/AccessDeniedContext.cjs');
var AccountExistsContext = require('../AccountExistsContext/AccountExistsContext.cjs');
var UserWalletsContext = require('../UserWalletsContext/UserWalletsContext.cjs');
var VerificationContext = require('../VerificationContext/VerificationContext.cjs');
require('react-dom');
require('../../utils/functions/compareChains/compareChains.cjs');
require('../../views/Passkey/utils/findPrimaryEmbeddedChain/findPrimaryEmbeddedChain.cjs');
var ThemeContext = require('../ThemeContext/ThemeContext.cjs');
require('../../utils/hooks/useUserUpdateRequest/useUpdateUser/userFieldsSchema.cjs');
require('bs58');
var useSetWalletConnectorVerifiedCredentials = require('../../utils/hooks/useSetWalletConnectorVerifiedCredentials/useSetWalletConnectorVerifiedCredentials.cjs');
require('@dynamic-labs/types');
var SocialRedirectContext = require('../SocialRedirectContext/SocialRedirectContext.cjs');
var LoadingContext = require('../LoadingContext/LoadingContext.cjs');
var WalletContext = require('../WalletContext/WalletContext.cjs');
require('../../utils/hooks/useEmbeddedWallet/useSecureEnclaveEmbeddedWallet/constants.cjs');
require('yup');
require('../MockContext/MockContext.cjs');
require('../../views/CollectUserDataView/useFields.cjs');
var FieldsStateContext = require('../FieldsStateContext/FieldsStateContext.cjs');
var UserFieldEditorContext = require('../UserFieldEditorContext/UserFieldEditorContext.cjs');
require('@dynamic-labs/rpc-providers');
var useValidateSession = require('../../utils/hooks/useValidateSession/useValidateSession.cjs');
var useCreateWalletConnectorOptions = require('../../utils/hooks/useCreateWalletConnectorOptions/useCreateWalletConnectorOptions.cjs');
var useCreateWalletGroups = require('../../utils/hooks/useCreateWalletGroups/useCreateWalletGroups.cjs');
var useWalletConnectors = require('../../utils/hooks/useWalletConnectors/useWalletConnectors.cjs');
var useWalletUiUtils = require('../../utils/hooks/useWalletUiUtils/useWalletUiUtils.cjs');
var useWalletConnectorNetwork = require('../../utils/hooks/useWalletConnectorNetwork/useWalletConnectorNetwork.cjs');
var useSetWalletConnectorFetchers = require('../../utils/hooks/useSetWalletConnectorFetchers/useSetWalletConnectorFetchers.cjs');
var DynamicWidgetContext = require('../../widgets/DynamicWidget/context/DynamicWidgetContext.cjs');
var useSendDynamicProps = require('../../utils/hooks/useSendDynamicProps/useSendDynamicProps.cjs');
require('../../store/state/tokenBalances.cjs');
require('../../store/state/multichainBalances.cjs');
var WalletGroupContext = require('../WalletGroupContext/WalletGroupContext.cjs');
var walletOptions = require('../../store/state/walletOptions/walletOptions.cjs');
require('../../shared/utils/functions/getInitialUrl/getInitialUrl.cjs');
var useEndUserWarning = require('../../utils/hooks/useEndUserWarning/useEndUserWarning.cjs');
var useDeviceFingerprint = require('../../utils/hooks/useDeviceFingerprint/useDeviceFingerprint.cjs');
var useAggregateWalletEvents = require('../../utils/hooks/useAggregateWalletEvents/useAggregateWalletEvents.cjs');
var useClientSessionKeys = require('../../utils/hooks/useClientSessionKeys/useClientSessionKeys.cjs');
var OnrampContext = require('../OnrampContext/OnrampContext.cjs');
require('../../../index.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');
var IpConfigurationContext = require('../IpConfigurationContext/IpConfigurationContext.cjs');
var ConnectWithOtpProvider = require('../ConnectWithOtpContext/ConnectWithOtpProvider.cjs');
require('../ConnectWithOtpContext/ConnectWithOtpContext.cjs');
require('../../widgets/DynamicBridgeWidget/views/WalletsView/components/SecondaryWallets/SecondaryWallets.cjs');
require('@hcaptcha/react-hcaptcha');
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');
var PasskeyContext = require('../PasskeyContext/PasskeyContext.cjs');
require('../../store/state/sendBalances.cjs');
var useNetworkConfigurationsFromProjectSettings = require('../../utils/hooks/useNetworkConfigurationsFromProjectSettings/useNetworkConfigurationsFromProjectSettings.cjs');
var SyncAuthFlow = require('../../components/SyncAuthFlow/SyncAuthFlow.cjs');
var WalletConnectorEvents = require('../../components/WalletConnectorEvents/WalletConnectorEvents.cjs');
var shouldFetchNonce = require('../../shared/utils/functions/shouldFetchNonce/shouldFetchNonce.cjs');
var store = require('../../store/internalImplementation/store.cjs');
var defaultDynamicSettings = require('../../store/state/dynamicContextProps/defaultDynamicSettings.cjs');
var parseTheme = require('../../utils/functions/parseTheme/parseTheme.cjs');
var useMultiWalletWidgetState = require('../../utils/hooks/multiWallet/useMultiWalletWidgetState/useMultiWalletWidgetState.cjs');
var useClearWalletConnectSessions = require('../../utils/hooks/useClearWalletConnectSessions/useClearWalletConnectSessions.cjs');
var useConnectWallet = require('../../utils/hooks/useConnectWallet/useConnectWallet.cjs');
var useFetchWalletsForChainsMap = require('../../utils/hooks/useFetchWalletsForChainsMap/useFetchWalletsForChainsMap.cjs');
var useGlobalLoading = require('../../utils/hooks/useGlobalLoading/useGlobalLoading.cjs');
var useWalletEventListeners = require('../../utils/hooks/useWalletEventListeners/useWalletEventListeners.cjs');
var useTabState = require('../../views/WalletList/hooks/useTabState.cjs');
var DynamicBridgeWidgetContext = require('../../widgets/DynamicBridgeWidget/context/DynamicBridgeWidgetContext/DynamicBridgeWidgetContext.cjs');
require('../../widgets/DynamicWidget/components/DynamicWidgetCard/DynamicWidgetCard.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('../../widgets/DynamicWidget/views/ReceiveWalletFunds/ReceiveWalletFunds.cjs');
var WidgetRegistryContextProvider = require('../WidgetRegistry/WidgetRegistryContextProvider.cjs');
var OnrampWidget = require('../../widgets/OnrampWidget/OnrampWidget.cjs');
var ErrorBoundary = require('../ErrorBoundary/ErrorBoundary.cjs');
var ErrorBoundaryExclude = require('../ErrorBoundary/ErrorBoundaryExclude.cjs');
require('../ErrorBoundary/ErrorBoundaryBase.cjs');
var PhantomRedirectContext = require('../PhantomRedirectContext/PhantomRedirectContext.cjs');
var ReinitializeContextProvider = require('../ReinitializeContext/ReinitializeContextProvider.cjs');
var SendBalanceContext = require('../SendBalanceContext/SendBalanceContext.cjs');
var UseNetworkValidation = require('../UseNetworkValidation/UseNetworkValidation.cjs');
var onReinitialize = require('./functions/onReinitialize/onReinitialize.cjs');
var helpers = require('./helpers/helpers.cjs');
var useDisplayOrderState = require('./hooks/useDisplayOrderState/useDisplayOrderState.cjs');
var useEmailLoginState = require('./hooks/useEmailLoginState/useEmailLoginState.cjs');
var useHandleLogout = require('./hooks/useHandleLogout/useHandleLogout.cjs');
var useNameService = require('./hooks/useNameService/useNameService.cjs');
var useSelectedWalletConnector = require('./hooks/useSelectedWalletConnector/useSelectedWalletConnector.cjs');
var useShowAuthFlow = require('./hooks/useShowAuthFlow/useShowAuthFlow.cjs');
var usePasskeySuccessPopup = require('./hooks/usePasskeySuccessPopup/usePasskeySuccessPopup.cjs');
var useTieCallbacksToEvents = require('./hooks/useTieCallbacksToEvents/useTieCallbacksToEvents.cjs');
var useMultiWallet = require('./hooks/useMultiWallet/useMultiWallet.cjs');
var useAutoselectPrimaryWallet = require('./hooks/useAutoselectPrimaryWallet/useAutoselectPrimaryWallet.cjs');
var useInitialViewType = require('./hooks/useInitialViewType/useInitialViewType.cjs');
var useMultiAsset = require('./hooks/useMultiAsset/useMultiAsset.cjs');
var useParentDynamicContextGuard = require('./hooks/useParentDynamicContextGuard/useParentDynamicContextGuard.cjs');
var useRegisterStorageService = require('./hooks/useRegisterStorageService/useRegisterStorageService.cjs');
var useRemoveWallet = require('./hooks/useRemoveWallet/useRemoveWallet.cjs');
var useShowDynamicUserProfile = require('./hooks/useShowDynamicUserProfile/useShowDynamicUserProfile.cjs');
var useShowEmbeddedWalletActionsUI = require('./hooks/useShowEmbeddedWalletActionsUI/useShowEmbeddedWalletActionsUI.cjs');
var useShowFiat = require('./hooks/useShowFiat/useShowFiat.cjs');
var useCustomerCallbacks = require('./useCustomerCallbacks/useCustomerCallbacks.cjs');

const PUBLIC_PROJECT_LIVE_ENVIRONMENT_ID = '2762a57b-faa4-41ce-9f16-abff9300e2c9';
const DynamicContext = React.createContext(undefined);
/** The context provider itself we only use internally */
const InnerDynamicContextProvider = (props) => {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s;
    const { children, theme, settings: settings$1, locale: locale$1, enableInstrumentation = false, } = props;
    const { accessDeniedMessagePrimary, accessDeniedMessageSecondary, accessDeniedButton, defaultPhoneInputIso2, coinbaseWalletPreference, detectNewWalletsForLinking = defaultDynamicSettings.defaultDynamicSettings.detectNewWalletsForLinking, enableConnectOnlyFallback = defaultDynamicSettings.defaultDynamicSettings.enableConnectOnlyFallback, deepLinkPreference: deepLinkPreferenceProp = defaultDynamicSettings.defaultDynamicSettings.deepLinkPreference, bridgeChains, cssOverrides, defaultNumberOfWalletsToShow = values.DEFAULT_NUMBER_OF_WALLETS_TO_SHOW, flowNetwork, initialAuthenticationMode = defaultDynamicSettings.defaultDynamicSettings.initialAuthenticationMode, debugError = defaultDynamicSettings.defaultDynamicSettings.debugError, displaySiweStatement = defaultDynamicSettings.defaultDynamicSettings.displaySiweStatement, newToWeb3WalletChainMap, enableVisitTrackingOnConnectOnly = defaultDynamicSettings.defaultDynamicSettings.enableVisitTrackingOnConnectOnly, environmentId, walletsFilter, logLevel = defaultDynamicSettings.defaultDynamicSettings.logLevel, mobileExperience, notInTheListImageUrl, onboardingImageUrl, policiesConsentInnerComponent, customPrivacyPolicy, privacyPolicyUrl, socialMediaLinkText, socialMediaIconUrl, socialMediaUrl, customTermsOfServices, termsOfServiceUrl, siweStatement, shadowDOMEnabled = defaultDynamicSettings.defaultDynamicSettings.shadowDOMEnabled, walletConnectors: walletConnectorsProp, socialProvidersFilter, showLockedWalletView = defaultDynamicSettings.defaultDynamicSettings.showLockedWalletView, walletConnectPreferredChains, walletConnectorExtensions, recommendedWallets, handlers, suppressEndUserConsoleWarning, transactionConfirmation: transactionConfirmationSettings, useMetamaskSdk = defaultDynamicSettings.defaultDynamicSettings.useMetamaskSdk, } = settings$1;
    let { appLogoUrl = defaultDynamicSettings.defaultDynamicSettings.appLogoUrl, appName = defaultDynamicSettings.defaultDynamicSettings.appName, } = settings$1;
    /**
     * initialize Storage
     */
    useRegisterStorageService.useRegisterStorageService({
        storagePostfix: settings$1.localStorageSuffix,
    });
    /**
     * initialize global store
     */
    store.initializeStore(props);
    dynamicContextProps.useSyncDynamicContextProps(props);
    React.useEffect(() => {
        authMode.setAuthMode(initialAuthenticationMode);
    }, [initialAuthenticationMode]);
    /**
     * Sets the chain info overrides if they are present
     */
    walletConnectorCore.setChainInfoOverrides((_a = settings$1.overrides) === null || _a === void 0 ? void 0 : _a.chainDisplayValues);
    const networkValidationMode = helpers.resolveNetworkValidationMode({
        bridgeChains: settings$1.bridgeChains,
        networkValidationMode: settings$1.networkValidationMode,
    });
    if (!environmentId) {
        throw new utils.MissingEnvironmentIdError();
    }
    logger.Logger.setLogLevel(logLevel);
    if (environmentId === PUBLIC_PROJECT_LIVE_ENVIRONMENT_ID) {
        logger$1.logger.warn(`WARNING: DYNAMIC is using a test environment ID ${environmentId}. Please sign up on https://app.dynamic.xyz/ to get your production environment ID.`);
    }
    const i18nSDKInstance = locale.Locale.setup(locale$1);
    const isBridgeFlow = Boolean(bridgeChains);
    const deepLinkPreference = helpers.getDeepLinkPreference(deepLinkPreferenceProp, isBridgeFlow);
    const { selectedTabIndex, setSelectedTabIndex, selectedTabSettings, tabsItems, } = useTabState.useTabState({ settingsOverrides: settings$1.overrides });
    // state to track the full connectivity status of the individual's wallets.
    // Set to true once the predetermined number of wallets is connected.
    const [bridgeOnboardingCompleted, setBridgeOnboardingCompleted, removeBridgeOnboardingCompleted,] = useLocalStorage.useLocalStorage(localStorage.BRIDGE_ONBOARDING_COMPLETED, false);
    const { setShowDynamicUserProfile, showDynamicUserProfile } = useShowDynamicUserProfile.useShowDynamicUserProfile();
    // Allows clients to control the Bridge Widget flow without need to click on Bridge Widget
    const [showBridgeWidget, setShowBridgeWidget] = React.useState(false);
    const [isSingleWalletAccount, setIsSingleWalletAccount] = React.useState(false);
    const userWithMissingInfo = useUser.useUserProfile();
    const user = useOnboardingCompleteUser.useOnboardingCompleteUserProfile();
    if (user) {
        logger.Logger.globalMetaData.set('user', user);
    }
    else {
        logger.Logger.globalMetaData.set('user', undefined);
    }
    // Calculates and stores a device fingerprint
    useDeviceFingerprint.useDeviceFingerprint();
    // Generate client session keys
    useClientSessionKeys.useClientSessionKeys();
    const isAuthenticated = Boolean(user);
    const [qrcodeUri, setQrcodeUri] = React.useState('');
    const [desktopUri, setDesktopUri] = React.useState('');
    const [multiWalletWidgetState, setMultiWalletWidgetState, { awaiting_account_switch: [accountSwitchState], awaiting_signature: [awaitingSignatureState], },] = useMultiWalletWidgetState.useMultiWalletWidgetState();
    const projectSettings = useProjectSettings.useProjectSettings();
    const refetchProjectSettings = useRefetchProjectSettings.useRefetchProjectSettings();
    const serverNetworkConfigurations = useNetworkConfigurationsFromProjectSettings.useNetworkConfigurationsFromProjectSettings({
        aptosNetworksOverrides: (_b = settings$1.overrides) === null || _b === void 0 ? void 0 : _b.aptosNetworks,
        cosmosNetworkOverrides: (_c = settings$1.overrides) === null || _c === void 0 ? void 0 : _c.cosmosNetworks,
        evmNetworksOverrides: (_d = settings$1.overrides) === null || _d === void 0 ? void 0 : _d.evmNetworks,
        projectSettings,
        solanaNetworksOverrides: (_e = settings$1.overrides) === null || _e === void 0 ? void 0 : _e.solNetworks,
        tronNetworksOverrides: (_f = settings$1.overrides) === null || _f === void 0 ? void 0 : _f.tronNetworks,
    });
    useSendDynamicProps.useSendDynamicProps({ environmentId, settings: settings$1 });
    // Console warning for end user safety
    useEndUserWarning.useEndUserWarning({
        projectSettings,
        suppress: suppressEndUserConsoleWarning,
    });
    const multiWallet = useMultiWallet.useMultiWallet({
        isBridgeFlow,
        multiWalletOverride: (_g = settings$1.overrides) === null || _g === void 0 ? void 0 : _g.multiWallet,
        multiWalletSettings: (_h = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.sdk) === null || _h === void 0 ? void 0 : _h.multiWallet,
    });
    const multiAsset = useMultiAsset.useMultiAsset({
        multiAssetOverride: (_j = settings$1.overrides) === null || _j === void 0 ? void 0 : _j.multiAsset,
        multiAssetSettings: (_k = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.sdk) === null || _k === void 0 ? void 0 : _k.enableMultiAsset,
    });
    const showFiat = useShowFiat.useShowFiat({
        showFiatOverride: (_l = settings$1.overrides) === null || _l === void 0 ? void 0 : _l.showFiat,
        showFiatSettings: (_m = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.sdk) === null || _m === void 0 ? void 0 : _m.showFiat,
    });
    // Used inside useVerifyOnAwaitingSignature. Is legacy and should be removed asap
    const [legacyIsVerifying, setLegacyIsVerifying] = React.useState(false);
    const walletBook$1 = walletBook.useWalletBookCdn();
    const { imageUserInAccessList, imageUserNotInAccessList, displayName, appLogo, } = (projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.general) || {};
    appLogoUrl = appLogo || appLogoUrl;
    appName = displayName || appName;
    const [loginWithEmail, setLogInWithEmail, resetLoginWithEmail] = useEmailLoginState.useEmailLoginState((projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.providers) || [], user);
    const [authorizationViewDisplayOrder, setAuthorizationViewDisplayOrder] = useDisplayOrderState.useDisplayOrderState(projectSettings);
    const showEmbeddedWalletActionsUI = useShowEmbeddedWalletActionsUI.useShowEmbeddedWalletActionsUI(transactionConfirmationSettings, projectSettings);
    const [confirmationModal, walletUiUtils] = useWalletUiUtils.useWalletUiUtils({
        hideEmbeddedWalletTransactionUIs: !showEmbeddedWalletActionsUI,
    });
    const connectorProps = React.useMemo(() => ({
        appLogoUrl,
        appName,
        coinbaseWalletPreference,
        deepLinkPreference,
        flowNetwork,
        mobileExperience,
        networkConfigurations: serverNetworkConfigurations,
        projectSettings,
        useMetamaskSdk,
        walletBook: walletBook$1,
        walletConnectPreferredChains,
        walletConnectorExtensions,
        walletConnectorsProp,
        walletUiUtils,
    }), [
        appLogoUrl,
        appName,
        coinbaseWalletPreference,
        deepLinkPreference,
        flowNetwork,
        mobileExperience,
        serverNetworkConfigurations,
        projectSettings,
        useMetamaskSdk,
        walletBook$1,
        walletConnectPreferredChains,
        walletConnectorExtensions,
        walletConnectorsProp,
        walletUiUtils,
    ]);
    useCreateWalletConnectorOptions.useCreateWalletConnectorOptions(connectorProps);
    const walletConnectorOptions = walletOptions.useWalletConnectorOptions();
    useCreateWalletGroups.useCreateWalletGroups({ walletConnectorOptions });
    const primaryWalletId$1 = primaryWalletId.usePrimaryWalletId();
    const authMode$1 = authMode.useAuthMode();
    const [isRenderingEmbeddedAuthFlow, setIsRenderingEmbeddedAuthFlow] = React.useState(false);
    const [showAuthFlow, setShowAuthFlow] = useShowAuthFlow.useShowAuthFlow({
        isMultiWalletEnabled: multiWallet,
        isRenderingEmbeddedAuthFlow,
        setShowDynamicUserProfile,
    });
    const { connectWallet, connectedWalletsInfo: connectedWalletsInfo$1, getConnectedWalletById, connectedWallets, disconnectWallet, refreshConnectedWallet, } = useConnectWallet.useConnectWallet({
        enableVisitTrackingOnConnectOnly,
        environmentId,
        handleConnectedWallet: handlers === null || handlers === void 0 ? void 0 : handlers.handleConnectedWallet,
        isBridgeFlow,
        primaryWalletId: primaryWalletId$1,
        setShowAuthFlow,
        walletConnectorOptions,
    });
    const bridgeChainsToConnect = React.useMemo(() => getMissingChains.getMissingChains(bridgeChains, connectedWalletsInfo$1), [bridgeChains, connectedWalletsInfo$1]);
    const { selectedWalletConnector, setSelectedWalletConnectorKey } = useSelectedWalletConnector.useSelectedWalletConnector({ walletConnectorOptions });
    //selected wallet to perform an action (become primary, unlink, etc)
    const [selectedWalletWithAction, setSelectedWalletWithAction] = React.useState(null);
    useSetWalletConnectorVerifiedCredentials.useSetWalletConnectorVerifiedCredentials(user !== null && user !== void 0 ? user : userWithMissingInfo, walletConnectorOptions);
    useSetWalletConnectorFetchers.useSetWalletConnectorFetchers(walletConnectorOptions, environmentId, projectSettings);
    const { primaryWallet, showQrcodeModal, secondaryWallets, setPrimaryWallet, setShowQrcodeModal, wallets: linkedOrConnectedWallets, } = useWalletConnectors.useWalletConnectors({
        canHaveMultipleWalletsConnected: multiWallet,
        connectedWallets,
        primaryWalletId: primaryWalletId$1,
        separateSmartWalletAndSigner: (_p = (_o = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.sdk) === null || _o === void 0 ? void 0 : _o.accountAbstraction) === null || _p === void 0 ? void 0 : _p.separateSmartWalletAndSigner,
        setMultiWalletWidgetState,
        user: user || userWithMissingInfo,
        walletConnectorOptions,
    });
    useAutoselectPrimaryWallet.useAutoselectPrimaryWallet(isBridgeFlow);
    const walletConnectors = React.useMemo(() => linkedOrConnectedWallets.map((wallet) => wallet.connector), [linkedOrConnectedWallets]);
    nonce.useFetchNonce({
        shouldFetch: shouldFetchNonce.shouldFetchNonce({ authMode: authMode$1 }),
    });
    const { getNameService, removeConnectedNameService } = useNameService.useNameService({
        currentWallet: primaryWallet !== null && primaryWallet !== void 0 ? primaryWallet : connectedWallets[0],
        user,
    });
    const { clearAllWalletConnectSessions } = useClearWalletConnectSessions.useClearWalletConnectSessions({
        connectors: walletConnectors,
    });
    const removeSessionStorageSessionKeys = () => {
        utils.tracing.logEvent('session-key', 'removeSessionStorageSessionKeys');
        utils.StorageService.removeItem(localStorage.SECURE_ENCLAVE_WALLET_SESSION_KEYS, localStorage.SECURE_ENCLAVE_WALLET_SESSION_KEYS_STORAGE_OPTIONS);
        walletConnectors.forEach((connector) => {
            if (walletConnectorCore.isSessionKeyCompatibleWalletConnector(connector) &&
                typeof (connector === null || connector === void 0 ? void 0 : connector.removeSessionKeys) === 'function') {
                connector === null || connector === void 0 ? void 0 : connector.removeSessionKeys();
            }
        });
    };
    const handleLogOut = useHandleLogout.useHandleLogout({
        bridgeChains,
        clearAllWalletConnectSessions,
        connectedWallets,
        environmentId,
        events: settings$1.events,
        initialAuthenticationMode,
        removeBridgeOnboardingCompleted,
        removeConnectedNameService,
        removeSessionStorageSessionKeys,
        resetLoginWithEmail,
        setLegacyIsVerifying,
        setMultiWalletWidgetState,
        setSelectedWalletConnectorKey,
        setShowAuthFlow,
        setShowBridgeWidget,
        setShowDynamicUserProfile,
        user,
        walletConnectors,
    });
    useValidateSession.useValidateSession({
        environmentId,
        handleLogOut,
    });
    // For some reason, calling useNonce in useGlobalLoading causes errors
    const nonce$1 = nonce.useNonce();
    const sdkHasLoaded = useGlobalLoading.useGlobalLoading({
        appName,
        connectedInfo: connectedWalletsInfo$1[0],
        connectedWallets,
        enableInstrumentation,
        environmentId,
        nonce: nonce$1,
        primaryWallet,
        primaryWalletId: primaryWalletId$1,
        projectSettings,
        user: user !== null && user !== void 0 ? user : userWithMissingInfo,
        walletBook: walletBook$1,
    });
    // Ties all client callbacks to dynamic's events, such that
    // when our events are triggered, so are the client callbacks
    useTieCallbacksToEvents.useTieCallbacksToEvents({
        clientCallbacks: settings$1.events,
        user,
    });
    const removeWallet = useRemoveWallet.useRemoveWallet({
        handleLogOut,
        secondaryWallets,
        setPrimaryWallet,
    });
    const { isLoading: loadingNetwork, network } = useWalletConnectorNetwork.useWalletConnectorNetwork(primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.connector, {
        onChange: (newNetwork) => {
            if (newNetwork) {
                dynamicEvents.dynamicEvents.emit('primaryWalletNetworkChanged', newNetwork);
            }
        },
    });
    useAggregateWalletEvents.useAggregateWalletEvents();
    useWalletEventListeners.useWalletEventListeners({
        detectNewWalletsForLinking,
        disconnectWallet,
        handleLogOut,
        multiWallet,
        multiWalletWidgetState,
        primaryWallet,
        refreshConnectedWallet,
        secondaryWallets,
        selectedWalletConnector,
        selectedWalletWithAction,
        setMultiWalletWidgetState,
        setSelectedWalletConnectorKey,
        setSelectedWalletWithAction,
        user,
    });
    const { walletsForChainsMap } = useFetchWalletsForChainsMap.useFetchWalletsForChainsMap(newToWeb3WalletChainMap);
    const { setCallback } = useCustomerCallbacks.useCustomerCallbacks({
        callbacks: {
            onAuthSuccess: (_q = settings$1.events) === null || _q === void 0 ? void 0 : _q.onAuthSuccess,
            onUserProfileUpdate: (_r = settings$1.events) === null || _r === void 0 ? void 0 : _r.onUserProfileUpdate,
        },
        handleLogOut,
        isAuthenticated,
        primaryWallet,
        user,
    });
    const sendWagmiSettings = React.useCallback(() => (settings$1) => {
        const { dynamicWagmiSettings } = settings$1;
        if (dynamicWagmiSettings) {
            settings.sendDynamicProps(environmentId, {
                dynamicWagmiSettings: { dynamicWagmiSettings },
            });
        }
    }, [environmentId]);
    const clearStatesOnBackClick = React.useCallback(() => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        setDesktopUri('');
        setLegacyIsVerifying(false);
        if (!user) {
            clearAllWalletConnectSessions();
        }
        setMultiWalletWidgetState('idle');
        if (authMode$1 !== 'connect-only') {
            connectedWalletsInfo.resetConnectedWalletsInfo();
        }
        if (utils.StorageService.getItem(localStorage.WALLET_PICKER_SEARCH_KEY)) {
            utils.StorageService.removeItem(localStorage.WALLET_PICKER_SEARCH_KEY);
        }
        if (utils.StorageService.getItem(localStorage.EXCHANGE_PICKER_SEARCH_KEY)) {
            utils.StorageService.removeItem(localStorage.EXCHANGE_PICKER_SEARCH_KEY);
        }
        utils.StorageService.removeItem(localStorage.PHANTOM_SIGNATURE_STATE);
        if (selectedWalletConnector &&
            (!primaryWallet ||
                primaryWallet.connector.key !== selectedWalletConnector.key)) {
            yield (selectedWalletConnector === null || selectedWalletConnector === void 0 ? void 0 : selectedWalletConnector.endSession());
        }
    }), [
        user,
        setMultiWalletWidgetState,
        authMode$1,
        selectedWalletConnector,
        primaryWallet,
        clearAllWalletConnectSessions,
    ]);
    const { passkeySuccessPopup, setPasskeySuccessPopup } = usePasskeySuccessPopup.usePasskeySuccessPopup();
    const memoizedLocale = React.useMemo(() => ({
        changeLanguage: locale.Locale.getInstance().changeLanguage,
    }), []);
    const linkedWallets = React.useMemo(() => authMode$1 === 'connect-only' || !user ? [] : linkedOrConnectedWallets, [authMode$1, linkedOrConnectedWallets, user]);
    const value = React.useMemo(() => {
        var _a;
        return ({
            accessDeniedButton,
            accessDeniedMessagePrimary,
            accessDeniedMessageSecondary,
            accountSwitchState,
            appLogoUrl,
            appName,
            authorizationViewDisplayOrder,
            awaitingSignatureState,
            bridgeChains,
            bridgeChainsToConnect,
            bridgeOnboardingCompleted,
            clearStatesOnBackClick,
            connectWallet,
            connectedWallets,
            cssOverrides,
            customPrivacyPolicy,
            customTermsOfServices,
            debugError,
            defaultNumberOfWalletsToShow,
            defaultPhoneInputIso2,
            desktopUri,
            detectNewWalletsForLinking,
            disconnectWallet,
            displaySiweStatement,
            enableConnectOnlyFallback,
            environmentId,
            events: settings$1.events,
            getConnectedWalletById,
            getNameService,
            handleLogOut,
            handlers,
            i18nSDKInstance,
            isBridgeFlow,
            isRenderingEmbeddedAuthFlow,
            isSingleWalletAccount,
            legacyIsVerifying,
            linkedWallets,
            loadingNetwork,
            locale: memoizedLocale,
            loginWithEmail,
            multiAsset,
            multiWallet,
            multiWalletWidgetState,
            network,
            networkConfigurations: serverNetworkConfigurations,
            networkValidationMode,
            newToWeb3WalletChainMap: walletsForChainsMap,
            notInTheListImageUrl: imageUserNotInAccessList || notInTheListImageUrl,
            onboardingImageUrl: imageUserInAccessList || onboardingImageUrl,
            overrides: settings$1.overrides,
            passkeySuccessPopup,
            policiesConsentInnerComponent,
            primaryWallet,
            primaryWalletId: primaryWalletId$1,
            privacyPolicyUrl,
            projectSettings,
            qrcodeUri,
            recommendedWallets,
            redirectUrl: settings$1.redirectUrl,
            refetchProjectSettings,
            removeBridgeOnboardingCompleted,
            removeWallet,
            sdkHasLoaded,
            secondaryWallets,
            selectedTabIndex,
            selectedTabSettings,
            selectedWalletConnector,
            selectedWalletWithAction,
            sendWagmiSettings,
            setAuthorizationViewDisplayOrder,
            setBridgeOnboardingCompleted,
            setCallback,
            setDesktopUri,
            setIsRenderingEmbeddedAuthFlow,
            setIsSingleWalletAccount,
            setLegacyIsVerifying,
            setLogInWithEmail,
            setMultiWalletWidgetState,
            setPasskeySuccessPopup,
            setPrimaryWallet,
            setQrcodeUri,
            setSelectedTabIndex,
            setSelectedWalletConnectorKey,
            setSelectedWalletWithAction,
            setShowAuthFlow,
            setShowBridgeWidget,
            setShowDynamicUserProfile,
            setShowQrcodeModal,
            shadowDOMEnabled,
            showAuthFlow,
            showBridgeWidget,
            showDynamicUserProfile,
            showFiat,
            showLockedWalletView,
            showQrcodeModal,
            siweStatement,
            socialMediaIconUrl: ((_a = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.general) === null || _a === void 0 ? void 0 : _a.supportUrls) || socialMediaIconUrl,
            socialMediaLinkText,
            socialMediaUrl,
            socialProvidersFilter,
            socialSettings: settings$1.social,
            tabsItems,
            termsOfServiceUrl,
            theme,
            user,
            userWithMissingInfo,
            walletConnectorOptions,
            walletUiUtils,
            walletsFilter,
        });
    }, [
        accessDeniedButton,
        accessDeniedMessagePrimary,
        accessDeniedMessageSecondary,
        accountSwitchState,
        appLogoUrl,
        appName,
        authorizationViewDisplayOrder,
        awaitingSignatureState,
        bridgeChains,
        bridgeChainsToConnect,
        bridgeOnboardingCompleted,
        clearStatesOnBackClick,
        connectWallet,
        connectedWallets,
        cssOverrides,
        customPrivacyPolicy,
        customTermsOfServices,
        debugError,
        defaultNumberOfWalletsToShow,
        defaultPhoneInputIso2,
        desktopUri,
        detectNewWalletsForLinking,
        disconnectWallet,
        displaySiweStatement,
        enableConnectOnlyFallback,
        environmentId,
        settings$1.events,
        settings$1.overrides,
        settings$1.redirectUrl,
        settings$1.social,
        getConnectedWalletById,
        getNameService,
        handleLogOut,
        removeWallet,
        handlers,
        i18nSDKInstance,
        isBridgeFlow,
        isRenderingEmbeddedAuthFlow,
        isSingleWalletAccount,
        legacyIsVerifying,
        linkedWallets,
        loadingNetwork,
        memoizedLocale,
        loginWithEmail,
        multiAsset,
        multiWallet,
        multiWalletWidgetState,
        network,
        serverNetworkConfigurations,
        networkValidationMode,
        walletsForChainsMap,
        imageUserNotInAccessList,
        notInTheListImageUrl,
        imageUserInAccessList,
        onboardingImageUrl,
        passkeySuccessPopup,
        policiesConsentInnerComponent,
        primaryWallet,
        primaryWalletId$1,
        privacyPolicyUrl,
        projectSettings,
        qrcodeUri,
        recommendedWallets,
        refetchProjectSettings,
        removeBridgeOnboardingCompleted,
        sdkHasLoaded,
        secondaryWallets,
        selectedTabIndex,
        selectedTabSettings,
        selectedWalletConnector,
        selectedWalletWithAction,
        sendWagmiSettings,
        setAuthorizationViewDisplayOrder,
        setBridgeOnboardingCompleted,
        setCallback,
        setLogInWithEmail,
        setMultiWalletWidgetState,
        setPasskeySuccessPopup,
        setPrimaryWallet,
        setSelectedTabIndex,
        setSelectedWalletConnectorKey,
        setShowAuthFlow,
        setShowDynamicUserProfile,
        setShowQrcodeModal,
        shadowDOMEnabled,
        showAuthFlow,
        showBridgeWidget,
        showDynamicUserProfile,
        showFiat,
        showLockedWalletView,
        showQrcodeModal,
        siweStatement,
        socialMediaIconUrl,
        socialMediaLinkText,
        socialMediaUrl,
        socialProvidersFilter,
        tabsItems,
        termsOfServiceUrl,
        theme,
        user,
        userWithMissingInfo,
        walletConnectorOptions,
        walletUiUtils,
        walletsFilter,
    ]);
    usePrefetch.usePrefetch({
        as: 'image',
        href: iconic.getIconicSpriteUrl(),
        id: 'sprite',
        type: 'image/svg+xml',
    });
    usePrefetch.usePrefetch({
        as: 'fetch',
        href: walletBook.getWalletBookCdnUrl(),
        id: 'wallet-book',
        type: 'application/json',
    });
    const initialViewType = useInitialViewType.useInitialViewType({
        bridgeOnboardingCompleted,
        connectedWallets,
        isAuthenticated: isAuthenticated || Boolean(primaryWallet),
        isBridgeFlow,
        isMultiWalletEnabled: multiWallet,
    });
    return (jsxRuntime.jsx(reactI18next.I18nextProvider, { i18n: i18nSDKInstance, children: jsxRuntime.jsx(DynamicContext.Provider, { value: value, children: jsxRuntime.jsx(walletBook.WalletBookContextProvider, { walletBook: walletBook$1, children: jsxRuntime.jsx(ThemeContext.ThemeContextProvider, { customerTheme: parseTheme.parseTheme(theme, ((_s = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.design) === null || _s === void 0 ? void 0 : _s.modal) || undefined), designSettings: projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.design, children: jsxRuntime.jsx(LoadingContext.LoadingContextProvider, { children: jsxRuntime.jsxs(ViewContext.ViewContextProvider, { initialViewType: initialViewType, children: [networkValidationMode === 'always' && jsxRuntime.jsx(UseNetworkValidation.UseNetworkValidation, {}), jsxRuntime.jsx(CaptchaContext.CaptchaContextProvider, { children: jsxRuntime.jsx(AccountExistsContext.AccountExistsContextProvider, { children: jsxRuntime.jsx(WalletContext.WalletContextProvider, { children: jsxRuntime.jsx(VerificationContext.VerificationProvider, { children: jsxRuntime.jsx(PasskeyContext.PasskeyContextProvider, { children: jsxRuntime.jsx(DynamicWidgetContext.DynamicWidgetContextProvider, { children: jsxRuntime.jsx(DynamicBridgeWidgetContext.DynamicBridgeWidgetContextProvider, { children: jsxRuntime.jsx(OnrampContext.OnrampContextProvider, { children: jsxRuntime.jsx(AccessDeniedContext.AccessDeniedContextProvider, { children: jsxRuntime.jsx(SendBalanceContext.SendBalanceContextProvider, { children: jsxRuntime.jsx(WalletGroupContext.WalletGroupContextProvider, { children: jsxRuntime.jsx(UserFieldEditorContext.UserFieldEditorContextProvider, { children: jsxRuntime.jsx(ConnectWithOtpProvider.ConnectWithOtpProvider, { children: jsxRuntime.jsx(PhantomRedirectContext.PhantomRedirectContextProvider, { children: jsxRuntime.jsxs(SocialRedirectContext.SocialRedirectContextProvider, { children: [jsxRuntime.jsx(app.DynamicAuthFlow, {}), jsxRuntime.jsx(OnrampWidget.OnrampWidget, {}), jsxRuntime.jsx(SyncAuthFlow.SyncAuthFlow, {}), jsxRuntime.jsx(WalletConnectorEvents.WalletConnectorEvents, { connectorProps: connectorProps }), confirmationModal, jsxRuntime.jsx(ErrorBoundaryExclude.ErrorBoundaryExclude, { children: children })] }) }) }) }) }) }) }) }) }) }) }) }) }) }) })] }) }) }) }) }) }));
};
/** The context provider you need to have access too all of Dynamic's hooks */
const DynamicContextProvider = (props) => {
    const apiBaseUrlOverride = utils.getEnvVarWithFallback('DYNAMIC_API_BASE_URL', props.settings.apiBaseUrl || '');
    ApiEndpoint.setBaseUrl(apiBaseUrlOverride);
    // Initialize client before anything else
    useInitializeSdkClient.useInitializeSdkClient(props);
    logger.Logger.setEnvironmentId(props.settings.environmentId);
    logger.Logger.setEmitErrors(props.emitErrors);
    useParentDynamicContextGuard.useParentDynamicContextGuard();
    return (jsxRuntime.jsx(ReinitializeContextProvider.ReinitializeContextProvider, { onReinitialize: onReinitialize.onReinitialize, children: jsxRuntime.jsx(ErrorBoundary.ErrorBoundary, { children: jsxRuntime.jsx(ErrorContext.ErrorContextProvider, { children: jsxRuntime.jsx(UserWalletsContext.UserWalletsProvider, { children: jsxRuntime.jsx(FieldsStateContext.FieldsStateProvider, { children: jsxRuntime.jsx(IpConfigurationContext.IpConfigurationContextProvider, { children: jsxRuntime.jsx(WidgetRegistryContextProvider.WidgetRegistryContextProvider, { children: jsxRuntime.jsx(InnerDynamicContextProvider, Object.assign({}, props)) }) }) }) }) }) }) }));
};

exports.DynamicContext = DynamicContext;
exports.DynamicContextProvider = DynamicContextProvider;
exports.InnerDynamicContextProvider = InnerDynamicContextProvider;
exports.PUBLIC_PROJECT_LIVE_ENVIRONMENT_ID = PUBLIC_PROJECT_LIVE_ENVIRONMENT_ID;
