"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("react");
const addresses_js_1 = require("../../../../../../constants/addresses.js");
const isSwapRequiredPostOnramp_js_1 = require("../../../../../../pay/buyWithFiat/isSwapRequiredPostOnramp.js");
const formatNumber_js_1 = require("../../../../../../utils/formatNumber.js");
const units_js_1 = require("../../../../../../utils/units.js");
const index_js_1 = require("../../../../../core/design-system/index.js");
const useChainQuery_js_1 = require("../../../../../core/hooks/others/useChainQuery.js");
const useWalletBalance_js_1 = require("../../../../../core/hooks/others/useWalletBalance.js");
const useBuyWithCryptoQuote_js_1 = require("../../../../../core/hooks/pay/useBuyWithCryptoQuote.js");
const useBuyWithFiatQuote_js_1 = require("../../../../../core/hooks/pay/useBuyWithFiatQuote.js");
const wallet_hooks_js_1 = require("../../../../../core/hooks/wallets/wallet-hooks.js");
const LoadingScreen_js_1 = require("../../../../wallets/shared/LoadingScreen.js");
const Drawer_js_1 = require("../../../components/Drawer.js");
const DynamicHeight_js_1 = require("../../../components/DynamicHeight.js");
const Skeleton_js_1 = require("../../../components/Skeleton.js");
const Spacer_js_1 = require("../../../components/Spacer.js");
const Spinner_js_1 = require("../../../components/Spinner.js");
const SwitchNetwork_js_1 = require("../../../components/SwitchNetwork.js");
const TokenIcon_js_1 = require("../../../components/TokenIcon.js");
const basic_js_1 = require("../../../components/basic.js");
const buttons_js_1 = require("../../../components/buttons.js");
const text_js_1 = require("../../../components/text.js");
const NetworkSelector_js_1 = require("../../NetworkSelector.js");
const TokenSelector_js_1 = require("../TokenSelector.js");
const nativeToken_js_1 = require("../nativeToken.js");
const EstimatedTimeAndFees_js_1 = require("./EstimatedTimeAndFees.js");
const PayWIthCreditCard_js_1 = require("./PayWIthCreditCard.js");
const PaymentSelection_js_1 = require("./PaymentSelection.js");
const FiatFlow_js_1 = require("./fiat/FiatFlow.js");
const useBuyTxStates_js_1 = require("./main/useBuyTxStates.js");
const useEnabledPaymentMethods_js_1 = require("./main/useEnabledPaymentMethods.js");
const useUISelectionStates_js_1 = require("./main/useUISelectionStates.js");
const openOnRamppopup_js_1 = require("./openOnRamppopup.js");
const BuyTokenInput_js_1 = require("./swap/BuyTokenInput.js");
const Fees_js_1 = require("./swap/Fees.js");
const PayWithCrypto_js_1 = require("./swap/PayWithCrypto.js");
const SwapFlow_js_1 = require("./swap/SwapFlow.js");
const pendingSwapTx_js_1 = require("./swap/pendingSwapTx.js");
const useSwapSupportedChains_js_1 = require("./swap/useSwapSupportedChains.js");
/**
 * @internal
 */
