'use client'
import { __awaiter } from '../../../../_virtual/_tslib.js';
import { jsx } from 'react/jsx-runtime';
import { createContext, useContext, useRef, useState, useCallback, useMemo } from 'react';
import { ProviderEnum } from '@dynamic-labs/sdk-api-core';
import { DynamicError, DeferredPromise } from '@dynamic-labs/utils';
import { onrampConfigurationToOnrampOption } from '../../utils/functions/onrampConfigurationToOnrampOption/onrampConfigurationToOnrampOption.js';
import { openOnrampPopup } from '../../utils/functions/openOnrampPopup.js';
import { rejectPromiseRef } from '../../utils/functions/rejectPromiseRef/rejectPromiseRef.js';
import { useWidgetContext } from '../../widgets/DynamicWidget/context/DynamicWidgetContext.js';
import '../DynamicContext/DynamicContext.js';
import '../../store/state/loadingAndLifecycle/loadingAndLifecycle.js';
import '@dynamic-labs/iconic';
import '@dynamic-labs/wallet-connector-core';
import '../ViewContext/ViewContext.js';
import '../../shared/logger.js';
import '@dynamic-labs/wallet-book';
import '../../utils/constants/colors.js';
import '../../utils/constants/values.js';
import '../../shared/consts/index.js';
import '../../events/dynamicEvents.js';
import '../CaptchaContext/CaptchaContext.js';
import '../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 '../AccessDeniedContext/AccessDeniedContext.js';
import '../AccountExistsContext/AccountExistsContext.js';
import '../UserWalletsContext/UserWalletsContext.js';
import '../../store/state/authMode/authMode.js';
import '../VerificationContext/VerificationContext.js';
import 'react-dom';
import '../../utils/functions/compareChains/compareChains.js';
import '../../views/Passkey/utils/findPrimaryEmbeddedChain/findPrimaryEmbeddedChain.js';
import '../ThemeContext/ThemeContext.js';
import '../../utils/hooks/useUserUpdateRequest/useUpdateUser/userFieldsSchema.js';
import 'bs58';
import '@dynamic-labs/types';
import '../SocialRedirectContext/SocialRedirectContext.js';
import '../LoadingContext/LoadingContext.js';
import '../WalletContext/WalletContext.js';
import '../../utils/hooks/useEmbeddedWallet/useSecureEnclaveEmbeddedWallet/constants.js';
import 'yup';
import '../MockContext/MockContext.js';
import '../../views/CollectUserDataView/useFields.js';
import '../FieldsStateContext/FieldsStateContext.js';
import '../UserFieldEditorContext/UserFieldEditorContext.js';
import '@dynamic-labs/rpc-providers';
import '../../store/state/walletOptions/walletOptions.js';
import 'react-i18next';
import '../../components/Accordion/components/AccordionItem/AccordionItem.js';
import '../../components/Alert/Alert.js';
import '../../components/ShadowDOM/ShadowDOM.js';
import '../../components/IconButton/IconButton.js';
import '../../components/InlineWidget/InlineWidget.js';
import '../../components/Input/Input.js';
import '../../components/IsBrowser/IsBrowser.js';
import '../../components/MenuList/Dropdown/Dropdown.js';
import '../../components/OverlayCard/OverlayCard.js';
import '../../components/Transition/ZoomTransition/ZoomTransition.js';
import '../../components/Transition/SlideInUpTransition/SlideInUpTransition.js';
import '../../components/Transition/OpacityTransition/OpacityTransition.js';
import '../../components/PasskeyCreatedSuccessBanner/PasskeyCreatedSuccessBanner.js';
import '../../components/Popper/Popper/Popper.js';
import '../../components/Popper/PopperContext/PopperContext.js';
import 'react-focus-lock';
import 'qrcode';
import 'formik';
import '../../utils/hooks/useSubdomainCheck/useSubdomainCheck.js';
import '../WalletGroupContext/WalletGroupContext.js';
import '../IpConfigurationContext/IpConfigurationContext.js';
import '../ConnectWithOtpContext/ConnectWithOtpContext.js';
import '../../widgets/DynamicBridgeWidget/views/WalletsView/components/SecondaryWallets/SecondaryWallets.js';
import '@hcaptcha/react-hcaptcha';
import '../../widgets/DynamicWidget/helpers/convertExchangeKeyAndProviderEnum.js';
import '../../views/ExchangeWhitelistWarning/ExchangeWhitelistWarning.js';
import '../ErrorContext/hooks/useErrorText/useErrorText.js';
import '../FooterAnimationContext/index.js';
import '../../views/MfaChooseDeviceView/useGetMfaOptions/useGetMfaOptions.js';
import '../PasskeyContext/PasskeyContext.js';
import '../../store/state/sendBalances.js';
import '../../store/state/connectorsInitializing/connectorsInitializing.js';
import '../../components/OverlayCardBase/OverlayCardTarget/OverlayCardTarget.js';
import '../../widgets/DynamicWidget/components/DynamicWidgetHeader/DynamicWidgetHeader.js';
import '../../views/TransactionConfirmationView/TransactionConfirmationView.js';
import '../../widgets/DynamicWidget/components/PasskeyCard/PasskeyCard.js';
import '../../widgets/DynamicWidget/views/CryptoComOnramp/CryptoComOnramp.js';
import '../../../index.js';
import '../../widgets/DynamicWidget/views/ReceiveWalletFunds/ReceiveWalletFunds.js';
import '../../store/state/tokenBalances.js';
import '../../store/state/multichainBalances.js';
import '../../shared/utils/functions/getInitialUrl/getInitialUrl.js';
import { useInternalDynamicContext } from '../DynamicContext/useDynamicContext/useInternalDynamicContext/useInternalDynamicContext.js';
import { useOnrampProviders } from './useOnrampProviders/useOnrampProviders.js';
import { getOnrampProviders } from './utils/getOnrampProviders.js';

