import { b as reactExports, cb as formatUnits, w as jsx, x as jsxs, dH as isDualVariantIcon, aP as MenuItem, B as Box, k as useTranslation, aU as ViewContext, I as CryptoFiatContext, G as EventTargetContext, F as useAnalytics, a1 as CryptoFiatActions, dI as DEFAULT_TOKEN_SYMBOLS, cT as st, M as HeaderNavigation, H as Heading, D as Body, z as SimpleLayout, r as ro, V as ViewActions, O as orchestrationEvents, bM as K } from './index-Cy6GwrlT.js';

var BridgeWidgetViews;
(function (BridgeWidgetViews) {
    BridgeWidgetViews["WALLET_NETWORK_SELECTION"] = "WALLET_NETWORK_SELECTION";
    BridgeWidgetViews["BRIDGE_FORM"] = "BRIDGE_FORM";
    BridgeWidgetViews["BRIDGE_REVIEW"] = "BRIDGE_REVIEW";
    BridgeWidgetViews["IN_PROGRESS"] = "IN_PROGRESS";
    BridgeWidgetViews["BRIDGE_FAILURE"] = "BRIDGE_FAILURE";
    BridgeWidgetViews["APPROVE_TRANSACTION"] = "APPROVE_TRANSACTION";
    BridgeWidgetViews["TRANSACTIONS"] = "TRANSACTIONS";
    BridgeWidgetViews["CLAIM_WITHDRAWAL"] = "CLAIM_WITHDRAWAL";
    BridgeWidgetViews["CLAIM_WITHDRAWAL_IN_PROGRESS"] = "CLAIM_WITHDRAWAL_IN_PROGRESS";
    BridgeWidgetViews["CLAIM_WITHDRAWAL_SUCCESS"] = "CLAIM_WITHDRAWAL_SUCCESS";
    BridgeWidgetViews["CLAIM_WITHDRAWAL_FAILURE"] = "CLAIM_WITHDRAWAL_FAILURE";
    BridgeWidgetViews["SERVICE_UNAVAILABLE"] = "SERVICE_UNAVAILABLE";
})(BridgeWidgetViews || (BridgeWidgetViews = {}));

/**
 * useMount hook to runs only once when the component mounts
 * after mounting condition is met
 *
 * @param fn function to run
 * @param shouldMount function to check mount condition
 * @param deps dependencies to watch for changes
 */
const useMount = (fn, shouldMount, deps) => {
    const isMounted = reactExports.useRef(false);
    const shouldMountCheck = () => {
        if (typeof shouldMount === 'function') {
            return shouldMount();
        }
        return true;
    };
    reactExports.useEffect(() => {
        if (isMounted.current)
            return;
        if (!shouldMountCheck())
            return;
        fn();
        isMounted.current = true;
    }, deps || []);
};

var SwapWidgetViews;
(function (SwapWidgetViews) {
    SwapWidgetViews["SWAP"] = "SWAP";
    SwapWidgetViews["IN_PROGRESS"] = "IN_PROGRESS";
    SwapWidgetViews["SUCCESS"] = "SUCCESS";
    SwapWidgetViews["FAIL"] = "FAIL";
    SwapWidgetViews["PRICE_SURGE"] = "PRICE_SURGE";
    SwapWidgetViews["APPROVE_ERC20"] = "APPROVE_ERC20_SWAP";
    SwapWidgetViews["SERVICE_UNAVAILABLE"] = "SERVICE_UNAVAILABLE";
})(SwapWidgetViews || (SwapWidgetViews = {}));

