import { _ as __awaiter } from './tslib.es6-2e1f499a.js';
import { jsx, jsxs } from 'react/jsx-runtime';
import { ThemeProvider } from '@wise/components-theming';
import { useState, useMemo } from 'react';
import { useIntl, FormattedMessage } from 'react-intl';
import { T as TapestryCard } from './TapestryCard-38ddeade.js';
import { s as styleInject } from './style-inject.es-1f59c1d0.js';
import { C as ComparisonTableHeroV2TableTrackingContextProvider, a as ComparisonTableHeroV2Table } from './ComparisonTableHeroV2Table-a6d41584.js';
import { SelectInputOptionContent, SelectInput, DateLookup, Button, Alert, Sentiment } from '@transferwise/components';
import { Flag } from '@wise/art';

var css_248z$1 = ".cc_selfServe__wrapper_3296223122 {\n  width: 552px;\n}\n@media (max-width: 575px) {\n  .cc_selfServe__wrapper_3296223122 {\n    width: 350px;\n  }\n}\n.cc_selfServe__wrapper_3296223122 .cc_tapestryCardContent_3296223122 {\n  border-radius: 40px;\n}\n.cc_selfServe__container_3296223122 {\n  padding: var(--size-32);\n  border-radius: 40px;\n  background: var(--color-white);\n}\n@media (max-width: 575px) {\n  .cc_selfServe__container_3296223122 {\n    padding: 20px;\n  }\n}\n.cc_selfServe__footer_3296223122 {\n  font-size: var(--font-size-14);\n}\n\n/*# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInNyYy9jb21wYXJpc29uLXNlbGYtc2VydmUvQ29tcGFyaXNvblNlbGZTZXJ2ZS5tb2R1bGUubGVzcyIsIkNvbXBhcmlzb25TZWxmU2VydmUubW9kdWxlLmxlc3MiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBR0E7RUFDRSxZQUFBO0FDRkY7QURJRTtFQUFBO0lBQ0UsWUFBQTtFQ0RGO0FBQ0Y7QURKQTtFQVFJLG1CQUFBO0FDREo7QURLQTtFQUNFLHVCQUFBO0VBQ0EsbUJBQUE7RUFDQSw4QkFBQTtBQ0hGO0FES0U7RUFBQTtJQUNFLGFBQUE7RUNGRjtBQUNGO0FES0E7RUFDRSw4QkFBQTtBQ0hGIiwiZmlsZSI6IkNvbXBhcmlzb25TZWxmU2VydmUubW9kdWxlLmxlc3MifQ== */";
var styles$1 = {"selfServe__wrapper":"cc_selfServe__wrapper_3296223122","tapestryCardContent":"cc_tapestryCardContent_3296223122","selfServe__container":"cc_selfServe__container_3296223122","selfServe__footer":"cc_selfServe__footer_3296223122"};
styleInject(css_248z$1);

const ComparisonSelfServeBreakdown = ({ data, trackEvent = () => {
    // do nothing
}, }) => {
    return (jsx(ComparisonTableHeroV2TableTrackingContextProvider, Object.assign({ trackEvent: trackEvent, trackingData: {
            comparisonResponse: {},
            componentType: 'SelfServeBreakdown',
            excludePartners: true,
            midMarketRate: data.wise.exchangeRate,
        } }, { children: jsx(ComparisonTableHeroV2Table, { showCheapestFlag: true, hideFooter: true, sendMoney: { currency: data.sourceCurrencyCode, value: data.sentAmount }, footerCTAType: "button", midMarketRate: data.wise.exchangeRate, quotes: [
                {
                    sourceCurrency: data.sourceCurrencyCode,
                    targetCurrency: data.targetCurrencyCode,
                    sendAmount: {
                        currency: data.sourceCurrencyCode,
                        value: data.sentAmount,
                    },
                    provider: {
                        name: 'Wise',
                        alias: 'wise',
                        logoUrl: 'https://wise.com/public-resources/assets/logos/wise-personal/logo.svg',
                        logoAltText: 'Wise',
                        partner: false,
                    },
                    rate: data.wise.exchangeRate,
                    fee: {
                        currency: data.sourceCurrencyCode,
                        value: data.wise.transferFees,
                    },
                    receivedAmount: {
                        value: data.wise.receivedAmount,
                        currency: data.targetCurrencyCode,
                    },
                    deliveryEstimation: {
                        providerGivesEstimate: false,
                        duration: null,
                    },
                },
                {
                    sourceCurrency: data.sourceCurrencyCode,
                    targetCurrency: data.targetCurrencyCode,
                    sendAmount: {
                        currency: data.sourceCurrencyCode,
                        value: data.sentAmount,
                    },
                    provider: {
                        name: 'Competitor',
                        alias: 'competitor',
                        logoUrl: '',
                        logoAltText: 'Competitor',
                        partner: false,
                    },
                    rate: data.competitor.exchangeRate || null,
                    fee: null,
                    receivedAmount: {
                        value: data.competitor.receivedAmount,
                        currency: data.targetCurrencyCode,
                    },
                    deliveryEstimation: {
                        providerGivesEstimate: false,
                        duration: null,
                    },
                    disableAdditionalInfo: !data.competitor.exchangeRate,
                },
            ] }) })));
};

