'use client'
import { __awaiter } from '../../../../../../_virtual/_tslib.js';
import { useRef, useState, useMemo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { ProviderEnum } from '@dynamic-labs/sdk-api-core';
import '../../../../context/DynamicContext/useDynamicContext/useDynamicContext.js';
import { useInternalDynamicContext } from '../../../../context/DynamicContext/useDynamicContext/useInternalDynamicContext/useInternalDynamicContext.js';
import { getOnrampProviders, getMoonPayCurrencies } from '../../../../data/api/onramp/onramp.js';
import { useEnvironmentId } from '../../../../store/state/dynamicContextProps/dynamicContextProps.js';
import { useMutation } from '../../../../utils/hooks/useMutation/useMutation.js';
import { usePromise } from '../../../../utils/hooks/usePromise/usePromise.js';

// 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 } = useTranslation();
    const { primaryWallet, network } = useInternalDynamicContext();
    const environmentId = useEnvironmentId();
    const isOpeningRef = useRef(false);
    // Only the user's explicit selection is stored; initial value is set once at mount.
    const [userSelectedToken, setUserSelectedToken] = 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(() => {
        if (!primaryWallet || !environmentId)
            return Promise.resolve([]);
        return 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 = useMemo(() => {
        if (!availableTokens.length)
            return userSelectedToken;
        const isValid = availableTokens.some((token) => token.code === userSelectedToken);
        return isValid ? userSelectedToken : availableTokens[0].code;
    }, [userSelectedToken, availableTokens]);
    const openMoonPayFn = useCallback(() => __awaiter(void 0, void 0, void 0, function* () {
        if (!primaryWallet || !environmentId || isOpeningRef.current)
            return;
        isOpeningRef.current = true;
        try {
            const providers = yield getOnrampProviders({
                chain: primaryWallet.chain,
                environmentId,
                includeDisabled: true,
                merchantName,
                networkId: network ? String(network) : undefined,
                token: selectedToken,
                walletAddress: effectiveWalletAddress,
            });
            const moonPayProvider = providers.find((provider) => provider.provider === 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(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,
    };
};

export { useMoonPayOnramp };
