import { toSeconds } from 'duration-fns';
import { i as isWiseQuote } from './quoteFilters-9ddc9e2f.js';
import { a as sortByDeliverySpeedEstimate } from './sortQuotesByDeliverySpeedEstimate-f8c8a1b8.js';

function sortWiseFollowedByOthers(q1, q2) {
  if (isWiseQuote(q1)) {
    return -1;
  }
  if (isWiseQuote(q2)) {
    return 1;
  }
  return q1.alias.localeCompare(q2.alias);
}
function sortQuotesByReceivedAmount(quotes) {
  return quotes.sort((q1, q2) => {
    if (q2.receivedAmount === q1.receivedAmount) {
      return sortWiseFollowedByOthers(q1, q2);
    }
    return q2.receivedAmount - q1.receivedAmount;
  });
}

const getCookies = () => {
    if (document.cookie) {
        return Object.fromEntries(document.cookie.split('; ').map((c) => c.split('=')));
    }
    return {};
};

const getCookieByName = (name) => {
    const cookies = getCookies();
    if (!cookies) {
        return null;
    }
    const cookieNameMatch = Object.keys(cookies).find((cookieName) => cookieName === name);
    if (!cookieNameMatch) {
        return null;
    }
    return decodeURIComponent(cookies[cookieNameMatch]);
};

const isWisePage = () => {
    const wiseDomain = 'wise.com';
    return window.location.hostname === wiseDomain;
};

const getVisitorId = () => {
    if (!isWisePage()) {
        return null;
    }
    return getCookieByName('gid');
};