const CurrencySelectOption = ({ currencyCode, currencyName, }) => {
    return (jsx(SelectInputOptionContent, { title: currencyCode, note: currencyName, icon: jsx(Flag, { code: currencyCode, intrinsicSize: 24 }) }));
};

var css_248z = ".cc_form__container_3296223122 fieldset {\n  width: 100% !important;\n}\n\n/*# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInNyYy9jb21wYXJpc29uLXNlbGYtc2VydmUvQ29tcGFyaXNvblNlbGZTZXJ2ZUZvcm0vQ29tcGFyaXNvblNlbGZTZXJ2ZUZvcm0ubW9kdWxlLmxlc3MiLCJDb21wYXJpc29uU2VsZlNlcnZlRm9ybS5tb2R1bGUubGVzcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQTtFQUVJLHNCQUFBO0FDQUoiLCJmaWxlIjoiQ29tcGFyaXNvblNlbGZTZXJ2ZUZvcm0ubW9kdWxlLmxlc3MifQ== */";
var styles = {"form__container":"cc_form__container_3296223122"};
styleInject(css_248z);

const ComparisonSelfServeForm = ({ initialSourceCurrencyCode, initialTargetCurrencyCode, routes, currencies, handleSubmit, isError, }) => {
    const { formatMessage } = useIntl();
    const [formData, setFormData] = useState({
        sourceCurrency: { code: initialSourceCurrencyCode },
        targetCurrency: { code: initialTargetCurrencyCode },
    });
    const [date, setDate] = useState(undefined);
    const sourceCurrencies = useMemo(() => {
        return routes.sourceCurrencies.map((sourceCurrency) => {
            var _a;
            return ({
                type: 'option',
                value: {
                    code: sourceCurrency.currencyCode,
                    name: (_a = currencies.find((c) => c.code === sourceCurrency.currencyCode.toUpperCase())) === null || _a === void 0 ? void 0 : _a.name,
                },
            });
        });
    }, [routes, currencies]);
    const targetCurrencies = useMemo(() => {
        var _a;
        const formSourceCurrency = formData.sourceCurrency;
        return (_a = routes.sourceCurrencies
            .find((sourceCurrency) => sourceCurrency.currencyCode === (formSourceCurrency === null || formSourceCurrency === void 0 ? void 0 : formSourceCurrency.code))) === null || _a === void 0 ? void 0 : _a.targetCurrencies.map((targetCurrency) => {
            var _a;
            return ({
                type: 'option',
                value: {
                    code: targetCurrency.currencyCode,
                    name: (_a = currencies.find((c) => c.code === targetCurrency.currencyCode.toUpperCase())) === null || _a === void 0 ? void 0 : _a.name,
                },
            });
        });
    }, [routes, formData.sourceCurrency, currencies]);
    const isSubmittable = formData.sourceCurrency &&
        formData.targetCurrency &&
        formData.sentAmount &&
        formData.receivedAmount &&
        formData.date;
    return (jsxs("div", Object.assign({ className: styles.form__container }, { children: [jsxs("div", Object.assign({ className: "row m-b-2" }, { children: [jsxs("div", Object.assign({ className: "col-xs-12 col-md-6" }, { children: [jsx("label", Object.assign({ htmlFor: "comparison-self-serve-source-currency-select" }, { children: jsx(FormattedMessage, { id: "self-serve.form.from.label" }) })), jsx("div", Object.assign({ id: "comparison-self-serve-source-currency-select", className: "m-b-2" }, { children: jsx(SelectInput, { filterable: true, items: sourceCurrencies, renderValue: (value) => (jsx(CurrencySelectOption, { currencyCode: value.code, currencyName: value.name })), value: formData.sourceCurrency, onChange: (currency) => {
                                        setFormData(Object.assign(Object.assign({}, formData), { sourceCurrency: currency }));
                                    } }) }))] })), jsxs("div", Object.assign({ className: "col-xs-12 col-md-6" }, { children: [jsx("label", Object.assign({ htmlFor: "comparison-self-serve-target-currency-select" }, { children: jsx(FormattedMessage, { id: "self-serve.form.to.label" }) })), jsx("div", Object.assign({ id: "comparison-self-serve-target-currency-select", className: "m-b-2" }, { children: jsx(SelectInput, { filterable: true, items: targetCurrencies, renderValue: (value) => (jsx(CurrencySelectOption, { currencyCode: value.code, currencyName: value.name })), value: formData.targetCurrency, onChange: (currency) => {
                                        setFormData(Object.assign(Object.assign({}, formData), { targetCurrency: currency }));
                                    } }) }))] }))] })), jsxs("div", Object.assign({ className: "m-b-2" }, { children: [jsx("label", Object.assign({ htmlFor: "comparison-self-serve-sent-amount" }, { children: jsx(FormattedMessage, { id: "self-serve.form.sent-amount.label" }) })), jsx("input", { type: "number", id: "comparison-self-serve-sent-amount", placeholder: formatMessage({
                            id: 'self-serve.form.sent-amount.placeholder',
                        }), className: "form-control", onChange: ({ target }) => setFormData(Object.assign(Object.assign({}, formData), { sentAmount: parseInt(target.value) })) })] })), jsxs("div", Object.assign({ className: "m-b-2" }, { children: [jsx("label", Object.assign({ htmlFor: "comparison-self-serve-received-amount" }, { children: jsx(FormattedMessage, { id: "self-serve.form.received-amount.label" }) })), jsx("input", { type: "number", id: "comparison-self-serve-received-amount", placeholder: formatMessage({
                            id: 'self-serve.form.received-amount.placeholder',
                        }), className: "form-control", onChange: ({ target }) => setFormData(Object.assign(Object.assign({}, formData), { receivedAmount: parseInt(target.value) })) })] })), jsxs("div", Object.assign({ className: "m-b-2" }, { children: [jsx("label", Object.assign({ htmlFor: "comparison-self-serve-exchange-rate" }, { children: jsx(FormattedMessage, { id: "self-serve.form.exchange-rate.label" }) })), jsx("input", { type: "number", id: "comparison-self-serve-exchange-rate", placeholder: formatMessage({
                            id: 'self-serve.form.exchange-rate.placeholder',
                        }), className: "form-control", onChange: ({ target }) => setFormData(Object.assign(Object.assign({}, formData), { exchangeRate: parseFloat(target.value) })) })] })), jsxs("div", Object.assign({ className: "m-b-2" }, { children: [jsx("label", Object.assign({ htmlFor: "comparison-self-serve-data" }, { children: jsx(FormattedMessage, { id: "self-serve.form.date.label" }) })), jsx("div", Object.assign({ id: "comparison-self-serve-data" }, { children: jsx(DateLookup, { max: new Date(), value: date, onChange: (date) => {
                                if (date) {
                                    setDate(date);
                                    setFormData(Object.assign(Object.assign({}, formData), { date: date.toISOString() }));
                                }
                            }, placeholder: formatMessage({ id: 'self-serve.form.date.label' }) }) }))] })), jsx("div", { children: jsx(Button, Object.assign({ disabled: !isSubmittable, block: true, onClick: () => handleSubmit(formData) }, { children: jsx(FormattedMessage, { id: "self-serve.form.cta" }) })) }), isError && (jsx("div", Object.assign({ className: "m-t-4" }, { children: jsx(Alert, { type: Sentiment.WARNING, message: formatMessage({ id: 'self-serve.form.error' }) }) })))] })));
};

