'use client'
import { __awaiter } from '../../../../_virtual/_tslib.js';
import { jsx, jsxs } from 'react/jsx-runtime';
import { createContext, useEffect, useState, useMemo, useCallback } from 'react';
import { I18nextProvider } from 'react-i18next';
import { getIconicSpriteUrl } from '@dynamic-labs/iconic';
import { Logger } from '@dynamic-labs/logger';
import { getEnvVarWithFallback, MissingEnvironmentIdError, StorageService, tracing } from '@dynamic-labs/utils';
import { useWalletBookCdn, getWalletBookCdnUrl, WalletBookContextProvider } from '@dynamic-labs/wallet-book';
import { setChainInfoOverrides, isSessionKeyCompatibleWalletConnector } from '@dynamic-labs/wallet-connector-core';
import { Locale } from '@dynamic-labs/locale';
import { DynamicAuthFlow } from '../../app.js';
import '@dynamic-labs-sdk/client/core';
import '@dynamic-labs/sdk-api-core';
import '../../client/client.js';
import '@dynamic-labs-sdk/client';
import { useInitializeSdkClient } from '../../client/extension/hooks/useInitializeSdkClient/useInitializeSdkClient.js';
import { DEFAULT_NUMBER_OF_WALLETS_TO_SHOW } from '../../utils/constants/values.js';
import '@dynamic-labs/multi-wallet';
import 'react-international-phone';
import { BRIDGE_ONBOARDING_COMPLETED, WALLET_PICKER_SEARCH_KEY, EXCHANGE_PICKER_SEARCH_KEY, PHANTOM_SIGNATURE_STATE, SECURE_ENCLAVE_WALLET_SESSION_KEYS, SECURE_ENCLAVE_WALLET_SESSION_KEYS_STORAGE_OPTIONS } from '../../utils/constants/localStorage.js';
import '../../utils/constants/colors.js';
import { ViewContextProvider } from '../ViewContext/ViewContext.js';
import { logger } from '../../shared/logger.js';
import { useLocalStorage } from '../../shared/utils/hooks/useLocalStorage/useLocalStorage.js';
import { usePrefetch } from '../../shared/utils/hooks/usePrefetch/usePrefetch.js';
import '../../shared/consts/index.js';
import { useFetchNonce, useNonce } from '../../store/state/nonce/nonce.js';
import ApiEndpoint from '../../config/ApiEndpoint.js';
import { sendDynamicProps } from '../../data/api/settings/settings.js';
import { useSyncDynamicContextProps } from '../../store/state/dynamicContextProps/dynamicContextProps.js';
import { usePrimaryWalletId } from '../../store/state/primaryWalletId/primaryWalletId.js';
import { resetConnectedWalletsInfo } from '../../store/state/connectedWalletsInfo/connectedWalletsInfo.js';
import { getMissingChains } from '../../utils/functions/getMissingChains/getMissingChains.js';
import { dynamicEvents } from '../../events/dynamicEvents.js';
import { useOnboardingCompleteUserProfile } from '../../client/extension/user/useOnboardingCompleteUser/useOnboardingCompleteUser.js';
import { useUserProfile } from '../../client/extension/user/useUser/useUser.js';
import { useProjectSettings } from '../../client/extension/projectSettings/useProjectSettings/useProjectSettings.js';
import { useRefetchProjectSettings } from '../../client/extension/projectSettings/useRefetchProjectSettings/useRefetchProjectSettings.js';
import '../../components/Accordion/components/AccordionItem/AccordionItem.js';
import '../../components/Alert/Alert.js';
import '../../store/state/loadingAndLifecycle/loadingAndLifecycle.js';
import { setAuthMode, useAuthMode } from '../../store/state/authMode/authMode.js';
import { CaptchaContextProvider } from '../CaptchaContext/CaptchaContext.js';
import { ErrorContextProvider } from '../ErrorContext/ErrorContext.js';
import { AccessDeniedContextProvider } from '../AccessDeniedContext/AccessDeniedContext.js';
import { AccountExistsContextProvider } from '../AccountExistsContext/AccountExistsContext.js';
import { UserWalletsProvider } from '../UserWalletsContext/UserWalletsContext.js';
import { VerificationProvider } from '../VerificationContext/VerificationContext.js';
import 'react-dom';
import '../../utils/functions/compareChains/compareChains.js';
import '../../views/Passkey/utils/findPrimaryEmbeddedChain/findPrimaryEmbeddedChain.js';
import { ThemeContextProvider } from '../ThemeContext/ThemeContext.js';
import '../../utils/hooks/useUserUpdateRequest/useUpdateUser/userFieldsSchema.js';
import 'bs58';
import { useSetWalletConnectorVerifiedCredentials } from '../../utils/hooks/useSetWalletConnectorVerifiedCredentials/useSetWalletConnectorVerifiedCredentials.js';
import '@dynamic-labs/types';
import { SocialRedirectContextProvider } from '../SocialRedirectContext/SocialRedirectContext.js';
import { LoadingContextProvider } from '../LoadingContext/LoadingContext.js';
import { WalletContextProvider } from '../WalletContext/WalletContext.js';
import '../../utils/hooks/useEmbeddedWallet/useSecureEnclaveEmbeddedWallet/constants.js';
import 'yup';
import '../MockContext/MockContext.js';
import '../../views/CollectUserDataView/useFields.js';
import { FieldsStateProvider } from '../FieldsStateContext/FieldsStateContext.js';
import { UserFieldEditorContextProvider } from '../UserFieldEditorContext/UserFieldEditorContext.js';
import '@dynamic-labs/rpc-providers';
import { useValidateSession } from '../../utils/hooks/useValidateSession/useValidateSession.js';
import { useCreateWalletConnectorOptions } from '../../utils/hooks/useCreateWalletConnectorOptions/useCreateWalletConnectorOptions.js';
import { useCreateWalletGroups } from '../../utils/hooks/useCreateWalletGroups/useCreateWalletGroups.js';
import { useWalletConnectors } from '../../utils/hooks/useWalletConnectors/useWalletConnectors.js';
import { useWalletUiUtils } from '../../utils/hooks/useWalletUiUtils/useWalletUiUtils.js';
import { useWalletConnectorNetwork } from '../../utils/hooks/useWalletConnectorNetwork/useWalletConnectorNetwork.js';
import { useSetWalletConnectorFetchers } from '../../utils/hooks/useSetWalletConnectorFetchers/useSetWalletConnectorFetchers.js';
import { DynamicWidgetContextProvider } from '../../widgets/DynamicWidget/context/DynamicWidgetContext.js';
import { useSendDynamicProps } from '../../utils/hooks/useSendDynamicProps/useSendDynamicProps.js';
import '../../store/state/tokenBalances.js';
import '../../store/state/multichainBalances.js';
import { WalletGroupContextProvider } from '../WalletGroupContext/WalletGroupContext.js';
import { useWalletConnectorOptions } from '../../store/state/walletOptions/walletOptions.js';
import '../../shared/utils/functions/getInitialUrl/getInitialUrl.js';
import { useEndUserWarning } from '../../utils/hooks/useEndUserWarning/useEndUserWarning.js';
import { useDeviceFingerprint } from '../../utils/hooks/useDeviceFingerprint/useDeviceFingerprint.js';
import { useAggregateWalletEvents } from '../../utils/hooks/useAggregateWalletEvents/useAggregateWalletEvents.js';
import { useClientSessionKeys } from '../../utils/hooks/useClientSessionKeys/useClientSessionKeys.js';
import { OnrampContextProvider } from '../OnrampContext/OnrampContext.js';
import '../../../index.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 { IpConfigurationContextProvider } from '../IpConfigurationContext/IpConfigurationContext.js';
import { ConnectWithOtpProvider } from '../ConnectWithOtpContext/ConnectWithOtpProvider.js';
import '../ConnectWithOtpContext/ConnectWithOtpContext.js';
import '../../widgets/DynamicBridgeWidget/views/WalletsView/components/SecondaryWallets/SecondaryWallets.js';
import '@hcaptcha/react-hcaptcha';
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 { PasskeyContextProvider } from '../PasskeyContext/PasskeyContext.js';
import '../../store/state/sendBalances.js';
import { useNetworkConfigurationsFromProjectSettings } from '../../utils/hooks/useNetworkConfigurationsFromProjectSettings/useNetworkConfigurationsFromProjectSettings.js';
import { SyncAuthFlow } from '../../components/SyncAuthFlow/SyncAuthFlow.js';
import { WalletConnectorEvents } from '../../components/WalletConnectorEvents/WalletConnectorEvents.js';
import { shouldFetchNonce } from '../../shared/utils/functions/shouldFetchNonce/shouldFetchNonce.js';
import { initializeStore } from '../../store/internalImplementation/store.js';
import { defaultDynamicSettings } from '../../store/state/dynamicContextProps/defaultDynamicSettings.js';
import { parseTheme } from '../../utils/functions/parseTheme/parseTheme.js';
import { useMultiWalletWidgetState } from '../../utils/hooks/multiWallet/useMultiWalletWidgetState/useMultiWalletWidgetState.js';
import { useClearWalletConnectSessions } from '../../utils/hooks/useClearWalletConnectSessions/useClearWalletConnectSessions.js';
import { useConnectWallet } from '../../utils/hooks/useConnectWallet/useConnectWallet.js';
import { useFetchWalletsForChainsMap } from '../../utils/hooks/useFetchWalletsForChainsMap/useFetchWalletsForChainsMap.js';
import { useGlobalLoading } from '../../utils/hooks/useGlobalLoading/useGlobalLoading.js';
import { useWalletEventListeners } from '../../utils/hooks/useWalletEventListeners/useWalletEventListeners.js';
import { useTabState } from '../../views/WalletList/hooks/useTabState.js';
import { DynamicBridgeWidgetContextProvider } from '../../widgets/DynamicBridgeWidget/context/DynamicBridgeWidgetContext/DynamicBridgeWidgetContext.js';
import '../../widgets/DynamicWidget/components/DynamicWidgetCard/DynamicWidgetCard.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 '../../widgets/DynamicWidget/views/ReceiveWalletFunds/ReceiveWalletFunds.js';
import { WidgetRegistryContextProvider } from '../WidgetRegistry/WidgetRegistryContextProvider.js';
import { OnrampWidget } from '../../widgets/OnrampWidget/OnrampWidget.js';
import { ErrorBoundary } from '../ErrorBoundary/ErrorBoundary.js';
import { ErrorBoundaryExclude } from '../ErrorBoundary/ErrorBoundaryExclude.js';
import '../ErrorBoundary/ErrorBoundaryBase.js';
import { PhantomRedirectContextProvider } from '../PhantomRedirectContext/PhantomRedirectContext.js';
import { ReinitializeContextProvider } from '../ReinitializeContext/ReinitializeContextProvider.js';
import { SendBalanceContextProvider } from '../SendBalanceContext/SendBalanceContext.js';
import { UseNetworkValidation } from '../UseNetworkValidation/UseNetworkValidation.js';
import { onReinitialize } from './functions/onReinitialize/onReinitialize.js';
import { resolveNetworkValidationMode, getDeepLinkPreference } from './helpers/helpers.js';
import { useDisplayOrderState } from './hooks/useDisplayOrderState/useDisplayOrderState.js';
import { useEmailLoginState } from './hooks/useEmailLoginState/useEmailLoginState.js';
import { useHandleLogout } from './hooks/useHandleLogout/useHandleLogout.js';
import { useNameService } from './hooks/useNameService/useNameService.js';
import { useSelectedWalletConnector } from './hooks/useSelectedWalletConnector/useSelectedWalletConnector.js';
import { useShowAuthFlow } from './hooks/useShowAuthFlow/useShowAuthFlow.js';
import { usePasskeySuccessPopup } from './hooks/usePasskeySuccessPopup/usePasskeySuccessPopup.js';
import { useTieCallbacksToEvents } from './hooks/useTieCallbacksToEvents/useTieCallbacksToEvents.js';
import { useMultiWallet } from './hooks/useMultiWallet/useMultiWallet.js';
import { useAutoselectPrimaryWallet } from './hooks/useAutoselectPrimaryWallet/useAutoselectPrimaryWallet.js';
import { useInitialViewType } from './hooks/useInitialViewType/useInitialViewType.js';
import { useMultiAsset } from './hooks/useMultiAsset/useMultiAsset.js';
import { useParentDynamicContextGuard } from './hooks/useParentDynamicContextGuard/useParentDynamicContextGuard.js';
import { useRegisterStorageService } from './hooks/useRegisterStorageService/useRegisterStorageService.js';
import { useRemoveWallet } from './hooks/useRemoveWallet/useRemoveWallet.js';
import { useShowDynamicUserProfile } from './hooks/useShowDynamicUserProfile/useShowDynamicUserProfile.js';
import { useShowEmbeddedWalletActionsUI } from './hooks/useShowEmbeddedWalletActionsUI/useShowEmbeddedWalletActionsUI.js';
import { useShowFiat } from './hooks/useShowFiat/useShowFiat.js';
import { useCustomerCallbacks } from './useCustomerCallbacks/useCustomerCallbacks.js';

