'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 utils = require('@dynamic-labs/utils');
require('./components/Accordion/components/AccordionItem/AccordionItem.cjs');
require('react-i18next');
require('@dynamic-labs/iconic');
var ViewContext = require('./context/ViewContext/ViewContext.cjs');
require('@dynamic-labs/wallet-connector-core');
require('./shared/logger.cjs');
require('@dynamic-labs/wallet-book');
var localStorage = require('./utils/constants/localStorage.cjs');
require('./utils/constants/colors.cjs');
require('./utils/constants/values.cjs');
require('@dynamic-labs/sdk-api-core');
var usePreventPageScroll = require('./shared/utils/hooks/usePreventPageScroll/usePreventPageScroll.cjs');
var index$1 = require('./shared/consts/index.cjs');
require('./components/Alert/Alert.cjs');
var dynamicEvents = require('./events/dynamicEvents.cjs');
require('./context/DynamicContext/useDynamicContext/useDynamicContext.cjs');
var useInternalDynamicContext = require('./context/DynamicContext/useDynamicContext/useInternalDynamicContext/useInternalDynamicContext.cjs');
require('./context/CaptchaContext/CaptchaContext.cjs');
require('./context/ErrorContext/ErrorContext.cjs');
require('@dynamic-labs/multi-wallet');
require('react-international-phone');
require('./store/state/nonce/nonce.cjs');
var isSupportedNetwork = require('./utils/functions/isSupportedNetwork/isSupportedNetwork.cjs');
require('@dynamic-labs-wallet/browser-wallet-client');
require('@dynamic-labs-sdk/client/core');
require('eventemitter3');
require('@dynamic-labs-sdk/client');
require('./config/ApiEndpoint.cjs');
require('@dynamic-labs/locale');
require('./store/state/dynamicContextProps/dynamicContextProps.cjs');
require('./store/state/primaryWalletId/primaryWalletId.cjs');
require('./store/state/connectedWalletsInfo/connectedWalletsInfo.cjs');
require('./utils/functions/getWaasAddressTypeLabel/getWaasAddressTypeLabel.cjs');
var AccessDeniedContext = require('./context/AccessDeniedContext/AccessDeniedContext.cjs');
var AccountExistsContext = require('./context/AccountExistsContext/AccountExistsContext.cjs');
var UserWalletsContext = require('./context/UserWalletsContext/UserWalletsContext.cjs');
require('./store/state/authMode/authMode.cjs');
var isConnectOnly = require('./utils/hooks/authenticationHooks/helpers/isConnectOnly.cjs');
require('./store/state/loadingAndLifecycle/loadingAndLifecycle.cjs');
require('./context/VerificationContext/VerificationContext.cjs');
require('react-dom');
require('./utils/functions/compareChains/compareChains.cjs');
require('./views/Passkey/utils/findPrimaryEmbeddedChain/findPrimaryEmbeddedChain.cjs');
require('./context/ThemeContext/ThemeContext.cjs');
require('./utils/hooks/useUserUpdateRequest/useUpdateUser/userFieldsSchema.cjs');
require('bs58');
require('@dynamic-labs/types');
var SocialRedirectContext = require('./context/SocialRedirectContext/SocialRedirectContext.cjs');
require('./context/LoadingContext/LoadingContext.cjs');
require('./context/WalletContext/WalletContext.cjs');
require('./utils/hooks/useEmbeddedWallet/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');
var useWalletItemActions = require('./utils/hooks/useWalletItemActions/useWalletItemActions.cjs');
var DynamicAuthModal = require('./modals/DynamicAuthModal/DynamicAuthModal.cjs');
require('./components/IconButton/IconButton.cjs');
require('formik');
require('./store/state/sendBalances.cjs');
require('./components/Input/Input.cjs');
require('./components/OverlayCard/OverlayCard.cjs');
require('./components/MenuList/Dropdown/Dropdown.cjs');
require('./components/Transition/ZoomTransition/ZoomTransition.cjs');
require('./components/Transition/SlideInUpTransition/SlideInUpTransition.cjs');
require('./components/Transition/OpacityTransition/OpacityTransition.cjs');
require('./views/TransactionConfirmationView/TransactionConfirmationView.cjs');
require('./context/PasskeyContext/PasskeyContext.cjs');
require('../index.cjs');
require('./components/ShadowDOM/ShadowDOM.cjs');
require('./utils/hooks/useSubdomainCheck/useSubdomainCheck.cjs');
require('./context/WalletGroupContext/WalletGroupContext.cjs');
require('./widgets/DynamicWidget/context/DynamicWidgetContext.cjs');
require('./utils/hooks/useGetMfaToken/useGetMfaToken.cjs');
require('./utils/hooks/useWalletBackup/useWalletBackup.cjs');
require('./utils/hooks/useWalletBackup/BackupError.cjs');
require('./utils/hooks/useWalletBackup/types.cjs');
require('./utils/hooks/useWalletBackup/cloudProviders.cjs');
require('@hcaptcha/react-hcaptcha');
require('@marsidev/react-turnstile');
require('./context/IpConfigurationContext/IpConfigurationContext.cjs');
require('./context/ConnectWithOtpContext/ConnectWithOtpContext.cjs');
require('./widgets/DynamicBridgeWidget/views/WalletsView/components/SecondaryWallets/SecondaryWallets.cjs');
require('./widgets/DynamicWidget/helpers/convertExchangeKeyAndProviderEnum.cjs');
require('./views/ExchangeWhitelistWarning/ExchangeWhitelistWarning.cjs');
require('./context/ErrorContext/hooks/useErrorText/useErrorText.cjs');
var index = require('./context/FooterAnimationContext/index.cjs');
require('./views/MfaChooseDeviceView/useGetMfaOptions/useGetMfaOptions.cjs');
require('./components/PasskeyCreatedSuccessBanner/PasskeyCreatedSuccessBanner.cjs');
require('./context/OnrampContext/OnrampContext.cjs');
require('./utils/hooks/useWalletDelegation/DelegationError.cjs');
require('./store/state/connectorsInitializing/connectorsInitializing.cjs');
require('./store/state/tokenBalances.cjs');
require('./store/state/multichainBalances.cjs');
require('@dynamic-labs/store');
require('./shared/utils/functions/getInitialUrl/getInitialUrl.cjs');
var isSelectedWalletAlreadyConnected = require('./utils/functions/isSelectedWalletAlreadyConnected/isSelectedWalletAlreadyConnected.cjs');
require('./components/InlineWidget/InlineWidget.cjs');
require('./components/IsBrowser/IsBrowser.cjs');
require('./components/Popper/Popper/Popper.cjs');
var PopperContext = require('./components/Popper/PopperContext/PopperContext.cjs');
var Portal = require('./components/Portal/Portal.cjs');
require('qrcode');
var RenderView = require('./components/RenderView/RenderView.cjs');
var useVerifyOnAwaitingSignature = require('./utils/hooks/multiWallet/useVerifyOnAwaitingSignature/useVerifyOnAwaitingSignature.cjs');