const API_HOST = '/gateway';
const getQuoteForRoute = (sourceAmount, sourceCurrency, targetCurrency) => __awaiter(void 0, void 0, void 0, function* () {
    const response = yield fetch(`${API_HOST}/v3/quotes`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            sourceAmount,
            sourceCurrency,
            targetCurrency,
            guaranteedTargetAmount: false,
            type: 'REGULAR',
        }),
    });
    const data = (yield response.json());
    return data.paymentOptions.find((paymentOption) => paymentOption.payIn === 'BANK_TRANSFER' && paymentOption.payOut === 'BANK_TRANSFER');
});
const getHistoricalRate = (sourceCurrency, targetCurrency, dateTime) => __awaiter(void 0, void 0, void 0, function* () {
    const params = new URLSearchParams({
        source: sourceCurrency,
        target: targetCurrency,
        time: dateTime,
    });
    const response = yield fetch(`${API_HOST}/v1/rates/live?${params.toString()}`);
    const data = (yield response.json());
    return data[0].value;
});
const compareProvider = (formData) => __awaiter(void 0, void 0, void 0, function* () {
    var _a, _b, _c, _d;
    const [quote, historicalRate] = yield Promise.all([
        getQuoteForRoute(formData.sentAmount, (_a = formData.sourceCurrency) === null || _a === void 0 ? void 0 : _a.code.toUpperCase(), (_b = formData.targetCurrency) === null || _b === void 0 ? void 0 : _b.code.toUpperCase()),
        getHistoricalRate((_c = formData.sourceCurrency) === null || _c === void 0 ? void 0 : _c.code.toUpperCase(), (_d = formData.targetCurrency) === null || _d === void 0 ? void 0 : _d.code.toUpperCase(), new Date(formData.date).toISOString().replace('Z', '')),
    ]);
    const receivedAmount = (formData.sentAmount - quote.fee.transferwise) * historicalRate;
    return {
        sourceCurrencyCode: formData.sourceCurrency.code.toUpperCase(),
        targetCurrencyCode: formData.targetCurrency.code.toUpperCase(),
        sentAmount: formData.sentAmount,
        wise: {
            receivedAmount,
            exchangeRate: historicalRate,
            transferFees: quote.fee.transferwise,
            exchangeRateMarkup: 0,
        },
        competitor: {
            receivedAmount: formData.receivedAmount,
            exchangeRate: formData.exchangeRate,
        },
    };
});