function BuyScreen(props) {
    const supportedDestinationsQuery = (0, useSwapSupportedChains_js_1.useBuySupportedDestinations)(props.client);
    if (!supportedDestinationsQuery.data) {
        return (0, jsx_runtime_1.jsx)(LoadingScreen_js_1.LoadingScreen, {});
    }
    return ((0, jsx_runtime_1.jsx)(BuyScreenContent, { ...props, onViewPendingTx: props.onViewPendingTx, supportedDestinations: supportedDestinationsQuery.data, buyForTx: props.buyForTx }));
}
exports.default = BuyScreen;
function useBuyScreenStates(options) {
    const { payOptions } = options;
    const [method, setMethod] = (0, react_1.useState)(payOptions.buyWithCrypto === false
        ? "creditCard"
        : payOptions.buyWithFiat === false
            ? "crypto"
            : "creditCard");
    const [screen, setScreen] = (0, react_1.useState)({
        type: "main",
    });
    const [drawerScreen, setDrawerScreen] = (0, react_1.useState)();
    const { drawerRef, drawerOverlayRef, onClose } = (0, Drawer_js_1.useDrawer)();
    function closeDrawer() {
        onClose(() => {
            setDrawerScreen(undefined);
        });
    }
    function showMainScreen() {
        setScreen({
            type: "main",
        });
    }
    return {
        method,
        setMethod,
        screen,
        setScreen,
        drawerScreen,
        setDrawerScreen,
        drawerRef,
        drawerOverlayRef,
        closeDrawer,
        showMainScreen,
    };
}
/**
 * @internal
 */
