'use client'
'use strict';

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

var _tslib = require('../../../../../../_virtual/_tslib.cjs');
var React = require('react');
var reactI18next = require('react-i18next');
var sdkApiCore = require('@dynamic-labs/sdk-api-core');
require('../../../../context/DynamicContext/useDynamicContext/useDynamicContext.cjs');
var useInternalDynamicContext = require('../../../../context/DynamicContext/useDynamicContext/useInternalDynamicContext/useInternalDynamicContext.cjs');
var onramp = require('../../../../data/api/onramp/onramp.cjs');
var dynamicContextProps = require('../../../../store/state/dynamicContextProps/dynamicContextProps.cjs');
var useMutation = require('../../../../utils/hooks/useMutation/useMutation.cjs');
var usePromise = require('../../../../utils/hooks/usePromise/usePromise.cjs');

// Only open URLs that are served over HTTPS from moonpay.com (or a subdomain).
const isMoonPayUrl = (url) => {
    try {
        const parsedUrl = new URL(url);
        return (parsedUrl.protocol === 'https:' &&
            (parsedUrl.hostname === 'moonpay.com' ||
                parsedUrl.hostname.endsWith('.moonpay.com')));
    }
    catch (_a) {
        return false;
    }
};
/**
 * Owns the MoonPay onramp data + actions: fetching supported currencies for the
 * connected wallet's chain, tracking the selected token, and opening the signed
 * MoonPay URL (validated against *.moonpay.com over HTTPS). The presentational
 * MoonPayOnramp view consumes this hook.
 */
const useMoonPayOnramp = ({ initialToken, merchantName, walletAddressOverride, onPaymentCreated, }) => {
    var _a;
    const { t } = reactI18next.useTranslation();
    const { primaryWallet, network } = useInternalDynamicContext.useInternalDynamicContext();
    const environmentId = dynamicContextProps.useEnvironmentId();
    const isOpeningRef = React.useRef(false);
    // Only the user's explicit selection is stored; initial value is set once at mount.
    const [userSelectedToken, setUserSelectedToken] = React.useState(initialToken !== null && initialToken !== void 0 ? initialToken : '');
    const effectiveWalletAddress = (_a = walletAddressOverride !== null && walletAddressOverride !== void 0 ? walletAddressOverride : primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.address) !== null && _a !== void 0 ? _a : '';
    const { data: availableTokens, isLoading: tokensLoading, error: tokensRawError, } = usePromise.usePromise(() => {
        if (!primaryWallet || !environmentId)
            return Promise.resolve([]);
        return onramp.getMoonPayCurrencies({
            chain: primaryWallet.chain,
            environmentId,
            networkId: network ? String(network) : undefined,
        });
    }, {
        deps: [primaryWallet, environmentId, network],
        enabled: Boolean(primaryWallet && environmentId),
        initialData: [],
    });
    // Derive the active token: honour the user's selection if it appears in the
    // currency list, otherwise fall back to the first available token.
    const selectedToken = React.useMemo(() => {
        if (!availableTokens.length)
            return userSelectedToken;
        const isValid = availableTokens.some((token) => token.code === userSelectedToken);
        return isValid ? userSelectedToken : availableTokens[0].code;
    }, [userSelectedToken, availableTokens]);
    const openMoonPayFn = React.useCallback(() => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        if (!primaryWallet || !environmentId || isOpeningRef.current)
            return;
        isOpeningRef.current = true;
        try {
            const providers = yield onramp.getOnrampProviders({
                chain: primaryWallet.chain,
                environmentId,
                includeDisabled: true,
                merchantName,
                networkId: network ? String(network) : undefined,
                token: selectedToken,
                walletAddress: effectiveWalletAddress,
            });
            const moonPayProvider = providers.find((provider) => provider.provider === sdkApiCore.ProviderEnum.MoonPay);
            if (!(moonPayProvider === null || moonPayProvider === void 0 ? void 0 : moonPayProvider.url)) {
                throw new Error('MoonPay provider not available');
            }
            if (!isMoonPayUrl(moonPayProvider.url)) {
                throw new Error('Invalid MoonPay URL');
            }
            if (onPaymentCreated) {
                onPaymentCreated(moonPayProvider.url);
            }
            else {
                window.open(moonPayProvider.url, '_blank', 'noopener,noreferrer');
            }
        }
        finally {
            isOpeningRef.current = false;
        }
    }), [
        primaryWallet,
        environmentId,
        network,
        selectedToken,
        effectiveWalletAddress,
        merchantName,
        onPaymentCreated,
    ]);
    const { mutate: openMoonPay, isLoading: isOpening, hasError: openMoonPayHasError, } = useMutation.useMutation(openMoonPayFn);
    const error = openMoonPayHasError
        ? t('dyn_moonpay_onramp.error', 'Failed to open MoonPay. Please try again.')
        : null;
    return {
        availableTokens,
        effectiveWalletAddress,
        error,
        isOpening,
        openMoonPay,
        primaryWallet,
        selectedToken,
        setSelectedToken: setUserSelectedToken,
        tokensError: Boolean(tokensRawError),
        tokensLoading,
    };
};

exports.useMoonPayOnramp = useMoonPayOnramp;
