'use client'
import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
import { useState, useMemo, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { StorageService } from '@dynamic-labs/utils';
import { ReactComponent as SvgNoWalletFound } from '../../assets/no-wallet-found.js';
import { classNames } from '../../utils/functions/classNames/classNames.js';
import '../../components/Accordion/components/AccordionItem/AccordionItem.js';
import '@dynamic-labs/iconic';
import '../../context/ViewContext/ViewContext.js';
import '../../../../_virtual/_tslib.js';
import '@dynamic-labs/wallet-connector-core';
import '../../shared/logger.js';
import '@dynamic-labs/wallet-book';
import { WALLET_PICKER_SEARCH_KEY, LAST_USED_WALLET } from '../../utils/constants/localStorage.js';
import '../../utils/constants/colors.js';
import '../../utils/constants/values.js';
import '@dynamic-labs/sdk-api-core';
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 { useErrorContext } from '../../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 { useProjectSettings } from '../../client/extension/projectSettings/useProjectSettings/useProjectSettings.js';
import '@dynamic-labs/locale';
import { useDynamicSettings } from '../../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 { useInternalUserWallets } from '../../context/UserWalletsContext/UserWalletsContext.js';
import '../../context/VerificationContext/VerificationContext.js';
import 'react-dom';
import '../../utils/functions/compareChains/compareChains.js';
import '../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 '../CollectUserDataView/useFields.js';
import '../../context/FieldsStateContext/FieldsStateContext.js';
import '../../context/UserFieldEditorContext/UserFieldEditorContext.js';
import '@dynamic-labs/rpc-providers';
import { useWalletGroups } from '../../store/state/walletOptions/walletOptions.js';
import { Typography } from '../../components/Typography/Typography.js';
import '../../context/FooterAnimationContext/index.js';
import '../../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 { WalletListItem } from '../WalletList/WalletListItem/WalletListItem.js';
import '../../widgets/DynamicWidget/components/DynamicWidgetHeader/DynamicWidgetHeader.js';
import 'react-focus-lock';
import '../../widgets/DynamicWidget/context/DynamicWidgetContext.js';
import { ErrorContainer } from '../../components/ErrorContainer/ErrorContainer.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 '../TransactionConfirmationView/TransactionConfirmationView.js';
import '../../components/PasskeyCreatedSuccessBanner/PasskeyCreatedSuccessBanner.js';
import '../../context/PasskeyContext/PasskeyContext.js';
import '../../widgets/DynamicWidget/components/PasskeyCard/PasskeyCard.js';
import '../../widgets/DynamicWidget/views/CryptoComOnramp/CryptoComOnramp.js';
import { useOnrampContext } from '../../context/OnrampContext/OnrampContext.js';
import '../../../index.js';
import '../../context/WalletGroupContext/WalletGroupContext.js';
import { walletListBuilder } from '../../utils/functions/walletListBuilder/walletListBuilder.js';
import { convertExchangeKeytoProviderEnum, convertProviderToExchangeKeyEnum } from '../../widgets/DynamicWidget/helpers/convertExchangeKeyAndProviderEnum.js';
import 'qrcode';
import '../../widgets/DynamicWidget/views/ReceiveWalletFunds/ReceiveWalletFunds.js';
import { Search } from '../../components/Search/Search.js';
import { DefaultFooter } from '../../layout/DynamicAuthLayout/DefaultFooter/DefaultFooter.js';
import { SearchNotFoundMessage } from '../WalletList/SearchNotFoundMessage/SearchNotFoundMessage.js';
import '../../context/IpConfigurationContext/IpConfigurationContext.js';
import '../../context/ConnectWithOtpContext/ConnectWithOtpContext.js';
import '../../widgets/DynamicBridgeWidget/views/WalletsView/components/SecondaryWallets/SecondaryWallets.js';
import '@hcaptcha/react-hcaptcha';
import { ExchangeListItem } from '../ExchangeList/ExchangeListItem/ExchangeListItem.js';
import '../ExchangeWhitelistWarning/ExchangeWhitelistWarning.js';
import '../../context/ErrorContext/hooks/useErrorText/useErrorText.js';
import '../MfaChooseDeviceView/useGetMfaOptions/useGetMfaOptions.js';
import { OnRampItem } from './OnRampItem/OnRampItem.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 '../../components/InlineWidget/InlineWidget.js';
import '../../components/IsBrowser/IsBrowser.js';
import '../../components/Popper/Popper/Popper.js';
import '../../components/Popper/PopperContext/PopperContext.js';

const UnifiedList = ({ onSelectWallet, onSelectExchange, onSelectOnRamp, showDefaultFooter, scrollContainerClassName, }) => {
    var _a, _b, _c;
    const { t } = useTranslation();
    const { error } = useErrorContext();
    const [footerBorderIsVisible, setFooterBorderIsVisible] = useState(true);
    const [filterValue, setFilterValue] = useState((_a = StorageService.getItem(WALLET_PICKER_SEARCH_KEY)) !== null && _a !== void 0 ? _a : '');
    const { userWallets } = useInternalUserWallets();
    const walletGroups = useWalletGroups();
    const { multiWallet, walletConnectorOptions } = useInternalDynamicContext();
    const { enabledOnrampProviders } = useOnrampContext();
    const dynamicSettings = useDynamicSettings();
    const { numberOfWallets, walletsList } = walletListBuilder({
        groupWallets: true,
        inputList: walletConnectorOptions,
        isWalletConnectList: false,
        lastUsedWalletKey: (_b = StorageService.getItem(LAST_USED_WALLET)) !== null && _b !== void 0 ? _b : undefined,
        loginWithEmail: true,
        multiWallet,
        numberOfWalletsToShow: (_c = dynamicSettings.defaultNumberOfWalletsToShow) !== null && _c !== void 0 ? _c : 10,
        recommendedWallets: dynamicSettings.recommendedWallets,
        searchFilter: filterValue,
        userWallets,
        walletGroups,
        walletsFilter: dynamicSettings.walletsFilter,
    });
    const projectSettings = useProjectSettings();
    const exchangeNames = useMemo(() => {
        if (!(projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.exchanges))
            return [];
        const names = projectSettings.exchanges.flatMap(({ exchange, enabledAt }) => {
            if (!enabledAt)
                return [];
            return [convertExchangeKeytoProviderEnum(exchange)];
        });
        return [...new Set(names)];
    }, [projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.exchanges]);
    const filteredExchanges = useMemo(() => {
        const term = filterValue.trim().toLowerCase();
        if (!term)
            return exchangeNames;
        return exchangeNames.filter((provider) => convertProviderToExchangeKeyEnum(provider).toLowerCase().includes(term));
    }, [exchangeNames, filterValue]);
    const onrampOptions = useMemo(() => enabledOnrampProviders.filter(({ isPaymentMethod }) => !isPaymentMethod), [enabledOnrampProviders]);
    const filteredOnramp = useMemo(() => {
        const term = filterValue.trim().toLowerCase();
        if (!term)
            return onrampOptions;
        return onrampOptions.filter(({ displayName }) => displayName.toLowerCase().includes(term));
    }, [onrampOptions, filterValue]);
    const scrollRef = useRef(null);
    const handleScroll = () => {
        const el = scrollRef.current;
        if (!el)
            return;
        setFooterBorderIsVisible(el.scrollTop <= el.clientHeight * 1.25);
    };
    const handleFilterChange = (value) => {
        StorageService.setItem(WALLET_PICKER_SEARCH_KEY, value);
        setFilterValue(value);
    };
    const isLoading = !projectSettings;
    const walletTrailing = (jsx(Typography, { variant: 'body_small', color: 'tertiary', copykey: 'dyn_unified_list.wallet', children: t('dyn_unified_list.wallet') }));
    const exchangeTrailing = (jsx(Typography, { variant: 'body_small', color: 'tertiary', copykey: 'dyn_unified_list.exchange', children: t('dyn_unified_list.exchange') }));
    const onrampTrailing = (jsx(Typography, { variant: 'body_small', color: 'tertiary', copykey: 'dyn_unified_list.onramp', children: t('dyn_unified_list.onramp') }));
    return (jsxs(Fragment, { children: [jsx("div", { className: classNames('unified-list__search-container', {
                    'unified-list__search-container--scroll': !error,
                }), children: jsx(Search, { copykey: 'dyn_unified_list.search.label', label: t('dyn_unified_list.search.label', {
                        count: numberOfWallets + filteredExchanges.length,
                    }), value: filterValue, onChange: ({ target: { value } }) => handleFilterChange(value), onClickClear: () => handleFilterChange('') }) }), Boolean(error) && (jsx(ErrorContainer, { className: 'unified-list__error-container', withIcon: false, children: error })), jsx("div", { className: classNames('unified-list__scroll-container', scrollContainerClassName, { 'unified-list__scroll-container--error': Boolean(error) }), ref: scrollRef, onScroll: handleScroll, "data-testid": 'unified-list-scroll-container', children: isLoading ? (jsx(Skeleton, { count: 10, className: 'unified-list__tile-skeleton' })) : (jsxs(Fragment, { children: [walletsList.length === 0 &&
                            filteredExchanges.length === 0 &&
                            filteredOnramp.length === 0 &&
                            (walletConnectorOptions.length ||
                                exchangeNames.length ||
                                onrampOptions.length) ? (jsx(SearchNotFoundMessage, { titleKey: t('dyn_unified_list.search.not_found.title'), subtitleKey: t('dyn_unified_list.search.not_found.description'), image: jsx(SvgNoWalletFound, {}) })) : (walletsList.map((wallet, idx) => (jsx(WalletListItem, { wallet: wallet, onResetSearchValue: () => handleFilterChange(''), recommendedWallets: dynamicSettings.recommendedWallets, onSelectWallet: onSelectWallet, trailingProp: walletTrailing }, `wallet_${wallet.key}_${idx}`)))), filteredExchanges.map((prov, idx) => (jsx(ExchangeListItem, { exchange: convertProviderToExchangeKeyEnum(prov), onResetSearchValue: () => handleFilterChange(''), onSelectExchange: onSelectExchange, trailingProp: exchangeTrailing }, `exchange_${prov}_${idx}`))), filteredOnramp.map((onramp, idx) => (jsx(OnRampItem, { onramp: onramp, onResetSearchValue: () => handleFilterChange(''), onSelectOnRamp: onSelectOnRamp, trailingProp: onrampTrailing }, `onramp_${onramp}_${idx}`)))] })) }), showDefaultFooter && (jsx(DefaultFooter, { hideBorder: !footerBorderIsVisible }))] }));
};

export { UnifiedList };