function BuyScreenContent(props) {
    const { client, supportedDestinations, connectLocale, payOptions, buyForTx } = props;
    const account = (0, wallet_hooks_js_1.useActiveAccount)();
    const activeChain = (0, wallet_hooks_js_1.useActiveWalletChain)();
    // prefetch chains metadata for destination chains
    (0, useChainQuery_js_1.useChainsQuery)(supportedDestinations.map((x) => x.chain) || [], 50);
    // screen
    const { method, setMethod, screen, setScreen, drawerScreen, setDrawerScreen, drawerRef, drawerOverlayRef, closeDrawer, showMainScreen, } = useBuyScreenStates({ payOptions });
    // UI selection
    const { tokenAmount, setTokenAmount, setHasEditedAmount, hasEditedAmount, toChain, setToChain, deferredTokenAmount, fromChain, setFromChain, toToken, setToToken, fromToken, setFromToken, selectedCurrency, } = (0, useUISelectionStates_js_1.useUISelectionStates)({
        payOptions,
        buyForTx,
        supportedDestinations,
    });
    // Buy Transaction flow states
    const { amountNeeded } = (0, useBuyTxStates_js_1.useBuyTxStates)({
        setTokenAmount,
        buyForTx,
        hasEditedAmount,
        isMainScreen: screen.type === "main",
        account,
    });
    // check if the screen is expanded or not
    const isExpanded = activeChain && tokenAmount;
    // update supportedSources whenever toToken or toChain is updated
    const supportedSourcesQuery = (0, useSwapSupportedChains_js_1.useBuySupportedSources)({
        client: props.client,
        destinationChainId: toChain.id,
        destinationTokenAddress: (0, nativeToken_js_1.isNativeToken)(toToken)
            ? addresses_js_1.NATIVE_TOKEN_ADDRESS
            : toToken.address,
    });
    const destinationSupportedTokens = (0, react_1.useMemo)(() => {
        return createSupportedTokens(supportedDestinations, payOptions, props.supportedTokens);
    }, [props.supportedTokens, supportedDestinations, payOptions]);
    const sourceSupportedTokens = (0, react_1.useMemo)(() => {
        if (!supportedSourcesQuery.data) {
            return undefined;
        }
        return createSupportedTokens(supportedSourcesQuery.data, payOptions, props.supportedTokens);
    }, [props.supportedTokens, supportedSourcesQuery.data, payOptions]);
    const { showPaymentSelection } = (0, useEnabledPaymentMethods_js_1.useEnabledPaymentMethods)({
        payOptions,
        supportedDestinations,
        toChain,
        toToken,
        method,
        setMethod,
    });
    // screens ----------------------------
    if (screen.type === "node") {
        return screen.node;
    }
    if (screen.type === "screen-id" && screen.name === "select-to-token") {
        const chains = supportedDestinations.map((x) => x.chain);
        // if token selection is disabled - only show network selector screen
        if (payOptions.prefillBuy?.allowEdits?.token === false) {
            return ((0, jsx_runtime_1.jsx)(ChainSelectionScreen, { chains: chains, client: props.client, connectLocale: props.connectLocale, setChain: setToChain, showMainScreen: showMainScreen }));
        }
        return ((0, jsx_runtime_1.jsx)(TokenSelector_js_1.TokenSelector, { onBack: showMainScreen, tokenList: ((toChain?.id ? destinationSupportedTokens[toChain.id] : undefined) ||
                []).filter((x) => x.address !== addresses_js_1.NATIVE_TOKEN_ADDRESS), onTokenSelect: (tokenInfo) => {
                setToToken(tokenInfo);
                showMainScreen();
            }, chain: toChain, chainSelection: 
            // hide chain selection if it's disabled
            payOptions.prefillBuy?.allowEdits?.chain !== false
                ? {
                    chains: chains,
                    select: (c) => {
                        setToChain(c);
                    },
                }
                : undefined, connectLocale: connectLocale, client: client }));
    }
    if (screen.type === "screen-id" &&
        screen.name === "select-from-token" &&
        supportedSourcesQuery.data &&
        sourceSupportedTokens) {
        const chains = supportedSourcesQuery.data.map((x) => x.chain);
        // if token selection is disabled - only show network selector screen
        if (payOptions.buyWithCrypto !== false &&
            payOptions.buyWithCrypto?.prefillSource?.allowEdits?.token === false) {
            return ((0, jsx_runtime_1.jsx)(ChainSelectionScreen, { chains: chains, client: props.client, connectLocale: props.connectLocale, setChain: setFromChain, showMainScreen: showMainScreen }));
        }
        return ((0, jsx_runtime_1.jsx)(TokenSelector_js_1.TokenSelector, { onBack: showMainScreen, tokenList: ((fromChain?.id ? sourceSupportedTokens[fromChain.id] : undefined) ||
                []).filter((x) => x.address !== addresses_js_1.NATIVE_TOKEN_ADDRESS), onTokenSelect: (tokenInfo) => {
                setFromToken(tokenInfo);
                setScreen({
                    type: "main",
                });
            }, chain: fromChain, chainSelection: 
            // hide chain selection if it's disabled
            payOptions.buyWithCrypto !== false &&
                payOptions.buyWithCrypto?.prefillSource?.allowEdits?.chain !== false
                ? {
                    chains: supportedSourcesQuery.data.map((x) => x.chain),
                    select: (c) => setFromChain(c),
                }
                : undefined, connectLocale: connectLocale, client: client }));
    }
    return ((0, jsx_runtime_1.jsx)(basic_js_1.Container, { animate: "fadein", children: (0, jsx_runtime_1.jsxs)("div", { onClick: (e) => {
                if (drawerScreen &&
                    drawerRef.current &&
                    !drawerRef.current.contains(e.target)) {
                    e.preventDefault();
                    e.stopPropagation();
                    closeDrawer();
                }
            }, children: [drawerScreen && ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)(Drawer_js_1.DrawerOverlay, { ref: drawerOverlayRef }), (0, jsx_runtime_1.jsx)(Drawer_js_1.Drawer, { ref: drawerRef, close: closeDrawer, children: (0, jsx_runtime_1.jsx)(DynamicHeight_js_1.DynamicHeight, { children: drawerScreen }) })] })), (0, jsx_runtime_1.jsxs)(basic_js_1.Container, { p: "lg", style: {
                        paddingBottom: 0,
                    }, children: [(0, jsx_runtime_1.jsx)(basic_js_1.ModalHeader, { title: props.buyForTx
                                ? `Not enough ${props.buyForTx.tokenSymbol}`
                                : "Buy", onBack: props.onBack }), (0, jsx_runtime_1.jsx)(Spacer_js_1.Spacer, { y: "lg" }), !isExpanded && (0, jsx_runtime_1.jsx)(Spacer_js_1.Spacer, { y: "xl" }), amountNeeded && props.buyForTx ? ((0, jsx_runtime_1.jsx)(BuyForTxUI, { amountNeeded: String((0, formatNumber_js_1.formatNumber)(Number((0, units_js_1.toEther)(amountNeeded)), 4)), buyForTx: props.buyForTx, client: client })) : null, (0, jsx_runtime_1.jsx)(BuyTokenInput_js_1.BuyTokenInput, { value: tokenAmount, onChange: async (value) => {
                                setHasEditedAmount(true);
                                setTokenAmount(value);
                            }, freezeAmount: payOptions.prefillBuy?.allowEdits?.amount === false, freezeChainAndToken: payOptions.prefillBuy?.allowEdits?.chain === false &&
                                payOptions.prefillBuy?.allowEdits?.token === false, token: toToken, chain: toChain, onSelectToken: () => {
                                setScreen({
                                    type: "screen-id",
                                    name: "select-to-token",
                                });
                            }, client: props.client, hideTokenSelector: !!props.buyForTx })] }), showPaymentSelection ? (0, jsx_runtime_1.jsx)(Spacer_js_1.Spacer, { y: "lg" }) : (0, jsx_runtime_1.jsx)(Spacer_js_1.Spacer, { y: "md" }), isExpanded && ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [showPaymentSelection && ((0, jsx_runtime_1.jsxs)(basic_js_1.Container, { px: "lg", children: [(0, jsx_runtime_1.jsx)(PaymentSelection_js_1.PaymentSelection, { selected: method, onSelect: setMethod }), (0, jsx_runtime_1.jsx)(Spacer_js_1.Spacer, { y: "md" })] })), method === "crypto" && account && activeChain && ((0, jsx_runtime_1.jsx)(SwapScreenContent, { ...props, setScreen: setScreen, setDrawerScreen: setDrawerScreen, tokenAmount: deferredTokenAmount, toChain: toChain, toToken: toToken, fromChain: fromChain, fromToken: fromToken, showFromTokenSelector: () => {
                                setScreen({
                                    type: "screen-id",
                                    name: "select-from-token",
                                });
                            }, account: account, activeChain: activeChain })), method === "creditCard" && account && ((0, jsx_runtime_1.jsx)(FiatScreenContent, { ...props, setScreen: setScreen, setDrawerScreen: setDrawerScreen, tokenAmount: deferredTokenAmount, toChain: toChain, toToken: toToken, closeDrawer: closeDrawer, selectedCurrency: selectedCurrency, showCurrencySelector: () => {
                                // currently disabled because we are only using Stripe
                            }, account: account })), (0, jsx_runtime_1.jsx)(Spacer_js_1.Spacer, { y: "sm" })] })), (0, jsx_runtime_1.jsxs)(basic_js_1.Container, { px: "lg", flex: "column", gap: "sm", children: [!isExpanded && ((0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, { children: !account && props.connectButton ? ((0, jsx_runtime_1.jsx)("div", { children: props.connectButton })) : ((0, jsx_runtime_1.jsx)(buttons_js_1.Button, { variant: "accent", fullWidth: true, disabled: true, "data-disable": true, children: "Continue" })) })), account && ((0, jsx_runtime_1.jsx)(buttons_js_1.Button, { variant: "outline", fullWidth: true, style: {
                                padding: index_js_1.spacing.xs,
                                fontSize: index_js_1.fontSize.sm,
                            }, onClick: props.onViewPendingTx, children: "View all transactions" }))] }), (0, jsx_runtime_1.jsx)(Spacer_js_1.Spacer, { y: "lg" })] }) }));
}
function SwapScreenContent(props) {
    const { setDrawerScreen, setScreen, account, client, toChain, tokenAmount, toToken, fromChain, fromToken, showFromTokenSelector, payOptions, } = props;
    const fromTokenBalanceQuery = (0, useWalletBalance_js_1.useWalletBalance)({
        address: account.address,
        chain: fromChain,
        tokenAddress: (0, nativeToken_js_1.isNativeToken)(fromToken) ? undefined : fromToken.address,
        client,
    });
    const quoteParams = tokenAmount && !(fromChain.id === toChain.id && fromToken === toToken)
        ? {
            // wallet
            fromAddress: account.address,
            // from
            fromChainId: fromChain.id,
            fromTokenAddress: (0, nativeToken_js_1.isNativeToken)(fromToken)
                ? addresses_js_1.NATIVE_TOKEN_ADDRESS
                : fromToken.address,
            // to
            toChainId: toChain.id,
            toTokenAddress: (0, nativeToken_js_1.isNativeToken)(toToken)
                ? addresses_js_1.NATIVE_TOKEN_ADDRESS
                : toToken.address,
            toAmount: tokenAmount,
            client,
        }
        : undefined;
    const quoteQuery = (0, useBuyWithCryptoQuote_js_1.useBuyWithCryptoQuote)(quoteParams, {
        // refetch every 30 seconds
        staleTime: 30 * 1000,
        refetchInterval: 30 * 1000,
        gcTime: 30 * 1000,
    });
    const sourceTokenAmount = quoteQuery.data?.swapDetails.fromAmount;
    const isNotEnoughBalance = !!sourceTokenAmount &&
        !!fromTokenBalanceQuery.data &&
        Number(fromTokenBalanceQuery.data.displayValue) < Number(sourceTokenAmount);
    const disableContinue = !quoteQuery.data || isNotEnoughBalance;
    const switchChainRequired = props.activeChain.id !== fromChain.id;
    function getErrorMessage(err) {
        const defaultMessage = "Unable to get price quote";
        try {
            if (err instanceof Error) {
                if (err.message.includes("Minimum")) {
                    const msg = err.message;
                    return msg.replace("Fetch failed: Error: ", "");
                }
            }
            return defaultMessage;
        }
        catch {
            return defaultMessage;
        }
    }
    function showSwapFlow() {
        if (!quoteQuery.data) {
            return;
        }
        setScreen({
            type: "node",
            node: ((0, jsx_runtime_1.jsx)(SwapFlow_js_1.SwapFlow, { isBuyForTx: !!props.buyForTx, isEmbed: props.isEmbed, client: client, onBack: () => {
                    setScreen({
                        type: "main",
                    });
                }, buyWithCryptoQuote: quoteQuery.data, account: account, onViewPendingTx: props.onViewPendingTx, isFiatFlow: false, onDone: props.onDone, onTryAgain: () => {
                    setScreen({
                        type: "main",
                    });
                    quoteQuery.refetch();
                } })),
        });
    }
    function showFees() {
        if (!quoteQuery.data) {
            return;
        }
        setDrawerScreen((0, jsx_runtime_1.jsxs)("div", { children: [(0, jsx_runtime_1.jsx)(text_js_1.Text, { size: "lg", color: "primaryText", children: "Fees" }), (0, jsx_runtime_1.jsx)(Spacer_js_1.Spacer, { y: "lg" }), (0, jsx_runtime_1.jsx)(Fees_js_1.SwapFees, { quote: quoteQuery.data, align: "left" })] }));
    }
    const prefillSource = payOptions.buyWithCrypto !== false
        ? payOptions.buyWithCrypto?.prefillSource
        : undefined;
    return ((0, jsx_runtime_1.jsxs)(basic_js_1.Container, { px: "lg", flex: "column", gap: "md", children: [(0, jsx_runtime_1.jsxs)("div", { children: [(0, jsx_runtime_1.jsx)(PayWithCrypto_js_1.PayWithCrypto, { value: sourceTokenAmount || "", onSelectToken: showFromTokenSelector, chain: fromChain, token: fromToken, isLoading: quoteQuery.isLoading && !sourceTokenAmount, client: client, freezeChainAndTokenSelection: prefillSource?.allowEdits?.chain === false &&
                            prefillSource?.allowEdits?.token === false }), (0, jsx_runtime_1.jsx)(EstimatedTimeAndFees_js_1.EstimatedTimeAndFees, { quoteIsLoading: quoteQuery.isLoading, estimatedSeconds: quoteQuery.data?.swapDetails.estimated.durationSeconds, onViewFees: showFees })] }), quoteQuery.error && ((0, jsx_runtime_1.jsx)(text_js_1.Text, { color: "danger", size: "sm", center: true, children: getErrorMessage(quoteQuery.error) })), switchChainRequired &&
                !quoteQuery.isLoading &&
                !isNotEnoughBalance &&
                !quoteQuery.error ? ((0, jsx_runtime_1.jsx)(SwitchNetwork_js_1.SwitchNetworkButton, { variant: "accent", fullWidth: true, chain: fromChain })) : ((0, jsx_runtime_1.jsx)(buttons_js_1.Button, { variant: disableContinue ? "outline" : "accent", fullWidth: true, "data-disabled": disableContinue, disabled: disableContinue, onClick: async () => {
                    if (!disableContinue) {
                        showSwapFlow();
                    }
                }, gap: "xs", children: isNotEnoughBalance ? ((0, jsx_runtime_1.jsx)(text_js_1.Text, { color: "danger", children: "Not Enough Funds" })) : quoteQuery.isLoading ? ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)(Spinner_js_1.Spinner, { size: "sm", color: "accentText" }), "Getting price quote"] })) : ("Continue") }))] }));
}
function FiatScreenContent(props) {
    const { toToken, tokenAmount, account, client, setScreen, setDrawerScreen, toChain, showCurrencySelector, selectedCurrency, } = props;
    const buyWithFiatOptions = props.payOptions.buyWithFiat;
    const fiatQuoteQuery = (0, useBuyWithFiatQuote_js_1.useBuyWithFiatQuote)(buyWithFiatOptions !== false && tokenAmount
        ? {
            fromCurrencySymbol: "USD", // STRIPE only supports USD
            toChainId: toChain.id,
            toAddress: account.address,
            toTokenAddress: (0, nativeToken_js_1.isNativeToken)(toToken)
                ? addresses_js_1.NATIVE_TOKEN_ADDRESS
                : toToken.address,
            toAmount: tokenAmount,
            client,
            isTestMode: buyWithFiatOptions?.testMode,
        }
        : undefined);
    function handleSubmit() {
        if (!fiatQuoteQuery.data) {
            return;
        }
        const hasTwoSteps = (0, isSwapRequiredPostOnramp_js_1.isSwapRequiredPostOnramp)(fiatQuoteQuery.data);
        let openedWindow = null;
        if (!hasTwoSteps) {
            openedWindow = (0, openOnRamppopup_js_1.openOnrampPopup)(fiatQuoteQuery.data.onRampLink, typeof props.theme === "string" ? props.theme : props.theme.type);
            (0, pendingSwapTx_js_1.addPendingTx)({
                type: "fiat",
                intentId: fiatQuoteQuery.data.intentId,
            });
        }
        setScreen({
            type: "node",
            node: ((0, jsx_runtime_1.jsx)(FiatFlow_js_1.FiatFlow, { isBuyForTx: !!props.buyForTx, quote: fiatQuoteQuery.data, onBack: () => {
                    setScreen({
                        type: "main",
                    });
                }, client: client, testMode: buyWithFiatOptions !== false
                    ? buyWithFiatOptions?.testMode || false
                    : false, theme: typeof props.theme === "string" ? props.theme : props.theme.type, onViewPendingTx: props.onViewPendingTx, openedWindow: openedWindow, onDone: props.onDone, isEmbed: props.isEmbed })),
        });
    }
    function showFees() {
        if (!fiatQuoteQuery.data) {
            return;
        }
        setDrawerScreen((0, jsx_runtime_1.jsxs)("div", { children: [(0, jsx_runtime_1.jsx)(text_js_1.Text, { size: "lg", color: "primaryText", children: "Fees" }), (0, jsx_runtime_1.jsx)(Spacer_js_1.Spacer, { y: "lg" }), (0, jsx_runtime_1.jsx)(Fees_js_1.FiatFees, { quote: fiatQuoteQuery.data })] }));
    }
    // biome-ignore lint/suspicious/noExplicitAny: <explanation>
    function getErrorMessage(err) {
        const defaultMessage = "Unable to get price quote";
        try {
            if (err.error.code === "MINIMUM_PURCHASE_AMOUNT") {
                const obj = err.error;
                return [
                    `Minimum purchase amount is $${obj.data.minimumAmountUSDCents / 100}`,
                    `Requested amount is $${obj.data.requestedAmountUSDCents / 100}`,
                ];
            }
        }
        catch { }
        return [defaultMessage];
    }
    const disableSubmit = !fiatQuoteQuery.data;
    return ((0, jsx_runtime_1.jsxs)(basic_js_1.Container, { px: "lg", flex: "column", gap: "md", children: [(0, jsx_runtime_1.jsxs)("div", { children: [(0, jsx_runtime_1.jsx)(PayWIthCreditCard_js_1.PayWithCreditCard, { isLoading: fiatQuoteQuery.isLoading, value: fiatQuoteQuery.data?.fromCurrencyWithFees.amount, client: client, currency: selectedCurrency, onSelectCurrency: showCurrencySelector, disableCurrencySelection: true }), (0, jsx_runtime_1.jsx)(EstimatedTimeAndFees_js_1.EstimatedTimeAndFees, { quoteIsLoading: fiatQuoteQuery.isLoading, estimatedSeconds: fiatQuoteQuery.data?.estimatedDurationSeconds, onViewFees: showFees })] }), fiatQuoteQuery.error && ((0, jsx_runtime_1.jsx)("div", { children: getErrorMessage(fiatQuoteQuery.error).map((msg) => ((0, jsx_runtime_1.jsx)(text_js_1.Text, { color: "danger", size: "sm", center: true, multiline: true, children: msg }, msg))) })), (0, jsx_runtime_1.jsx)(buttons_js_1.Button, { variant: disableSubmit ? "outline" : "accent", "data-disabled": disableSubmit, disabled: disableSubmit, fullWidth: true, onClick: handleSubmit, gap: "xs", children: fiatQuoteQuery.isLoading ? ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)(Spinner_js_1.Spinner, { size: "sm", color: "accentText" }), "Getting price quote"] })) : ("Continue") })] }));
}
function BuyForTxUI(props) {
    const chainQuery = (0, useChainQuery_js_1.useChainQuery)(props.buyForTx.tx.chain);
    return ((0, jsx_runtime_1.jsxs)(basic_js_1.Container, { children: [(0, jsx_runtime_1.jsx)(Spacer_js_1.Spacer, { y: "xs" }), (0, jsx_runtime_1.jsxs)(basic_js_1.Container, { flex: "row", style: {
                    justifyContent: "space-between",
                }, children: [(0, jsx_runtime_1.jsx)(text_js_1.Text, { size: "sm", children: "Amount Needed" }), (0, jsx_runtime_1.jsxs)(basic_js_1.Container, { flex: "column", style: {
                            alignItems: "flex-end",
                        }, children: [(0, jsx_runtime_1.jsxs)(basic_js_1.Container, { flex: "row", gap: "xs", center: "y", children: [(0, jsx_runtime_1.jsxs)(text_js_1.Text, { color: "primaryText", size: "sm", children: [props.amountNeeded, " ", props.buyForTx.tokenSymbol] }), (0, jsx_runtime_1.jsx)(TokenIcon_js_1.TokenIcon, { chain: props.buyForTx.tx.chain, client: props.client, size: "sm", token: nativeToken_js_1.NATIVE_TOKEN })] }), (0, jsx_runtime_1.jsx)(Spacer_js_1.Spacer, { y: "xxs" }), chainQuery.data ? ((0, jsx_runtime_1.jsxs)(text_js_1.Text, { size: "sm", children: [" ", chainQuery.data.name] })) : ((0, jsx_runtime_1.jsx)(Skeleton_js_1.Skeleton, { height: index_js_1.fontSize.sm, width: "50px" }))] })] }), (0, jsx_runtime_1.jsx)(Spacer_js_1.Spacer, { y: "md" }), (0, jsx_runtime_1.jsx)(basic_js_1.Line, {}), (0, jsx_runtime_1.jsx)(Spacer_js_1.Spacer, { y: "md" }), (0, jsx_runtime_1.jsxs)(basic_js_1.Container, { flex: "row", style: {
                    justifyContent: "space-between",
                }, children: [(0, jsx_runtime_1.jsx)(text_js_1.Text, { size: "sm", children: "Your Balance" }), (0, jsx_runtime_1.jsxs)(basic_js_1.Container, { flex: "row", gap: "xs", children: [(0, jsx_runtime_1.jsxs)(text_js_1.Text, { color: "primaryText", size: "sm", children: [(0, formatNumber_js_1.formatNumber)(Number((0, units_js_1.toEther)(props.buyForTx.balance)), 4), " ", props.buyForTx.tokenSymbol] }), (0, jsx_runtime_1.jsx)(TokenIcon_js_1.TokenIcon, { chain: props.buyForTx.tx.chain, client: props.client, size: "sm", token: nativeToken_js_1.NATIVE_TOKEN })] })] }), (0, jsx_runtime_1.jsx)(Spacer_js_1.Spacer, { y: "md" }), (0, jsx_runtime_1.jsx)(basic_js_1.Line, {}), (0, jsx_runtime_1.jsx)(Spacer_js_1.Spacer, { y: "lg" }), (0, jsx_runtime_1.jsx)(text_js_1.Text, { center: true, size: "sm", children: "Purchase" }), (0, jsx_runtime_1.jsx)(Spacer_js_1.Spacer, { y: "xxs" })] }));
}
function createSupportedTokens(data, payOptions, supportedTokensOverrides) {
    const tokens = {};
    const isBuyWithFiatDisabled = payOptions.buyWithFiat === false;
    const isBuyWithCryptoDisabled = payOptions.buyWithCrypto === false;
    for (const x of data) {
        tokens[x.chain.id] = x.tokens.filter((t) => {
            // it token supports both - include it
            if (t.buyWithCryptoEnabled && t.buyWithFiatEnabled) {
                return true;
            }
            // if buyWithFiat is disabled, and buyWithCrypto is not supported by token - exclude the token
            if (!t.buyWithCryptoEnabled && isBuyWithFiatDisabled) {
                return false;
            }
            // if buyWithCrypto is disabled, and buyWithFiat is not supported by token - exclude the token
            if (!t.buyWithFiatEnabled && isBuyWithCryptoDisabled) {
                return false;
            }
            return true; // include the token
        });
    }
    // override with props.supportedTokens
    if (supportedTokensOverrides) {
        for (const k in supportedTokensOverrides) {
            const key = Number(k);
            const tokenList = supportedTokensOverrides[key];
            if (tokenList) {
                tokens[key] = tokenList;
            }
        }
    }
    return tokens;
}
function ChainSelectionScreen(props) {
    return ((0, jsx_runtime_1.jsx)(NetworkSelector_js_1.NetworkSelectorContent, { client: props.client, connectLocale: props.connectLocale, showTabs: false, onBack: props.showMainScreen, chains: props.chains, closeModal: props.showMainScreen, networkSelector: {
            renderChain(renderChainProps) {
                return ((0, jsx_runtime_1.jsx)(NetworkSelector_js_1.ChainButton, { chain: renderChainProps.chain, confirming: false, switchingFailed: false, onClick: () => {
                        props.setChain(renderChainProps.chain);
                        props.showMainScreen();
                    }, client: props.client, connectLocale: props.connectLocale }));
            },
        } }));
}
//# sourceMappingURL=BuyScreen.js.map