'use strict';

var Button_resolver = require('../../button/Button.resolver.js');
var SelectInput = require('../../inputs/SelectInput/SelectInput.js');
var icons = require('@transferwise/icons');
require('clsx');
var reactIntl = require('react-intl');
require('../../dateLookup/dateTrigger/DateTrigger.messages.js');
var jsxRuntime = require('react/jsx-runtime');
var React = require('react');
require('@headlessui/react');
var SelectInputOptionContent = require('../../inputs/SelectInput/OptionContent/SelectInputOptionContent.js');
var SelectInputTriggerButton = require('../../inputs/SelectInput/TriggerButton/SelectInputTriggerButton.js');
require('../../inputs/contexts.js');
require('../../header/Header.js');
require('virtua');
require('../../common/theme.js');
require('../../common/direction.js');
require('@transferwise/neptune-tokens');
require('../../common/propsValues/control.js');
require('../../common/propsValues/size.js');
require('../../common/propsValues/typography.js');
require('../../common/propsValues/width.js');
require('../../common/propsValues/type.js');
require('../../common/propsValues/dateMode.js');
require('../../common/propsValues/monthFormat.js');
require('../../common/propsValues/position.js');
require('../../common/propsValues/layouts.js');
require('../../common/propsValues/status.js');
require('../../common/propsValues/sentiment.js');
require('../../common/propsValues/profileType.js');
require('../../common/propsValues/variant.js');
require('../../common/propsValues/scroll.js');
require('../../common/propsValues/markdownNodeType.js');
require('../../common/fileType.js');
var index = require('../../common/locale/index.js');
require('../../common/closeButton/CloseButton.messages.js');
require('../../inputs/SelectInput/SelectInput.messages.js');
var art = require('@wise/art');
var ExpressiveMoneyInput_messages = require('../ExpressiveMoneyInput.messages.js');
var formatting = require('@transferwise/formatting');

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(SelectInputOptionContent.SelectInputOptionContent, {
        title: formatting.formatCurrencyCode(code),
        note: label,
        icon: /*#__PURE__*/jsxRuntime.jsx(art.Flag, {
          code: code,
          intrinsicSize: 24
        })
      });
    },
    renderTrigger: () => /*#__PURE__*/jsxRuntime.jsx(SelectInputTriggerButton.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: /*#__PURE__*/jsxRuntime.jsxs(jsxRuntime.Fragment, {
        children: [/*#__PURE__*/jsxRuntime.jsx("span", {
          "aria-hidden": true,
          children: formatting.formatCurrencyCode(currency)
        }), /*#__PURE__*/jsxRuntime.jsx("span", {
          className: "sr-only",
          children: index.getLocaleCurrencyName(intl, 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 formatting.formatCurrencyCode(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
