'use client'
'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var _tslib = require('../../../../../_virtual/_tslib.cjs');
var React = require('react');
require('@dynamic-labs-sdk/client/core');
require('@dynamic-labs/sdk-api-core');
require('../../../client/client.cjs');
require('@dynamic-labs-sdk/client');
require('../../../config/ApiEndpoint.cjs');
require('@dynamic-labs/iconic');
require('@dynamic-labs/wallet-connector-core');
require('react/jsx-runtime');
require('../../../context/ViewContext/ViewContext.cjs');
var logger = require('../../../shared/logger.cjs');
require('@dynamic-labs/wallet-book');
require('@dynamic-labs/utils');
require('../../constants/colors.cjs');
require('../../constants/values.cjs');
require('../../../shared/consts/index.cjs');
require('@dynamic-labs/multi-wallet');
require('react-international-phone');
require('../../../store/state/nonce/nonce.cjs');
require('@dynamic-labs/locale');
require('../../../store/state/dynamicContextProps/dynamicContextProps.cjs');
require('../../../store/state/primaryWalletId/primaryWalletId.cjs');
require('../../../store/state/connectedWalletsInfo/connectedWalletsInfo.cjs');
require('../../../events/dynamicEvents.cjs');
var useOnboardingCompleteUser = require('../../../client/extension/user/useOnboardingCompleteUser/useOnboardingCompleteUser.cjs');
var useProjectSettings = require('../../../client/extension/projectSettings/useProjectSettings/useProjectSettings.cjs');
var OnrampContext = require('../../../context/OnrampContext/OnrampContext.cjs');
var useConnectUnifiedForFunding = require('../useConnectUnifiedForFunding/useConnectUnifiedForFunding.cjs');
var useSocialAccounts = require('../useSocialAccounts/useSocialAccounts.cjs');
var usePromptAmountAndFundWithWallet = require('../useFundWithWallet/usePromptAmountAndFundWithWallet/usePromptAmountAndFundWithWallet.cjs');
var usePromptAndFundWithExchange = require('../usePromptAndFundWithExchange/usePromptAndFundWithExchange.cjs');
var useWalletItemActions = require('../useWalletItemActions/useWalletItemActions.cjs');
var walletOptions = require('../../../store/state/walletOptions/walletOptions.cjs');
require('../../../context/DynamicContext/DynamicContext.cjs');
require('../../../store/state/loadingAndLifecycle/loadingAndLifecycle.cjs');
require('../../../context/CaptchaContext/CaptchaContext.cjs');
require('../../../context/ErrorContext/ErrorContext.cjs');
require('../../../context/AccessDeniedContext/AccessDeniedContext.cjs');
require('../../../context/AccountExistsContext/AccountExistsContext.cjs');
require('../../../context/UserWalletsContext/UserWalletsContext.cjs');
require('../../../store/state/authMode/authMode.cjs');
require('../../../context/VerificationContext/VerificationContext.cjs');
require('react-dom');
require('../../functions/compareChains/compareChains.cjs');
require('../../../views/Passkey/utils/findPrimaryEmbeddedChain/findPrimaryEmbeddedChain.cjs');
require('../../../context/ThemeContext/ThemeContext.cjs');
require('../useUserUpdateRequest/useUpdateUser/userFieldsSchema.cjs');
require('bs58');
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('react-i18next');
require('../../../components/Accordion/components/AccordionItem/AccordionItem.cjs');
require('../../../components/Alert/Alert.cjs');
require('../../../context/WalletContext/WalletContext.cjs');
require('../../../components/ShadowDOM/ShadowDOM.cjs');
require('../../../components/IconButton/IconButton.cjs');
require('../../../components/InlineWidget/InlineWidget.cjs');
require('../../../components/Input/Input.cjs');
require('../../../components/IsBrowser/IsBrowser.cjs');
require('../../../components/MenuList/Dropdown/Dropdown.cjs');
require('../../../components/OverlayCard/OverlayCard.cjs');
require('../../../components/Transition/ZoomTransition/ZoomTransition.cjs');
require('../../../components/Transition/SlideInUpTransition/SlideInUpTransition.cjs');
require('../../../components/Transition/OpacityTransition/OpacityTransition.cjs');
require('../../../components/PasskeyCreatedSuccessBanner/PasskeyCreatedSuccessBanner.cjs');
require('../../../components/Popper/Popper/Popper.cjs');
require('../../../components/Popper/PopperContext/PopperContext.cjs');
require('react-focus-lock');
require('qrcode');
require('formik');
require('../useSubdomainCheck/useSubdomainCheck.cjs');
require('../../../context/WalletGroupContext/WalletGroupContext.cjs');
require('../../../context/IpConfigurationContext/IpConfigurationContext.cjs');
require('../../../context/SocialRedirectContext/SocialRedirectContext.cjs');
require('../../../context/ConnectWithOtpContext/ConnectWithOtpContext.cjs');
require('../../../widgets/DynamicBridgeWidget/views/WalletsView/components/SecondaryWallets/SecondaryWallets.cjs');
require('@hcaptcha/react-hcaptcha');
require('../../../context/LoadingContext/LoadingContext.cjs');
require('../../../widgets/DynamicWidget/context/DynamicWidgetContext.cjs');
require('../../../widgets/DynamicWidget/helpers/convertExchangeKeyAndProviderEnum.cjs');
require('../../../views/ExchangeWhitelistWarning/ExchangeWhitelistWarning.cjs');
require('../../../context/ErrorContext/hooks/useErrorText/useErrorText.cjs');
require('../../../context/FooterAnimationContext/index.cjs');
require('@dynamic-labs/types');
require('../useEmbeddedWallet/useSecureEnclaveEmbeddedWallet/constants.cjs');
require('../../../views/MfaChooseDeviceView/useGetMfaOptions/useGetMfaOptions.cjs');
require('../../../context/PasskeyContext/PasskeyContext.cjs');
require('../../../store/state/sendBalances.cjs');
require('../../../store/state/connectorsInitializing/connectorsInitializing.cjs');
require('../../../components/OverlayCardBase/OverlayCardTarget/OverlayCardTarget.cjs');
require('../../../widgets/DynamicWidget/components/DynamicWidgetHeader/DynamicWidgetHeader.cjs');
require('../../../views/TransactionConfirmationView/TransactionConfirmationView.cjs');
require('../../../widgets/DynamicWidget/components/PasskeyCard/PasskeyCard.cjs');
require('../../../widgets/DynamicWidget/views/CryptoComOnramp/CryptoComOnramp.cjs');
require('../../../../index.cjs');
require('../../../widgets/DynamicWidget/views/ReceiveWalletFunds/ReceiveWalletFunds.cjs');
require('../../../store/state/tokenBalances.cjs');
require('../../../store/state/multichainBalances.cjs');
require('../../../shared/utils/functions/getInitialUrl/getInitialUrl.cjs');
var useInternalDynamicContext = require('../../../context/DynamicContext/useDynamicContext/useInternalDynamicContext/useInternalDynamicContext.cjs');