const ComparisonSelfServe = ({ initialSourceCurrencyCode, initialTargetCurrencyCode, routes, currencies, formResultCallback, trackEvent, }) => {
    const [feeBreakdown, setFeeBreakdown] = useState();
    const [isError, setIsError] = useState(false);
    const handleFormSubmit = (formData) => __awaiter(void 0, void 0, void 0, function* () {
        try {
            const comparison = yield compareProvider(formData);
            setFeeBreakdown(comparison);
            if (formResultCallback) {
                formResultCallback(comparison);
            }
        }
        catch (error) {
            setIsError(true);
            console.error(error);
        }
    });
    if (feeBreakdown) {
        return jsx(ComparisonSelfServeBreakdown, { data: feeBreakdown, trackEvent: trackEvent });
    }
    return (jsxs("div", Object.assign({ className: styles$1.selfServe__wrapper }, { children: [jsx(TapestryCard, { children: jsx(ThemeProvider, Object.assign({ theme: "personal" }, { children: jsx("div", Object.assign({ className: styles$1.selfServe__container }, { children: jsx(ComparisonSelfServeForm, { initialSourceCurrencyCode: initialSourceCurrencyCode, initialTargetCurrencyCode: initialTargetCurrencyCode, routes: routes, currencies: currencies, handleSubmit: (data) => handleFormSubmit(data), isError: isError }) })) })) }), jsx("div", { children: jsx("p", Object.assign({ className: `text-xs-center m-t-5 ${styles$1.selfServe__footer}` }, { children: jsx(FormattedMessage, { id: "self-serve.form.footer.info" }) })) })] })));
};

export { ComparisonSelfServe as C };
//# sourceMappingURL=ComparisonSelfServe-95b65d75.js.map
