import { a as ComparisonTable, w as withComparisonResources } from '../index-861c1077.js';
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import autoBind from 'react-autobind';
import { i as isWiseQuote } from '../quoteFilters-9ddc9e2f.js';
import { s as styles } from '../ReceiveAmount-cf275e96.js';
import { T as Table } from '../tracking-7717c145.js';
import { MoneyInput, Loader, Size } from '@transferwise/components';
import { FormattedMessage, injectIntl, useIntl } from 'react-intl';
import { s as styleInject } from '../style-inject.es-1f59c1d0.js';
import { getRateInAllFormats } from '@transferwise/formatting';
import { i as injectTheme, t as timeAgoFrom } from '../ErrorTemplate-39049770.js';
import { Switch } from '@transferwise/icons';
import { C as CurrencySelector } from '../CurrencySelector-18c13b52.js';
import '../clients.js';
import '../encodeQueryParams-96e87b36.js';
import '../fetchQuotes-31ac98ed.js';
import '../transformQuotesResponse.js';
import '../extractQuote-aa1e3309.js';
import '../sortQuotesByDeliverySpeedEstimate-f8c8a1b8.js';
import 'date-fns';
import 'duration-fns';
import '../createUrl-71d09e7b.js';
import 'react-intersection-observer';
import '../TapestryCard-38ddeade.js';
import 'react/jsx-runtime';
import '@wise/components-theming';
import '../TransferFee-05335190.js';
import '../deliveryEstimationFormatter-39a5e91c.js';
import '../index-27c99b06.js';
import '../DeliveryEstimation-28e7c50f.js';
import '../aliasFilter-a7b9c811.js';
import '../provider-constants-b35398f2.js';
import '../ExchangeRateIndicator-7977c22d.js';
import '../isConsideredMidmarketRate-4f12041d.js';
import '../Label-19e06f9d.js';
import '../ProviderLogo-d98111d0.js';
import '../generateUrl-3fc80d02.js';
import '../ArrowIcon-b7e50f4d.js';
import 'date-fns/formatDistanceToNow';
import 'date-fns/locale/be';
import 'date-fns/locale/bg';
import 'date-fns/locale/ca';
import 'date-fns/locale/cs';
import 'date-fns/locale/da';
import 'date-fns/locale/de';
import 'date-fns/locale/el';
import 'date-fns/locale/en-GB';
import 'date-fns/locale/eo';
import 'date-fns/locale/es';
import 'date-fns/locale/fi';
import 'date-fns/locale/fr';
import 'date-fns/locale/hr';
import 'date-fns/locale/hu';
import 'date-fns/locale/id';
import 'date-fns/locale/is';
import 'date-fns/locale/it';
import 'date-fns/locale/ja';
import 'date-fns/locale/ko';
import 'date-fns/locale/mk';
import 'date-fns/locale/nb';
import 'date-fns/locale/nl';
import 'date-fns/locale/pl';
import 'date-fns/locale/pt';
import 'date-fns/locale/ro';
import 'date-fns/locale/ru';
import 'date-fns/locale/sk';
import 'date-fns/locale/sl';
import 'date-fns/locale/sr';
import 'date-fns/locale/sv';
import 'date-fns/locale/th';
import 'date-fns/locale/tr';
import 'date-fns/locale/zh-CN';
import 'date-fns/locale/zh-HK';
import '@wise/art';
import '../currencies-1f1f52ab.js';

var debounce = ((wait, onFinish) => {
  let timeout;
  return (...args) => {
    const later = () => {
      timeout = null;
      onFinish(...args);
    };
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
  };
});

var css_248z = ".cc_comparison-money-input_3296223122 {\n  margin-bottom: 0;\n}\n\n/*# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInNyYy9jb21wYXJpc29uL2NvbXBvbmVudHMvYXRvbXMvQW1vdW50VG9TZW5kLm1vZHVsZS5sZXNzIiwiQW1vdW50VG9TZW5kLm1vZHVsZS5sZXNzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBO0VBQ0UsZ0JBQUE7QUNDRiIsImZpbGUiOiJBbW91bnRUb1NlbmQubW9kdWxlLmxlc3MifQ== */";
var s = {"comparison-money-input":"cc_comparison-money-input_3296223122","comparisonMoneyInput":"cc_comparison-money-input_3296223122"};
styleInject(css_248z);

