import { jsx } from 'react/jsx-runtime';
import { createContext, useContext, useMemo } from 'react';
import { toSeconds } from 'duration-fns';
import { calculateSavingsWithRespectToWiseQuote } from './savingsCalculator.js';
import { T as Table } from './tracking-6183d916.js';

function r(e){var t,f,n="";if("string"==typeof e||"number"==typeof e)n+=e;else if("object"==typeof e)if(Array.isArray(e)){var o=e.length;for(t=0;t<o;t++)e[t]&&(f=r(e[t]))&&(n&&(n+=" "),n+=f);}else for(f in e)e[f]&&(n&&(n+=" "),n+=f);return n}function clsx(){for(var e,t,f=0,n="",o=arguments.length;f<o;f++)(e=arguments[f])&&(t=r(e))&&(n&&(n+=" "),n+=t);return n}

/* eslint-disable fp/no-mutation */
function transformComparisonV4Response(comparisonResponse, excludePartners) {
    if ((comparisonResponse === null || comparisonResponse === void 0 ? void 0 : comparisonResponse.providers) == null) {
        return [];
    }
    const sourceCurrency = comparisonResponse.sourceCurrency;
    const targetCurrency = comparisonResponse.targetCurrency;
    const sendAmount = comparisonResponse.amount;
    let providers;
    if (excludePartners) {
        providers = comparisonResponse.providers.filter((provider) => isProviderWithQuote(provider) && !provider.partner);
    }
    else {
        providers = comparisonResponse.providers.filter((provider) => isProviderWithQuote(provider));
    }
    return providers
        .map((provider) => transformQuoteFromProvider(sourceCurrency, targetCurrency, sendAmount, provider))
        .sort((a, b) => b.receivedAmount.value - a.receivedAmount.value);
}
function isProviderWithQuote(provider) {
    var _a;
    return ((_a = provider === null || provider === void 0 ? void 0 : provider.quotes) === null || _a === void 0 ? void 0 : _a.length) > 0;
}
function transformQuoteFromProvider(sourceCurrency, targetCurrency, sendAmount, provider) {
    const bestQuote = getBestQuote(provider.quotes);
    return {
        sourceCurrency: sourceCurrency,
        targetCurrency: targetCurrency,
        sendAmount: {
            currency: sourceCurrency,
            value: sendAmount,
        },
        provider: {
            alias: provider.alias,
            name: provider.name,
            logoUrl: provider.logos.normal.pngUrl || '',
            logoCircleUrl: provider.logos.circle.svgUrl || provider.logos.circle.pngUrl || '',
            logoAltText: provider.logos.altText,
            partner: provider.partner,
        },
        markup: bestQuote.markup,
        rate: bestQuote.rate,
        fee: {
            currency: sourceCurrency,
            value: bestQuote.fee,
        },
        receivedAmount: {
            currency: targetCurrency,
            value: bestQuote.receivedAmount,
        },
        deliveryEstimation: Object.assign({}, bestQuote.deliveryEstimation),
    };
}
function getBestQuote(comparisonQuotes) {
    var _a, _b;
    if ((_b = (_a = comparisonQuotes[0]) === null || _a === void 0 ? void 0 : _a.deliveryEstimation) === null || _b === void 0 ? void 0 : _b.providerGivesEstimate) {
        const maximumReceivedAmount = comparisonQuotes.reduce((max, quote) => (quote.receivedAmount > max.receivedAmount ? quote : max), comparisonQuotes[0]).receivedAmount;
        const bestQuotes = comparisonQuotes.filter((quote) => quote.receivedAmount === maximumReceivedAmount);
        const bestQuotesWithSpeed = bestQuotes.filter((quote) => quote.deliveryEstimation.duration !== null);
        const bestQuotesWithSpeedSorted = bestQuotesWithSpeed.sort((a, b) => {
            var _a, _b, _c, _d;
            return toSeconds(((_b = (_a = a.deliveryEstimation) === null || _a === void 0 ? void 0 : _a.duration) === null || _b === void 0 ? void 0 : _b.max) || 0) -
                toSeconds(((_d = (_c = b.deliveryEstimation) === null || _c === void 0 ? void 0 : _c.duration) === null || _d === void 0 ? void 0 : _d.max) || 0);
        });
        return bestQuotesWithSpeedSorted.length > 0 ? bestQuotesWithSpeedSorted[0] : bestQuotes[0];
    }
    return comparisonQuotes.reduce((max, quote) => (quote.receivedAmount > max.receivedAmount ? quote : max), comparisonQuotes[0]);
}

