'use strict';

var React = require('react');
var reactIntl = require('react-intl');
var contexts = require('../inputs/contexts.js');
var SelectInput = require('../inputs/SelectInput.js');
var PhoneNumberInput_messages = require('./PhoneNumberInput.messages.js');
var countries = require('./data/countries.js');
var index = require('./utils/setDefaultPrefix/index.js');
var isValidPhoneNumber = require('./utils/isValidPhoneNumber/isValidPhoneNumber.js');
var index$1 = require('./utils/explodeNumberModel/index.js');
var index$2 = require('./utils/findCountryByPrefix/index.js');
var cleanNumber = require('./utils/cleanNumber/cleanNumber.js');
var sortArrayByProperty = require('./utils/sortArrayByProperty/sortArrayByProperty.js');
var groupCountriesByPrefix = require('./utils/groupCountriesByPrefix/groupCountriesByPrefix.js');
var excludeCountries = require('./utils/excludeCountries/excludeCountries.js');
var jsxRuntime = require('react/jsx-runtime');
var size = require('../common/propsValues/size.js');

const ALLOWED_PHONE_CHARS = /^$|^[\d-\s]+$/;
const defaultSelectProps = {};
const defaultDisabledCountries = [];
const PhoneNumberInput = ({
  id,
  'aria-labelledby': ariaLabelledByProp,
  required,
  disabled,
  initialValue,
  onChange,
  onFocus,
  onBlur,
  countryCode,
  searchPlaceholder = 'Prefix',
  size: size$1 = size.Size.MEDIUM,
  placeholder,
  selectProps = defaultSelectProps,
  disabledCountries = defaultDisabledCountries
}) => {
  const inputAttributes = contexts.useInputAttributes({
    nonLabelable: true
  });
  const ariaLabelledBy = ariaLabelledByProp ?? inputAttributes['aria-labelledby'];
  const {
    locale,
    formatMessage
  } = reactIntl.useIntl();
  const [internalValue, setInternalValue] = React.useState(() => {
    const cleanValue = initialValue ? cleanNumber.cleanNumber(initialValue) : null;
    if (!cleanValue || !isValidPhoneNumber.isValidPhoneNumber(cleanValue)) {
      return {
        prefix: index.setDefaultPrefix(locale, countryCode),
        suffix: ''
      };
    }
    return index$1.explodeNumberModel(cleanValue);
  });
  const [broadcastedValue, setBroadcastedValue] = React.useState(null);
  const [suffixDirty, setSuffixDirty] = React.useState(false);
  React.useEffect(() => {
    if (internalValue.suffix) {
      setSuffixDirty(true);
    }
  }, [internalValue.suffix]);
  const countriesByPrefix = React.useMemo(() => groupCountriesByPrefix.groupCountriesByPrefix(sortArrayByProperty.sortArrayByProperty(excludeCountries.excludeCountries(countries, disabledCountries), 'iso3')), [disabledCountries]);
  const onSuffixChange = event => {
    const suffix = event.target.value;
    if (ALLOWED_PHONE_CHARS.test(suffix)) {
      setInternalValue(prev => ({
        ...prev,
        suffix
      }));
    }
  };
  const onPaste = event => {
    if (!event.nativeEvent.clipboardData) {
      return;
    }
    const pastedValue = (event.nativeEvent.clipboardData.getData('text/plain') || '').replace(/(\s|-)+/g, '');
    const pastedNumber = index$1.explodeNumberModel(pastedValue);
    if (pastedNumber.prefix != null && countriesByPrefix.has(pastedNumber.prefix) && ALLOWED_PHONE_CHARS.test(pastedNumber.suffix)) {
      setInternalValue(pastedNumber);
    }
  };
  React.useEffect(() => {
    if (broadcastedValue === null) {
      setBroadcastedValue(internalValue);
      return;
    }
    const internalPhoneNumber = `${internalValue.prefix ?? ''}${internalValue.suffix}`;
    const broadcastedPhoneNumber = `${broadcastedValue.prefix ?? ''}${broadcastedValue.suffix}`;
    if (internalPhoneNumber === broadcastedPhoneNumber) {
      return;
    }
    const newValue = isValidPhoneNumber.isValidPhoneNumber(internalPhoneNumber) ? cleanNumber.cleanNumber(internalPhoneNumber) : null;
    onChange(newValue, internalValue.prefix ?? '');
    setBroadcastedValue(internalValue);
  }, [onChange, broadcastedValue, internalValue]);
  return /*#__PURE__*/jsxRuntime.jsxs("div", {
    role: "group",
    ...inputAttributes,
    "aria-labelledby": ariaLabelledBy,
    className: "tw-telephone",
    children: [/*#__PURE__*/jsxRuntime.jsx("div", {
      className: "tw-telephone__country-select",
      children: /*#__PURE__*/jsxRuntime.jsx(SelectInput.SelectInput, {
        placeholder: formatMessage(PhoneNumberInput_messages.selectInputPlaceholder),
        items: [...countriesByPrefix].map(([prefix, countries]) => ({
          type: 'option',
          value: prefix,
          filterMatchers: [prefix, ...countries.map(country => country.name), ...countries.map(country => country.iso3)]
        })),
        value: internalValue.prefix,
        renderValue: (prefix, withinTrigger) => /*#__PURE__*/jsxRuntime.jsx(SelectInput.SelectInputOptionContent, {
          title: prefix,
          note: withinTrigger ? undefined : countriesByPrefix.get(prefix)?.map(country => country.iso3).join(', ')
        }),
        filterable: true,
        filterPlaceholder: searchPlaceholder,
        disabled: disabled,
        size: size$1,
        onChange: prefix => {
          const country = prefix != null ? index$2.findCountryByPrefix(prefix) : null;
          setInternalValue(prev => ({
            ...prev,
            prefix,
            format: country?.phoneFormat
          }));
        },
        onClose: () => {
          if (suffixDirty) {
            onBlur?.();
          }
        },
        ...selectProps
      })
    }), /*#__PURE__*/jsxRuntime.jsx("div", {
      className: "tw-telephone__number-input",
      children: /*#__PURE__*/jsxRuntime.jsx("div", {
        className: `input-group input-group-${size$1}`,
        children: /*#__PURE__*/jsxRuntime.jsx("input", {
          id: id,
          autoComplete: "tel-national",
          name: "phoneNumber",
          inputMode: "numeric",
          value: internalValue.suffix,
          className: "form-control",
          disabled: disabled,
          required: required,
          placeholder: placeholder,
          onChange: onSuffixChange,
          onPaste: onPaste,
          onFocus: onFocus,
          onBlur: () => onBlur?.()
        })
      })
    })]
  });
};

module.exports = PhoneNumberInput;
//# sourceMappingURL=PhoneNumberInput.js.map
