import PropTypes from 'prop-types';
import React, { Component } from 'react';
import autoBind from 'react-autobind';
import { findMaxAmountCollected, fetchRate, fetchQuotes, fetchReferenceQuotes } from './clients.js';
import { c as createUrl } from './createUrl-71d09e7b.js';
import { t as trackQuotesLoad, a as trackIfWiseIsNotTheCheapest, b as trackIfWiseIsNotTheFastest, c as trackRouteChange, d as trackWhenError, e as trackClickToSeeAvailableComparison, f as trackClickToSendMoney, g as trackClickToSeePricingDisclaimer, h as trackSpeedTooltipClick, i as trackClickToSeeDisclaimer, j as trackProviderClicked, k as trackAmountChange, T as Table, l as trackTableViewed, s as sortQuotesByReceivedAmount, m as getTrackingTriggerIndex } from './tracking-7717c145.js';
import { Popover, Position, Button, Size, ControlType, Priority, Loader } from '@transferwise/components';
import { formatMoney } from '@transferwise/formatting';
import { InView } from 'react-intersection-observer';
import { FormattedMessage, useIntl, injectIntl } from 'react-intl';
import { s as styles, R as ReceiveAmount, f as filterQuotes, i as isWisePresentAndNotCheapest, C as CurrencyRouteDescription, S as ShowMoreProviders } from './ReceiveAmount-ae20c20a.js';
import { i as injectTheme, E as ErrorTemplate, D as Disclaimer } from './ErrorTemplate-28d6d334.js';
import { T as TapestryCard } from './TapestryCard-0917e400.js';
import { T as TransferFee, C as ConditionalWrapper } from './TransferFee-d60db2da.js';
import { i as isDeliveryEstimationCollectedForAllProviders } from './deliveryEstimationFormatter-5aea20f1.js';
import { D as DeliveryEstimation } from './DeliveryEstimation-ef9b56d5.js';
import { E as ExchangeRateIndicator } from './ExchangeRateIndicator-e3721dde.js';
import { L as Label } from './Label-25a8b620.js';
import { P as ProviderLogo } from './ProviderLogo-cc9009cf.js';
import { i as isWiseAlias } from './aliasFilter-a7b9c811.js';
import { g as generateUrl, A as AvailablePages } from './generateUrl-3fc80d02.js';
import { i as isConsideredMidmarketRate } from './isConsideredMidmarketRate-4f12041d.js';
import { W as WISE_ALIAS } from './provider-constants-b35398f2.js';
import { Warning, ArrowRight } from '@transferwise/icons';
import { s as styleInject } from './style-inject.es-1f59c1d0.js';

const iso3ToIso2Countries = {
  AFG: 'AF',
  ALA: 'AX',
  ALB: 'AL',
  DZA: 'DZ',
  ASM: 'AS',
  AND: 'AD',
  AGO: 'AO',
  AIA: 'AI',
  ATA: 'AQ',
  ATG: 'AG',
  ARG: 'AR',
  ARM: 'AM',
  ABW: 'AW',
  AUS: 'AU',
  AUT: 'AT',
  AZE: 'AZ',
  BHS: 'BS',
  BHR: 'BH',
  BGD: 'BD',
  BRB: 'BB',
  BLR: 'BY',
  BEL: 'BE',
  BLZ: 'BZ',
  BEN: 'BJ',
  BMU: 'BM',
  BTN: 'BT',
  BOL: 'BO',
  BIH: 'BA',
  BWA: 'BW',
  BVT: 'BV',
  BRA: 'BR',
  VGB: 'VG',
  IOT: 'IO',
  BRN: 'BN',
  BGR: 'BG',
  BFA: 'BF',
  BDI: 'BI',
  KHM: 'KH',
  CMR: 'CM',
  CAN: 'CA',
  CPV: 'CV',
  CYM: 'KY',
  CAF: 'CF',
  TCD: 'TD',
  CHL: 'CL',
  CHN: 'CN',
  HKG: 'HK',
  MAC: 'MO',
  CXR: 'CX',
  CCK: 'CC',
  COL: 'CO',
  COM: 'KM',
  COG: 'CG',
  COD: 'CD',
  COK: 'CK',
  CRI: 'CR',
  CIV: 'CI',
  HRV: 'HR',
  CUB: 'CU',
  CYP: 'CY',
  CZE: 'CZ',
  DNK: 'DK',
  DJI: 'DJ',
  DMA: 'DM',
  DOM: 'DO',
  ECU: 'EC',
  EGY: 'EG',
  SLV: 'SV',
  GNQ: 'GQ',
  ERI: 'ER',
  EST: 'EE',
  ETH: 'ET',
  FLK: 'FK',
  FRO: 'FO',
  FJI: 'FJ',
  FIN: 'FI',
  FRA: 'FR',
  GUF: 'GF',
  PYF: 'PF',
  ATF: 'TF',
  GAB: 'GA',
  GMB: 'GM',
  GEO: 'GE',
  DEU: 'DE',
  GHA: 'GH',
  GIB: 'GI',
  GRC: 'GR',
  GRL: 'GL',
  GRD: 'GD',
  GLP: 'GP',
  GUM: 'GU',
  GTM: 'GT',
  GGY: 'GG',
  GIN: 'GN',
  GNB: 'GW',
  GUY: 'GY',
  HTI: 'HT',
  HMD: 'HM',
  VAT: 'VA',
  HND: 'HN',
  HUN: 'HU',
  ISL: 'IS',
  IND: 'IN',
  IDN: 'ID',
  IRN: 'IR',
  IRQ: 'IQ',
  IRL: 'IE',
  IMN: 'IM',
  ISR: 'IL',
  ITA: 'IT',
  JAM: 'JM',
  JPN: 'JP',
  JEY: 'JE',
  JOR: 'JO',
  KAZ: 'KZ',
  KEN: 'KE',
  KIR: 'KI',
  PRK: 'KP',
  KOR: 'KR',
  KWT: 'KW',
  KGZ: 'KG',
  LAO: 'LA',
  LVA: 'LV',
  LBN: 'LB',
  LSO: 'LS',
  LBR: 'LR',
  LBY: 'LY',
  LIE: 'LI',
  LTU: 'LT',
  LUX: 'LU',
  MKD: 'MK',
  MDG: 'MG',
  MWI: 'MW',
  MYS: 'MY',
  MDV: 'MV',
  MLI: 'ML',
  MLT: 'MT',
  MHL: 'MH',
  MTQ: 'MQ',
  MRT: 'MR',
  MUS: 'MU',
  MYT: 'YT',
  MEX: 'MX',
  FSM: 'FM',
  MDA: 'MD',
  MCO: 'MC',
  MNG: 'MN',
  MNE: 'ME',
  MSR: 'MS',
  MAR: 'MA',
  MOZ: 'MZ',
  MMR: 'MM',
  NAM: 'NA',
  NRU: 'NR',
  NPL: 'NP',
  NLD: 'NL',
  ANT: 'AN',
  NCL: 'NC',
  NZL: 'NZ',
  NIC: 'NI',
  NER: 'NE',
  NGA: 'NG',
  NIU: 'NU',
  NFK: 'NF',
  MNP: 'MP',
  NOR: 'NO',
  OMN: 'OM',
  PAK: 'PK',
  PLW: 'PW',
  PSE: 'PS',
  PAN: 'PA',
  PNG: 'PG',
  PRY: 'PY',
  PER: 'PE',
  PHL: 'PH',
  PCN: 'PN',
  POL: 'PL',
  PRT: 'PT',
  PRI: 'PR',
  QAT: 'QA',
  REU: 'RE',
  ROU: 'RO',
  RUS: 'RU',
  RWA: 'RW',
  BLM: 'BL',
  SHN: 'SH',
  KNA: 'KN',
  LCA: 'LC',
  MAF: 'MF',
  SPM: 'PM',
  VCT: 'VC',
  WSM: 'WS',
  SMR: 'SM',
  STP: 'ST',
  SAU: 'SA',
  SEN: 'SN',
  SRB: 'RS',
  SYC: 'SC',
  SLE: 'SL',
  SGP: 'SG',
  SVK: 'SK',
  SVN: 'SI',
  SLB: 'SB',
  SOM: 'SO',
  ZAF: 'ZA',
  SGS: 'GS',
  SSD: 'SS',
  ESP: 'ES',
  LKA: 'LK',
  SDN: 'SD',
  SUR: 'SR',
  SJM: 'SJ',
  SWZ: 'SZ',
  SWE: 'SE',
  CHE: 'CH',
  SYR: 'SY',
  TWN: 'TW',
  TJK: 'TJ',
  TZA: 'TZ',
  THA: 'TH',
  TLS: 'TL',
  TGO: 'TG',
  TKL: 'TK',
  TON: 'TO',
  TTO: 'TT',
  TUN: 'TN',
  TUR: 'TR',
  TKM: 'TM',
  TCA: 'TC',
  TUV: 'TV',
  UGA: 'UG',
  UKR: 'UA',
  ARE: 'AE',
  GBR: 'GB',
  USA: 'US',
  UMI: 'UM',
  URY: 'UY',
  UZB: 'UZ',
  VUT: 'VU',
  VEN: 'VE',
  VNM: 'VN',
  VIR: 'VI',
  WLF: 'WF',
  ESH: 'EH',
  YEM: 'YE',
  ZMB: 'ZM',
  ZWE: 'ZW'
};
function iso3ToIso2(iso3Country) {
  return iso3ToIso2Countries[iso3Country];
}