var EventName;
(function (EventName) {
    EventName["ProviderFilteringOptionChanged"] = "ProviderFilteringOptionChanged";
    EventName["FeeBreakdownPopoverStarted"] = "FeeBreakdownPopoverStarted";
    EventName["MobileFeeBreakdownStarted"] = "MobileFeeBreakdownStarted";
    EventName["LargestProviderTableRendered"] = "LargestProviderTableRendered";
    EventName["RowWasSeen"] = "RowWasSeen";
    EventName["WiseHasHiddenFee"] = "WiseHasHiddenFee";
})(EventName || (EventName = {}));
var WidgetName;
(function (WidgetName) {
    WidgetName["TransferFeeComparison"] = "Transfer-Fee-Comparison";
})(WidgetName || (WidgetName = {}));
var Table;
(function (Table) {
    Table["ProviderComparison"] = "Provider Comparison";
    Table["Hero"] = "Hero";
    Table["Educational"] = "Educational";
    Table["TransferFee"] = "Transfer Fee";
    Table["HeroV2"] = "HeroV2";
})(Table || (Table = {}));
var TableEvent;
(function (TableEvent) {
    TableEvent["AMOUNT_CHANGED"] = "AMOUNT_CHANGED";
    TableEvent["CURRENCIES_SWAPPED"] = "CURRENCIES_SWAPPED";
    TableEvent["DELIVERY_ESTIMATOR_CLICKED"] = "DELIVERY_ESTIMATOR_CLICKED";
    TableEvent["DISCLAIMER_CLICKED"] = "DISCLAIMER_CLICKED";
    TableEvent["FEE_BREAKDOWN_POPOVER_CLICKED"] = "FEE_BREAKDOWN_POPOVER_CLICKED";
    TableEvent["PRICING_DISCLAIMER_CLICKED"] = "PRICING_DISCLAIMER_CLICKED";
    TableEvent["PROVIDER_CLICKED"] = "PROVIDER_CLICKED";
    TableEvent["QUOTES_LOADED"] = "QUOTES_LOADED";
    TableEvent["SEE_AVAILABLE_COMPARISON_CLICKED"] = "SEE_AVAILABLE_COMPARISON_CLICKED";
    TableEvent["SEND_MONEY_CTA_CLICKED"] = "SEND_MONEY_CTA_CLICKED";
    TableEvent["SOURCE_CURRENCY_CHANGED"] = "SOURCE_CURRENCY_CHANGED";
    TableEvent["TABLE_VIEWED"] = "TABLE_VIEWED";
    TableEvent["TARGET_CURRENCY_CHANGED"] = "TARGET_CURRENCY_CHANGED";
    TableEvent["UNSUPPORTED_AMOUNT"] = "UNSUPPORTED_AMOUNT";
    TableEvent["UNSUPPORTED_ROUTE"] = "UNSUPPORTED_ROUTE";
    TableEvent["WISE_IS_NOT_THE_CHEAPEST"] = "WISE_IS_NOT_THE_CHEAPEST";
    TableEvent["WISE_IS_NOT_THE_FASTEST"] = "WISE_IS_NOT_THE_FASTEST";
    TableEvent["EXPAND_ROW_CLICKED"] = "EXPAND_ROW_CLICKED";
})(TableEvent || (TableEvent = {}));
const EventNames = {
    [TableEvent.AMOUNT_CHANGED]: {
        gtm: 'comparison_amount_changed',
        mixpanel: 'Comparison - Amount Changed',
    },
    [TableEvent.CURRENCIES_SWAPPED]: {
        gtm: 'comparison_currencies_swapped',
        mixpanel: 'Comparison - Currencies Swapped',
    },
    [TableEvent.DELIVERY_ESTIMATOR_CLICKED]: {
        gtm: 'comparison_delivery_estimator_clicked',
        mixpanel: 'Comparison - Delivery Estimator Clicked',
    },
    [TableEvent.DISCLAIMER_CLICKED]: {
        gtm: 'comparison_disclaimer_clicked',
        mixpanel: 'Comparison - Disclaimer Clicked',
    },
    [TableEvent.EXPAND_ROW_CLICKED]: {
        gtm: 'comparison_expand_row_clicked',
        mixpanel: 'Comparison - Expand Row Clicked',
    },
    [TableEvent.FEE_BREAKDOWN_POPOVER_CLICKED]: {
        gtm: 'comparison_fee_breakdown_popover_clicked',
        mixpanel: 'Comparison - Fee Breakdown Popover Clicked',
    },
    [TableEvent.PRICING_DISCLAIMER_CLICKED]: {
        gtm: 'comparison_pricing_disclaimer_clicked',
        mixpanel: 'Comparison - Pricing Disclaimer Clicked',
    },
    [TableEvent.PROVIDER_CLICKED]: {
        gtm: 'comparison_provider_clicked',
        mixpanel: 'Comparison - Provider Clicked',
    },
    [TableEvent.QUOTES_LOADED]: {
        gtm: 'comparison_quotes_loaded',
        mixpanel: 'Comparison - Quotes Loaded',
    },
    [TableEvent.SEE_AVAILABLE_COMPARISON_CLICKED]: {
        gtm: 'comparison_see_available_comparison_clicked',
        mixpanel: 'Comparison - See Available Comparison Clicked',
    },
    [TableEvent.SEND_MONEY_CTA_CLICKED]: {
        gtm: 'comparison_send_money_cta_clicked',
        mixpanel: 'Comparison - Send Money CTA Clicked',
    },
    [TableEvent.SOURCE_CURRENCY_CHANGED]: {
        gtm: 'comparison_source_currency_changed',
        mixpanel: 'Comparison - Source Currency Changed',
    },
    [TableEvent.TABLE_VIEWED]: {
        gtm: 'comparison_table_viewed',
        mixpanel: 'Comparison - Table Viewed',
    },
    [TableEvent.TARGET_CURRENCY_CHANGED]: {
        gtm: 'comparison_target_currency_changed',
        mixpanel: 'Comparison - Target Currency Changed',
    },
    [TableEvent.UNSUPPORTED_AMOUNT]: {
        gtm: 'comparison_amount_unsupported',
        mixpanel: 'Comparison - Amount Unsupported',
    },
    [TableEvent.UNSUPPORTED_ROUTE]: {
        gtm: 'comparison_route_unsupported',
        mixpanel: 'Comparison - Route Unsupported',
    },
    [TableEvent.WISE_IS_NOT_THE_CHEAPEST]: {
        gtm: 'comparison_wise_is_not_the_cheapest',
        mixpanel: 'Comparison - Wise Is Not The Cheapest',
    },
    [TableEvent.WISE_IS_NOT_THE_FASTEST]: {
        gtm: 'comparison_wise_is_not_the_fastest',
        mixpanel: 'Comparison - Wise Is Not The Fastest',
    },
};