const viewsToDisableCloseOnOverlayClick = [
    'email-wallet-otp-verification-view',
    'social-redirect-view',
    'passkey-intro',
    'setup-password-for-wallet-creation',
    'mfa-display-backup-codes',
];
// Embedded-wallet reveal/export views are pushed during a step-up flow and can
// be wiped by a stale portal-exit unmount when a step-up reauth closes right as
// the export re-opens the flow (iOS handoff race). These are the only views the
// unmount reset must preserve; every other flow resets normally.
const viewsToPreserveOnReopen = [
    'embedded-reveal-view',
    'embedded-reveal-account-view',
];
const Main = () => {
    const { selectedWalletConnector, linkedWallets, projectSettings, setShowAuthFlow, showAuthFlow, walletConnectorOptions, clearStatesOnBackClick, user, disconnectWallet, connectedWallets, handleLogOutWithReason, } = useInternalDynamicContext.useInternalDynamicContext();
    const { view, clearStackAndPushInitialView } = ViewContext.useViewContext();
    const { setDeniedAddress, setDeniedOauthProvider } = AccessDeniedContext.useAccessDeniedContext();
    const { setExistentAccountData } = AccountExistsContext.useAccountExistsContext();
    const { setSocialProvider } = SocialRedirectContext.useSocialRedirectContext();
    usePreventPageScroll.usePreventPageScroll(showAuthFlow);
    const { userWallets } = UserWalletsContext.useInternalUserWallets();
    const handleClose = () => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        var _a;
        if (viewsToDisableCloseOnOverlayClick.includes(view.type))
            return;
        if ((_a = view.events) === null || _a === void 0 ? void 0 : _a.onClose) {
            view.events.onClose();
            return;
        }
        if ((view.type === 'network-not-supported' ||
            view.type === 'network-not-supported-manual') &&
            userWallets.length === 1) {
            yield handleLogOutWithReason('network-unsupported');
        }
        if (view.type === 'farcaster-connect-view') {
            setSocialProvider(undefined);
            dynamicEvents.dynamicEvents.emit('farcasterConnectCancelled');
        }
        setShowAuthFlow(false, { emitCancelAuth: true });
        setDeniedAddress('');
        setDeniedOauthProvider(undefined);
        setExistentAccountData(undefined);
        clearStatesOnBackClick();
    });
    const handleOnPortalExiting = React.useCallback(() => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        // In the connect only mode (default and bridge)
        // We want to disconnect wallet when users closes `network not supported` view
        // without updating network in wallet
        // We use onExiting instead onUnmount to avoid jump effect in inline widget
        const viewsToDisconnectWalletOnClose = [
            'network-not-supported',
            'network-not-supported-manual',
        ];
        if (!isConnectOnly.isConnectOnly() ||
            !viewsToDisconnectWalletOnClose.includes(view.type) ||
            !selectedWalletConnector)
            return;
        const walletByConnectorKey = connectedWallets.find((connectedWallet) => connectedWallet.connector.key === selectedWalletConnector.key);
        if (!walletByConnectorKey) {
            return;
        }
        // Validate the network
        if (!isSupportedNetwork.isSupportedNetwork({
            network: yield walletByConnectorKey.connector.getNetwork(true),
            walletConnector: walletByConnectorKey.connector,
        })) {
            disconnectWallet(walletByConnectorKey.id);
        }
    }), [selectedWalletConnector, connectedWallets, disconnectWallet, view]);
    // Always-current values so the portal's exit-transition unmount callback
    // (which may be invoked with a stale closure) reads the live state.
    const showAuthFlowRef = React.useRef(showAuthFlow);
    showAuthFlowRef.current = showAuthFlow;
    // Optional chaining: `view` can be undefined in some render/test contexts, and
    // this runs during render (unlike the callbacks below, which read it lazily).
    const viewTypeRef = React.useRef(view === null || view === void 0 ? void 0 : view.type);
    viewTypeRef.current = view === null || view === void 0 ? void 0 : view.type;
    const handleOnPortalUnmount = React.useCallback(() => {
        // IMPORTANT: we need to reset the view because we reset state that the view depends on
        // so if the previous view renders when the user reopens the widget, it will crash.
        // BUT: when an embedded-wallet reveal/export view is active and the flow is (re-)open,
        // a stale exit-transition unmount (step-up reauth closing right as the export re-opens
        // the flow — an iOS handoff race) would wipe the freshly-pushed export view back to the
        // root "connect/link wallet" list. Preserve ONLY those views; every other flow (e.g.
        // delegated-access "Done") must still reset normally.
        const currentViewType = viewTypeRef.current;
        if (showAuthFlowRef.current &&
            currentViewType !== undefined &&
            viewsToPreserveOnReopen.includes(currentViewType)) {
            return;
        }
        clearStackAndPushInitialView();
    }, [clearStackAndPushInitialView]);
    useVerifyOnAwaitingSignature.useVerifyOnAwaitingSignature();
    const { handleAlreadyConnectedWallet, handleCustodialWalletClick, handleInstalledExtensionClick, handleMobileWalletClick, handleUninstalledClick, } = useWalletItemActions.useWalletItemActions();
    /* istanbul ignore next */
    const handleNewToWeb3WalletIntent = (walletConnector) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        setShowAuthFlow(true);
        if (isSelectedWalletAlreadyConnected.isSelectedWalletAlreadyConnected(linkedWallets, walletConnector, user)) {
            // wallet is already connected
            handleAlreadyConnectedWallet(walletConnector);
        }
        else if (walletConnector.canConnectViaCustodialService) {
            // providers like blocto and dapper
            handleCustodialWalletClick(walletConnector);
        }
        else if (utils.isMobile()) {
            // mobile wallets
            handleMobileWalletClick(walletConnector);
        }
        else if (walletConnector.isInstalledOnBrowser()) {
            // browser extensions or injected wallets
            handleInstalledExtensionClick(walletConnector);
        }
        else {
            // wallet requiring a qr code (wallet connect/coinbase wallet)
            handleUninstalledClick(walletConnector);
        }
    });
    React.useEffect(() => {
        const newToWeb3WalletKey = utils.StorageService.getItem(localStorage.NEWTOWEB3_WALLET_EXTENSION_FLAG_KEY);
        if ((walletConnectorOptions === null || walletConnectorOptions === void 0 ? void 0 : walletConnectorOptions.length) && newToWeb3WalletKey) {
            const wallet = walletConnectorOptions.find((wallet) => wallet.key === newToWeb3WalletKey);
            if (wallet === null || wallet === void 0 ? void 0 : wallet.walletConnector) {
                handleNewToWeb3WalletIntent(wallet.walletConnector);
            }
            utils.StorageService.removeItem(localStorage.NEWTOWEB3_WALLET_EXTENSION_FLAG_KEY);
        }
    }, [walletConnectorOptions]);
    const showDynamicAuth = showAuthFlow && Boolean(projectSettings);
    return (jsxRuntime.jsx(index.FooterAnimationContextProvider, { children: jsxRuntime.jsx(Portal.Portal, { zIndex: index$1.authModalZIndex, isShown: showDynamicAuth, handleClose: handleClose, withBackdrop: true, transitionEvents: {
                onExiting: handleOnPortalExiting,
                onUnmount: handleOnPortalUnmount,
            }, children: jsxRuntime.jsx(PopperContext.PopperProvider, { children: jsxRuntime.jsx(DynamicAuthModal.DynamicAuthModal, { transitionProps: {
                        isShown: showDynamicAuth,
                    }, onClose: handleClose, projectSettings: projectSettings, children: jsxRuntime.jsx(RenderView.RenderView, {}) }) }) }) }));
};

exports.Main = Main;
exports["default"] = Main;