const makeAsync = fn => (...args) => setTimeout(() => fn.apply(undefined, args), 0);

const executeAsync = fn => makeAsync(fn)();
function parseBool(input) {
  if (typeof input === 'boolean') {
    return input;
  }
  return input === 'true';
}
function toLowerCase(providerNames) {
  return providerNames.map(p => p.toLowerCase());
}
function normaliseToIso2(country) {
  return !country || country.length === 2 ? country : iso3ToIso2(country);
}
function extractRequiredProps(props) {
  const sendAmount = props.sendAmount ? parseFloat(props.sendAmount) : parseFloat(props.amount);
  const sourceCurrency = props.sourceCurrency || props.source;
  const targetCurrency = props.targetCurrency || props.target;
  return {
    sendAmount,
    sourceCurrency,
    targetCurrency
  };
}
function isValidAffiliate(affiliateLink) {
  return !!(affiliateLink.match(/^(https?:\/\/transferwise\.com)\//) || affiliateLink.match(/^(https?:\/\/wise\.com)\//) || affiliateLink.match(/^(https?:\/\/(wise\.|transferwise\.)?prf\.hn)\//));
}
function withComparisonResources(WrappedComponent) {
  class RequestComparisonResources extends Component {
    constructor(props) {
      super(props);
      const {
        route,
        quotes,
        referenceQuotes,
        wiseFee
      } = this.props;
      autoBind(this);
      this.componentType = props.componentType ? props.componentType : WrappedComponent.componentType;
      const {
        sendAmount,
        sourceCurrency,
        targetCurrency
      } = extractRequiredProps(props);
      this.state = {
        sendAmount,
        lastAmountFetched: sendAmount,
        sourceCurrency,
        targetCurrency,
        midMarketRate: route?.rate,
        wiseFee,
        // TODO Rename
        route,
        quotes,
        referenceQuotes,
        error: false,
        loadingRates: !route,
        loadingQuotes: quotes.length === 0,
        loadingReferenceQuotes: referenceQuotes.length === 0,
        // State private to this component
        sourceCountry: normaliseToIso2(props.sourceCountry),
        providerCountry: props.providerCountry,
        whitelistedProviders: props.providers ? toLowerCase(props.providers) : null
      };
    }
    componentDidMount() {
      const {
        sendAmount,
        sourceCurrency,
        targetCurrency,
        maxAmountCollected
      } = extractRequiredProps(this.props);
      const {
        sourceCountry,
        providerCountry,
        referenceQuotes,
        wiseFee
      } = {
        ...this.props,
        ...this.state
      };
      const {
        route,
        quotes,
        trackEvent
      } = {
        ...this.props
      };
      if (!route) {
        this.fetchAndProcessRates(sourceCurrency, targetCurrency);
      }
      if (quotes.length === 0) {
        this.fetchAndProcessQuotes(sourceCurrency, targetCurrency, sendAmount, sourceCountry, providerCountry, route?.rate, wiseFee).then(newQuotes => {
          this.performPostMountTracking(newQuotes, trackEvent);
        });
      } else {
        this.performPostMountTracking(quotes, trackEvent);
      }
      if (referenceQuotes.length === 0) {
        this.fetchAndProcessReferenceQuotes(sourceCurrency, targetCurrency, sourceCountry);
      } else if (!maxAmountCollected) {
        this.setState({
          ...this.state,
          maxAmountCollected: findMaxAmountCollected(sourceCurrency, targetCurrency, referenceQuotes)
        });
      }
    }
    performPostMountTracking(quotes, trackEvent) {
      const context = {
        ...this.state,
        componentType: this.componentType
      };
      const filteredProviders = this.filterByWhitelistedProviders(quotes);
      const enrichedContext = this.enrichContext(context);
      trackQuotesLoad(context, quotes, trackEvent);
      trackIfWiseIsNotTheCheapest(filteredProviders, enrichedContext, trackEvent);
      trackIfWiseIsNotTheFastest(filteredProviders, enrichedContext, trackEvent);
    }
    onRouteChange(route, context) {
      const {
        sourceCurrency,
        targetCurrency
      } = this.state;
      const derivedSourceCurrency = route.sourceCurrency || sourceCurrency;
      const derivedTargetCurrency = route.targetCurrency || targetCurrency;
      this.setState({
        sourceCurrency: derivedSourceCurrency,
        targetCurrency: derivedTargetCurrency,
        midMarketRate: this.isOriginalRoute(derivedSourceCurrency, derivedTargetCurrency) ? this.props.route?.rate : null
      }, () => this.continueOnRouteChange(route, context));
    }
    continueOnRouteChange(route, context) {
      const {
        onComparisonParamsChange,
        trackEvent
      } = this.props;
      const {
        sendAmount,
        sourceCurrency,
        targetCurrency,
        midMarketRate
      } = this.state;
      const updatedFilters = this.removeAllFilters();
      executeAsync(() => onComparisonParamsChange({
        sourceCurrency,
        targetCurrency,
        sendAmount
      }));
      return this.fetchAndProcessAllResources(sourceCurrency, targetCurrency, sendAmount, updatedFilters.sourceCountry, updatedFilters.providerCountry, midMarketRate).then(response => {
        const updatedContext = {
          ...context,
          quotes: response.quotes
        };
        trackIfWiseIsNotTheCheapest(this.filterByWhitelistedProviders(response.quotes), this.enrichContext(context), trackEvent);
        trackIfWiseIsNotTheFastest(this.filterByWhitelistedProviders(response.quotes), this.enrichContext(context), trackEvent);
        trackRouteChange(route, this.enrichContext(updatedContext), trackEvent);
      });
    }
    onError(errorType, context) {
      const {
        trackEvent
      } = this.props;
      trackWhenError(errorType, this.enrichContext(context), trackEvent);
    }
    onClickToSeeAnAvailableComparison(maxAmountCollected, context) {
      const {
        trackEvent
      } = this.props;
      this.updateAmountAndShowLoader(maxAmountCollected);
      this.fetchQuotesForAmount(maxAmountCollected).then(response => {
        const updatedContext = {
          ...context,
          quotes: response.quotes
        };
        trackClickToSeeAvailableComparison(maxAmountCollected, this.enrichContext(updatedContext), trackEvent);
      });
    }
    onCallToActionClick(context) {
      const {
        trackLeavePageEvent
      } = this.props;
      const navigateTo = () => {
        window.location.href = this.linkToTW(context);
      };
      trackClickToSendMoney(this.enrichContext(context), trackLeavePageEvent, navigateTo);
    }
    onClickToSeePricingDisclaimer(targetCountry, providerAlias, context) {
      const {
        trackEvent
      } = this.props;
      trackClickToSeePricingDisclaimer(targetCountry, providerAlias, this.enrichContext(context), trackEvent);
    }
    onClickingDeliveryEstimationTooltip(context) {
      const {
        trackEvent
      } = this.props;
      trackSpeedTooltipClick(this.enrichContext(context), trackEvent);
    }
    onClickToSeeDisclaimer(context) {
      const {
        trackEvent
      } = this.props;
      trackClickToSeeDisclaimer(this.enrichContext(context), trackEvent);
    }
    onProviderClick(providerName, context) {
      const {
        trackEvent
      } = this.props;
      trackProviderClicked(providerName, this.enrichContext(context), trackEvent);
    }
    onAmountChangeFinish(amount, context) {
      const {
        trackEvent
      } = this.props;
      const {
        lastAmountFetched
      } = this.state;
      this.fetchQuotesForAmount(amount).then(response => {
        this.setState({
          lastAmountFetched: amount
        });
        const updatedContext = {
          ...context,
          quotes: response.quotes
        };
        trackAmountChange(amount, lastAmountFetched, this.enrichContext(updatedContext), trackEvent);
      });
    }
    updateAmountAndShowLoader(inputValue) {
      const {
        onComparisonParamsChange
      } = this.props;
      const {
        sourceCurrency,
        targetCurrency
      } = this.state;
      this.setState({
        loadingQuotes: true,
        sendAmount: inputValue
      });
      executeAsync(() => {
        onComparisonParamsChange({
          sourceCurrency,
          targetCurrency,
          sendAmount: inputValue
        });
      });
    }
    fetchQuotesForAmount(amount) {
      const {
        sourceCurrency,
        targetCurrency,
        sourceCountry,
        providerCountry,
        midMarketRate
      } = this.state;
      return this.fetchAndProcessQuotes(sourceCurrency, targetCurrency, amount, sourceCountry, providerCountry, midMarketRate).then(response => {
        this.setState({
          lastAmountFetched: amount
        });
        return response;
      });
    }
    fetchAndProcessAllResources(sourceCurrency, targetCurrency, sendAmount, sourceCountry, providerCountry, midMarketRate, wiseFee) {
      const ratesPromise = this.fetchAndProcessRates(sourceCurrency, targetCurrency);
      const quotesPromise = this.fetchAndProcessQuotes(sourceCurrency, targetCurrency, sendAmount, sourceCountry, providerCountry, midMarketRate, wiseFee);
      const referenceQuotesPromise = this.fetchAndProcessReferenceQuotes(sourceCurrency, targetCurrency, sourceCountry);
      return Promise.all([ratesPromise, quotesPromise, referenceQuotesPromise]).then(response => ({
        route: response[0],
        quotes: response[1],
        referenceQuotes: response[2]
      }));
    }
    fetchAndProcessRates(sourceCurrency, targetCurrency) {
      return this.loadRates(sourceCurrency, targetCurrency).then(route => {
        this.setState({
          route,
          loadingRates: false
        });
        return route;
      }).catch(() => {
        this.setState({
          loadingRates: false
        });
        return null;
      });
    }
    fetchAndProcessQuotes(sourceCurrency, targetCurrency, sendAmount, sourceCountry, providerCountry, midMarketRate, wiseFee) {
      return this.loadQuotes(sourceCurrency, targetCurrency, sendAmount, sourceCountry, providerCountry, midMarketRate, wiseFee).then(quotes => this.filterByWhitelistedProviders(quotes)).then(filteredQuotes => this.validateQuotes(filteredQuotes)).then(validatedQuotes => {
        this.setState({
          ...validatedQuotes,
          loadingQuotes: false
        });
        return validatedQuotes.quotes;
      });
    }
    fetchAndProcessReferenceQuotes(sourceCurrency, targetCurrency, sourceCountry) {
      return this.loadReferenceQuotes(sourceCurrency, targetCurrency, sourceCountry).then(referenceQuotes => {
        this.setState({
          ...referenceQuotes,
          loadingReferenceQuotes: false
        });
        return referenceQuotes.referenceQuotes;
      });
    }
    isOriginalRoute(currentSourceCurrency, currentTargetCurrency) {
      return this.props.sourceCurrency === currentSourceCurrency && this.props.targetCurrency === currentTargetCurrency;
    }
    validateQuotes(quotes) {
      if (quotes && !quotes.length) {
        return {
          quotes,
          ...this.determineErrorType()
        };
      }
      return {
        quotes,
        errorType: null,
        error: false
      };
    }
    loadRates(sourceCurrency, targetCurrency) {
      this.setState({
        loadingRates: true
      });
      return fetchRate(sourceCurrency, targetCurrency).then(result => result.route).catch(error => {
        this.setState({
          loadingRates: false
        });
        // eslint-disable-next-line no-console
        console.error('Failed to fetch mid-market rate', error);
        throw error;
      });
    }
    loadQuotes(sourceCurrency, targetCurrency, sendAmount, sourceCountry, providerCountry, midMarketRate, wiseFee) {
      this.setState({
        loadingQuotes: true
      });
      return fetchQuotes(sourceCurrency, targetCurrency, sendAmount, midMarketRate, wiseFee, {
        sourceCountry,
        providerCountry
      }).then(result => result.quotes);
    }
    loadReferenceQuotes(sourceCurrency, targetCurrency, sourceCountry) {
      this.setState({
        loadingReferenceQuotes: true
      });
      return fetchReferenceQuotes(sourceCurrency, targetCurrency, {
        sourceCountry
      }).then(result => ({
        referenceQuotes: result.referenceQuotes,
        maxAmountCollected: result.maxAmountCollected
      }));
    }
    filterByWhitelistedProviders(quotes) {
      const {
        whitelistedProviders
      } = this.state;
      if (!whitelistedProviders) {
        return quotes;
      }
      return quotes.filter(p => whitelistedProviders.includes(p.alias));
    }

    // TODO Could use a refactor
    // eslint-disable-next-line react/destructuring-assignment
    determineErrorType(maxAmountCollected = this.state.maxAmountCollected) {
      const errorType = this.isLimitReached(maxAmountCollected) ? 'UNSUPPORTED_AMOUNT' : 'UNSUPPORTED_ROUTE';
      return {
        errorType,
        error: true
      };
    }
    isLimitReached(maxAmountCollected) {
      const {
        sendAmount
      } = this.state;
      return sendAmount > maxAmountCollected && maxAmountCollected !== 0;
    }
    linkToTW(context) {
      const {
        sendAmount,
        sourceCurrency,
        targetCurrency
      } = extractRequiredProps(context);
      const {
        affiliateLink
      } = this.props;
      if (affiliateLink && isValidAffiliate(affiliateLink)) {
        return affiliateLink;
      }
      const redirectUrl = '/transferFlow#/enterpayment?' + `amount=${sendAmount}&` + `sourceCurrency=${sourceCurrency}&` + `targetCurrency=${targetCurrency}`;

      // TODO: Wise migration
      return createUrl('/register?interested_in=send_money&context=comparison&cta=comparison_send_money' + `&redirect_url=${encodeURIComponent(redirectUrl)}#/?redirectUrl=${encodeURIComponent(redirectUrl)}`);
    }
    removeAllFilters() {
      const updatedFilters = {
        sourceCountry: null,
        providerCountry: null,
        whitelistedProviders: null
      };
      this.setState(updatedFilters);
      return updatedFilters;
    }
    enrichContext(context) {
      const {
        sendAmount,
        sourceCurrency,
        targetCurrency,
        sourceCountry,
        providerCountry,
        whitelistedProviders
      } = this.state;
      return {
        amount: sendAmount,
        source: sourceCurrency,
        target: targetCurrency,
        sourceCountry,
        providerCountry,
        whitelistedProviders,
        componentType: this.componentType,
        ...context
      };
    }
    render() {
      // TODO We should probably conditionally render the below once the data is actually available
      const {
        maxVisibleProviders,
        expandDisclaimer,
        excludePartners,
        deliveryEstimationEnabled,
        showSendMoneyButton,
        providerLogoRedirectEnabled,
        trackEvent,
        showMoreProvidersOption
      } = this.props;
      const {
        sendAmount,
        sourceCountry,
        providerCountry,
        quotes,
        referenceQuotes,
        error,
        errorType,
        sourceCurrency,
        targetCurrency,
        route,
        maxAmountCollected,
        loadingReferenceQuotes,
        loadingQuotes,
        loadingRates
      } = this.state;
      return /*#__PURE__*/React.createElement(WrappedComponent, {
        maxVisibleProviders: parseFloat(maxVisibleProviders),
        expandDisclaimer: parseBool(expandDisclaimer),
        amount: parseFloat(sendAmount),
        sourceCountry: sourceCountry,
        providerCountry: providerCountry,
        quotes: quotes,
        referenceQuotes: referenceQuotes,
        error: error,
        errorType: errorType,
        sourceCurrency: sourceCurrency,
        targetCurrency: targetCurrency,
        midMarketRate: route,
        excludePartners: excludePartners,
        maxAmountCollected: maxAmountCollected,
        loadingReferenceQuotes: loadingReferenceQuotes,
        loadingQuotes: loadingQuotes,
        loadingRates: loadingRates,
        onAmountChange: this.updateAmountAndShowLoader,
        onAmountChangeFinish: this.onAmountChangeFinish,
        onRouteChange: this.onRouteChange,
        onError: this.onError,
        onCallToActionClick: this.onCallToActionClick,
        onClickToSeeAnAvailableComparison: this.onClickToSeeAnAvailableComparison,
        onClickToSeePricingDisclaimer: this.onClickToSeePricingDisclaimer,
        onClickingDeliveryEstimationTooltip: this.onClickingDeliveryEstimationTooltip,
        onClickToSeeDisclaimer: this.onClickToSeeDisclaimer,
        deliveryEstimationEnabled: deliveryEstimationEnabled,
        showSendMoneyButton: showSendMoneyButton,
        providerLogoRedirectEnabled: providerLogoRedirectEnabled,
        onProviderClick: this.onProviderClick,
        trackEvent: trackEvent,
        showMoreProvidersOption: showMoreProvidersOption
      });
    }
  }

  /* eslint-disable react/no-unused-prop-types */
  RequestComparisonResources.propTypes = {
    // We parse this from a string today, and don't expect a number - review
    amount: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
    sendAmount: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
    source: PropTypes.string,
    target: PropTypes.string,
    sourceCurrency: PropTypes.string.isRequired,
    targetCurrency: PropTypes.string.isRequired,
    wiseFee: PropTypes.number,
    sourceCountry: PropTypes.string,
    providerCountry: PropTypes.string,
    providers: PropTypes.arrayOf(PropTypes.string),
    maxVisibleProviders: PropTypes.oneOfType([
    // we pass string not number  review
    PropTypes.string, PropTypes.number]),
    expandDisclaimer: PropTypes.oneOfType([
    // we pass string not bool, review
    PropTypes.string, PropTypes.bool]),
    componentType: PropTypes.string,
    // TODO this needs to be renamed, its not really a route
    route: PropTypes.shape({
      rate: PropTypes.number.isRequired,
      source: PropTypes.string.isRequired,
      target: PropTypes.string.isRequired,
      time: PropTypes.string.isRequired
    }).isRequired,
    quotes: PropTypes.arrayOf(PropTypes.shape({
      id: PropTypes.number.isRequired,
      name: PropTypes.string.isRequired,
      alias: PropTypes.string.isRequired,
      logo: PropTypes.string.isRequired,
      rate: PropTypes.number.isRequired,
      fees: PropTypes.number.isRequired,
      receivedAmount: PropTypes.number.isRequired,
      dateCollected: PropTypes.string.isRequired
    })),
    referenceQuotes: PropTypes.arrayOf(PropTypes.shape({
      alias: PropTypes.string.isRequired,
      country: PropTypes.string,
      logo: PropTypes.string.isRequired,
      name: PropTypes.string.isRequired,
      // This is a nasty shaped thing today, its dynamic keys of routes mapped straight from the API response
      routes: PropTypes.objectOf(PropTypes.object)
    })),
    excludePartners: PropTypes.bool,
    affiliateLink: PropTypes.string,
    trackEvent: PropTypes.func,
    trackLeavePageEvent: PropTypes.func,
    onComparisonParamsChange: PropTypes.func,
    deliveryEstimationEnabled: PropTypes.bool,
    showSendMoneyButton: PropTypes.bool,
    providerLogoRedirectEnabled: PropTypes.bool,
    showMoreProvidersOption: PropTypes.bool
  };
  /* eslint-enable react/no-unused-prop-types */

  RequestComparisonResources.defaultProps = {
    maxVisibleProviders: 5,
    expandDisclaimer: false,
    quotes: [],
    referenceQuotes: [],
    providers: null,
    excludePartners: false,
    affiliateLink: null,
    trackEvent: () => {},
    trackLeavePageEvent: (event, attributes, callback) => callback(),
    onComparisonParamsChange: () => {},
    deliveryEstimationEnabled: false,
    showSendMoneyButton: true,
    sourceCountry: null,
    providerCountry: null,
    componentType: '',
    source: null,
    target: null,
    providerLogoRedirectEnabled: false,
    showMoreProvidersOption: true
  };
  return RequestComparisonResources;
}

function calculateDifferenceWithTwoDecimalPlaces(referenceAmount, compareAmount) {
  const difference = compareAmount - referenceAmount;
  return parseFloat(Math.round(difference * 100) / 100);
}

// TODO: Reasoning for this functionality
// We are showing the pricing disclaimer when the reduced quote has a specified target country. This is an issue as
// a currency which has no currency union e.g. BWP may show a pricing disclaimer as target country is specified even
// though BWP is only supported by one country.
//
// To combat this, we introduce the concept of currency union. So not only if the target country is specified, it must
// be a currency union of the pricing disclaimer to be shown.
//
// Cons:
// This will not work with global currencies but is not a currency union. i.e. global USD is a concept. So you can send
// USD to a country that doesn't official support it. USD is a currency union so it would matter in this case as a
// pricing disclaimer is valid. But this might be the case in the future with other non union currencies.
//
// Other idea:
// You can take a look at the quotes received and deduce whether or not to show the pricing disclaimer or not. For
// instance, if you have two or more quotes for a given route and provider, you know they could have different prices
// and so show the disclaimer.
//
// Cons:
// You need to have all the available routes and quotes for every provider. It might be the case that we only scrape
// one country for EUR, but the provider supports a lot more. But because one only scrape on country, the pricing
// disclaimer would not turn up.

const currencyUnions = [{
  code: 'XOF'
}, {
  code: 'XAF'
}, {
  code: 'XPF'
}, {
  code: 'XCD'
}, {
  code: 'EUR'
}, {
  code: 'HKD'
}, {
  code: 'SGD'
}, {
  code: 'AUD'
}, {
  code: 'GBP'
}, {
  code: 'INR'
}, {
  code: 'NZD'
}, {
  code: 'ILS'
}, {
  code: 'RUB'
}, {
  code: 'ZAR'
}, {
  code: 'CHF'
}, {
  code: 'USD'
}];
function getAllCurrencyUnions() {
  return currencyUnions;
}
function isCurrencyUnion(code) {
  return getAllCurrencyUnions().find(c => code === c.code);
}

var css_248z = "\n/*# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiIsImZpbGUiOiJQcmljaW5nRGlzY2xhaW1lci5sZXNzIn0= */";
styleInject(css_248z);

const createClassNames$1 = classNames => classNames.map(className => `${styles[className]}`).join(' ');
const title = ({
  params
}) => /*#__PURE__*/React.createElement("span", null, /*#__PURE__*/React.createElement("span", {
  className: createClassNames$1(['popover-title__route'])
}, params.sourceCurrency, " ", /*#__PURE__*/React.createElement(ArrowRight, null), " ", params.targetCurrency), /*#__PURE__*/React.createElement(FormattedMessage, {
  id: "in"
}), /*#__PURE__*/React.createElement("img", {
  className: createClassNames$1(['flag-icon']),
  src: `https://wise.com/web-art/assets/flags/${params.targetCountry.toLowerCase()}.svg`,
  onError: `this.onerror=null;this.src=https://wise.com/web-art/assets/flags/${params.targetCurrency?.toLowerCase()}.svg`,
  alt: `${params.targetCountry.toLowerCase()}`
}));
const PricingDisclaimer = ({
  messageKey,
  params,
  onClickToSeePricingDisclaimer
}) =>
/*#__PURE__*/
// eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/interactive-supports-focus
React.createElement("span", {
  className: styles['pricing-disclaimer'],
  role: "button",
  onClick: () => onClickToSeePricingDisclaimer()
}, /*#__PURE__*/React.createElement("span", {
  className: styles['pricing-disclaimer-popover']
}, /*#__PURE__*/React.createElement(Popover, {
  classNames: styles,
  title: title({
    params
  }),
  content: /*#__PURE__*/React.createElement(FormattedMessage, {
    values: params,
    id: messageKey
  }),
  preferredPlacement: Position.LEFT_TOP
}, /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement(Warning, {
  className: styles['tw-alert-icon'],
  size: 16,
  "data-testid": "alert-icon"
})))));
title.propTypes = {
  params: PropTypes.shape({
    sourceCurrency: PropTypes.string.isRequired,
    targetCurrency: PropTypes.string.isRequired,
    targetCountry: PropTypes.string.isRequired
  }).isRequired
};
PricingDisclaimer.propTypes = {
  params: PropTypes.shape({
    sourceCurrency: PropTypes.string.isRequired,
    targetCurrency: PropTypes.string.isRequired,
    targetCountry: PropTypes.string.isRequired
  }).isRequired,
  messageKey: PropTypes.string.isRequired,
  onClickToSeePricingDisclaimer: PropTypes.func
};
PricingDisclaimer.defaultProps = {
  onClickToSeePricingDisclaimer: () => {}
};

const TranslateInCountry = ({
  code
}) => /*#__PURE__*/React.createElement(FormattedMessage, {
  id: `in-${code}`
});
TranslateInCountry.propTypes = {
  code: PropTypes.string.isRequired
};

function renderPricingDisclaimer(targetCountry, sourceCurrency, targetCurrency, alias, onClickToSeePricingDisclaimer) {
  return /*#__PURE__*/React.createElement(React.Fragment, null, targetCountry && isCurrencyUnion(targetCurrency) && /*#__PURE__*/React.createElement(PricingDisclaimer, {
    messageKey: "target-country-pricing-disclaimer",
    params: {
      inCountry: /*#__PURE__*/React.createElement(TranslateInCountry, {
        code: targetCountry
      }),
      sourceCurrency,
      targetCurrency,
      targetCountry
    },
    onClickToSeePricingDisclaimer: () => onClickToSeePricingDisclaimer(targetCountry, alias)
  }));
}

// TODO Extract as component
function renderCallToAction(createClassNames, onCallToActionClick) {
  return /*#__PURE__*/React.createElement("div", {
    className: createClassNames(['btn-container', 'send-with-tw-cta_provider']),
    "data-testid": "send-with-tw-cta"
  }, /*#__PURE__*/React.createElement(Button, {
    size: Size.SMALL,
    type: ControlType.POSITIVE,
    priority: Priority.PRIMARY,
    "data-tracking-id": "comparison-cta",
    onClick: onCallToActionClick,
    className: createClassNames(['send-with-tw-cta_provider'])
  }, /*#__PURE__*/React.createElement(FormattedMessage, {
    id: "send-money"
  })));
}
const addDeliveryEstimation$1 = (deliveryEstimation, isPartner, styles, alias, onClickingDeliveryEstimationTooltip, formatMessage) => /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("td", {
  "data-label": formatMessage({
    id: 'should-arrive'
  }),
  className: styles['table-plain__cell']
}, /*#__PURE__*/React.createElement(DeliveryEstimation, {
  styles: styles,
  deliveryEstimation: deliveryEstimation,
  isPartner: isPartner,
  alias: alias,
  onClickingDeliveryEstimationTooltip: onClickingDeliveryEstimationTooltip
})));
const Provider = /*#__PURE__*/React.forwardRef(({
  styles,
  createClassNames,
  alias,
  name,
  logo,
  logoAltText,
  source: sourceCurrency,
  target: targetCurrency,
  targetCountry,
  providerRate,
  midMarketRate,
  showDeliveryEstimation,
  deliveryEstimation,
  amount,
  fees,
  differenceToCheapest,
  isPartner,
  onCallToActionClick,
  onClickToSeePricingDisclaimer,
  onClickingDeliveryEstimationTooltip,
  showSendMoneyButton,
  providerLogoRedirectEnabled,
  onProviderClick,
  isCentre,
  isScreenModeDark
}, ref) => {
  const {
    formatMessage,
    locale
  } = useIntl();
  const MID_MARKET_URL = createUrl(generateUrl(locale, 'mid-market-rate/', AvailablePages.MID_MARKET_RATE));
  const WISE_FEES_URL = createUrl('/gb/pricing/send-money');
  const getProviderLogoUrl = () => {
    if (providerLogoRedirectEnabled && alias !== WISE_ALIAS) {
      const path = 'compare/' + alias + '-exchange-rate';
      return createUrl(generateUrl(locale, path, AvailablePages.PROVIDER_PAGE));
    }
  };
  return /*#__PURE__*/React.createElement("tr", {
    className: `${styles['table-plain__row']}
          ${isScreenModeDark ? styles[isScreenModeDark ? 'table-plain__row--dark' : ''] : ''}
        `,
    "data-testid": isCentre ? 'centre-provider-row' : 'provider-row',
    ref: ref
  }, /*#__PURE__*/React.createElement("td", {
    className: styles['table-plain__cell']
  }, /*#__PURE__*/React.createElement(ProviderLogo, {
    logo: logo,
    alias: alias,
    altText: logoAltText,
    isPartner: isPartner,
    providerLogoRedirectUrl: getProviderLogoUrl(),
    onProviderClick: () => onProviderClick(name)
  })), showDeliveryEstimation ? addDeliveryEstimation$1(deliveryEstimation, isPartner, styles, alias, onClickingDeliveryEstimationTooltip, formatMessage) : '', /*#__PURE__*/React.createElement("td", {
    className: styles['table-plain__cell'],
    "data-label": formatMessage({
      id: 'exchange-rate'
    })
  }, /*#__PURE__*/React.createElement(ExchangeRateIndicator, {
    styles: styles,
    referenceRate: midMarketRate,
    rate: providerRate,
    label: isConsideredMidmarketRate(providerRate, midMarketRate) ? /*#__PURE__*/React.createElement(Label, {
      styles: styles,
      message: "mid-market-rate",
      link: MID_MARKET_URL,
      target: "_blank"
    }) : null,
    sourceCurrency: sourceCurrency,
    targetCurrency: targetCurrency
  })), /*#__PURE__*/React.createElement("td", {
    className: styles['table-plain__cell'],
    "data-label": formatMessage({
      id: 'transfer-fee'
    })
  }, /*#__PURE__*/React.createElement(TransferFee, {
    styles: styles,
    currency: sourceCurrency,
    fee: fees,
    alias: alias,
    label: isWiseAlias(alias) || isPartner ?
    /*#__PURE__*/
    // TODO Condition could actually be where any rate >= than midmarket
    React.createElement(Label, {
      styles: styles,
      message: "transparent-fee",
      link: WISE_FEES_URL,
      target: "_blank"
    }) : null
  })), /*#__PURE__*/React.createElement("td", {
    className: createClassNames(['table-plain__cell', 'featured--last-cell']),
    "data-label": formatMessage({
      id: 'you-receive'
    })
  }, /*#__PURE__*/React.createElement(ReceiveAmount, {
    styles: styles,
    amount: amount,
    currency: targetCurrency,
    differenceToCheapest: parseFloat(differenceToCheapest),
    optionalInlineElement: renderPricingDisclaimer(targetCountry, sourceCurrency, targetCurrency, alias, onClickToSeePricingDisclaimer)
  }), showSendMoneyButton && isWiseAlias(alias) && renderCallToAction(createClassNames, onCallToActionClick)));
});
Provider.propTypes = {
  styles: PropTypes.shape({
    'pull-xs-left': PropTypes.string,
    'text-xs-right': PropTypes.string,
    'table-plain__row': PropTypes.string,
    'table-plain__row--dark': PropTypes.string,
    'table-plain__cell': PropTypes.string
  }),
  createClassNames: PropTypes.func.isRequired,
  alias: PropTypes.string.isRequired,
  logo: PropTypes.string.isRequired,
  logoAltText: PropTypes.string.isRequired,
  name: PropTypes.string.isRequired,
  source: PropTypes.string.isRequired,
  target: PropTypes.string.isRequired,
  targetCountry: PropTypes.string,
  providerRate: PropTypes.number.isRequired,
  midMarketRate: PropTypes.number.isRequired,
  showDeliveryEstimation: PropTypes.bool,
  deliveryEstimation: PropTypes.shape({
    // eslint-disable-next-line react/forbid-prop-types
    duration: PropTypes.object,
    providerGivesEstimate: PropTypes.bool
  }),
  amount: PropTypes.number.isRequired,
  fees: PropTypes.number.isRequired,
  differenceToCheapest: PropTypes.number.isRequired,
  isPartner: PropTypes.bool.isRequired,
  onCallToActionClick: PropTypes.func,
  onClickToSeePricingDisclaimer: PropTypes.func,
  onClickingDeliveryEstimationTooltip: PropTypes.func,
  showSendMoneyButton: PropTypes.bool,
  providerLogoRedirectEnabled: PropTypes.bool,
  onProviderClick: PropTypes.func,
  isCentre: PropTypes.bool,
  isScreenModeDark: PropTypes.bool
};
Provider.defaultProps = {
  styles: {},
  targetCountry: undefined,
  onCallToActionClick: () => {},
  onClickToSeePricingDisclaimer: undefined,
  showDeliveryEstimation: false,
  deliveryEstimation: {
    duration: null,
    providerGivesEstimate: true
  },
  onClickingDeliveryEstimationTooltip: () => {},
  showSendMoneyButton: true,
  providerLogoRedirectEnabled: false,
  providerLogoRedirectUrl: null,
  onProviderClick: () => {},
  isCentre: false,
  isScreenModeDark: false
};
var Provider$1 = injectTheme(Provider);

