'use client'
import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
import { useState, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { WalletIcon } from '@dynamic-labs/wallet-book';
import { Icon } from '../../../../components/Icon/Icon.js';
import { ModalHeader } from '../../../../components/ModalHeader/ModalHeader.js';
import { Typography } from '../../../../components/Typography/Typography.js';
import { TypographyButton } from '../../../../components/TypographyButton/TypographyButton.js';
import { ReactComponent as SvgChevronDown } from '../../../../shared/assets/chevron-down.js';
import '@dynamic-labs/iconic';
import '../../../../context/ViewContext/ViewContext.js';
import { shortenWalletAddress } from '../../../../shared/utils/functions/shortenWalletAddress/shortenWalletAddress.js';
import '../../../../context/DynamicContext/useDynamicContext/useDynamicContext.js';
import { useInternalDynamicContext } from '../../../../context/DynamicContext/useDynamicContext/useInternalDynamicContext/useInternalDynamicContext.js';
import { useWidgetContext } from '../../context/DynamicWidgetContext.js';
import { createFundingButtons } from '../ReceiveWalletFunds/utils/createFundingButtons/createFundingButtons.js';
import { CryptoTokenSelectScreen } from './CryptoTokenSelectScreen/CryptoTokenSelectScreen.js';
import { isTrustedImageUrl } from './isTrustedImageUrl.js';
import { useMoonPayOnramp } from './useMoonPayOnramp.js';

const MoonPayOnramp = ({ onBack, hideBackButton = false, onPaymentCreated, token: initialToken, merchantName, walletAddress: walletAddressOverride, }) => {
    var _a;
    const { t } = useTranslation();
    const { setShowAuthFlow, setShowDynamicUserProfile } = useInternalDynamicContext();
    const { setDynamicWidgetView } = useWidgetContext();
    const { primaryWallet, availableTokens, tokensLoading, tokensError, selectedToken, setSelectedToken, isOpening, error, effectiveWalletAddress, openMoonPay, } = useMoonPayOnramp({
        initialToken,
        merchantName,
        onPaymentCreated,
        walletAddressOverride,
    });
    const [showTokenSelect, setShowTokenSelect] = useState(false);
    // createFundingButtons calls onBack directly when provided, so this default
    // only runs when no onBack prop was passed.
    const handleBack = useCallback(() => {
        setDynamicWidgetView('choose-onramp-provider');
    }, [setDynamicWidgetView]);
    const { backButton, closeButton } = createFundingButtons({
        defaultBackAction: handleBack,
        hideBackButton,
        onBack,
        setShowAuthFlow,
        setShowDynamicUserProfile,
    });
    if (!primaryWallet)
        return null;
    if (showTokenSelect) {
        return (jsx(CryptoTokenSelectScreen, { tokens: availableTokens, currentToken: selectedToken, onClose: () => setShowTokenSelect(false), onSelectToken: (tokenCode) => {
                setSelectedToken(tokenCode);
                setShowTokenSelect(false);
            } }));
    }
    const selectedTokenData = availableTokens.find((tok) => tok.code === selectedToken);
    const selectedTokenName = (_a = selectedTokenData === null || selectedTokenData === void 0 ? void 0 : selectedTokenData.name) !== null && _a !== void 0 ? _a : selectedToken;
    const selectedTokenIcon = selectedTokenData === null || selectedTokenData === void 0 ? void 0 : selectedTokenData.icon;
    const tokenSelectorContent = (() => {
        if (tokensLoading) {
            return (jsx(Typography, { variant: 'body_small', weight: 'medium', children: t('dyn_moonpay_onramp.loading_tokens', 'Loading tokens...') }));
        }
        if (tokensError) {
            return (jsx(Typography, { variant: 'body_small', color: 'error-1', weight: 'medium', children: t('dyn_moonpay_onramp.tokens_error', 'Failed to load tokens') }));
        }
        return (jsxs(Fragment, { children: [isTrustedImageUrl(selectedTokenIcon) && (jsx("img", { src: selectedTokenIcon, alt: selectedTokenName, className: 'fund-from-wallet__content__currency-selector__dropdown__content__icon', "aria-hidden": 'true' })), jsx(Typography, { variant: 'body_small', weight: 'medium', children: selectedTokenName })] }));
    })();
    return (jsxs("div", { className: 'fund-from-wallet fund-from-wallet--moonpay', children: [jsx(ModalHeader, { leading: backButton, trailing: closeButton, children: jsx(Typography, { variant: 'title', copykey: 'dyn_moonpay_onramp.title', children: t('dyn_moonpay_onramp.title', 'Buy Crypto') }) }), jsxs("div", { className: 'fund-from-wallet__content', children: [error && (jsx(Typography, { color: 'error-1', variant: 'body_normal', weight: 'medium', className: 'fund-from-wallet__content__error', children: error })), jsxs("div", { className: 'fund-from-wallet__content__currency-selector', children: [jsx(Typography, { variant: 'body_small', weight: 'medium', color: 'secondary', copykey: 'dyn_moonpay_onramp.token_label', children: t('dyn_moonpay_onramp.token_label', 'Select Token') }), jsxs("div", { className: 'fund-from-wallet__content__currency-selector__dropdown', onClick: () => !tokensLoading && !tokensError && setShowTokenSelect(true), role: 'button', tabIndex: 0, onKeyDown: (e) => {
                                    if (e.key === 'Enter' || e.key === ' ') {
                                        e.preventDefault();
                                        if (!tokensLoading && !tokensError) {
                                            setShowTokenSelect(true);
                                        }
                                    }
                                }, "aria-label": t('dyn_moonpay_onramp.select_token', 'Select Token'), "aria-expanded": showTokenSelect, "aria-haspopup": 'dialog', "data-testid": 'token-select-dropdown', children: [jsx("div", { className: 'fund-from-wallet__content__currency-selector__dropdown__content', children: tokenSelectorContent }), jsx("div", { className: 'fund-from-wallet__content__currency-selector__dropdown__icon', children: jsx(Icon, { color: 'text-tertiary', size: 'small', children: jsx(SvgChevronDown, {}) }) })] })] }), jsx("div", { className: 'fund-from-wallet__content__wallet-card', children: jsxs("div", { className: 'fund-from-wallet__content__wallet-card__wallet-details', children: [jsx(WalletIcon, { icon: primaryWallet.connector.metadata.icon, walletKey: primaryWallet.connector.key, className: 'fund-from-wallet__content__wallet-card__wallet-details__icon' }), jsxs("div", { className: 'fund-from-wallet__content__wallet-card__wallet-details__rows', children: [jsx(Typography, { variant: 'body_small', weight: 'medium', copykey: 'dyn_moonpay_onramp.wallet_detail_to', children: t('dyn_moonpay_onramp.wallet_detail_to', 'Tokens will be sent to') }), jsx(Typography, { variant: 'body_small', color: 'secondary', weight: 'medium', children: shortenWalletAddress(effectiveWalletAddress) })] })] }) })] }), jsx(TypographyButton, { dataTestId: 'confirm-button', buttonVariant: 'brand-primary', buttonPadding: 'large', typographyProps: { color: 'white' }, className: 'fund-from-wallet__confirm-button', disabled: isOpening ||
                    tokensLoading ||
                    tokensError ||
                    !selectedToken ||
                    availableTokens.length === 0 ||
                    !effectiveWalletAddress, onClick: openMoonPay, children: isOpening
                    ? t('dyn_moonpay_onramp.opening', 'Opening MoonPay...')
                    : t('dyn_moonpay_onramp.continue', 'Continue to MoonPay') })] }));
};

export { MoonPayOnramp };