class AmountToSend extends Component {
  constructor(props) {
    super(props);
    const {
      debounceAmountMillis,
      onChangeFinish
    } = props;
    this.debouncedOnChange = debounce(debounceAmountMillis, onChangeFinish);
  }
  onChangeEvent(inputValue, onChange) {
    onChange(inputValue);
    this.debouncedOnChange(inputValue);
  }
  render() {
    const {
      source,
      amount,
      onChange
    } = this.props;
    return /*#__PURE__*/React.createElement("div", {
      className: styles['size-1-of-1']
    }, /*#__PURE__*/React.createElement("div", {
      className: `${s['comparison-money-input']} ${styles['form-group']} ${styles['form-group-lg']}`
    }, /*#__PURE__*/React.createElement("label", {
      htmlFor: "money-input"
    }, /*#__PURE__*/React.createElement(FormattedMessage, {
      id: "send-exactly"
    })), /*#__PURE__*/React.createElement(MoneyInput, {
      amount: amount,
      onAmountChange: input => {
        input && this.onChangeEvent(input, onChange);
      },
      selectedCurrency: {
        currency: source
      },
      currencies: []
    })));
  }
}
AmountToSend.propTypes = {
  source: PropTypes.string.isRequired,
  amount: PropTypes.number.isRequired,
  onChange: PropTypes.func.isRequired,
  onChangeFinish: PropTypes.func.isRequired,
  debounceAmountMillis: PropTypes.number
};
AmountToSend.defaultProps = {
  debounceAmountMillis: 350
};

const INTERVAL = 60000;
const createClassNames$3 = classNames => classNames.map(className => `${styles[className]}`).join(' ');
class MidMarketDescription extends Component {
  constructor(props) {
    super(props);
    autoBind(this);
    this.state = {
      intervalId: null,
      formatLocale: null
    };
  }
  componentDidMount() {
    this.setState({
      intervalId: setInterval(this.timer, INTERVAL)
    });
  }
  componentWillUnmount() {
    const {
      intervalId
    } = this.state;
    clearInterval(intervalId);
  }
  timer() {
    this.forceUpdate();
  }
  render() {
    const {
      rateTime,
      intl,
      isScreenModeDark
    } = this.props;
    return /*#__PURE__*/React.createElement("small", {
      className: createClassNames$3(['small', 'text-xs-center', 'text-md-left', 'rate-description', isScreenModeDark ? 'rate-description--dark' : ''])
    }, /*#__PURE__*/React.createElement(FormattedMessage, {
      id: "rate-description"
    }), /*#__PURE__*/React.createElement("p", {
      className: styles['rate-description']
    }, rateTime ? /*#__PURE__*/React.createElement(FormattedMessage, {
      values: {
        minutes: timeAgoFrom(new Date(rateTime), intl.locale)
      },
      id: "rate-description-time"
    }) : /*#__PURE__*/React.createElement(FormattedMessage, {
      id: "rate-description-default-time"
    })));
  }
}
MidMarketDescription.propTypes = {
  rateTime: PropTypes.string
};
MidMarketDescription.defaultProps = {
  rateTime: undefined
};
var MidMarketDescription$1 = injectTheme(injectIntl(MidMarketDescription));

const createClassNames$2 = classNames => classNames.map(className => `${styles[className]}`).join(' ');
const MidMarketRate = ({
  source,
  target,
  midMarketRate,
  loading,
  lang
}) => {
  const {
    locale
  } = useIntl();
  return /*#__PURE__*/React.createElement("div", {
    className: createClassNames$2(['size-1-of-1', 'd-flex', 'flex-column', 'flex-center', 'flex-left-md', 'm-b-5', 'm-b-0-md']),
    "data-testid": "mid-market-rate"
  }, /*#__PURE__*/React.createElement("span", {
    className: createClassNames$2(['d-flex', 'align-items-center'])
  }, /*#__PURE__*/React.createElement("span", {
    className: createClassNames$2(['dot-success', 'animate-blink'])
  }), /*#__PURE__*/React.createElement("strong", {
    id: "route-rate",
    className: createClassNames$2(['h3', 'strong', 'text-md-left'])
  }, loading ? /*#__PURE__*/React.createElement(Loader, {
    size: Size.EXTRA_SMALL,
    classNames: styles,
    "data-testid": "loader"
  }) : getRateInAllFormats(midMarketRate.rate, source, target, {}, locale).formats.equation.output)), /*#__PURE__*/React.createElement(MidMarketDescription$1, {
    rateTime: midMarketRate.time
  }));
};
MidMarketRate.propTypes = {
  source: PropTypes.string.isRequired,
  target: PropTypes.string.isRequired,
  midMarketRate: PropTypes.shape({
    rate: PropTypes.string,
    time: PropTypes.string
  }).isRequired,
  loading: PropTypes.bool.isRequired
};