/* eslint-disable sonarjs/no-duplicate-string */
function createClassNames(classNames) {
  return classNames.map(className => `${styles[className] || className}`).join(' ');
}
function applyLimitToQuotes(quotes, limitQuotes, maxVisibleProviders) {
  if (limitQuotes && quotes.length >= maxVisibleProviders) {
    return quotes.slice(0, maxVisibleProviders);
  }
  return quotes;
}
function addDeliveryEstimation(isScreenModeDark) {
  return (
    /*#__PURE__*/
    // eslint-disable-next-line sonarjs/no-duplicate-string
    React.createElement("th", {
      className: createClassNames(['table-plain__th', isScreenModeDark ? 'table-plain__th--dark' : ''])
    }, /*#__PURE__*/React.createElement(FormattedMessage, {
      id: "should-arrive"
    }))
  );
}
function calculateHighestReceivedAmount(quotes, excludePartners = false) {
  const sortedQuotes = sortQuotesByReceivedAmount(quotes, excludePartners);
  return sortedQuotes.length > 0 ? sortedQuotes[0].receivedAmount : 0;
}
function calculateCentreProviderIndex(quotes) {
  return quotes ? getTrackingTriggerIndex(quotes.length) : null;
}
class ComparisonTable extends Component {
  constructor(props) {
    super(props);
    autoBind(this);
    this.state = {
      limitQuotes: true,
      centreProviderViewed: false
    };
  }
  componentDidUpdate(previousProps, previousState, snapshot) {
    const {
      onError,
      error,
      errorType,
      sourceCurrency,
      targetCurrency,
      amount
    } = this.props;
    const context = {
      ...this.props,
      ...this.state
    };
    if (!previousProps.error && error) {
      onError(errorType, context);
    }
    if (previousProps.sourceCurrency !== sourceCurrency || previousProps.targetCurrency !== targetCurrency || previousProps.amount !== amount) {
      this.setState({
        centreProviderViewed: false
      });
    }
  }
  onCallToActionClick() {
    const {
      onCallToActionClick
    } = this.props;
    const context = {
      ...this.props,
      ...this.state
    };
    onCallToActionClick(context);
  }
  onClickToSeeAnAvailableComparison(maxAmountCollected) {
    const {
      onClickToSeeAnAvailableComparison
    } = this.props;
    const context = {
      ...this.props,
      ...this.state
    };
    onClickToSeeAnAvailableComparison(maxAmountCollected, context);
  }
  onClickToSeePricingDisclaimer(targetCountry, providerAlias) {
    const {
      onClickToSeePricingDisclaimer
    } = this.props;
    const context = {
      ...this.props,
      ...this.state
    };
    onClickToSeePricingDisclaimer(targetCountry, providerAlias, context);
  }
  onClickToSeeDisclaimer() {
    const {
      onClickToSeeDisclaimer
    } = this.props;
    const context = {
      ...this.props,
      ...this.state
    };
    onClickToSeeDisclaimer(context);
  }
  onProviderClick(providerName) {
    const {
      onProviderClick
    } = this.props;
    const context = {
      ...this.props,
      ...this.state
    };
    onProviderClick(providerName, context);
  }
  onClickingDeliveryEstimationTooltip() {
    const {
      onClickingDeliveryEstimationTooltip
    } = this.props;
    const context = {
      ...this.props,
      ...this.state
    };
    onClickingDeliveryEstimationTooltip(context);
  }
  toggleLimitQuotes() {
    this.setState(state => ({
      limitQuotes: !state.limitQuotes
    }));
  }
  onTableView = (inView, quotes) => {
    if (!inView) {
      return;
    }
    this.setState({
      centreProviderViewed: true
    });
    const {
      amount,
      sourceCurrency,
      targetCurrency,
      trackEvent
    } = this.props;
    const trackingContext = {
      amount,
      source: sourceCurrency,
      target: targetCurrency,
      quotes,
      componentType: Table.Educational
    };
    trackTableViewed(trackingContext, trackEvent);
  };
  render() {
    const {
      amount,
      midMarketRate: midMarketRateAndRoute,
      quotes,
      maxAmountCollected,
      sourceCurrency,
      targetCurrency,
      loadingQuotes,
      loadingRates,
      maxVisibleProviders,
      expandDisclaimer,
      error,
      errorType,
      referenceQuotes,
      loadingReferenceQuotes,
      excludePartners,
      deliveryEstimationEnabled,
      showSendMoneyButton,
      intl,
      providerLogoRedirectEnabled,
      isScreenModeDark,
      showMoreProvidersOption
    } = this.props;
    const currentLocale = intl.locale;
    const showDeliveryEstimation = deliveryEstimationEnabled && isDeliveryEstimationCollectedForAllProviders(quotes);

    // TODO Renaming here to avoid confusion on usage below. This needs a wider refactor further up the stack
    const midMarketRate = midMarketRateAndRoute ? midMarketRateAndRoute.rate : midMarketRateAndRoute;
    const {
      limitQuotes,
      centreProviderViewed
    } = this.state;
    const highestReceivedAmount = calculateHighestReceivedAmount(quotes, excludePartners);
    const filteredQuotes = filterQuotes(quotes, {
      excludePartners
    });
    const limitedQuotes = applyLimitToQuotes(filteredQuotes, limitQuotes, maxVisibleProviders);
    const centreProviderIndex = calculateCentreProviderIndex(limitedQuotes);
    const shouldShowFooter = showMoreProvidersOption || isWisePresentAndNotCheapest(quotes);
    const ProviderRow = /*#__PURE__*/React.forwardRef((props, reference) => {
      const {
        quote,
        isCentre
      } = props;
      return /*#__PURE__*/React.createElement(Provider$1, {
        alias: quote.alias,
        amount: quote.receivedAmount,
        createClassNames: createClassNames,
        differenceToCheapest: calculateDifferenceWithTwoDecimalPlaces(highestReceivedAmount, quote.receivedAmount),
        fees: quote.fees,
        highestReceivedAmount: quote.receivedAmount === highestReceivedAmount,
        key: quote.id,
        logo: quote.logos.normal.svgUrl,
        logoAltText: quote.logos.altText ? quote.logos.altText : quote.name,
        name: quote.name,
        providerRate: quote.rate,
        midMarketRate: midMarketRate,
        deliveryEstimation: quote.deliveryEstimation,
        showDeliveryEstimation: showDeliveryEstimation,
        source: sourceCurrency,
        styles: styles,
        target: targetCurrency,
        targetCountry: quote.targetCountry,
        isPartner: quote.partner,
        showSendMoneyButton: showSendMoneyButton,
        onCallToActionClick: this.onCallToActionClick,
        onClickToSeePricingDisclaimer: this.onClickToSeePricingDisclaimer,
        onClickingDeliveryEstimationTooltip: this.onClickingDeliveryEstimationTooltip,
        providerLogoRedirectEnabled: providerLogoRedirectEnabled,
        onProviderClick: this.onProviderClick,
        isCentre: isCentre,
        isScreenModeDark: isScreenModeDark,
        ref: reference
      });
    });
    return /*#__PURE__*/React.createElement("div", {
      className: styles['comparison-table']
    }, /*#__PURE__*/React.createElement(TapestryCard, {
      screenMode: isScreenModeDark ? 'dark' : 'light'
    }, /*#__PURE__*/React.createElement("div", {
      className: createClassNames(['card-table'])
    }, loadingQuotes || loadingRates ? /*#__PURE__*/React.createElement(WrappedLoader, null) : error ? /*#__PURE__*/React.createElement(ErrorTemplate, {
      createClassNames: createClassNames,
      style: styles,
      errorType: errorType,
      maxAmountCollected: maxAmountCollected,
      source: sourceCurrency,
      onClickToSeeAnAvailableComparison: this.onClickToSeeAnAvailableComparison
    }) : /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement("table", {
      className: createClassNames(['table-plain'])
    }, /*#__PURE__*/React.createElement("thead", {
      className: createClassNames(['thead'])
    }, /*#__PURE__*/React.createElement("tr", null, /*#__PURE__*/React.createElement("th", {
      className: createClassNames(['table-plain__th', isScreenModeDark ? 'table-plain__th--dark' : ''])
    }, /*#__PURE__*/React.createElement(FormattedMessage, {
      id: "provider"
    })), showDeliveryEstimation ? addDeliveryEstimation(isScreenModeDark) : '', /*#__PURE__*/React.createElement("th", {
      className: createClassNames(['table-plain__th', isScreenModeDark ? 'table-plain__th--dark' : ''])
    }, /*#__PURE__*/React.createElement(FormattedMessage, {
      id: "exchange-rate"
    }), /*#__PURE__*/React.createElement("span", {
      className: styles.headingInfo
    }, /*#__PURE__*/React.createElement(CurrencyRouteDescription, {
      sourceCurrency: sourceCurrency,
      targetCurrency: targetCurrency,
      exchangeRate: midMarketRate,
      styles: styles
    }))), /*#__PURE__*/React.createElement("th", {
      className: createClassNames(['table-plain__th', isScreenModeDark ? 'table-plain__th--dark' : ''])
    }, /*#__PURE__*/React.createElement(FormattedMessage, {
      id: "transfer-fee"
    })), /*#__PURE__*/React.createElement("th", {
      className: createClassNames(['table-plain__th', 'featured--th', isScreenModeDark ? 'table-plain__th--dark' : ''])
    }, /*#__PURE__*/React.createElement(FormattedMessage, {
      id: "you-receive"
    }), /*#__PURE__*/React.createElement("span", {
      className: createClassNames(['table-plain__th--small', isScreenModeDark ? 'table-plain__th--dark' : ''])
    }, /*#__PURE__*/React.createElement(FormattedMessage, {
      values: {
        amountWithCurrency: formatMoney(amount, sourceCurrency, currentLocale)
      },
      id: "sending-amount"
    }))))), /*#__PURE__*/React.createElement("tbody", {
      className: styles.tbody
    }, limitedQuotes.map((quote, index) => {
      const isCentreProvider = index === centreProviderIndex;
      return (
        /*#__PURE__*/
        // eslint-disable-next-line react/jsx-key
        React.createElement(ConditionalWrapper, {
          key: quote.alias,
          condition: !centreProviderViewed && isCentreProvider,
          wrapper: children => /*#__PURE__*/React.createElement(InView, {
            onChange: (inView, _) => this.onTableView(inView, limitedQuotes),
            threshold: 1,
            triggerOnce: true
          }, ({
            _,
            ref
          }) => /*#__PURE__*/React.cloneElement(children, {
            ref: ref,
            isCentre: true
          }))
        }, /*#__PURE__*/React.createElement(ProviderRow, {
          quote: quote
        }))
      );
    })), (quotes.length > maxVisibleProviders && !error || isWisePresentAndNotCheapest(quotes)) && /*#__PURE__*/React.createElement("tfoot", {
      className: `${styles.tfoot} ${isScreenModeDark ? styles['tfoot--dark'] : ''}`
    }, shouldShowFooter && /*#__PURE__*/React.createElement("tr", null, /*#__PURE__*/React.createElement("td", {
      className: createClassNames(['alert', 'alert-info', isScreenModeDark ? 'alert--dark' : '']),
      role: "alert"
    }, isWisePresentAndNotCheapest(quotes) && /*#__PURE__*/React.createElement("span", {
      "data-testid": "competitor-is-cheaper"
    }, /*#__PURE__*/React.createElement(CompetitorIsCheaperMessage, {
      deliveryEstimationShown: showDeliveryEstimation
    })), showMoreProvidersOption && quotes.length > maxVisibleProviders && !error && /*#__PURE__*/React.createElement("div", {
      className: "text-xs-center"
    }, /*#__PURE__*/React.createElement(ShowMoreProviders, {
      isExpanded: !limitQuotes,
      onToggle: this.toggleLimitQuotes
    })))))))))), /*#__PURE__*/React.createElement(Disclaimer, {
      referenceQuotes: referenceQuotes,
      loading: loadingReferenceQuotes,
      createClassNames: createClassNames,
      expandDisclaimer: expandDisclaimer,
      style: styles,
      onClickToSeeDisclaimer: this.onClickToSeeDisclaimer
    }));
  }
}

