'use strict';

var Button_resolver = require('../../button/Button.resolver.js');
var SelectInput = require('../../inputs/SelectInput.js');
var icons = require('@transferwise/icons');
var art = require('@wise/art');
var React = require('react');
var reactIntl = require('react-intl');
var ExpressiveMoneyInput_messages = require('../ExpressiveMoneyInput.messages.js');
var jsxRuntime = require('react/jsx-runtime');

const CurrencySelector = ({
  id,
  currency,
  options = [],
  labelId,
  onChange,
  addons,
  onOpen,
  onSearchChange
}) => {
  const intl = reactIntl.useIntl();
  const allCurrencyOptions = React.useMemo(() => getUniqueCurrencies(options), [options]);
  const activeCurrencyOption = React.useMemo(() => {
    // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
    return allCurrencyOptions.find(option => option.code === currency);
  }, [currency, allCurrencyOptions]);
  const disabled = !onChange || options.length === 0 || options.length === 1 && options[0].currencies.length <= 1;
  const [searchQuery, setSearchQuery] = React.useState('');
  const handleTriggerClick = event => {
    const triggerEl = event.currentTarget;
    if (triggerEl?.getAttribute('aria-expanded') === 'false') {
      onOpen?.();
    }
  };
  const items = searchQuery ? filterAndSortCurrenciesForQuery(allCurrencyOptions, searchQuery).map(getCurrencySelectOption) : options.map(getCurrencyGroup);
  return /*#__PURE__*/jsxRuntime.jsx(SelectInput.SelectInput, {
    compareValues: "code",
    disabled: disabled,
    id: id,
    value: activeCurrencyOption,
    filterable: true,
    filterPlaceholder: intl.formatMessage(ExpressiveMoneyInput_messages.default.currencySelectorSearchPlaceholder),
    UNSAFE_triggerButtonProps: {
      id: undefined,
      'aria-labelledby': undefined,
      'aria-describedby': labelId,
      'aria-invalid': undefined,
      'aria-label': intl.formatMessage(ExpressiveMoneyInput_messages.default.currencySelectorSelectCurrency)
    },
    items: items,
    renderValue: ({
      code,
      label
    }) => {
      return /*#__PURE__*/jsxRuntime.jsx(SelectInput.SelectInputOptionContent, {
        title: code,
        note: label,
        icon: /*#__PURE__*/jsxRuntime.jsx(art.Flag, {
          code: code,
          intrinsicSize: 24
        })
      });
    },
    renderTrigger: () => /*#__PURE__*/jsxRuntime.jsx(SelectInput.SelectInputTriggerButton, {
      as: ButtonInput
      // @ts-expect-error new (v2) ButtonProps
      ,
      addonStart: {
        type: 'avatar',
        value: [addons ? addons[0] : null, {
          ...(addons && addons.length > 1 ? {
            ...addons[1]
          } : {
            asset: /*#__PURE__*/jsxRuntime.jsx(art.Flag, {
              code: currency
            })
          })
        }].filter(Boolean).filter(avatar => !(avatar && Object.keys(avatar).length === 0))
      },
      addonEnd: disabled ? undefined : {
        type: 'icon',
        value: /*#__PURE__*/jsxRuntime.jsx(icons.ChevronDown, {})
      },
      onClick: event => handleTriggerClick(event),
      children: currency
    }),
    onChange: newValue => {
      onChange?.(newValue.code);
    },
    onFilterChange: ({
      queryNormalized
    }) => {
      setSearchQuery(queryNormalized ?? '');
      if (queryNormalized) {
        onSearchChange?.({
          query: queryNormalized,
          resultCount: filterAndSortCurrenciesForQuery(allCurrencyOptions, queryNormalized).length
        });
      }
    }
  });
};
const ButtonInput = /*#__PURE__*/React.forwardRef(function ButtonInput({
  children,
  ...rest
}, ref) {
  return /*#__PURE__*/jsxRuntime.jsx(Button_resolver.default, {
    ref: ref,
    size: "md",
    v2: true,
    className: "wds-currency-selector",
    priority: "secondary-neutral",
    ...rest,
    children: children
  });
});
const getCurrencySelectOption = currency => {
  return {
    type: 'option',
    value: currency,
    filterMatchers: currency.keywords
  };
};
const getCurrencyGroup = section => {
  return {
    type: 'group',
    label: section.title,
    options: section.currencies.map(getCurrencySelectOption)
  };
};
const getUniqueCurrencies = options => {
  const allCurrencyOptions = options.flatMap(section => section.currencies);
  const uniqueCurrencies = new Map();
  allCurrencyOptions.forEach(currencyObj => {
    uniqueCurrencies.set(currencyObj.code, currencyObj);
  });
  return Array.from(uniqueCurrencies.values());
};
const filterAndSortCurrenciesForQuery = (currencies, query) => {
  return currencies.filter(currency => {
    return currency.code.toLowerCase().includes(query) || (currency.label ?? '').toLowerCase().includes(query) || currency.keywords?.some(keyword => keyword.toLowerCase().includes(query));
  })
  // prefer exact matches, then sort alphabetically by code
  .sort((a, b) => {
    const aCode = a.code.toLowerCase();
    const bCode = b.code.toLowerCase();
    if (aCode === query) {
      return -1;
    }
    if (bCode === query) {
      return 1;
    }
    return aCode.localeCompare(bCode);
  });
};

exports.ButtonInput = ButtonInput;
exports.CurrencySelector = CurrencySelector;
//# sourceMappingURL=CurrencySelector.js.map