const createClassNames$1 = classNames => classNames.map(className => `${styles[className]}`).join(' ');

// FIXME This randomly chooses a currency that's not the same one as "selected"?, it should be deterministic ideally
function getTopCurrency(selectedCurrency) {
  const topCurrencies = ['GBP', 'EUR', 'USD', 'AUD'];
  const index = Math.floor(Math.random() * (topCurrencies.length - 1));
  return topCurrencies.filter(c => c !== selectedCurrency)[index];
}
function getRouteAttributesToUpdate(type, selectedCurrency, currencyToCheck) {
  const attributesToUpdate = {
    [type]: selectedCurrency
  };
  if (selectedCurrency === currencyToCheck) {
    const currencyRoute = {
      sourceCurrency: 'targetCurrency',
      targetCurrency: 'sourceCurrency'
    };
    attributesToUpdate[currencyRoute[type]] = getTopCurrency(selectedCurrency);
  }
  return attributesToUpdate;
}
class RouteSelector extends Component {
  constructor(props) {
    super(props);
    autoBind(this);
    this.state = {
      search: ''
    };
  }
  onSelectChange(type) {
    return selectedCurrencyProfile => {
      this.updateCurrenciesRoute(type, selectedCurrencyProfile.code);
    };
  }
  updateCurrenciesRoute(type, selectedCurrency) {
    const {
      sourceCurrency,
      targetCurrency,
      onRouteChange
    } = this.props;
    const route = {
      sourceCurrency: () => getRouteAttributesToUpdate(type, selectedCurrency, targetCurrency),
      targetCurrency: () => getRouteAttributesToUpdate(type, selectedCurrency, sourceCurrency)
    };
    const attributesToUpdate = route[type]();
    this.setState({
      search: ''
    });
    onRouteChange({
      ...attributesToUpdate
    });
    return attributesToUpdate;
  }
  handleSwapCurrencies() {
    const {
      onRouteChange,
      sourceCurrency,
      targetCurrency
    } = this.props;
    onRouteChange({
      sourceCurrency: targetCurrency,
      targetCurrency: sourceCurrency
    });
  }
  render() {
    const {
      sourceCurrency,
      targetCurrency
    } = this.props;
    const {
      search
    } = this.state;
    return /*#__PURE__*/React.createElement("div", {
      className: createClassNames$1(['m-b-5', 'd-flex', 'flex-column', 'flex-row-md', 'align-items-center'])
    }, /*#__PURE__*/React.createElement("div", {
      className: createClassNames$1(['size-1-of-1'])
    }, /*#__PURE__*/React.createElement(CurrencySelector, {
      type: "sourceCurrency",
      currencyCode: sourceCurrency,
      style: styles,
      search: search,
      onSelectChange: this.onSelectChange
    })), /*#__PURE__*/React.createElement("div", {
      className: createClassNames$1(['d-flex']),
      onClick: this.handleSwapCurrencies
    }, /*#__PURE__*/React.createElement(Switch, {
      size: 24,
      className: styles['tw-swap-icon']
    })), /*#__PURE__*/React.createElement("div", {
      className: createClassNames$1(['size-1-of-1'])
    }, /*#__PURE__*/React.createElement(CurrencySelector, {
      type: "targetCurrency",
      currencyCode: targetCurrency,
      style: styles,
      search: search,
      onSelectChange: this.onSelectChange
    })));
  }
}
RouteSelector.propTypes = {
  sourceCurrency: PropTypes.string.isRequired,
  targetCurrency: PropTypes.string.isRequired,
  onRouteChange: PropTypes.func.isRequired
};

