import { b as reactExports, Z as ConnectLoaderContext, G as EventTargetContext, k as useTranslation, aU as ViewContext, a5 as SharedViews, F as useAnalytics, U as UserJourney, V as ViewActions, w as jsx, z as SimpleLayout, M as HeaderNavigation, d8 as sendOnRampWidgetCloseEvent, O as orchestrationEvents, r as ro, B as Box, aK as isPassportProvider, d9 as url, da as TRANSAK_ORIGIN, db as jt, c5 as FooterLogo, x as jsxs, d1 as SimpleTextBody, bH as viewReducer, bI as initialViewState, cR as NATIVE, a0 as LoadingView, dc as sendOnRampSuccessEvent, c6 as StatusType, d7 as StatusView, dd as sendOnRampFailedEvent, bQ as ServiceUnavailableErrorView } from './index-Cy6GwrlT.js';
import { O as OnRampWidgetViews, T as TopUpView } from './TopUpView-Cn30wgNE.js';
import { S as SpendingCapHero } from './SpendingCapHero-O4mxTGj9.js';

const containerStyle = (showIframe) => ({
    position: 'relative',
    maxWidth: '420px',
    height: '100%',
    borderRadius: 'base.borderRadius.x6',
    overflow: 'hidden',
    marginLeft: 'base.spacing.x2',
    marginRight: 'base.spacing.x2',
    marginBottom: 'base.spacing.x2',
    display: showIframe ? 'block' : 'none',
});
const boxMainStyle = (showIframe) => ({
    display: showIframe ? 'block' : 'none',
});

var TransakEvents;
(function (TransakEvents) {
    TransakEvents["TRANSAK_WIDGET_OPEN"] = "TRANSAK_WIDGET_OPEN";
    TransakEvents["TRANSAK_ORDER_CREATED"] = "TRANSAK_ORDER_CREATED";
    TransakEvents["TRANSAK_ORDER_SUCCESSFUL"] = "TRANSAK_ORDER_SUCCESSFUL";
    TransakEvents["TRANSAK_ORDER_FAILED"] = "TRANSAK_ORDER_FAILED";
})(TransakEvents || (TransakEvents = {}));
var TransakStatuses;
(function (TransakStatuses) {
    TransakStatuses["PROCESSING"] = "PROCESSING";
    TransakStatuses["COMPLETED"] = "COMPLETED";
})(TransakStatuses || (TransakStatuses = {}));

