'use client'
import { jsx } from 'react/jsx-runtime';
import { useMemo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { SocialIcon } from '@dynamic-labs/iconic';
import { WalletIcon } from '@dynamic-labs/wallet-book';
import '@dynamic-labs/utils';
import '../../../../../components/Accordion/components/AccordionItem/AccordionItem.js';
import { ReactComponent as SvgAddThick } from '../../../../../shared/assets/add-thick.js';
import { ReactComponent as SvgGlobe } from '../../../../../shared/assets/globe.js';
import { ReactComponent as SvgLinkCircle } from '../../../../../shared/assets/link-circle.js';
import { ReactComponent as SvgQrCode } from '../../../../../shared/assets/qr-code.js';
import { ReactComponent as SvgWalletOutlineV2 } from '../../../../../shared/assets/wallet-outline-v2.js';
import '../../../../../context/ViewContext/ViewContext.js';
import '../../../../../../../_virtual/_tslib.js';
import '@dynamic-labs/wallet-connector-core';
import '../../../../../shared/logger.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 '../../../../../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 '../../../../../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 { useIconThemeVariant } from '../../../../../utils/hooks/useIconThemeVariant/useIconThemeVariant.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 { useWalletGroups } from '../../../../../store/state/walletOptions/walletOptions.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 '../../../../../context/WalletGroupContext/WalletGroupContext.js';
import '../../../components/DynamicWidgetHeader/DynamicWidgetHeader.js';
import 'react-focus-lock';
import '../../../../../context/ThemeContext/ThemeContext.js';
import { Icon } from '../../../../../components/Icon/Icon.js';
import { useWidgetContext } from '../../../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 '../../../components/PasskeyCard/PasskeyCard.js';
import '../../CryptoComOnramp/CryptoComOnramp.js';
import { useOnrampContext } from '../../../../../context/OnrampContext/OnrampContext.js';
import { FilterChain } from '../../../../../utils/functions/walletFilters/index.js';
import { useInternalFundWithWallet } from '../../../../../utils/hooks/useFundWithWallet/useFundWithWallet.js';
import { useWalletList } from '../../../../../utils/hooks/useWalletList/useWalletList.js';
import { convertExchangeKeytoProviderEnum } from '../../../helpers/convertExchangeKeyAndProviderEnum.js';
import { useStartExchangeFunding } from './useStartExchangeFunding/useStartExchangeFunding.js';
import { useStartExternalWalletFunding } from './useStartExternalWalletFunding/useStartExternalWalletFunding.js';
import { useStartLinkedWalletFunding } from './useStartLinkedWalletFunding/useStartLinkedWalletFunding.js';
import 'qrcode';
import '../../ReceiveWalletFunds/ReceiveWalletFunds.js';
import '../../../../../../index.js';
import '../../../../../context/IpConfigurationContext/IpConfigurationContext.js';
import '../../../../../context/ConnectWithOtpContext/ConnectWithOtpContext.js';
import '../../../../DynamicBridgeWidget/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 '../../../../../components/InlineWidget/InlineWidget.js';
import '../../../../../components/IsBrowser/IsBrowser.js';
import '../../../../../components/Popper/Popper/Popper.js';
import '../../../../../components/Popper/PopperContext/PopperContext.js';

const slicePreviewIcons = (icons) => {
    if (icons.length > MAX_PREVIEW_ICONS)
        return icons.slice(0, MAX_PREVIEW_ICONS).concat(jsx("div", { className: 'choose-wallet-funding-method__options__option__trailing__preview-icons__plus-icon', children: jsx(Icon, { color: 'text-tertiary', children: jsx(SvgAddThick, {}) }) }, 'plus-icon'));
    return icons;
};
const MAX_PREVIEW_ICONS = 3;
const useFundingMethods = () => {
    var _a;
    const { t } = useTranslation();
    const { setDynamicWidgetView } = useWidgetContext();
    const { externalWalletFundingEnabled } = useInternalFundWithWallet();
    const { enabledOnrampProviders, selectOnrampProvider } = useOnrampContext();
    const iconThemeVariant = useIconThemeVariant();
    const { primaryWallet } = useInternalDynamicContext();
    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 viewWalletsFilter = useMemo(() => (primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.chain)
        ? FilterChain(primaryWallet.chain)
        : undefined, [primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.chain]);
    const { walletsList } = useWalletList({
        viewWalletsFilter,
    });
    const walletGroups = useWalletGroups();
    const { startExternalWalletFunding } = useStartExternalWalletFunding();
    const { startExchangeFunding } = useStartExchangeFunding();
    const { startLinkedWalletFunding, filteredLinkedWallets } = useStartLinkedWalletFunding();
    const onrampOptions = useMemo(() => enabledOnrampProviders.filter(({ isPaymentMethod }) => !isPaymentMethod), [enabledOnrampProviders]);
    const paymentMethods = useMemo(() => enabledOnrampProviders.filter(({ isPaymentMethod }) => isPaymentMethod), [enabledOnrampProviders]);
    const handleQrClick = useCallback(() => setDynamicWidgetView('deposit-view'), [setDynamicWidgetView]);
    const handleBuyCryptoClick = useCallback(() => {
        if (!primaryWallet) {
            return;
        }
        onrampOptions.length > 1
            ? setDynamicWidgetView('choose-onramp-provider')
            : selectOnrampProvider({
                provider: onrampOptions[0],
                wallet: primaryWallet,
            });
    }, [
        onrampOptions,
        setDynamicWidgetView,
        primaryWallet,
        selectOnrampProvider,
    ]);
    const previewWalletIcons = useMemo(() => {
        if (!externalWalletFundingEnabled)
            return [];
        return slicePreviewIcons(walletsList.map(({ key, walletConnector }, index) => {
            var _a, _b, _c;
            return (jsx("div", { className: 'choose-wallet-funding-method__options__option__trailing__preview-icons__wallet-icon', style: { '--z-index': MAX_PREVIEW_ICONS - index }, children: jsx(WalletIcon, { icon: (_a = walletConnector === null || walletConnector === void 0 ? void 0 : walletConnector.metadata.icon) !== null && _a !== void 0 ? _a : (_c = (_b = walletGroups[key]) === null || _b === void 0 ? void 0 : _b.brand) === null || _c === void 0 ? void 0 : _c.icon, walletKey: key, isGroup: false }) }, key));
        }));
    }, [externalWalletFundingEnabled, walletsList, walletGroups]);
    const exchangeIcons = useMemo(() => {
        const icons = exchangeNames.map((providerKey, index) => (jsx("div", { className: 'choose-wallet-funding-method__options__option__trailing__preview-icons__wallet-icon', style: { '--z-index': MAX_PREVIEW_ICONS - index }, children: jsx(SocialIcon, { name: providerKey, variant: iconThemeVariant }) }, providerKey)));
        return slicePreviewIcons(icons);
    }, [exchangeNames, iconThemeVariant]);
    const previewOnrampIcons = useMemo(() => {
        if (!onrampOptions.length)
            return [];
        return slicePreviewIcons(onrampOptions.map(({ iconUrl, id }) => (jsx("div", { className: 'choose-wallet-funding-method__options__option__trailing__preview-icons__onramp-icon', children: jsx("img", { src: iconUrl, alt: `${id}-icon` }) }, id))));
    }, [onrampOptions]);
    return useMemo(() => {
        var _a;
        const methods = [
            {
                icon: jsx(SvgQrCode, {}),
                key: 'qr',
                label: t('dyn_wallet_funding.funding_method_selection.qr_option'),
                onClick: handleQrClick,
                showChevron: true,
            },
        ];
        if (primaryWallet) {
            paymentMethods.forEach((option) => {
                const { id, iconUrl, displayName } = option;
                methods.push({
                    icon: jsx("img", { src: iconUrl, alt: displayName }),
                    key: id,
                    label: displayName,
                    onClick: () => selectOnrampProvider({
                        provider: option,
                        wallet: primaryWallet,
                    }),
                    showChevron: false,
                });
            });
        }
        if (onrampOptions.length) {
            methods.push({
                icon: jsx(SvgGlobe, {}),
                key: 'buy',
                label: t('dyn_wallet_funding.funding_method_selection.buy_option'),
                onClick: handleBuyCryptoClick,
                previewIcons: previewOnrampIcons,
                showChevron: onrampOptions.length > 1,
            });
        }
        if (filteredLinkedWallets.length > 0) {
            methods.push({
                icon: jsx(SvgLinkCircle, {}),
                key: 'linked-wallet',
                label: t('dyn_wallet_funding.funding_method_selection.linked_wallet_option'),
                onClick: startLinkedWalletFunding,
                showChevron: true,
            });
        }
        if (exchangeNames.length > 0 &&
            ((_a = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.sdk.featureFlags) === null || _a === void 0 ? void 0 : _a.enableExchanges)) {
            methods.push({
                icon: jsx(SvgGlobe, {}),
                key: 'exchange',
                label: t('dyn_wallet_funding.funding_method_selection.exchange_option'),
                onClick: startExchangeFunding,
                previewIcons: exchangeIcons,
                showChevron: true,
            });
        }
        if (externalWalletFundingEnabled) {
            methods.push({
                icon: jsx(SvgWalletOutlineV2, {}),
                key: 'external-wallet',
                label: t('dyn_wallet_funding.funding_method_selection.external_wallet_option'),
                onClick: startExternalWalletFunding,
                previewIcons: previewWalletIcons,
                showChevron: true,
            });
        }
        return methods;
    }, [
        t,
        handleQrClick,
        primaryWallet,
        onrampOptions.length,
        filteredLinkedWallets.length,
        exchangeNames.length,
        (_a = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.sdk.featureFlags) === null || _a === void 0 ? void 0 : _a.enableExchanges,
        externalWalletFundingEnabled,
        paymentMethods,
        selectOnrampProvider,
        handleBuyCryptoClick,
        previewOnrampIcons,
        startLinkedWalletFunding,
        startExchangeFunding,
        exchangeIcons,
        startExternalWalletFunding,
        previewWalletIcons,
    ]);
};

export { useFundingMethods };