const PUBLIC_PROJECT_LIVE_ENVIRONMENT_ID = '2762a57b-faa4-41ce-9f16-abff9300e2c9';
const DynamicContext = 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, locale, enableInstrumentation = false, } = props;
    const { accessDeniedMessagePrimary, accessDeniedMessageSecondary, accessDeniedButton, defaultPhoneInputIso2, coinbaseWalletPreference, detectNewWalletsForLinking = defaultDynamicSettings.detectNewWalletsForLinking, enableConnectOnlyFallback = defaultDynamicSettings.enableConnectOnlyFallback, deepLinkPreference: deepLinkPreferenceProp = defaultDynamicSettings.deepLinkPreference, bridgeChains, cssOverrides, defaultNumberOfWalletsToShow = DEFAULT_NUMBER_OF_WALLETS_TO_SHOW, flowNetwork, initialAuthenticationMode = defaultDynamicSettings.initialAuthenticationMode, debugError = defaultDynamicSettings.debugError, displaySiweStatement = defaultDynamicSettings.displaySiweStatement, newToWeb3WalletChainMap, enableVisitTrackingOnConnectOnly = defaultDynamicSettings.enableVisitTrackingOnConnectOnly, environmentId, walletsFilter, logLevel = defaultDynamicSettings.logLevel, mobileExperience, notInTheListImageUrl, onboardingImageUrl, policiesConsentInnerComponent, customPrivacyPolicy, privacyPolicyUrl, socialMediaLinkText, socialMediaIconUrl, socialMediaUrl, customTermsOfServices, termsOfServiceUrl, siweStatement, shadowDOMEnabled = defaultDynamicSettings.shadowDOMEnabled, walletConnectors: walletConnectorsProp, socialProvidersFilter, showLockedWalletView = defaultDynamicSettings.showLockedWalletView, walletConnectPreferredChains, walletConnectorExtensions, recommendedWallets, handlers, suppressEndUserConsoleWarning, transactionConfirmation: transactionConfirmationSettings, useMetamaskSdk = defaultDynamicSettings.useMetamaskSdk, } = settings;
    let { appLogoUrl = defaultDynamicSettings.appLogoUrl, appName = defaultDynamicSettings.appName, } = settings;
    /**
     * initialize Storage
     */
    useRegisterStorageService({
        storagePostfix: settings.localStorageSuffix,
    });
    /**
     * initialize global store
     */
    initializeStore(props);
    useSyncDynamicContextProps(props);
    useEffect(() => {
        setAuthMode(initialAuthenticationMode);
    }, [initialAuthenticationMode]);
    /**
     * Sets the chain info overrides if they are present
     */
    setChainInfoOverrides((_a = settings.overrides) === null || _a === void 0 ? void 0 : _a.chainDisplayValues);
    const networkValidationMode = resolveNetworkValidationMode({
        bridgeChains: settings.bridgeChains,
        networkValidationMode: settings.networkValidationMode,
    });
    if (!environmentId) {
        throw new MissingEnvironmentIdError();
    }
    Logger.setLogLevel(logLevel);
    if (environmentId === PUBLIC_PROJECT_LIVE_ENVIRONMENT_ID) {
        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.setup(locale);
    const isBridgeFlow = Boolean(bridgeChains);
    const deepLinkPreference = getDeepLinkPreference(deepLinkPreferenceProp, isBridgeFlow);
    const { selectedTabIndex, setSelectedTabIndex, selectedTabSettings, tabsItems, } = useTabState({ settingsOverrides: settings.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(BRIDGE_ONBOARDING_COMPLETED, false);
    const { setShowDynamicUserProfile, showDynamicUserProfile } = useShowDynamicUserProfile();
    // Allows clients to control the Bridge Widget flow without need to click on Bridge Widget
    const [showBridgeWidget, setShowBridgeWidget] = useState(false);
    const [isSingleWalletAccount, setIsSingleWalletAccount] = useState(false);
    const userWithMissingInfo = useUserProfile();
    const user = useOnboardingCompleteUserProfile();
    if (user) {
        Logger.globalMetaData.set('user', user);
    }
    else {
        Logger.globalMetaData.set('user', undefined);
    }
    // Calculates and stores a device fingerprint
    useDeviceFingerprint();
    // Generate client session keys
    useClientSessionKeys();
    const isAuthenticated = Boolean(user);
    const [qrcodeUri, setQrcodeUri] = useState('');
    const [desktopUri, setDesktopUri] = useState('');
    const [multiWalletWidgetState, setMultiWalletWidgetState, { awaiting_account_switch: [accountSwitchState], awaiting_signature: [awaitingSignatureState], },] = useMultiWalletWidgetState();
    const projectSettings = useProjectSettings();
    const refetchProjectSettings = useRefetchProjectSettings();
    const serverNetworkConfigurations = useNetworkConfigurationsFromProjectSettings({
        aptosNetworksOverrides: (_b = settings.overrides) === null || _b === void 0 ? void 0 : _b.aptosNetworks,
        cosmosNetworkOverrides: (_c = settings.overrides) === null || _c === void 0 ? void 0 : _c.cosmosNetworks,
        evmNetworksOverrides: (_d = settings.overrides) === null || _d === void 0 ? void 0 : _d.evmNetworks,
        projectSettings,
        solanaNetworksOverrides: (_e = settings.overrides) === null || _e === void 0 ? void 0 : _e.solNetworks,
        tronNetworksOverrides: (_f = settings.overrides) === null || _f === void 0 ? void 0 : _f.tronNetworks,
    });
    useSendDynamicProps({ environmentId, settings });
    // Console warning for end user safety
    useEndUserWarning({
        projectSettings,
        suppress: suppressEndUserConsoleWarning,
    });
    const multiWallet = useMultiWallet({
        isBridgeFlow,
        multiWalletOverride: (_g = settings.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({
        multiAssetOverride: (_j = settings.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({
        showFiatOverride: (_l = settings.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] = useState(false);
    const 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((projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.providers) || [], user);
    const [authorizationViewDisplayOrder, setAuthorizationViewDisplayOrder] = useDisplayOrderState(projectSettings);
    const showEmbeddedWalletActionsUI = useShowEmbeddedWalletActionsUI(transactionConfirmationSettings, projectSettings);
    const [confirmationModal, walletUiUtils] = useWalletUiUtils({
        hideEmbeddedWalletTransactionUIs: !showEmbeddedWalletActionsUI,
    });
    const connectorProps = useMemo(() => ({
        appLogoUrl,
        appName,
        coinbaseWalletPreference,
        deepLinkPreference,
        flowNetwork,
        mobileExperience,
        networkConfigurations: serverNetworkConfigurations,
        projectSettings,
        useMetamaskSdk,
        walletBook,
        walletConnectPreferredChains,
        walletConnectorExtensions,
        walletConnectorsProp,
        walletUiUtils,
    }), [
        appLogoUrl,
        appName,
        coinbaseWalletPreference,
        deepLinkPreference,
        flowNetwork,
        mobileExperience,
        serverNetworkConfigurations,
        projectSettings,
        useMetamaskSdk,
        walletBook,
        walletConnectPreferredChains,
        walletConnectorExtensions,
        walletConnectorsProp,
        walletUiUtils,
    ]);
    useCreateWalletConnectorOptions(connectorProps);
    const walletConnectorOptions = useWalletConnectorOptions();
    useCreateWalletGroups({ walletConnectorOptions });
    const primaryWalletId = usePrimaryWalletId();
    const authMode = useAuthMode();
    const [isRenderingEmbeddedAuthFlow, setIsRenderingEmbeddedAuthFlow] = useState(false);
    const [showAuthFlow, setShowAuthFlow] = useShowAuthFlow({
        isMultiWalletEnabled: multiWallet,
        isRenderingEmbeddedAuthFlow,
        setShowDynamicUserProfile,
    });
    const { connectWallet, connectedWalletsInfo, getConnectedWalletById, connectedWallets, disconnectWallet, refreshConnectedWallet, } = useConnectWallet({
        enableVisitTrackingOnConnectOnly,
        environmentId,
        handleConnectedWallet: handlers === null || handlers === void 0 ? void 0 : handlers.handleConnectedWallet,
        isBridgeFlow,
        primaryWalletId,
        setShowAuthFlow,
        walletConnectorOptions,
    });
    const bridgeChainsToConnect = useMemo(() => getMissingChains(bridgeChains, connectedWalletsInfo), [bridgeChains, connectedWalletsInfo]);
    const { selectedWalletConnector, setSelectedWalletConnectorKey } = useSelectedWalletConnector({ walletConnectorOptions });
    //selected wallet to perform an action (become primary, unlink, etc)
    const [selectedWalletWithAction, setSelectedWalletWithAction] = useState(null);
    useSetWalletConnectorVerifiedCredentials(user !== null && user !== void 0 ? user : userWithMissingInfo, walletConnectorOptions);
    useSetWalletConnectorFetchers(walletConnectorOptions, environmentId, projectSettings);
    const { primaryWallet, showQrcodeModal, secondaryWallets, setPrimaryWallet, setShowQrcodeModal, wallets: linkedOrConnectedWallets, } = useWalletConnectors({
        canHaveMultipleWalletsConnected: multiWallet,
        connectedWallets,
        primaryWalletId,
        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(isBridgeFlow);
    const walletConnectors = useMemo(() => linkedOrConnectedWallets.map((wallet) => wallet.connector), [linkedOrConnectedWallets]);
    useFetchNonce({
        shouldFetch: shouldFetchNonce({ authMode }),
    });
    const { getNameService, removeConnectedNameService } = useNameService({
        currentWallet: primaryWallet !== null && primaryWallet !== void 0 ? primaryWallet : connectedWallets[0],
        user,
    });
    const { clearAllWalletConnectSessions } = useClearWalletConnectSessions({
        connectors: walletConnectors,
    });
    const removeSessionStorageSessionKeys = () => {
        tracing.logEvent('session-key', 'removeSessionStorageSessionKeys');
        StorageService.removeItem(SECURE_ENCLAVE_WALLET_SESSION_KEYS, SECURE_ENCLAVE_WALLET_SESSION_KEYS_STORAGE_OPTIONS);
        walletConnectors.forEach((connector) => {
            if (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({
        bridgeChains,
        clearAllWalletConnectSessions,
        connectedWallets,
        environmentId,
        events: settings.events,
        initialAuthenticationMode,
        removeBridgeOnboardingCompleted,
        removeConnectedNameService,
        removeSessionStorageSessionKeys,
        resetLoginWithEmail,
        setLegacyIsVerifying,
        setMultiWalletWidgetState,
        setSelectedWalletConnectorKey,
        setShowAuthFlow,
        setShowBridgeWidget,
        setShowDynamicUserProfile,
        user,
        walletConnectors,
    });
    useValidateSession({
        environmentId,
        handleLogOut,
    });
    // For some reason, calling useNonce in useGlobalLoading causes errors
    const nonce = useNonce();
    const sdkHasLoaded = useGlobalLoading({
        appName,
        connectedInfo: connectedWalletsInfo[0],
        connectedWallets,
        enableInstrumentation,
        environmentId,
        nonce,
        primaryWallet,
        primaryWalletId,
        projectSettings,
        user: user !== null && user !== void 0 ? user : userWithMissingInfo,
        walletBook,
    });
    // Ties all client callbacks to dynamic's events, such that
    // when our events are triggered, so are the client callbacks
    useTieCallbacksToEvents({
        clientCallbacks: settings.events,
        user,
    });
    const removeWallet = useRemoveWallet({
        handleLogOut,
        secondaryWallets,
        setPrimaryWallet,
    });
    const { isLoading: loadingNetwork, network } = useWalletConnectorNetwork(primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.connector, {
        onChange: (newNetwork) => {
            if (newNetwork) {
                dynamicEvents.emit('primaryWalletNetworkChanged', newNetwork);
            }
        },
    });
    useAggregateWalletEvents();
    useWalletEventListeners({
        detectNewWalletsForLinking,
        disconnectWallet,
        handleLogOut,
        multiWallet,
        multiWalletWidgetState,
        primaryWallet,
        refreshConnectedWallet,
        secondaryWallets,
        selectedWalletConnector,
        selectedWalletWithAction,
        setMultiWalletWidgetState,
        setSelectedWalletConnectorKey,
        setSelectedWalletWithAction,
        user,
    });
    const { walletsForChainsMap } = useFetchWalletsForChainsMap(newToWeb3WalletChainMap);
    const { setCallback } = useCustomerCallbacks({
        callbacks: {
            onAuthSuccess: (_q = settings.events) === null || _q === void 0 ? void 0 : _q.onAuthSuccess,
            onUserProfileUpdate: (_r = settings.events) === null || _r === void 0 ? void 0 : _r.onUserProfileUpdate,
        },
        handleLogOut,
        isAuthenticated,
        primaryWallet,
        user,
    });
    const sendWagmiSettings = useCallback(() => (settings) => {
        const { dynamicWagmiSettings } = settings;
        if (dynamicWagmiSettings) {
            sendDynamicProps(environmentId, {
                dynamicWagmiSettings: { dynamicWagmiSettings },
            });
        }
    }, [environmentId]);
    const clearStatesOnBackClick = useCallback(() => __awaiter(void 0, void 0, void 0, function* () {
        setDesktopUri('');
        setLegacyIsVerifying(false);
        if (!user) {
            clearAllWalletConnectSessions();
        }
        setMultiWalletWidgetState('idle');
        if (authMode !== 'connect-only') {
            resetConnectedWalletsInfo();
        }
        if (StorageService.getItem(WALLET_PICKER_SEARCH_KEY)) {
            StorageService.removeItem(WALLET_PICKER_SEARCH_KEY);
        }
        if (StorageService.getItem(EXCHANGE_PICKER_SEARCH_KEY)) {
            StorageService.removeItem(EXCHANGE_PICKER_SEARCH_KEY);
        }
        StorageService.removeItem(PHANTOM_SIGNATURE_STATE);
        if (selectedWalletConnector &&
            (!primaryWallet ||
                primaryWallet.connector.key !== selectedWalletConnector.key)) {
            yield (selectedWalletConnector === null || selectedWalletConnector === void 0 ? void 0 : selectedWalletConnector.endSession());
        }
    }), [
        user,
        setMultiWalletWidgetState,
        authMode,
        selectedWalletConnector,
        primaryWallet,
        clearAllWalletConnectSessions,
    ]);
    const { passkeySuccessPopup, setPasskeySuccessPopup } = usePasskeySuccessPopup();
    const memoizedLocale = useMemo(() => ({
        changeLanguage: Locale.getInstance().changeLanguage,
    }), []);
    const linkedWallets = useMemo(() => authMode === 'connect-only' || !user ? [] : linkedOrConnectedWallets, [authMode, linkedOrConnectedWallets, user]);
    const value = 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.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.overrides,
            passkeySuccessPopup,
            policiesConsentInnerComponent,
            primaryWallet,
            primaryWalletId,
            privacyPolicyUrl,
            projectSettings,
            qrcodeUri,
            recommendedWallets,
            redirectUrl: settings.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.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.events,
        settings.overrides,
        settings.redirectUrl,
        settings.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,
        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({
        as: 'image',
        href: getIconicSpriteUrl(),
        id: 'sprite',
        type: 'image/svg+xml',
    });
    usePrefetch({
        as: 'fetch',
        href: getWalletBookCdnUrl(),
        id: 'wallet-book',
        type: 'application/json',
    });
    const initialViewType = useInitialViewType({
        bridgeOnboardingCompleted,
        connectedWallets,
        isAuthenticated: isAuthenticated || Boolean(primaryWallet),
        isBridgeFlow,
        isMultiWalletEnabled: multiWallet,
    });
    return (jsx(I18nextProvider, { i18n: i18nSDKInstance, children: jsx(DynamicContext.Provider, { value: value, children: jsx(WalletBookContextProvider, { walletBook: walletBook, children: jsx(ThemeContextProvider, { customerTheme: 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: jsx(LoadingContextProvider, { children: jsxs(ViewContextProvider, { initialViewType: initialViewType, children: [networkValidationMode === 'always' && jsx(UseNetworkValidation, {}), jsx(CaptchaContextProvider, { children: jsx(AccountExistsContextProvider, { children: jsx(WalletContextProvider, { children: jsx(VerificationProvider, { children: jsx(PasskeyContextProvider, { children: jsx(DynamicWidgetContextProvider, { children: jsx(DynamicBridgeWidgetContextProvider, { children: jsx(OnrampContextProvider, { children: jsx(AccessDeniedContextProvider, { children: jsx(SendBalanceContextProvider, { children: jsx(WalletGroupContextProvider, { children: jsx(UserFieldEditorContextProvider, { children: jsx(ConnectWithOtpProvider, { children: jsx(PhantomRedirectContextProvider, { children: jsxs(SocialRedirectContextProvider, { children: [jsx(DynamicAuthFlow, {}), jsx(OnrampWidget, {}), jsx(SyncAuthFlow, {}), jsx(WalletConnectorEvents, { connectorProps: connectorProps }), confirmationModal, jsx(ErrorBoundaryExclude, { children: children })] }) }) }) }) }) }) }) }) }) }) }) }) }) }) })] }) }) }) }) }) }));
};
/** The context provider you need to have access too all of Dynamic's hooks */
const DynamicContextProvider = (props) => {
    const apiBaseUrlOverride = getEnvVarWithFallback('DYNAMIC_API_BASE_URL', props.settings.apiBaseUrl || '');
    ApiEndpoint.setBaseUrl(apiBaseUrlOverride);
    // Initialize client before anything else
    useInitializeSdkClient(props);
    Logger.setEnvironmentId(props.settings.environmentId);
    Logger.setEmitErrors(props.emitErrors);
    useParentDynamicContextGuard();
    return (jsx(ReinitializeContextProvider, { onReinitialize: onReinitialize, children: jsx(ErrorBoundary, { children: jsx(ErrorContextProvider, { children: jsx(UserWalletsProvider, { children: jsx(FieldsStateProvider, { children: jsx(IpConfigurationContextProvider, { children: jsx(WidgetRegistryContextProvider, { children: jsx(InnerDynamicContextProvider, Object.assign({}, props)) }) }) }) }) }) }) }));
};

export { DynamicContext, DynamicContextProvider, InnerDynamicContextProvider, PUBLIC_PROJECT_LIVE_ENVIRONMENT_ID };