const usePayWithDynamic = () => {
    const connectUnifiedForFunding = useConnectUnifiedForFunding.useConnectUnifiedForFunding();
    const projectSettings = useProjectSettings.useProjectSettings();
    const { linkSocialAccount, signInWithSocialAccount } = useSocialAccounts.useSocialAccounts();
    const user = useOnboardingCompleteUser.useOnboardingCompleteUser();
    const { openOnramp, setEnabledOnrampProvidersTargetValue } = OnrampContext.useOnrampContext();
    const promptWallet = usePromptAmountAndFundWithWallet.usePromptAmountAndFundWithWallet();
    const promptExchange = usePromptAndFundWithExchange.usePromptAmountAndFundWithExchange();
    const { handleWalletItemClick } = useWalletItemActions.useWalletItemActions();
    const { walletConnectorOptions } = walletOptions.getWalletOptions();
    const { setShowAuthFlow, setShowDynamicUserProfile } = useInternalDynamicContext.useInternalDynamicContext();
    // Flow for funding via wallet
    const handleWalletFlow = React.useCallback(({ wallet, props, onBack }) => {
        // If user is not onboarded, trigger wallet connector UI
        if (!user) {
            const option = walletConnectorOptions.find(({ key }) => key === wallet.connector.key);
            if (option)
                handleWalletItemClick(option);
        }
        // Prompt for amount and execute wallet funding (shows deposit screen)
        promptWallet({
            amount: { rule: 'exact', value: props.tokenAmount },
            destinationAddress: props.destinationAddress,
            network: props.network,
            onBack,
            token: { rule: 'exact-with-amount', value: props.tokenSymbol },
            wallet: wallet,
        });
        setShowAuthFlow(false);
    }, [
        handleWalletItemClick,
        promptWallet,
        setShowAuthFlow,
        user,
        walletConnectorOptions,
    ]);
    // Flow for linking or signing in with social account before exchange
    const handleSocialConnect = React.useCallback((_a) => _tslib.__awaiter(void 0, [_a], void 0, function* ({ provider, exchange, props, isSocialProviderAlreadyVerified, }) {
        // if connected social return since already signed in
        if (isSocialProviderAlreadyVerified) {
            return false;
        }
        const payload = {
            payingWithDynamic: {
                chainName: props.chainName,
                destinationAddress: props.destinationAddress,
                network: props.network,
                tokenAmount: props.tokenAmount,
                tokenSymbol: props.tokenSymbol,
            },
            triggerFundFromExchangeOnSuccess: exchange,
        };
        if (user) {
            // link if user exists
            yield linkSocialAccount(provider, payload);
        }
        else {
            // sign in if no user
            yield signInWithSocialAccount(provider, payload);
        }
        return true;
    }), [linkSocialAccount, signInWithSocialAccount, user]);
    // exchange flow
    const handleExchangeFlow = React.useCallback((_b) => _tslib.__awaiter(void 0, [_b], void 0, function* ({ exchange, props, onBack }) {
        var _c, _d, _e, _f, _g;
        const fullExchange = (_c = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.exchanges) === null || _c === void 0 ? void 0 : _c.find((e) => e.exchange === exchange);
        // Social provider for this exchange, if any
        const provider = fullExchange === null || fullExchange === void 0 ? void 0 : fullExchange.socialProvider;
        const isProviderSocialConnectEnabled = provider &&
            Boolean((_e = (_d = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.providers) === null || _d === void 0 ? void 0 : _d.find((p) => p.provider === provider)) === null || _e === void 0 ? void 0 : _e.enabledAt);
        // Check if user already verified this social provider
        const isSocialProviderAlreadyVerified = (_g = (_f = user === null || user === void 0 ? void 0 : user.verifiedCredentials) === null || _f === void 0 ? void 0 : _f.some((c) => c.oauthProvider === provider)) !== null && _g !== void 0 ? _g : false;
        // If exchange requires social connect, handle that first
        if (isProviderSocialConnectEnabled && provider) {
            const handled = yield handleSocialConnect({
                exchange,
                isSocialProviderAlreadyVerified,
                props,
                provider,
            });
            // Social connect flow opened, stop here
            if (handled)
                return;
            // If already connected, prompt amount and fund with exchange
            promptExchange({
                exchange,
                onBack,
                payingWithDynamic: props,
            });
            return;
        }
        // No social provider = use on-ramp provider if configured
        if (fullExchange === null || fullExchange === void 0 ? void 0 : fullExchange.onRampProvider) {
            yield openOnramp({
                address: props.destinationAddress,
                chainName: props.chainName,
                network: String(props.network),
                onrampProvider: fullExchange.onRampProvider,
                overrideOnRamp: true,
                payingWithDynamic: true,
                token: props.tokenSymbol,
                tokenAmount: props.tokenAmount,
            });
        }
    }), [
        projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.exchanges,
        projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.providers,
        user === null || user === void 0 ? void 0 : user.verifiedCredentials,
        handleSocialConnect,
        promptExchange,
        openOnramp,
    ]);
    const payWithDynamic = React.useCallback((props) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        try {
            setEnabledOnrampProvidersTargetValue({
                address: props.destinationAddress,
                chainName: props.chainName,
                network: String(props.network),
                token: props.tokenSymbol,
                tokenAmount: props.tokenAmount,
            });
            const result = yield connectUnifiedForFunding({
                initiatedByWidget: false,
            });
            if (result.kind === 'wallet') {
                handleWalletFlow({
                    onBack: () => {
                        setShowAuthFlow(true);
                        setShowDynamicUserProfile(false);
                        payWithDynamic(props);
                    },
                    props,
                    wallet: result.wallet,
                });
            }
            else if (result.kind === 'exchange') {
                yield handleExchangeFlow({
                    exchange: result.exchange,
                    onBack: () => {
                        setShowAuthFlow(true);
                        setShowDynamicUserProfile(false);
                        payWithDynamic(props);
                    },
                    props,
                });
            }
            else {
                yield openOnramp({
                    address: props.destinationAddress,
                    chainName: props.chainName,
                    network: String(props.network),
                    onrampProvider: result.onramp.id,
                    payingWithDynamic: true,
                    token: props.tokenSymbol,
                    tokenAmount: props.tokenAmount,
                });
            }
        }
        catch (error) {
            logger.logger.error('usePayWithDynamic failed', error);
        }
    }), [
        setEnabledOnrampProvidersTargetValue,
        connectUnifiedForFunding,
        handleWalletFlow,
        setShowAuthFlow,
        setShowDynamicUserProfile,
        handleExchangeFlow,
        openOnramp,
    ]);
    return payWithDynamic;
};

exports.usePayWithDynamic = usePayWithDynamic;