const getFastestProviders = (quotes) => {
    // sort quotes by max in deliveryEstimation.duration on where the smallest max first
    // then take the first one, and if there are more that are equal to the first one, also take them
    const sortedQuotes = quotes
        .filter((quote) => { var _a, _b; return (_b = (_a = quote === null || quote === void 0 ? void 0 : quote.deliveryEstimation) === null || _a === void 0 ? void 0 : _a.duration) === null || _b === void 0 ? void 0 : _b.max; })
        .sort((a, b) => {
        var _a, _b, _c;
        return toSeconds(((_a = a.deliveryEstimation.duration) === null || _a === void 0 ? void 0 : _a.max) || 0) -
            toSeconds(((_c = (_b = b.deliveryEstimation) === null || _b === void 0 ? void 0 : _b.duration) === null || _c === void 0 ? void 0 : _c.max) || 0);
    });
    const fastestProviders = sortedQuotes.filter((quote) => {
        var _a, _b, _c;
        return sortedQuotes.length > 0 &&
            ((_a = quote.deliveryEstimation.duration) === null || _a === void 0 ? void 0 : _a.max) &&
            ((_b = sortedQuotes[0].deliveryEstimation.duration) === null || _b === void 0 ? void 0 : _b.max) &&
            toSeconds((_c = quote.deliveryEstimation.duration) === null || _c === void 0 ? void 0 : _c.max) ===
                toSeconds(sortedQuotes[0].deliveryEstimation.duration.max);
    });
    return fastestProviders.map((quote) => quote.provider.alias);
};

// Create the context
const ComparisonTableHeroV2TableTrackingContext = createContext(undefined);
function useComparisonTableHeroV2TableTrackingContext() {
    const context = useContext(ComparisonTableHeroV2TableTrackingContext);
    if (!context) {
        throw new Error('useComparisonTableHeroV2TableTrackingContext must be used within a ComparisonTableHeroV2TableTrackingContextProvider');
    }
    const quotes = useMemo(() => transformComparisonV4Response(context.trackingData.comparisonResponse, context.trackingData.excludePartners), [context.trackingData]);
    const cheapestProviderAliases = useMemo(() => {
        const sortedQuotes = quotes.sort((a, b) => b.receivedAmount.value - a.receivedAmount.value);
        const cheapestProviders = quotes.filter((quote) => quote.receivedAmount === sortedQuotes[0].receivedAmount);
        return cheapestProviders.map((quote) => quote.provider.alias);
    }, [quotes]);
    const fastestProviderAliases = useMemo(() => {
        // eslint-disable-next-line @typescript-eslint/no-unsafe-return
        return getFastestProviders(quotes);
    }, [quotes]);
    const trackingContext = useMemo(() => ({
        amount: context.trackingData.comparisonResponse.amount,
        source: context.trackingData.comparisonResponse.sourceCurrency,
        target: context.trackingData.comparisonResponse.targetCurrency,
        quotes: quotes,
        componentType: Table.HeroV2,
        savingsAgainstWise: calculateSavingsWithRespectToWiseQuote(quotes, context.trackingData.excludePartners),
        midMarketRate: { rate: context.trackingData.midMarketRate },
        cheapestProviders: cheapestProviderAliases,
        fastestProviders: fastestProviderAliases,
        isWiseTheCheapest: cheapestProviderAliases.filter((alias) => alias === 'wise').length > 0,
        isWiseTheFastest: fastestProviderAliases.filter((alias) => alias === 'wise').length > 0,
    }), [
        cheapestProviderAliases,
        context.trackingData.comparisonResponse.amount,
        context.trackingData.comparisonResponse.sourceCurrency,
        context.trackingData.comparisonResponse.targetCurrency,
        context.trackingData.excludePartners,
        context.trackingData.midMarketRate,
        fastestProviderAliases,
        quotes,
    ]);
    return { trackingContext, trackEvent: context.trackEvent };
}
// Create a provider component for the context
const ComparisonTableHeroV2TableTrackingContextProvider = ({ children, trackingData, trackEvent, }) => {
    return (
    // eslint-disable-next-line react/jsx-no-constructed-context-values
    jsx(ComparisonTableHeroV2TableTrackingContext.Provider, Object.assign({ value: { trackingData, trackEvent } }, { children: children })));
};

export { ComparisonTableHeroV2TableTrackingContextProvider as C, clsx as c, getFastestProviders as g, transformComparisonV4Response as t, useComparisonTableHeroV2TableTrackingContext as u };
//# sourceMappingURL=ComparisonTableHeroV2TrackingContext-3f2aabac.js.map
