import Button from '../../button/Button.resolver.mjs';
import { SelectInput } from '../../inputs/SelectInput/SelectInput.mjs';
import { ChevronDown } from '@transferwise/icons';
import 'clsx';
import { useIntl } from 'react-intl';
import '../../dateLookup/dateTrigger/DateTrigger.messages.mjs';
import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
import { useMemo, useState, forwardRef } from 'react';
import '@headlessui/react';
import { SelectInputOptionContent } from '../../inputs/SelectInput/OptionContent/SelectInputOptionContent.mjs';
import { SelectInputTriggerButton } from '../../inputs/SelectInput/TriggerButton/SelectInputTriggerButton.mjs';
import '../../inputs/contexts.mjs';
import '../../header/Header.mjs';
import 'virtua';
import '../../common/theme.mjs';
import '../../common/direction.mjs';
import '@transferwise/neptune-tokens';
import '../../common/propsValues/control.mjs';
import '../../common/propsValues/size.mjs';
import '../../common/propsValues/typography.mjs';
import '../../common/propsValues/width.mjs';
import '../../common/propsValues/type.mjs';
import '../../common/propsValues/dateMode.mjs';
import '../../common/propsValues/monthFormat.mjs';
import '../../common/propsValues/position.mjs';
import '../../common/propsValues/layouts.mjs';
import '../../common/propsValues/status.mjs';
import '../../common/propsValues/sentiment.mjs';
import '../../common/propsValues/profileType.mjs';
import '../../common/propsValues/variant.mjs';
import '../../common/propsValues/scroll.mjs';
import '../../common/propsValues/markdownNodeType.mjs';
import '../../common/fileType.mjs';
import { getLocaleCurrencyName } from '../../common/locale/index.mjs';
import '../../common/closeButton/CloseButton.messages.mjs';
import '../../inputs/SelectInput/SelectInput.messages.mjs';
import { Flag } from '@wise/art';
import messages from '../ExpressiveMoneyInput.messages.mjs';
import { formatCurrencyCode } from '@transferwise/formatting';

const CurrencySelector = ({
  id,
  currency,
  options = [],
  labelId,
  onChange,
  addons,
  onOpen,
  onSearchChange
}) => {
  const intl = useIntl();
  const allCurrencyOptions = useMemo(() => getUniqueCurrencies(options), [options]);
  const activeCurrencyOption = 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] = 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__*/jsx(SelectInput, {
    compareValues: "code",
    disabled: disabled,
    id: id,
    value: activeCurrencyOption,
    filterable: true,
    filterPlaceholder: intl.formatMessage(messages.currencySelectorSearchPlaceholder),
    UNSAFE_triggerButtonProps: {
      id: undefined,
      'aria-labelledby': undefined,
      'aria-describedby': labelId,
      'aria-invalid': undefined,
      'aria-label': intl.formatMessage(messages.currencySelectorSelectCurrency)
    },
    items: items,
    renderValue: ({
      code,
      label
    }) => {
      return /*#__PURE__*/jsx(SelectInputOptionContent, {
        title: formatCurrencyCode(code),
        note: label,
        icon: /*#__PURE__*/jsx(Flag, {
          code: code,
          intrinsicSize: 24
        })
      });
    },
    renderTrigger: () => /*#__PURE__*/jsx(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__*/jsx(Flag, {
              code: currency
            })
          })
        }].filter(Boolean).filter(avatar => !(avatar && Object.keys(avatar).length === 0))
      },
      addonEnd: disabled ? undefined : {
        type: 'icon',
        value: /*#__PURE__*/jsx(ChevronDown, {})
      },
      onClick: event => handleTriggerClick(event),
      children: /*#__PURE__*/jsxs(Fragment, {
        children: [/*#__PURE__*/jsx("span", {
          "aria-hidden": true,
          children: formatCurrencyCode(currency)
        }), /*#__PURE__*/jsx("span", {
          className: "sr-only",
          children: 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__*/forwardRef(function ButtonInput({
  children,
  ...rest
}, ref) {
  return /*#__PURE__*/jsx(Button, {
    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 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);
  });
};

export { ButtonInput, CurrencySelector };
//# sourceMappingURL=CurrencySelector.mjs.map