const convertFeeToFiat = (fee, token, conversions) => {
    let feeAmountInFiat = -1;
    if (fee && token) {
        const formattedAmount = formatUnits(fee, token.decimals);
        const gasFeeTokenConversion = conversions.get(token.symbol.toLocaleLowerCase());
        if (gasFeeTokenConversion) {
            const parsedAmount = parseFloat(formattedAmount);
            if (Number.isNaN(parsedAmount))
                return feeAmountInFiat;
            feeAmountInFiat = parsedAmount * gasFeeTokenConversion;
        }
    }
    return feeAmountInFiat;
};
// Formats a value to 2 decimal places unless the value is less than 0.01, in which case it will show the first non-zero digit of the decimal places
function formatFiatDecimals(value) {
    if (value < 0) {
        return '-.--';
    }
    const str = value.toString();
    if (str.includes('e') || value === 0) {
        // In this scenario, converting the fee to fiat has given us an exponent from
        // parseFloat as the fee value is very low. If the value is low enough that converting
        // the fee to fiat has returned an exponent, then it is significantly low enough to
        // be considered essentially zero.
        return '0.00';
    }
    if (value < 0.01) {
        for (let i = 0; i < str.length; i++) {
            if (str[i] !== '0' && str[i] !== '.') {
                return value.toFixed(i - 1);
            }
        }
    }
    return value.toFixed(2);
}
const getOnRampFeeEstimation = (onRampFees) => {
    const { minPercentage, maxPercentage } = onRampFees;
    if (minPercentage === undefined || maxPercentage === undefined)
        return '-.--';
    return `${minPercentage}% to ${maxPercentage}`;
};
const getBridgeFeeEstimation = (bridgeFees, conversions) => {
    const { fees, token } = bridgeFees;
    const feeAmount = fees.totalFees;
    if (feeAmount === undefined)
        return '-.--';
    if (token === undefined)
        return '-.--';
    const feesInFiat = convertFeeToFiat(fees.totalFees, token, conversions);
    if (feesInFiat < 0)
        return '-.--';
    return formatFiatDecimals(feesInFiat);
};

var OnRampWidgetViews;
(function (OnRampWidgetViews) {
    OnRampWidgetViews["ONRAMP"] = "ONRAMP";
    OnRampWidgetViews["IN_PROGRESS_LOADING"] = "IN_PROGRESS_LOADING";
    OnRampWidgetViews["IN_PROGRESS"] = "IN_PROGRESS";
    OnRampWidgetViews["SUCCESS"] = "SUCCESS";
    OnRampWidgetViews["FAIL"] = "FAIL";
})(OnRampWidgetViews || (OnRampWidgetViews = {}));

function TopUpMenuItem({ testId, icon, iconVariant, intentIcon, heading, caption, onClick, renderFeeFunction, isDisabled, }) {
    return (jsx(Box, { testId: "top-up-view", sx: { paddingY: '1px' }, children: jsxs(MenuItem, { testId: `menu-item-${testId}`, size: "small", emphasized: true, onClick: !isDisabled ? onClick : undefined, sx: isDisabled ? { opacity: '0.5', cursor: 'not-allowed' } : {}, children: [isDualVariantIcon(icon) ? (jsx(MenuItem.Icon, { icon: icon, variant: iconVariant })) : (jsx(MenuItem.Icon, { icon: icon })), jsx(MenuItem.Label, { size: "medium", children: heading }), jsx(MenuItem.IntentIcon, { icon: intentIcon }), jsxs(MenuItem.Caption, { testId: `menu-item-caption-${testId}`, children: [caption, jsx("br", {}), isDisabled ? '' : renderFeeFunction('-.--', false)] })] }) }));
}

/**
 * Handle asynchronous operations with memoization.
 * It only re-executes the async function when dependencies change.
 */
const useAsyncMemo = (asyncFn, dependencies) => {
    const [value, setValue] = reactExports.useState();
    reactExports.useEffect(() => {
        let isMounted = true;
        asyncFn().then((result) => {
            if (isMounted)
                setValue(result);
        });
        return () => {
            isMounted = false;
        };
    }, dependencies);
    return value;
};