/* eslint-disable fp/no-mutation */
function isNotEmpty(quotes) {
  return quotes && quotes.length > 1;
}
function isWiseTheCheapest(quotes = []) {
  const sortedQuotes = sortQuotesByReceivedAmount(quotes);
  return sortedQuotes[0] && isWiseQuote(sortedQuotes[0]);
}
function isWiseTheFastest(quotes = []) {
  const sortedQuotes = sortByDeliverySpeedEstimate(quotes);
  return sortedQuotes[0] && isWiseQuote(sortedQuotes[0]);
}
function mapDeliveryEstimation(deliveryEstimation = {}) {
  const duration = deliveryEstimation.duration || {};
  const min = duration.min ? toSeconds(duration.min) : null;
  const max = duration.max ? toSeconds(duration.max) : null;
  return {
    duration: {
      min,
      max
    },
    providerGivesEstimate: deliveryEstimation.providerGivesEstimate
  };
}
function findCheapestProviders(quotes) {
  if (!quotes || quotes.length === 0) {
    return;
  }
  const sortedQuotes = sortQuotesByReceivedAmount(quotes);
  const highestReceivedAmount = sortedQuotes[0].receivedAmount;
  const quotesWithHighestReceivedAmount = sortedQuotes.filter(quote => quote.receivedAmount === highestReceivedAmount);
  return quotesWithHighestReceivedAmount.map(quote => quote.alias);
}
function deriveStandardFields(context) {
  return {
    componentType: context.componentType,
    amount: context.amount,
    sourceCurrency: context.source,
    targetCurrency: context.target,
    sourceCountry: context.sourceCountry,
    providerCountry: context.providerCountry,
    providerQuotes: context.quotes && context.quotes.map(p => ({
      name: p.name,
      rate: p.rate,
      fees: p.fees,
      receivedAmount: p.receivedAmount,
      deliveryEstimation: mapDeliveryEstimation(p.deliveryEstimation)
    })),
    whitelistedProviders: context.whitelistedProviders && context.whitelistedProviders.join(),
    cheapestProviders: context.quotes && findCheapestProviders(context.quotes),
    savingsAgainstWise: context.savingsAgainstWise,
    affiliateLink: context.affiliateLink,
    lang: context.lang,
    midMarketRate: context.midMarketRate && context.midMarketRate.rate,
    visitorId: getVisitorId(),
    isWiseTheCheapest: context.quotes && isWiseTheCheapest(context.quotes)
  };
}
function deriveAdditionalFieldsBasedOnVariant(context) {
  if (context.componentType === Table.ProviderComparison) {
    return {
      provider: {
        name: context.provider && context.provider.name
      },
      routes: context.routes && context.routes.map(r => ({
        targetCurrency: r.baseProviderQuote?.targetCurrency,
        deliveryEstimation: mapDeliveryEstimation(r.baseProviderQuote?.deliveryEstimation),
        fee: r.baseProviderQuote?.fee,
        rate: r.baseProviderQuote?.rate,
        receivedAmount: r.baseProviderQuote?.receivedAmount,
        wiseQuote: {
          deliveryEstimation: mapDeliveryEstimation(r.comparedProviderQuote?.deliveryEstimation),
          savings: r.comparedProviderQuote?.receivedAmount - r.baseProviderQuote?.receivedAmount
        }
      }))
    };
  }
  if (context.componentType === Table.TransferFee) {
    return {
      isSpeedShown: context.showSpeed,
      providerName: context.providerName
    };
  }
  if (context.componentType === Table.HeroV2) {
    return {
      providerName: context.providerName,
      isRowExpanded: context.isRowExpanded,
      cheapestProviders: context.cheapestProviders,
      fastestProviders: context.fastestProviders,
      isWiseTheCheapest: context.isWiseTheCheapest,
      isWiseTheFastest: context.isWiseTheFastest
    };
  }
}
function filterNonPopulatedFields(attributes) {
  const attributesForTracking = {};
  Object.keys(attributes).forEach(key => {
    if (attributes[key] != null) {
      attributesForTracking[key] = attributes[key];
    }
  });
  return attributesForTracking;
}

