'use client'
import { __awaiter } from '../../_virtual/_tslib.js';
import { jsx } from 'react/jsx-runtime';
import { useCallback, useRef, useEffect } from 'react';
import { StorageService, isMobile } from '@dynamic-labs/utils';
import './components/Accordion/components/AccordionItem/AccordionItem.js';
import 'react-i18next';
import '@dynamic-labs/iconic';
import { useViewContext } from './context/ViewContext/ViewContext.js';
import '@dynamic-labs/wallet-connector-core';
import './shared/logger.js';
import '@dynamic-labs/wallet-book';
import { NEWTOWEB3_WALLET_EXTENSION_FLAG_KEY } from './utils/constants/localStorage.js';
import './utils/constants/colors.js';
import './utils/constants/values.js';
import '@dynamic-labs/sdk-api-core';
import { usePreventPageScroll } from './shared/utils/hooks/usePreventPageScroll/usePreventPageScroll.js';
import { authModalZIndex } from './shared/consts/index.js';
import './components/Alert/Alert.js';
import { dynamicEvents } from './events/dynamicEvents.js';
import './context/DynamicContext/useDynamicContext/useDynamicContext.js';
import { useInternalDynamicContext } from './context/DynamicContext/useDynamicContext/useInternalDynamicContext/useInternalDynamicContext.js';
import './context/CaptchaContext/CaptchaContext.js';
import './context/ErrorContext/ErrorContext.js';
import '@dynamic-labs/multi-wallet';
import 'react-international-phone';
import './store/state/nonce/nonce.js';
import { isSupportedNetwork } from './utils/functions/isSupportedNetwork/isSupportedNetwork.js';
import '@dynamic-labs-wallet/browser-wallet-client';
import '@dynamic-labs-sdk/client/core';
import 'eventemitter3';
import '@dynamic-labs-sdk/client';
import './config/ApiEndpoint.js';
import '@dynamic-labs/locale';
import './store/state/dynamicContextProps/dynamicContextProps.js';
import './store/state/primaryWalletId/primaryWalletId.js';
import './store/state/connectedWalletsInfo/connectedWalletsInfo.js';
import './utils/functions/getWaasAddressTypeLabel/getWaasAddressTypeLabel.js';
import { useAccessDeniedContext } from './context/AccessDeniedContext/AccessDeniedContext.js';
import { useAccountExistsContext } from './context/AccountExistsContext/AccountExistsContext.js';
import { useInternalUserWallets } from './context/UserWalletsContext/UserWalletsContext.js';
import './store/state/authMode/authMode.js';
import { isConnectOnly } from './utils/hooks/authenticationHooks/helpers/isConnectOnly.js';
import './store/state/loadingAndLifecycle/loadingAndLifecycle.js';
import './context/VerificationContext/VerificationContext.js';
import 'react-dom';
import './utils/functions/compareChains/compareChains.js';
import './views/Passkey/utils/findPrimaryEmbeddedChain/findPrimaryEmbeddedChain.js';
import './context/ThemeContext/ThemeContext.js';
import './utils/hooks/useUserUpdateRequest/useUpdateUser/userFieldsSchema.js';
import 'bs58';
import '@dynamic-labs/types';
import { useSocialRedirectContext } from './context/SocialRedirectContext/SocialRedirectContext.js';
import './context/LoadingContext/LoadingContext.js';
import './context/WalletContext/WalletContext.js';
import './utils/hooks/useEmbeddedWallet/useSecureEnclaveEmbeddedWallet/constants.js';
import 'yup';
import './context/MockContext/MockContext.js';
import './views/CollectUserDataView/useFields.js';
import './context/FieldsStateContext/FieldsStateContext.js';
import './context/UserFieldEditorContext/UserFieldEditorContext.js';
import '@dynamic-labs/rpc-providers';
import './store/state/walletOptions/walletOptions.js';
import { useWalletItemActions } from './utils/hooks/useWalletItemActions/useWalletItemActions.js';
import { DynamicAuthModal } from './modals/DynamicAuthModal/DynamicAuthModal.js';
import './components/IconButton/IconButton.js';
import 'formik';
import './store/state/sendBalances.js';
import './components/Input/Input.js';
import './components/OverlayCard/OverlayCard.js';
import './components/MenuList/Dropdown/Dropdown.js';
import './components/Transition/ZoomTransition/ZoomTransition.js';
import './components/Transition/SlideInUpTransition/SlideInUpTransition.js';
import './components/Transition/OpacityTransition/OpacityTransition.js';
import './views/TransactionConfirmationView/TransactionConfirmationView.js';
import './context/PasskeyContext/PasskeyContext.js';
import '../index.js';
import './components/ShadowDOM/ShadowDOM.js';
import './utils/hooks/useSubdomainCheck/useSubdomainCheck.js';
import './context/WalletGroupContext/WalletGroupContext.js';
import './widgets/DynamicWidget/context/DynamicWidgetContext.js';
import './utils/hooks/useGetMfaToken/useGetMfaToken.js';
import './utils/hooks/useWalletBackup/useWalletBackup.js';
import './utils/hooks/useWalletBackup/BackupError.js';
import './utils/hooks/useWalletBackup/types.js';
import './utils/hooks/useWalletBackup/cloudProviders.js';
import '@hcaptcha/react-hcaptcha';
import '@marsidev/react-turnstile';
import './context/IpConfigurationContext/IpConfigurationContext.js';
import './context/ConnectWithOtpContext/ConnectWithOtpContext.js';
import './widgets/DynamicBridgeWidget/views/WalletsView/components/SecondaryWallets/SecondaryWallets.js';
import './widgets/DynamicWidget/helpers/convertExchangeKeyAndProviderEnum.js';
import './views/ExchangeWhitelistWarning/ExchangeWhitelistWarning.js';
import './context/ErrorContext/hooks/useErrorText/useErrorText.js';
import { FooterAnimationContextProvider } from './context/FooterAnimationContext/index.js';
import './views/MfaChooseDeviceView/useGetMfaOptions/useGetMfaOptions.js';
import './components/PasskeyCreatedSuccessBanner/PasskeyCreatedSuccessBanner.js';
import './context/OnrampContext/OnrampContext.js';
import './utils/hooks/useWalletDelegation/DelegationError.js';
import './store/state/connectorsInitializing/connectorsInitializing.js';
import './store/state/tokenBalances.js';
import './store/state/multichainBalances.js';
import '@dynamic-labs/store';
import './shared/utils/functions/getInitialUrl/getInitialUrl.js';
import { isSelectedWalletAlreadyConnected } from './utils/functions/isSelectedWalletAlreadyConnected/isSelectedWalletAlreadyConnected.js';
import './components/InlineWidget/InlineWidget.js';
import './components/IsBrowser/IsBrowser.js';
import './components/Popper/Popper/Popper.js';
import { PopperProvider } from './components/Popper/PopperContext/PopperContext.js';
import { Portal } from './components/Portal/Portal.js';
import 'qrcode';
import { RenderView } from './components/RenderView/RenderView.js';
import { useVerifyOnAwaitingSignature } from './utils/hooks/multiWallet/useVerifyOnAwaitingSignature/useVerifyOnAwaitingSignature.js';

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();
    const { view, clearStackAndPushInitialView } = useViewContext();
    const { setDeniedAddress, setDeniedOauthProvider } = useAccessDeniedContext();
    const { setExistentAccountData } = useAccountExistsContext();
    const { setSocialProvider } = useSocialRedirectContext();
    usePreventPageScroll(showAuthFlow);
    const { userWallets } = useInternalUserWallets();
    const handleClose = () => __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.emit('farcasterConnectCancelled');
        }
        setShowAuthFlow(false, { emitCancelAuth: true });
        setDeniedAddress('');
        setDeniedOauthProvider(undefined);
        setExistentAccountData(undefined);
        clearStatesOnBackClick();
    });
    const handleOnPortalExiting = useCallback(() => __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() ||
            !viewsToDisconnectWalletOnClose.includes(view.type) ||
            !selectedWalletConnector)
            return;
        const walletByConnectorKey = connectedWallets.find((connectedWallet) => connectedWallet.connector.key === selectedWalletConnector.key);
        if (!walletByConnectorKey) {
            return;
        }
        // Validate the network
        if (!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 = 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 = useRef(view === null || view === void 0 ? void 0 : view.type);
    viewTypeRef.current = view === null || view === void 0 ? void 0 : view.type;
    const handleOnPortalUnmount = 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();
    const { handleAlreadyConnectedWallet, handleCustodialWalletClick, handleInstalledExtensionClick, handleMobileWalletClick, handleUninstalledClick, } = useWalletItemActions();
    /* istanbul ignore next */
    const handleNewToWeb3WalletIntent = (walletConnector) => __awaiter(void 0, void 0, void 0, function* () {
        setShowAuthFlow(true);
        if (isSelectedWalletAlreadyConnected(linkedWallets, walletConnector, user)) {
            // wallet is already connected
            handleAlreadyConnectedWallet(walletConnector);
        }
        else if (walletConnector.canConnectViaCustodialService) {
            // providers like blocto and dapper
            handleCustodialWalletClick(walletConnector);
        }
        else if (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);
        }
    });
    useEffect(() => {
        const newToWeb3WalletKey = StorageService.getItem(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);
            }
            StorageService.removeItem(NEWTOWEB3_WALLET_EXTENSION_FLAG_KEY);
        }
    }, [walletConnectorOptions]);
    const showDynamicAuth = showAuthFlow && Boolean(projectSettings);
    return (jsx(FooterAnimationContextProvider, { children: jsx(Portal, { zIndex: authModalZIndex, isShown: showDynamicAuth, handleClose: handleClose, withBackdrop: true, transitionEvents: {
                onExiting: handleOnPortalExiting,
                onUnmount: handleOnPortalUnmount,
            }, children: jsx(PopperProvider, { children: jsx(DynamicAuthModal, { transitionProps: {
                        isShown: showDynamicAuth,
                    }, onClose: handleClose, projectSettings: projectSettings, children: jsx(RenderView, {}) }) }) }) }));
};

export { Main, Main as default };