const TOOLKIT_BASE_URL = {
    [K.SANDBOX]: 'https://checkout-playground.sandbox.immutable.com',
    [K.PRODUCTION]: 'https://toolkit.immutable.com',
};
function TopUpView({ widgetEvent, checkout, 
// eslint-disable-next-line @typescript-eslint/no-unused-vars
provider, // Keep this for future use
showOnrampOption, showSwapOption, showBridgeOption, tokenAddress, amount, analytics, onCloseButtonClick, onBackButtonClick, heading, subheading, }) {
    const { t } = useTranslation();
    const { userJourney } = analytics;
    const { viewDispatch } = reactExports.useContext(ViewContext);
    const { cryptoFiatState, cryptoFiatDispatch } = reactExports.useContext(CryptoFiatContext);
    const { conversions, fiatSymbol } = cryptoFiatState;
    const environment = checkout?.config.environment ?? K.SANDBOX;
    const { eventTargetState: { eventTarget }, } = reactExports.useContext(EventTargetContext);
    const [onRampFeesPercentage, setOnRampFeesPercentage] = reactExports.useState('-.--');
    const swapFeesInFiat = '0.05';
    const [, setBridgeFeesInFiat] = reactExports.useState('-.--');
    const title = heading ? t(...heading) : t('views.TOP_UP_VIEW.header.title');
    const description = subheading ? t(...subheading) : null;
    const { page, track } = useAnalytics();
    const isSwapAvailable = useAsyncMemo(async () => {
        if (!checkout)
            return undefined;
        try {
            return checkout.isSwapAvailable();
        }
        catch (error) {
            return false;
        }
    }, [checkout]);
    useMount(() => {
        page({ userJourney, screen: 'TopUp' });
    });
    reactExports.useEffect(() => {
        if (!cryptoFiatDispatch)
            return;
        cryptoFiatDispatch({
            payload: {
                type: CryptoFiatActions.SET_TOKEN_SYMBOLS,
                tokenSymbols: DEFAULT_TOKEN_SYMBOLS,
            },
        });
    }, [cryptoFiatDispatch]);
    // Bridge fees estimation
    reactExports.useEffect(() => {
        if (!checkout)
            return;
        (async () => {
            const bridgeEstimate = await checkout.gasEstimate({
                gasEstimateType: st.BRIDGE_TO_L2,
            });
            const est = await getBridgeFeeEstimation(bridgeEstimate, conversions);
            setBridgeFeesInFiat(est);
        })();
    }, [checkout !== undefined]);
    // Onramp fees estimation
    reactExports.useEffect(() => {
        if (!checkout)
            return;
        (async () => {
            const onRampFeesEstimate = await checkout.getExchangeFeeEstimate();
            const onRampFees = getOnRampFeeEstimation(onRampFeesEstimate);
            setOnRampFeesPercentage(onRampFees);
        })();
    }, [checkout !== undefined]);
    const localTrack = (control, extras, controlType = 'Button') => {
        track({
            userJourney,
            screen: 'TopUp',
            control,
            controlType,
            extras,
        });
    };
    const onClickSwap = () => {
        if (widgetEvent === ro.IMTBL_SWAP_WIDGET_EVENT) {
            const data = {
                toTokenAddress: '',
                fromAmount: '',
                fromTokenAddress: '',
            };
            viewDispatch({
                payload: {
                    type: ViewActions.UPDATE_VIEW,
                    view: {
                        type: SwapWidgetViews.SWAP,
                        data,
                    },
                },
            });
            localTrack('Swap', { ...data, widgetEvent });
            return;
        }
        const data = {
            fromTokenAddress: '',
            toTokenAddress: tokenAddress ?? '',
            amount: '',
        };
        orchestrationEvents.sendRequestSwapEvent(eventTarget, widgetEvent, data);
        localTrack('Swap', { ...data, widgetEvent });
    };
    const onClickBridge = () => {
        if (widgetEvent === ro.IMTBL_BRIDGE_WIDGET_EVENT) {
            const data = {
                fromTokenAddress: '',
                fromAmount: '',
            };
            viewDispatch({
                payload: {
                    type: ViewActions.UPDATE_VIEW,
                    view: {
                        type: BridgeWidgetViews.WALLET_NETWORK_SELECTION,
                        data,
                    },
                },
            });
            localTrack('Bridge', { ...data, widgetEvent });
            return;
        }
        const data = {
            tokenAddress: '',
            amount: '',
        };
        orchestrationEvents.sendRequestBridgeEvent(eventTarget, widgetEvent, data);
        localTrack('Bridge', { ...data, widgetEvent });
    };
    const onClickOnRamp = () => {
        if (widgetEvent === ro.IMTBL_ONRAMP_WIDGET_EVENT) {
            const data = {
                tokenAddress: '',
                amount: '',
            };
            viewDispatch({
                payload: {
                    type: ViewActions.UPDATE_VIEW,
                    view: {
                        type: OnRampWidgetViews.ONRAMP,
                        data,
                    },
                },
            });
            localTrack('OnRamp', { ...data, widgetEvent });
            return;
        }
        const data = {
            tokenAddress: tokenAddress ?? '',
            amount: amount ?? '',
        };
        orchestrationEvents.sendRequestOnrampEvent(eventTarget, widgetEvent, data);
        localTrack('OnRamp', { ...data, widgetEvent });
    };
    const onClickAdvancedOptions = () => {
        const toolkitBaseUrl = TOOLKIT_BASE_URL[environment];
        const data = {
            tokenAddress: tokenAddress ?? '',
            amount: amount ?? '',
        };
        localTrack('AdvancedOptions', { ...data, widgetEvent });
        window.open(`${toolkitBaseUrl}/squid-bridge/`, '_blank');
    };
    const renderFees = (txt) => (jsx(Box, { sx: {
            fontSize: 'base.text.caption.small.regular.fontSize',
            c: 'base.color.translucent.standard.600',
        }, children: txt }));
    const topUpFeatures = reactExports.useMemo(() => [
        {
            testId: 'onramp',
            icon: 'BankCard',
            iconVariant: 'bold',
            textConfigKey: 'views.TOP_UP_VIEW.topUpOptions.debit',
            onClickEvent: onClickOnRamp,
            fee: () => renderFees(`${t('views.TOP_UP_VIEW.topUpOptions.debit.subcaption')} ≈ ${onRampFeesPercentage}%`),
            isAvailable: true,
            isEnabled: showOnrampOption,
        },
        {
            testId: 'onramp',
            icon: 'BankCard',
            textConfigKey: 'views.TOP_UP_VIEW.topUpOptions.credit',
            onClickEvent: onClickOnRamp,
            fee: () => renderFees(`${t('views.TOP_UP_VIEW.topUpOptions.credit.subcaption')} ≈ ${onRampFeesPercentage}%`),
            isAvailable: true,
            isEnabled: showOnrampOption,
        },
        {
            testId: 'advanced',
            icon: 'Minting',
            iconVariant: 'bold',
            intentIcon: 'JumpTo',
            textConfigKey: 'views.TOP_UP_VIEW.topUpOptions.advanced',
            onClickEvent: onClickAdvancedOptions,
            fee: () => renderFees(''),
            isAvailable: true,
            isEnabled: true,
        },
        {
            testId: 'swap',
            icon: 'Swap',
            textConfigKey: 'views.TOP_UP_VIEW.topUpOptions.swap',
            onClickEvent: onClickSwap,
            fee: () => renderFees(`${t('views.TOP_UP_VIEW.topUpOptions.swap.subcaption')} ≈ $${swapFeesInFiat} ${fiatSymbol.toUpperCase()}`),
            isAvailable: !!isSwapAvailable,
            isEnabled: showSwapOption,
        },
        {
            testId: 'bridge',
            icon: 'ArrowForward',
            textConfigKey: 'views.TOP_UP_VIEW.topUpOptions.bridge',
            onClickEvent: onClickBridge,
            fee: () => renderFees(''),
            isAvailable: true,
            isEnabled: showBridgeOption,
        },
    ], [showBridgeOption, showOnrampOption, showSwapOption]);
    return (jsx(SimpleLayout, { header: (jsx(HeaderNavigation, { onBackButtonClick: onBackButtonClick, onCloseButtonClick: onCloseButtonClick, showBack: true })), children: jsxs(Box, { sx: { paddingX: 'base.spacing.x4', paddingY: 'base.spacing.x4' }, children: [jsx(Heading, { size: "small", children: title }), description && (jsx(Body, { size: "small", sx: { color: 'base.color.text.body.secondary' }, children: description })), jsx(Box, { sx: { paddingY: 'base.spacing.x4' }, children: topUpFeatures
                        .sort((a, b) => Number(b.isAvailable) - Number(a.isAvailable))
                        .map((element) => element.isEnabled && (jsx(TopUpMenuItem, { testId: element.testId, icon: element.icon, iconVariant: element.iconVariant, intentIcon: element.intentIcon, heading: t(`${element.textConfigKey}.heading`), caption: !element.isAvailable
                            ? t(`${element.textConfigKey}.disabledCaption`)
                            : t(`${element.textConfigKey}.caption`), onClick: element.onClickEvent, renderFeeFunction: element.fee, isDisabled: !element.isAvailable }, t(`${element.textConfigKey}.heading`).toLowerCase()))) })] }) }));
}

export { BridgeWidgetViews as B, OnRampWidgetViews as O, SwapWidgetViews as S, TopUpView as T, useMount as u };