/**
 * TODO We could choose to model these events separately instead of piecing together
 * which event was fired from the props and state.
 */
function trackRouteChange(route, context, trackEvent) {
  const source = route.sourceCurrency;
  const target = route.targetCurrency;
  const SOURCE_KEY = 'source';
  const TARGET_KEY = 'target';
  const filteredRouteChanges = filterNonPopulatedFields({
    [SOURCE_KEY]: source,
    [TARGET_KEY]: target
  });
  const partsOfRouteChanged = Object.keys(filteredRouteChanges);
  const trackingAttributes = {
    ...deriveStandardFields(context),
    ...deriveAdditionalFieldsBasedOnVariant(context)
  };
  let eventNames;
  if (partsOfRouteChanged.length === 2) {
    eventNames = EventNames[TableEvent.CURRENCIES_SWAPPED];
    trackingAttributes.sourceCurrency = source;
    trackingAttributes.targetCurrency = target;
  } else {
    const partOfRouteChanged = partsOfRouteChanged[0];
    if (partOfRouteChanged === SOURCE_KEY) {
      trackingAttributes.previousCurrency = context.sourceCurrency;
      trackingAttributes.targetCurrency = context.targetCurrency;
      eventNames = EventNames[TableEvent.SOURCE_CURRENCY_CHANGED];
    } else if (partOfRouteChanged === TARGET_KEY) {
      trackingAttributes.previousCurrency = context.targetCurrency;
      trackingAttributes.sourceCurrency = context.sourceCurrency;
      eventNames = EventNames[TableEvent.TARGET_CURRENCY_CHANGED];
    }
    trackingAttributes[partOfRouteChanged + 'Currency'] = filteredRouteChanges[partOfRouteChanged];
  }
  trackingAttributes.midMarketRate = route.rate;
  trackEvent(eventNames, filterNonPopulatedFields(trackingAttributes));
}
function trackAmountChange(newAmount, previousAmount, context, trackEvent) {
  const trackingAttributes = deriveStandardFields(context);
  trackingAttributes.previousAmount = previousAmount;
  trackingAttributes.amount = newAmount;
  trackEvent(EventNames[TableEvent.AMOUNT_CHANGED], filterNonPopulatedFields(trackingAttributes));
}

/**
 * TODO Refactor - The extraction of the attributes and mapping of error types
 *
 * TODO This event isn't technically just "unsupported amount". It could be a route where we have an amount but
 * not for the passed source, target, *sourceCountry*, *providerCountry* etc...
 */