const transakIframeId = 'transak-iframe';
const IN_PROGRESS_VIEW_DELAY_MS = 6000; // 6 second
function useWidgetUrl(checkout, provider, tokenAddress, tokenAmount, passport, showMenu, customSubTitle) {
    const [widgetUrl, setWidgetUrl] = reactExports.useState(undefined);
    reactExports.useEffect(() => {
        if (!checkout || !provider)
            return;
        const params = {
            exchangeType: jt.ONRAMP,
            browserProvider: provider,
            tokenAddress,
            tokenAmount,
            passport,
            showMenu,
            customSubTitle,
        };
        checkout.createFiatRampUrl(params).then(setWidgetUrl);
    }, [checkout, provider, tokenAddress, tokenAmount, passport, showMenu, customSubTitle]);
    return widgetUrl;
}
function useWalletAddress(provider) {
    const [userWalletAddress, setUserWalletAddress] = reactExports.useState(undefined);
    reactExports.useEffect(() => {
        if (!provider)
            return;
        provider.getSigner().then((signer) => signer.getAddress()).then(setUserWalletAddress);
    }, [provider]);
    return userWalletAddress;
}
function OnRampMain({ passport, showIframe, tokenAmount, tokenAddress, showBackButton, showMenu, customTitle, customSubTitle, showHeader = true, }) {
    const { connectLoaderState } = reactExports.useContext(ConnectLoaderContext);
    const { checkout, provider } = connectLoaderState;
    const { eventTargetState: { eventTarget }, } = reactExports.useContext(EventTargetContext);
    const { t } = useTranslation();
    const { viewState, viewDispatch } = reactExports.useContext(ViewContext);
    const widgetUrl = useWidgetUrl(checkout, provider, tokenAddress, tokenAmount, passport, showMenu, customSubTitle);
    const userWalletAddress = useWalletAddress(provider);
    const eventTimer = reactExports.useRef();
    const isPassport = !!passport && isPassportProvider(provider);
    const openedFromTopUpView = reactExports.useMemo(() => viewState.history.length > 2
        && viewState.history[viewState.history.length - 2].type
            === SharedViews.TOP_UP_VIEW, [viewState.history]);
    const showBack = showBackButton || openedFromTopUpView;
    const { track } = useAnalytics();
    const trackSegmentEvents = reactExports.useCallback(async (event, walletAddress) => {
        const miscProps = {
            userId: walletAddress.toLowerCase(),
            isPassportWallet: isPassport,
        };
        switch (event.event_id) {
            case TransakEvents.TRANSAK_WIDGET_OPEN:
                track({
                    userJourney: UserJourney.ON_RAMP,
                    screen: 'InputScreen',
                    control: 'TransakWidgetOpen',
                    controlType: 'IframeEvent',
                    extras: { ...miscProps },
                }); // checkoutOnRampInputScreen_TransakWidgetOpenIframeEvent
                break;
            case TransakEvents.TRANSAK_ORDER_CREATED:
                track({
                    userJourney: UserJourney.ON_RAMP,
                    screen: 'InputScreen',
                    control: 'OrderCreated',
                    controlType: 'IframeEvent',
                    extras: { ...miscProps },
                }); // checkoutOnRampInputScreen_OrderCreatedIframeEvent
                break;
            case TransakEvents.TRANSAK_ORDER_SUCCESSFUL:
                if (event.data.status === TransakStatuses.PROCESSING) {
                    // user paid
                    track({
                        userJourney: UserJourney.ON_RAMP,
                        screen: 'OrderInProgress',
                        control: 'PaymentProcessing',
                        controlType: 'IframeEvent',
                        extras: {
                            ...miscProps,
                            transactionHash: event.data.transactionHash,
                        },
                    }); // checkoutOnRampOrderInProgress_PaymentProcessingIframeEvent
                }
                if (event.data.status === TransakStatuses.COMPLETED) {
                    track({
                        userJourney: UserJourney.ON_RAMP,
                        screen: 'Success',
                        control: 'PaymentCompleted',
                        controlType: 'IframeEvent',
                        extras: {
                            ...miscProps,
                            transactionHash: event.data.transactionHash,
                        },
                    }); // checkoutOnRampSuccess_PaymentCompletedIframeEvent
                }
                break;
            case TransakEvents.TRANSAK_ORDER_FAILED: // payment failed
                track({
                    userJourney: UserJourney.ON_RAMP,
                    screen: 'Failure',
                    control: 'PaymentFailed',
                    controlType: 'IframeEvent',
                    extras: { ...miscProps },
                }); // checkoutOnRampFailure_PaymentFailedIframeEvent
                break;
        }
    }, [isPassport, track]);
    const transakEventHandler = reactExports.useCallback((event) => {
        if (eventTimer.current)
            clearTimeout(eventTimer.current);
        if (event.event_id === TransakEvents.TRANSAK_WIDGET_OPEN) {
            viewDispatch({
                payload: {
                    type: ViewActions.UPDATE_VIEW,
                    view: {
                        type: OnRampWidgetViews.ONRAMP,
                        data: {
                            amount: viewState.view.data?.amount ?? tokenAmount,
                            tokenAddress: viewState.view.data?.tokenAddress ?? tokenAddress,
                        },
                    },
                },
            });
            return;
        }
        if (event.event_id === TransakEvents.TRANSAK_ORDER_SUCCESSFUL
            && event.data.status === TransakStatuses.PROCESSING) {
            // this handles 3DS -- once the user has completed the verification,
            // kick off teh loading screen and then fake a IN_PROGRESS_VIEW_DELAY_MS
            // delay before showing the IN_PROGRESS screen
            viewDispatch({
                payload: {
                    type: ViewActions.UPDATE_VIEW,
                    view: {
                        type: OnRampWidgetViews.IN_PROGRESS_LOADING,
                    },
                },
            });
            eventTimer.current = window.setTimeout(() => {
                viewDispatch({
                    payload: {
                        type: ViewActions.UPDATE_VIEW,
                        view: {
                            type: OnRampWidgetViews.IN_PROGRESS,
                        },
                    },
                });
            }, IN_PROGRESS_VIEW_DELAY_MS);
            return;
        }
        if (event.event_id === TransakEvents.TRANSAK_ORDER_SUCCESSFUL
            && event.data.status === TransakStatuses.COMPLETED) {
            viewDispatch({
                payload: {
                    type: ViewActions.UPDATE_VIEW,
                    view: {
                        type: OnRampWidgetViews.SUCCESS,
                        data: {
                            transactionHash: event.data.transactionHash,
                        },
                    },
                },
            });
            return;
        }
        if (event.event_id === TransakEvents.TRANSAK_ORDER_FAILED) {
            viewDispatch({
                payload: {
                    type: ViewActions.UPDATE_VIEW,
                    view: {
                        type: OnRampWidgetViews.FAIL,
                        data: {
                            amount: tokenAmount,
                            tokenAddress,
                        },
                        reason: `Transaction failed: ${event.data.statusReason}`,
                    },
                },
            });
        }
    }, [viewDispatch, tokenAmount, tokenAddress, viewState.view.data?.amount, viewState.view.data?.tokenAddress]);
    reactExports.useEffect(() => {
        const domIframe = document.getElementById(transakIframeId);
        if (!domIframe)
            return;
        const handleTransakEvents = (event) => {
            const host = url.parse(event.origin)?.host?.toLowerCase();
            if (event.source === domIframe.contentWindow
                && host
                && TRANSAK_ORIGIN.includes(host)) {
                trackSegmentEvents(event.data, userWalletAddress ?? '');
                transakEventHandler(event.data);
            }
        };
        window.addEventListener('message', handleTransakEvents);
        // eslint-disable-next-line consistent-return
        return () => {
            window.removeEventListener('message', handleTransakEvents);
        };
    }, [trackSegmentEvents, transakEventHandler, userWalletAddress]);
    return (jsx(Box, { sx: boxMainStyle(showIframe), children: jsx(SimpleLayout, { header: showHeader ? (jsx(HeaderNavigation, { title: customTitle ?? t('views.ONRAMP.header.title'), onCloseButtonClick: () => sendOnRampWidgetCloseEvent(eventTarget), showBack: showBack, onBackButtonClick: () => {
                    orchestrationEvents.sendRequestGoBackEvent(eventTarget, ro.IMTBL_ONRAMP_WIDGET_EVENT, {});
                } })) : undefined, footerBackgroundColor: "base.color.translucent.emphasis.200", children: jsx(Box, { sx: containerStyle(showIframe), children: jsx("iframe", { title: "Transak", id: transakIframeId, src: widgetUrl, allow: "camera;microphone;fullscreen;payment", referrerPolicy: "strict-origin-when-cross-origin", style: {
                        height: '100%',
                        width: '100%',
                        border: 'none',
                        position: 'absolute',
                    } }) }) }) }));
}

