'use client'
import { __awaiter } from '../../../../../_virtual/_tslib.js';
import { useRef, useCallback } from 'react';
import { DynamicError, DeferredPromise } from '@dynamic-labs/utils';
import '../../../context/DynamicContext/useDynamicContext/useDynamicContext.js';
import { useInternalDynamicContext } from '../../../context/DynamicContext/useDynamicContext/useInternalDynamicContext/useInternalDynamicContext.js';
import { useViewContext } from '../../../context/ViewContext/ViewContext.js';
import { useInternalDynamicEvents } from '../events/useDynamicEvents/useDynamicEvents.js';
import { useFundingExchangeHelpers } from '../useFundingExchangeHelpers/useFundingExchangeHelpers.js';
import { rejectPromiseRef } from '../../functions/rejectPromiseRef/rejectPromiseRef.js';

const useConnectExchangeForFunding = () => {
    const { setShowAuthFlow } = useInternalDynamicContext();
    const { clearStackAndPush } = useViewContext();
    const { selectExchangeConfig } = useFundingExchangeHelpers();
    const promiseRef = useRef(null);
    useInternalDynamicEvents('authFlowClose', () => {
        rejectPromiseRef(promiseRef, new DynamicError('User cancelled', 'user_cancelled'));
    });
    return useCallback((_a) => __awaiter(void 0, [_a], void 0, function* ({ initiatedByWidget }) {
        if (promiseRef.current)
            return promiseRef.current.promise;
        promiseRef.current = new DeferredPromise();
        const { onSelectExchange, showDefaultFooter } = selectExchangeConfig({
            initiatedByWidget,
            promiseRef,
            resultBuilder: (exchange) => exchange,
        });
        clearStackAndPush('external-funding-exchange-list', {
            onSelectExchange,
            showDefaultFooter,
        });
        setShowAuthFlow(true, {
            emitCancelAuth: false,
            ignoreIfIsEmbeddedWidget: true,
            initializeWalletConnect: false,
            performMultiWalletChecks: false,
        });
        return promiseRef.current.promise;
    }), [clearStackAndPush, selectExchangeConfig, setShowAuthFlow]);
};

export { useConnectExchangeForFunding };