function trackWhenError(errorType, context, trackEvent) {
  const eventNames = {
    UNSUPPORTED_AMOUNT: EventNames[TableEvent.UNSUPPORTED_AMOUNT],
    UNSUPPORTED_ROUTE: EventNames[TableEvent.UNSUPPORTED_ROUTE]
  };
  if (Object.keys(eventNames).includes(errorType)) {
    const trackingAttributes = deriveStandardFields(context);
    trackEvent(eventNames[errorType], filterNonPopulatedFields(trackingAttributes));
  }
}
function trackClickToSendMoney(context, trackLeavePageEvent, callback = () => {}) {
  const trackingAttributes = {
    ...deriveStandardFields(context),
    ...deriveAdditionalFieldsBasedOnVariant(context)
  };
  trackLeavePageEvent(EventNames[TableEvent.SEND_MONEY_CTA_CLICKED], filterNonPopulatedFields(trackingAttributes), callback);
}
function trackClickToSeeAvailableComparison(maxAmountCollected, context, trackEvent) {
  const trackingAttributes = deriveStandardFields(context);
  trackingAttributes.maxAmountCollected = maxAmountCollected;
  trackEvent(EventNames[TableEvent.SEE_AVAILABLE_COMPARISON_CLICKED], filterNonPopulatedFields(trackingAttributes));
}
function trackIfWiseIsNotTheCheapest(quotes, context, trackEvent) {
  if (isNotEmpty(quotes) && !isWiseTheCheapest(quotes)) {
    const updatedContext = {
      ...context,
      quotes
    };
    const trackingAttributes = deriveStandardFields(updatedContext);
    trackEvent(EventNames[TableEvent.WISE_IS_NOT_THE_CHEAPEST], filterNonPopulatedFields(trackingAttributes));
  }
}
function trackIfWiseIsNotTheFastest(quotes, context, trackEvent) {
  if (isNotEmpty(quotes) && !isWiseTheFastest(quotes)) {
    const updatedContext = {
      ...context,
      quotes
    };
    const trackingAttributes = deriveStandardFields(updatedContext);
    trackEvent(EventNames[TableEvent.WISE_IS_NOT_THE_FASTEST], filterNonPopulatedFields(trackingAttributes));
  }
}
function trackClickToSeePricingDisclaimer(targetCountry, providerAlias, context, trackEvent) {
  const trackingAttributes = deriveStandardFields(context);
  trackingAttributes.targetCountry = targetCountry;
  trackingAttributes.providerAlias = providerAlias;
  trackEvent(EventNames[TableEvent.PRICING_DISCLAIMER_CLICKED], filterNonPopulatedFields(trackingAttributes));
}
function trackSpeedTooltipClick(context, trackEvent) {
  const trackingAttributes = deriveStandardFields(context);
  trackEvent(EventNames[TableEvent.DELIVERY_ESTIMATOR_CLICKED], filterNonPopulatedFields(trackingAttributes));
}
function trackQuotesLoad(context, quotes, trackEvent) {
  const trackingAttributes = deriveStandardFields({
    ...context,
    quotes
  });
  trackEvent(EventNames[TableEvent.QUOTES_LOADED], filterNonPopulatedFields(trackingAttributes));
}
function trackTableViewed(context, trackEvent) {
  const trackingAttributes = {
    ...deriveStandardFields(context),
    ...deriveAdditionalFieldsBasedOnVariant(context)
  };
  trackEvent(EventNames[TableEvent.TABLE_VIEWED], filterNonPopulatedFields(trackingAttributes));
}
function trackFeePopoverClicked(context, trackEvent) {
  const trackingAttributes = {
    ...deriveStandardFields(context),
    ...deriveAdditionalFieldsBasedOnVariant(context)
  };
  trackEvent(EventNames[TableEvent.FEE_BREAKDOWN_POPOVER_CLICKED], filterNonPopulatedFields(trackingAttributes));
}
function trackExpandRowClicked(context, trackEvent) {
  const trackingAttributes = {
    ...deriveStandardFields(context),
    ...deriveAdditionalFieldsBasedOnVariant(context)
  };
  trackEvent(EventNames[TableEvent.EXPAND_ROW_CLICKED], filterNonPopulatedFields(trackingAttributes));
}
function trackClickToSeeDisclaimer(context, trackEvent) {
  const trackingAttributes = {
    ...deriveStandardFields(context),
    ...deriveAdditionalFieldsBasedOnVariant(context)
  };
  trackEvent(EventNames[TableEvent.DISCLAIMER_CLICKED], filterNonPopulatedFields(trackingAttributes));
}
function trackProviderClicked(providerName, context, trackEvent) {
  const trackingAttributes = {
    ...deriveStandardFields(context)
  };
  trackingAttributes.providerName = providerName;
  trackEvent(EventNames[TableEvent.PROVIDER_CLICKED], filterNonPopulatedFields(trackingAttributes));
}
function getTrackingTriggerIndex(rowsLength) {
  const indexValue = Math.ceil(rowsLength * 0.25);
  return Math.max(0, indexValue - 1);
}

export { Table as T, trackIfWiseIsNotTheCheapest as a, trackIfWiseIsNotTheFastest as b, trackRouteChange as c, trackWhenError as d, trackClickToSeeAvailableComparison as e, trackClickToSendMoney as f, trackClickToSeePricingDisclaimer as g, trackSpeedTooltipClick as h, trackClickToSeeDisclaimer as i, trackProviderClicked as j, trackAmountChange as k, trackTableViewed as l, getTrackingTriggerIndex as m, trackFeePopoverClicked as n, trackExpandRowClicked as o, sortQuotesByReceivedAmount as s, trackQuotesLoad as t };
//# sourceMappingURL=tracking-4fba21bf.js.map
