'use client'
import { jsxs, jsx } from 'react/jsx-runtime';
import { useCallback, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { WalletIcon } from '@dynamic-labs/wallet-book';
import '@dynamic-labs/utils';
import '../../components/Accordion/components/AccordionItem/AccordionItem.js';
import '@dynamic-labs/iconic';
import '../../context/ViewContext/ViewContext.js';
import '../../../../_virtual/_tslib.js';
import { getChainIcon } from '../../shared/utils/functions/chain/getChainIcon.js';
import '@dynamic-labs/wallet-connector-core';
import { logger } from '../../shared/logger.js';
import '../../utils/constants/colors.js';
import '../../utils/constants/values.js';
import '@dynamic-labs/sdk-api-core';
import { useOnClickOutside } from '../../shared/utils/hooks/useOnClickOutside/index.js';
import '../../shared/consts/index.js';
import '../../components/Alert/Alert.js';
import '../../events/dynamicEvents.js';
import '../../context/DynamicContext/DynamicContext.js';
import '../../store/state/loadingAndLifecycle/loadingAndLifecycle.js';
import '../../store/state/authMode/authMode.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 '@dynamic-labs-sdk/client/core';
import '../../client/client.js';
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 '../../context/AccessDeniedContext/AccessDeniedContext.js';
import '../../context/AccountExistsContext/AccountExistsContext.js';
import '../../context/UserWalletsContext/UserWalletsContext.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 '../../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 '../../context/FooterAnimationContext/index.js';
import { ShadowDOM } from '../../components/ShadowDOM/ShadowDOM.js';
import '../../components/Transition/ZoomTransition/ZoomTransition.js';
import '../../components/Transition/SlideInUpTransition/SlideInUpTransition.js';
import '../../components/Transition/OpacityTransition/OpacityTransition.js';
import '../../components/OverlayCardBase/OverlayCardTarget/OverlayCardTarget.js';
import { Skeleton } from '../../components/Skeleton/Skeleton.js';
import '../../context/WalletGroupContext/WalletGroupContext.js';
import '../DynamicWidget/components/DynamicWidgetHeader/DynamicWidgetHeader.js';
import 'react-focus-lock';
import { shortenWalletAddress } from '../../shared/utils/functions/shortenWalletAddress/shortenWalletAddress.js';
import '../DynamicWidget/context/DynamicWidgetContext.js';
import '../../components/IconButton/IconButton.js';
import '../../components/MenuList/Dropdown/Dropdown.js';
import 'formik';
import '../../utils/hooks/useSubdomainCheck/useSubdomainCheck.js';
import '../../store/state/sendBalances.js';
import '../../components/Input/Input.js';
import '../../components/OverlayCard/OverlayCard.js';
import '../../views/TransactionConfirmationView/TransactionConfirmationView.js';
import '../../components/PasskeyCreatedSuccessBanner/PasskeyCreatedSuccessBanner.js';
import '../../context/PasskeyContext/PasskeyContext.js';
import '../DynamicWidget/components/PasskeyCard/PasskeyCard.js';
import '../DynamicWidget/views/CryptoComOnramp/CryptoComOnramp.js';
import '../../context/OnrampContext/OnrampContext.js';
import '../../../index.js';
import '../DynamicWidget/helpers/convertExchangeKeyAndProviderEnum.js';
import 'qrcode';
import '../DynamicWidget/views/ReceiveWalletFunds/ReceiveWalletFunds.js';
import '../../context/IpConfigurationContext/IpConfigurationContext.js';
import '../../context/ConnectWithOtpContext/ConnectWithOtpContext.js';
import './views/WalletsView/components/SecondaryWallets/SecondaryWallets.js';
import '@hcaptcha/react-hcaptcha';
import '../../views/ExchangeWhitelistWarning/ExchangeWhitelistWarning.js';
import '../../context/ErrorContext/hooks/useErrorText/useErrorText.js';
import '../../views/MfaChooseDeviceView/useGetMfaOptions/useGetMfaOptions.js';
import '../../store/state/connectorsInitializing/connectorsInitializing.js';
import '../../store/state/tokenBalances.js';
import '../../store/state/multichainBalances.js';
import '../../shared/utils/functions/getInitialUrl/getInitialUrl.js';
import { InlineWidgetButton } from '../../components/InlineWidget/components/InlineWidgetButton/InlineWidgetButton.js';
import { InlineWidget } from '../../components/InlineWidget/InlineWidget.js';
import '../../components/IsBrowser/IsBrowser.js';
import '../../components/Popper/Popper/Popper.js';
import '../../components/Popper/PopperContext/PopperContext.js';
import { DynamicBridgeUserProfile } from './components/DynamicBridgeUserProfile/DynamicBridgeUserProfile.js';
import { useDynamicBridgeWidgetContext } from './context/DynamicBridgeWidgetContext/DynamicBridgeWidgetContext.js';

const DynamicBridgeWidget = ({ className, variant = 'modal', iconVariant = 'chain', }) => {
    const { showAuthFlow, setShowBridgeWidget, bridgeChains, setShowAuthFlow, connectedWallets, sdkHasLoaded, primaryWallet, setPrimaryWallet, } = useInternalDynamicContext();
    const { widgetRef, inlineControlsRef } = useDynamicBridgeWidgetContext();
    const { t } = useTranslation();
    const closeOnOutsideClick = useCallback((e) => {
        var _a;
        const target = e.composedPath().shift();
        if ((_a = inlineControlsRef.current) === null || _a === void 0 ? void 0 : _a.contains(target))
            return;
        if (variant === 'dropdown' && !showAuthFlow) {
            setShowBridgeWidget(false);
        }
    }, [inlineControlsRef, variant, showAuthFlow, setShowBridgeWidget]);
    useOnClickOutside(widgetRef, closeOnOutsideClick);
    useEffect(() => {
        // no need to update primary wallet if it's already set to the correct chain
        if (!primaryWallet ||
            !bridgeChains ||
            connectedWallets.length <= 1 ||
            primaryWallet.chain === bridgeChains[0].chain) {
            return;
        }
        // find a connected wallet that matches the primary bridge chain
        const newPrimaryWallet = connectedWallets.find((wallet) => wallet.chain === bridgeChains[0].chain);
        // if a new primary wallet is found, update the primary wallet
        if (newPrimaryWallet) {
            logger.debug('[DynamicBridgeWidget] bridgeChains changed - updating primary wallet', {
                bridgeChains,
                connectedWallets: connectedWallets.map((wallet) => ({
                    address: wallet.address,
                    chain: wallet.chain,
                    id: wallet.id,
                })),
                newPrimaryWallet: {
                    address: newPrimaryWallet.address,
                    chain: newPrimaryWallet.chain,
                    id: newPrimaryWallet.id,
                },
                oldPrimaryWallet: {
                    address: primaryWallet.address,
                    chain: primaryWallet.chain,
                    id: primaryWallet.id,
                },
            });
            setPrimaryWallet(newPrimaryWallet.id);
        }
    }, [bridgeChains, primaryWallet, connectedWallets, setPrimaryWallet]);
    return (jsxs(ShadowDOM, { id: 'dynamic-bridge-widget', className: 'dynamic-widget__container', children: [jsx(InlineWidget, { ref: inlineControlsRef, className: className, dataTestId: 'BridgeWidgetNav', children: bridgeChains === null || bridgeChains === void 0 ? void 0 : bridgeChains.map(({ chain }) => {
                    const ChainIcon = getChainIcon(chain);
                    if (!sdkHasLoaded) {
                        return (jsx(InlineWidgetButton, { icon: jsx(ChainIcon, {}), className: 'dynamic-bridge-widget__skeleton-button', children: jsx(Skeleton, { className: 'dynamic-bridge-widget__skeleton' }) }, `skeleton-${chain}`));
                    }
                    const connectedChainWallets = connectedWallets.filter(({ chain: connectedChain }) => connectedChain === chain);
                    if (connectedChainWallets.length > 0) {
                        return connectedChainWallets.map((wallet) => (jsx(InlineWidgetButton, { icon: iconVariant === 'wallet' ? (jsx(WalletIcon, { icon: wallet.connector.metadata.icon, walletKey: wallet.connector.key })) : (jsx(ChainIcon, {})), onClick: () => setShowBridgeWidget(true), children: shortenWalletAddress(wallet.address) }, wallet.id)));
                    }
                    return (jsx(InlineWidgetButton, { icon: jsx(ChainIcon, {}), onClick: () => setShowAuthFlow(true), copykey: 'dyn_bridge.widget.connect', children: t('dyn_bridge.widget.connect') }, chain));
                }) }), jsx(DynamicBridgeUserProfile, { variant: variant })] }));
};

export { DynamicBridgeWidget };