/* eslint-disable jest/require-hook */
function createClassNames(classNames) {
  return classNames.map(className => `${styles[className]}`).join(' ');
}
class Comparison extends Component {
  static mapQuoteToMidMarketRate(twQuote) {
    return {
      rate: twQuote.rate,
      source: twQuote.source,
      target: twQuote.target,
      time: twQuote.dateCollected
    };
  }
  constructor(props) {
    super(props);
    autoBind(this);
    this.state = {
      amount: props.amount,
      // FIXME: Updates to these props aren't propagated to the state
      sourceCurrency: props.sourceCurrency,
      targetCurrency: props.targetCurrency
    };
  }
  onRouteChange(route) {
    const {
      onRouteChange
    } = this.props;
    const context = {
      ...this.props,
      ...this.state
    };
    onRouteChange(route, context);
    this.setState({
      ...route
    });
  }
  onAmountChangeFinish(amount) {
    const {
      onAmountChangeFinish
    } = this.props;
    const context = {
      ...this.props,
      ...this.state
    };
    onAmountChangeFinish(amount, context);
  }
  getMidMarketRate() {
    const {
      midMarketRate,
      quotes
    } = this.props;
    const twQuote = quotes.find(quote => isWiseQuote(quote));
    return twQuote ? Comparison.mapQuoteToMidMarketRate(twQuote) : midMarketRate;
  }
  render() {
    const {
      amount,
      quotes,
      referenceQuotes,
      maxAmountCollected,
      loadingRates,
      loadingQuotes,
      loadingReferenceQuotes,
      sourceCountry,
      providerCountry,
      providers,
      maxVisibleProviders,
      expandDisclaimer,
      excludePartners,
      error,
      errorType,
      onAmountChange,
      onAmountChangeFinish,
      onRouteChange,
      onError,
      onCallToActionClick,
      onClickToSeeAnAvailableComparison,
      onClickToSeePricingDisclaimer,
      onClickToSeeDisclaimer,
      onProviderClick,
      deliveryEstimationEnabled,
      onClickingDeliveryEstimationTooltip,
      showSendMoneyButton,
      providerLogoRedirectEnabled,
      trackEvent,
      showMoreProvidersOption
    } = this.props;
    const {
      sourceCurrency,
      targetCurrency
    } = this.state;
    return /*#__PURE__*/React.createElement("div", {
      className: styles['comparison-widget']
    }, /*#__PURE__*/React.createElement("div", {
      className: styles.card
    }, /*#__PURE__*/React.createElement("div", {
      className: styles['card-header']
    }, /*#__PURE__*/React.createElement(RouteSelector, {
      sourceCurrency: sourceCurrency,
      targetCurrency: targetCurrency,
      onRouteChange: this.onRouteChange
    }), /*#__PURE__*/React.createElement("div", {
      className: createClassNames(['d-flex', 'flex-column', 'flex-row-md', 'align-items-center'])
    }, /*#__PURE__*/React.createElement(MidMarketRate, {
      source: sourceCurrency,
      target: targetCurrency,
      midMarketRate: !loadingRates && !loadingQuotes && this.getMidMarketRate() // TODO maybe to state
      ,
      loading: loadingRates || loadingQuotes
    }), /*#__PURE__*/React.createElement("div", {
      className: styles['m-x-md-4']
    }), /*#__PURE__*/React.createElement(AmountToSend, {
      placeholderAmount: 1000,
      amount: amount,
      onChange: onAmountChange,
      onChangeFinish: this.onAmountChangeFinish,
      source: sourceCurrency
    })))), /*#__PURE__*/React.createElement(ComparisonTable, {
      amount: amount,
      sourceCurrency: sourceCurrency,
      targetCurrency: targetCurrency,
      midMarketRate: !loadingRates && !loadingQuotes && this.getMidMarketRate() // TODO maybe to state
      ,
      quotes: quotes,
      referenceQuotes: referenceQuotes,
      maxAmountCollected: maxAmountCollected,
      loadingRates: loadingRates,
      loadingQuotes: loadingQuotes,
      loadingReferenceQuotes: loadingReferenceQuotes,
      sourceCountry: sourceCountry,
      providerCountry: providerCountry,
      providers: providers,
      maxVisibleProviders: maxVisibleProviders,
      expandDisclaimer: expandDisclaimer,
      excludePartners: excludePartners,
      error: error,
      errorType: errorType,
      onAmountChange: onAmountChange,
      onAmountChangeFinish: onAmountChangeFinish,
      onRouteChange: onRouteChange,
      onError: onError,
      onCallToActionClick: onCallToActionClick,
      onClickToSeeAnAvailableComparison: onClickToSeeAnAvailableComparison,
      onClickToSeePricingDisclaimer: onClickToSeePricingDisclaimer,
      onClickToSeeDisclaimer: onClickToSeeDisclaimer,
      deliveryEstimationEnabled: deliveryEstimationEnabled,
      onClickingDeliveryEstimationTooltip: onClickingDeliveryEstimationTooltip,
      showSendMoneyButton: showSendMoneyButton,
      providerLogoRedirectEnabled: providerLogoRedirectEnabled,
      onProviderClick: onProviderClick,
      trackEvent: trackEvent,
      showMoreProvidersOption: showMoreProvidersOption
    }));
  }
}