function OrderInProgress() {
    const { eventTargetState: { eventTarget } } = reactExports.useContext(EventTargetContext);
    const { t } = useTranslation();
    return (jsx(SimpleLayout, { testId: "order-in-progress-view", header: (jsx(HeaderNavigation, { transparent: true, onCloseButtonClick: () => sendOnRampWidgetCloseEvent(eventTarget) })), footer: (jsx(FooterLogo, {})), heroContent: jsx(SpendingCapHero, {}), floatHeader: true, children: jsxs(SimpleTextBody, { heading: t('views.ONRAMP.IN_PROGRESS.content.heading'), children: [t('views.ONRAMP.IN_PROGRESS.content.body1'), jsx("br", {}), jsx("br", {}), t('views.ONRAMP.IN_PROGRESS.content.body2')] }) }));
}

function OnRampWidget({ amount, tokenAddress, config, showBackButton, onrampConfig, }) {
    const { isOnRampEnabled, isSwapEnabled, isBridgeEnabled, } = config;
    const [viewState, viewDispatch] = reactExports.useReducer(viewReducer, {
        ...initialViewState,
        history: [],
    });
    const viewReducerValues = reactExports.useMemo(() => ({ viewState, viewDispatch }), [viewState, viewReducer]);
    const { connectLoaderState } = reactExports.useContext(ConnectLoaderContext);
    const { checkout, provider } = connectLoaderState;
    const [tknAddr, setTknAddr] = reactExports.useState(tokenAddress);
    const { eventTargetState: { eventTarget } } = reactExports.useContext(EventTargetContext);
    const { t } = useTranslation();
    const showIframe = reactExports.useMemo(() => viewState.view.type === OnRampWidgetViews.ONRAMP, [viewState.view.type]);
    reactExports.useEffect(() => {
        if (!checkout || !provider)
            return;
        (async () => {
            const network = await checkout.getNetworkInfo({
                provider,
            });
            /* If the provider's network is not supported, return out of this and let the
          connect loader handle the switch network functionality */
            if (!network.isSupported) {
                return;
            }
            const address = tknAddr?.toLocaleLowerCase() === NATIVE
                ? NATIVE
                : tokenAddress;
            setTknAddr(address);
        })();
    }, [checkout, provider, viewDispatch]);
    return (jsxs(ViewContext.Provider, { value: viewReducerValues, children: [viewState.view.type === SharedViews.LOADING_VIEW && (jsx(LoadingView, { loadingText: t('views.ONRAMP.initialLoadingText') })), viewState.view.type === OnRampWidgetViews.IN_PROGRESS_LOADING && (jsx(LoadingView, { loadingText: t('views.ONRAMP.IN_PROGRESS_LOADING.loading.text') })), viewState.view.type === OnRampWidgetViews.IN_PROGRESS && (jsx(OrderInProgress, {})), viewState.view.type === OnRampWidgetViews.SUCCESS && (jsx(StatusView, { statusText: t('views.ONRAMP.SUCCESS.text'), actionText: t('views.ONRAMP.SUCCESS.actionText'), onRenderEvent: () => sendOnRampSuccessEvent(eventTarget, viewState.view.data.transactionHash), onActionClick: () => sendOnRampWidgetCloseEvent(eventTarget), statusType: StatusType.SUCCESS, testId: "success-view" })), viewState.view.type === OnRampWidgetViews.FAIL && (jsx(StatusView, { statusText: t('views.ONRAMP.FAIL.text'), actionText: t('views.ONRAMP.FAIL.actionText'), onRenderEvent: () => sendOnRampFailedEvent(eventTarget, viewState.view.reason
                    ?? 'Transaction failed'), onActionClick: () => {
                    viewDispatch({
                        payload: {
                            type: ViewActions.UPDATE_VIEW,
                            view: {
                                type: OnRampWidgetViews.ONRAMP,
                                data: viewState.view.data,
                            },
                        },
                    });
                }, statusType: StatusType.FAILURE, onCloseClick: () => sendOnRampWidgetCloseEvent(eventTarget), testId: "fail-view" })), (viewState.view.type !== OnRampWidgetViews.SUCCESS
                && viewState.view.type !== OnRampWidgetViews.FAIL) && (jsx(OnRampMain, { passport: checkout?.passport, showIframe: showIframe, tokenAmount: amount ?? viewState.view.data?.amount, tokenAddress: tknAddr ?? viewState.view.data?.tokenAddress, showBackButton: showBackButton, showMenu: onrampConfig?.showMenu, customTitle: onrampConfig?.customTitle, customSubTitle: onrampConfig?.customSubTitle, showHeader: onrampConfig?.showHeader })), viewState.view.type === SharedViews.TOP_UP_VIEW && (jsx(TopUpView, { analytics: { userJourney: UserJourney.ON_RAMP }, widgetEvent: ro.IMTBL_ONRAMP_WIDGET_EVENT, checkout: checkout, provider: provider, showOnrampOption: isOnRampEnabled, showSwapOption: isSwapEnabled, showBridgeOption: isBridgeEnabled, onCloseButtonClick: () => sendOnRampWidgetCloseEvent(eventTarget) })), viewState.view.type
                === SharedViews.SERVICE_UNAVAILABLE_ERROR_VIEW && (jsx(ServiceUnavailableErrorView, { onCloseClick: () => sendOnRampWidgetCloseEvent(eventTarget) }))] }));
}

export { OnRampWidget as default };