// TODO Disabling linting for now as the passed props themselves need a refactor
/* eslint-disable react/require-default-props */
ComparisonTable.propTypes = {
  amount: PropTypes.number.isRequired,
  sourceCurrency: PropTypes.string.isRequired,
  targetCurrency: PropTypes.string.isRequired,
  // eslint-disable-next-line react/require-default-props
  // TODO This is really confusingly named, refactor
  midMarketRate: PropTypes.shape({
    rate: PropTypes.number.isRequired,
    source: PropTypes.string.isRequired,
    target: PropTypes.string.isRequired,
    time: PropTypes.string.isRequired
  }),
  // Probably should be required, but as could be async today w/ WithComparisonResources, its optional

  quotes: PropTypes.arrayOf(PropTypes.shape({
    id: PropTypes.number.isRequired,
    name: PropTypes.string.isRequired,
    alias: PropTypes.string.isRequired,
    logos: PropTypes.shape({
      normal: PropTypes.shape({
        svgUrl: PropTypes.string,
        pngUrl: PropTypes.string
      }),
      altText: PropTypes.string.isRequired
    }),
    rate: PropTypes.number.isRequired,
    fees: PropTypes.number.isRequired,
    receivedAmount: PropTypes.number.isRequired,
    dateCollected: PropTypes.string.isRequired,
    deliveryEstimation: PropTypes.shape({
      duration: PropTypes.shape({
        min: PropTypes.string,
        max: PropTypes.string
      }),
      providerGivesEstimate: PropTypes.bool
    })
  })),
  // Probably should be required, but as could be async today w/ WithComparisonResources, its optional

  referenceQuotes: PropTypes.arrayOf(PropTypes.shape({
    alias: PropTypes.string.isRequired,
    country: PropTypes.string,
    logo: PropTypes.string.isRequired,
    name: PropTypes.string.isRequired,
    // This is a nasty shaped thing today, its dynamic keys of routes mapped straight from the API response
    routes: PropTypes.objectOf(PropTypes.object)
  })),
  // Probably should be required, but as could be async today w/ WithComparisonResources, its optional

  // Probably should be required, but as is async today and may use WithComparisonResources, its optional
  maxAmountCollected: PropTypes.number,
  loadingRates: PropTypes.bool.isRequired,
  loadingQuotes: PropTypes.bool.isRequired,
  loadingReferenceQuotes: PropTypes.bool.isRequired,
  maxVisibleProviders: PropTypes.number,
  expandDisclaimer: PropTypes.bool,
  excludePartners: PropTypes.bool,
  error: PropTypes.bool,
  errorType: PropTypes.oneOf(['UNSUPPORTED_AMOUNT', 'UNSUPPORTED_ROUTE', 'EXCEPTION']),
  onError: PropTypes.func,
  showSendMoneyButton: PropTypes.bool,
  onCallToActionClick: PropTypes.func,
  onClickToSeeAnAvailableComparison: PropTypes.func,
  onClickToSeePricingDisclaimer: PropTypes.func,
  onClickToSeeDisclaimer: PropTypes.func,
  onClickingDeliveryEstimationTooltip: PropTypes.func,
  deliveryEstimationEnabled: PropTypes.bool,
  providerLogoRedirectEnabled: PropTypes.bool,
  onProviderClick: PropTypes.func,
  trackEvent: PropTypes.func,
  isScreenModeDark: PropTypes.bool,
  showMoreProvidersOption: PropTypes.bool
};
ComparisonTable.defaultProps = {
  deliveryEstimationEnabled: false,
  excludePartners: false,
  showSendMoneyButton: true,
  providerLogoRedirectEnabled: false,
  onClickToSeeDisclaimer: () => {},
  onProviderClick: () => {},
  trackEvent: () => {},
  showMoreProvidersOption: true
};

// eslint-disable-next-line fp/no-mutation
ComparisonTable.componentType = Table.Educational;
const WrappedLoader = () => /*#__PURE__*/React.createElement("div", {
  className: createClassNames(['text-xs-center', 'loader', 'm-b-3', 'p-t-5', 'p-b-5'])
}, /*#__PURE__*/React.createElement(Loader, {
  classNames: styles
}));
const CompetitorIsCheaperMessage = ({
  deliveryEstimationShown
}) => /*#__PURE__*/React.createElement(FormattedMessage, {
  id: deliveryEstimationShown ? 'not-cheapest-with-speed' : 'not-cheapest-without-speed'
});
CompetitorIsCheaperMessage.propTypes = {
  deliveryEstimationShown: PropTypes.bool
};
CompetitorIsCheaperMessage.defaultProps = {
  // Based on the copy, this is the safer default as it makes less excuses
  deliveryEstimationShown: true
};
var ComparisonTable$1 = injectTheme(injectIntl(ComparisonTable));

const ComparisonTableContainer = withComparisonResources(ComparisonTable$1);

export { ComparisonTableContainer as C, ComparisonTable$1 as a, withComparisonResources as w };
//# sourceMappingURL=index-f727dceb.js.map