// TODO Disabling linting for now as the passed props themselves need a refactor
/* eslint-disable react/require-default-props */
Comparison.propTypes = {
  amount: PropTypes.number.isRequired,
  sourceCurrency: PropTypes.string.isRequired,
  targetCurrency: PropTypes.string.isRequired,
  // eslint-disable-next-line react/require-default-props
  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,
    logo: PropTypes.string.isRequired,
    rate: PropTypes.number.isRequired,
    fees: PropTypes.number.isRequired,
    receivedAmount: PropTypes.number.isRequired,
    dateCollected: PropTypes.string.isRequired
  })),
  // 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,
  sourceCountry: PropTypes.string,
  providerCountry: PropTypes.string,
  providers: PropTypes.arrayOf(PropTypes.string),
  maxVisibleProviders: PropTypes.number,
  expandDisclaimer: PropTypes.bool,
  excludePartners: PropTypes.bool,
  error: PropTypes.bool,
  errorType: PropTypes.oneOf([null, 'UNSUPPORTED_AMOUNT', 'UNSUPPORTED_ROUTE', 'EXCEPTION']),
  onAmountChange: PropTypes.func,
  onAmountChangeFinish: PropTypes.func,
  onRouteChange: PropTypes.func,
  onError: PropTypes.func,
  onCallToActionClick: PropTypes.func,
  onClickToSeeAnAvailableComparison: PropTypes.func,
  onClickToSeePricingDisclaimer: PropTypes.func,
  onClickToSeeDisclaimer: PropTypes.func,
  onProviderClick: PropTypes.func,
  onClickingDeliveryEstimationTooltip: PropTypes.func,
  deliveryEstimationEnabled: PropTypes.bool,
  showSendMoneyButton: PropTypes.bool,
  providerLogoRedirectEnabled: PropTypes.bool,
  trackEvent: PropTypes.func,
  showMoreProvidersOption: PropTypes.bool
};
Comparison.defaultProps = {
  sourceCountry: null,
  providerCountry: null,
  providers: [],
  excludePartners: false,
  expandDisclaimer: false,
  maxVisibleProviders: 5,
  error: false,
  errorType: null,
  onAmountChange: () => {},
  onAmountChangeFinish: () => {},
  onRouteChange: () => {},
  onError: () => {},
  onCallToActionClick: () => {},
  onClickToSeeAnAvailableComparison: () => {},
  onClickToSeePricingDisclaimer: () => {},
  onClickToSeeDisclaimer: () => {},
  onProviderClick: () => {},
  onClickingDeliveryEstimationTooltip: () => {},
  deliveryEstimationEnabled: false,
  showSendMoneyButton: true,
  providerLogoRedirectEnabled: false,
  trackEvent: () => {},
  showMoreProvidersOption: true
};

// eslint-disable-next-line fp/no-mutation
Comparison.componentType = Table.Educational;

const ComparisonContainer = withComparisonResources(Comparison);

export { Comparison, ComparisonContainer };
//# sourceMappingURL=index.js.map