const OnrampContext = createContext(undefined);
const OnrampContextProvider = ({ children, }) => {
    var _a, _b, _c, _d, _e;
    const promiseRef = useRef(null);
    const [selectedOnrampProvider, setSelectedOnrampProvider] = useState();
    const [showOnramp, _setShowOnramp] = useState(false);
    const [override, setOverride] = useState(false);
    const [overrideOnrampProvider, setOverrideOnrampProvider] = useState(undefined);
    const { environmentId, network, primaryWallet, projectSettings, overrides } = useInternalDynamicContext();
    const { setDynamicWidgetView } = useWidgetContext();
    const [enabledOnrampProvidersTarget, setEnabledOnrampProvidersTarget] = useState({});
    // Fetch onramp providers by default so Buy button is available in funding methods
    const [shouldFetchOnramps, setShouldFetchOnramps] = useState(true);
    const setShowOnramp = useCallback((value) => {
        _setShowOnramp(value);
        if (!value && promiseRef.current) {
            rejectPromiseRef(promiseRef, new DynamicError('User cancelled'));
        }
    }, []);
    const setEnabledOnrampProvidersTargetValue = useCallback(({ address, token, network, tokenAmount, chainName, currency, }) => {
        setEnabledOnrampProvidersTarget({
            address,
            chainName,
            currency,
            network,
            token,
            tokenAmount,
        });
        // Trigger fetch when target is set with specific parameters
        if (address || token || network || tokenAmount || chainName || currency) {
            setShouldFetchOnramps(true);
        }
    }, []);
    const resetOverrides = useCallback(() => {
        setOverrideOnrampProvider(undefined);
        setOverride(false);
    }, []);
    const { enabledOnRamps: enabledOnrampProvidersInDashboard } = useOnrampProviders({
        environmentId,
        includeDisabled: true,
        network,
        primaryWallet,
        projectSettingsOnramps: (_b = (_a = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.sdk) === null || _a === void 0 ? void 0 : _a.funding) === null || _b === void 0 ? void 0 : _b.onramps,
        shouldFetch: shouldFetchOnramps,
        target: enabledOnrampProvidersTarget,
    });
    const enabledOnrampProvidersInDashboardOptions = useMemo(() => {
        const options = enabledOnrampProvidersInDashboard.map((provider) => {
            const option = onrampConfigurationToOnrampOption(provider);
            // Route Crypto.com selection to a custom UI instead of immediate popup/link
            if (option.id === ProviderEnum.CryptoDotCom) {
                option.onClick = () => setDynamicWidgetView('crypto-com-onramp');
            }
            return option;
        });
        return options;
    }, [enabledOnrampProvidersInDashboard, setDynamicWidgetView]);
    const onrampOverrides = useMemo(() => {
        const configuredOverrides = overrides === null || overrides === void 0 ? void 0 : overrides.onrampOptions;
        if (typeof configuredOverrides === 'function') {
            return configuredOverrides(enabledOnrampProvidersInDashboardOptions);
        }
        return configuredOverrides || [];
    }, [overrides === null || overrides === void 0 ? void 0 : overrides.onrampOptions, enabledOnrampProvidersInDashboardOptions]);
    const onrampEnabled = useMemo(() => {
        var _a, _b, _c;
        // If onrampOptions is explicitly defined and results in an empty array, disable onramp
        if ((overrides === null || overrides === void 0 ? void 0 : overrides.onrampOptions) !== undefined &&
            onrampOverrides.length === 0) {
            return false;
        }
        // If we have overrides with items, enable onramp
        if (onrampOverrides.length > 0) {
            return true;
        }
        // Otherwise use the original logic for dashboard providers
        return Boolean(((_c = (_b = (_a = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.sdk) === null || _a === void 0 ? void 0 : _a.funding) === null || _b === void 0 ? void 0 : _b.onramps) === null || _c === void 0 ? void 0 : _c.length) &&
            enabledOnrampProvidersInDashboard.length);
    }, [
        (_e = (_d = (_c = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.sdk) === null || _c === void 0 ? void 0 : _c.funding) === null || _d === void 0 ? void 0 : _d.onramps) === null || _e === void 0 ? void 0 : _e.length,
        enabledOnrampProvidersInDashboard.length,
        onrampOverrides.length,
        overrides === null || overrides === void 0 ? void 0 : overrides.onrampOptions,
    ]);
    const hasPrimaryWallet = useMemo(() => Boolean(primaryWallet), [primaryWallet]);
    const setSelectedAndShowOnramp = useCallback(({ provider, wallet, payingWithDynamic, }) => {
        var _a;
        if (hasPrimaryWallet || payingWithDynamic) {
            setSelectedOnrampProvider(provider.id);
        }
        setShowOnramp(true);
        const shouldOpenPopup = provider.openMode === 'popup' && provider.url && setShowOnramp;
        if (!shouldOpenPopup) {
            return;
        }
        return openOnrampPopup((_a = provider.url) !== null && _a !== void 0 ? _a : '', wallet, setShowOnramp, provider.id);
    }, [hasPrimaryWallet, setShowOnramp]);
    const enabledOnrampProviders = useMemo(() => {
        // If we have explicit overrides (even empty array), use them
        if ((overrides === null || overrides === void 0 ? void 0 : overrides.onrampOptions) !== undefined) {
            return onrampOverrides;
        }
        // Otherwise fall back to dashboard options
        return enabledOnrampProvidersInDashboardOptions;
    }, [
        enabledOnrampProvidersInDashboardOptions,
        onrampOverrides,
        overrides === null || overrides === void 0 ? void 0 : overrides.onrampOptions,
    ]);
    const openOnramp = useCallback((_f) => __awaiter(void 0, [_f], void 0, function* ({ onrampProvider, address, token, tokenAmount, network: networkOverride, chainName, currency, overrideOnRamp, payingWithDynamic, }) {
        var _g, _h, _j, _k;
        if (!onrampEnabled && !overrideOnRamp && !payingWithDynamic) {
            throw new Error('Onramp is not enabled');
        }
        setOverride(false);
        if (promiseRef.current) {
            return promiseRef.current.promise;
        }
        promiseRef.current = new DeferredPromise();
        // Trigger onramp providers fetch if not already done
        if (!shouldFetchOnramps) {
            setShouldFetchOnramps(true);
        }
        let localOnrampProviders = enabledOnrampProvidersInDashboardOptions;
        const networkToUse = networkOverride || network;
        const shouldOverrideOnrampProviders = overrideOnRamp ||
            Boolean(address) ||
            Boolean(token) ||
            Boolean(networkOverride) ||
            Boolean(tokenAmount) ||
            Boolean(chainName) ||
            Boolean(currency);
        const allPayingParameters = Boolean(chainName) &&
            Boolean(networkToUse) &&
            Boolean(token) &&
            Boolean(tokenAmount) &&
            Boolean(address);
        if (payingWithDynamic && !allPayingParameters) {
            rejectPromiseRef(promiseRef, new Error('PayingWithDynamic: Missing parameters'));
            return (_g = promiseRef.current) === null || _g === void 0 ? void 0 : _g.promise;
        }
        if (shouldOverrideOnrampProviders)
            setOverride(true);
        if (shouldOverrideOnrampProviders ||
            (payingWithDynamic && allPayingParameters)) {
            localOnrampProviders = (yield getOnrampProviders({
                address,
                chainName,
                currency,
                environmentId,
                includeDisabled: overrideOnRamp,
                network: networkToUse,
                primaryWallet,
                token,
                tokenAmount,
            })).map((provider) => onrampConfigurationToOnrampOption(provider));
        }
        const onrampOption = localOnrampProviders.find((p) => p.id === onrampProvider);
        if (payingWithDynamic && !onrampOption) {
            rejectPromiseRef(promiseRef, new Error('PayingWithDynamic: Onramp provider not found'));
            return (_h = promiseRef.current) === null || _h === void 0 ? void 0 : _h.promise;
        }
        if (!onrampOption) {
            rejectPromiseRef(promiseRef, new Error('Onramp provider not found'));
            return (_j = promiseRef.current) === null || _j === void 0 ? void 0 : _j.promise;
        }
        setOverrideOnrampProvider(onrampOption);
        setSelectedAndShowOnramp({ payingWithDynamic, provider: onrampOption });
        return (_k = promiseRef.current) === null || _k === void 0 ? void 0 : _k.promise;
    }), [
        enabledOnrampProvidersInDashboardOptions,
        environmentId,
        onrampEnabled,
        primaryWallet,
        network,
        setSelectedAndShowOnramp,
        shouldFetchOnramps,
    ]);
    const selectedOnramp = useMemo(() => {
        let selected;
        if (override) {
            selected = overrideOnrampProvider;
        }
        else if (enabledOnrampProviders.length) {
            selected = enabledOnrampProviders.find((p) => p.id === selectedOnrampProvider);
        }
        return selected;
    }, [
        overrideOnrampProvider,
        enabledOnrampProviders,
        override,
        selectedOnrampProvider,
    ]);
    const selectOnrampProvider = useCallback(({ provider, wallet }) => {
        if (provider.onClick) {
            provider.onClick({ wallet });
            return;
        }
        resetOverrides();
        setSelectedAndShowOnramp({ provider, wallet });
    }, [setSelectedAndShowOnramp, resetOverrides]);
    const value = useMemo(() => ({
        enabledOnrampProviders,
        onrampEnabled,
        openOnramp,
        selectOnrampProvider,
        selectedOnramp,
        setEnabledOnrampProvidersTargetValue,
        setShowOnramp,
        showOnramp,
    }), [
        enabledOnrampProviders,
        onrampEnabled,
        openOnramp,
        selectedOnramp,
        setEnabledOnrampProvidersTargetValue,
        showOnramp,
        setShowOnramp,
        selectOnrampProvider,
    ]);
    return (jsx(OnrampContext.Provider, { value: value, children: children }));
};
const useOnrampContext = () => {
    const context = useContext(OnrampContext);
    if (!context)
        throw new Error('useOnrampContext must be used within a OnrampContextProvider');
    return context;
};

export { OnrampContext, OnrampContextProvider, useOnrampContext };
