'use strict';

var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var _slicedToArray = require('@babel/runtime/helpers/slicedToArray');
var _objectWithoutProperties = require('@babel/runtime/helpers/objectWithoutProperties');
var React = require('react');
var reactQuery = require('@tanstack/react-query');
var min = require('libphonenumber-js/min');
var neetoCist = require('@bigbinary/neeto-cist');
var Input = require('@bigbinary/neetoui/Input');
var classnames = require('classnames');
var Select = require('@bigbinary/neetoui/Select');
var reactI18next = require('react-i18next');
var index_es5_min = require('./index.es5.min-CUvhPmKJ.js');
var ramda = require('ramda');
var Tooltip = require('@bigbinary/neetoui/Tooltip');
var Typography = require('@bigbinary/neetoui/Typography');
var jsxRuntime = require('react/jsx-runtime');
var _asyncToGenerator = require('@babel/runtime/helpers/asyncToGenerator');
var i18next = require('i18next');
var utils = require('@bigbinary/neeto-commons-frontend/utils');
var yup = require('yup');
var axios = require('axios');
var injectCss = require('./inject-css-B6qYtOJe.js');

function _interopNamespaceDefault(e) {
  var n = Object.create(null);
  if (e) {
    Object.keys(e).forEach(function (k) {
      if (k !== 'default') {
        var d = Object.getOwnPropertyDescriptor(e, k);
        Object.defineProperty(n, k, d.get ? d : {
          enumerable: true,
          get: function () { return e[k]; }
        });
      }
    });
  }
  n.default = e;
  return Object.freeze(n);
}

var yup__namespace = /*#__PURE__*/_interopNamespaceDefault(yup);

var IP_LOOKUP_ACCESS_TOKEN = "083c694c79f119c7f227e737de9a5c8c";
var IP_LOOKUP_STORAGE_KEY = "IP_LOOKUP_DETAILS_STORAGE";
var MAX_CACHE_AGE = 60 * 60 * 1000;

var COUNTRY_PICKER_OPTIONS = min.getCountries().filter(function (code) {
  return index_es5_min.index_es5_minExports.countries[code];
}).map(function (code) {
  return {
    label: index_es5_min.index_es5_minExports.countries[code].name,
    value: code
  };
}).sort(function (a, b) {
  return a.label.localeCompare(b.label);
});
var COUNTRY_PICKER_STYLES = {
  menuPortal: ramda.mergeLeft({
    width: 196,
    zIndex: 99999
  }),
  control: ramda.mergeLeft({
    border: "none !important",
    cursor: "pointer",
    gap: 4
  }),
  input: ramda.assoc("position", "absolute !important"),
  valueContainer: ramda.assoc("padding", "0 !important"),
  indicatorsContainer: ramda.assoc("paddingRight", "0 !important")
};

var _excluded$2 = ["countryCode", "showEmoji"];
function ownKeys$2(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread$2(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$2(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$2(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var SingleValue$1 = function SingleValue(_ref) {
  var countryCode = _ref.countryCode,
    _ref$showEmoji = _ref.showEmoji,
    showEmoji = _ref$showEmoji === void 0 ? false : _ref$showEmoji,
    otherProps = _objectWithoutProperties(_ref, _excluded$2);
  if (!showEmoji) return null;
  var countryData = index_es5_min.index_es5_minExports.countries[countryCode];
  return /*#__PURE__*/jsxRuntime.jsx(Tooltip, {
    content: countryData === null || countryData === void 0 ? void 0 : countryData.name,
    children: /*#__PURE__*/jsxRuntime.jsx(Typography, _objectSpread$2(_objectSpread$2({
      className: "neeto-molecules-phone-number-input__flag cursor-pointer text-center text-xl",
      style: "body2"
    }, otherProps), {}, {
      children: countryData === null || countryData === void 0 ? void 0 : countryData.emoji
    }))
  });
};
var SingleValue = /*#__PURE__*/React.memo(SingleValue$1);

var _excluded$1 = ["countryCode", "onChange"];
function ownKeys$1(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread$1(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$1(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$1(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var CountryPicker$1 = function CountryPicker(_ref) {
  var countryCode = _ref.countryCode,
    _onChange = _ref.onChange,
    otherProps = _objectWithoutProperties(_ref, _excluded$1);
  var _useState = React.useState(""),
    _useState2 = _slicedToArray(_useState, 2),
    searchTerm = _useState2[0],
    setSearchTerm = _useState2[1];
  var _useTranslation = reactI18next.useTranslation(),
    t = _useTranslation.t;
  return /*#__PURE__*/jsxRuntime.jsx("div", {
    className: classnames("flex-shrink-0", {
      "w-10": !searchTerm,
      "w-24": searchTerm
    }),
    children: /*#__PURE__*/jsxRuntime.jsx(Select, _objectSpread$1({
      isSearchable: true,
      "aria-label": t("neetoMolecules.phoneNumberInput.countryCodeAriaLabel"),
      "data-testid": "phonenumber-country-picker",
      options: COUNTRY_PICKER_OPTIONS,
      strategy: "fixed",
      styles: COUNTRY_PICKER_STYLES,
      value: {
        value: countryCode
      },
      components: {
        SingleValue: function SingleValue$1() {
          return /*#__PURE__*/jsxRuntime.jsx(SingleValue, {
            countryCode: countryCode,
            showEmoji: true
          });
        }
      },
      isOptionSelected: function isOptionSelected(_ref2, _ref3) {
        var value = _ref2.value;
        var _ref4 = _slicedToArray(_ref3, 1),
          selectedOption = _ref4[0];
        return (selectedOption === null || selectedOption === void 0 ? void 0 : selectedOption.name) === value;
      },
      onChange: function onChange(option) {
        return _onChange(option.value);
      },
      onInputChange: setSearchTerm
    }, otherProps))
  });
};
var CountryPicker = /*#__PURE__*/React.memo(CountryPicker$1);

var fetchLocationDetails$1 = function fetchLocationDetails() {
  return axios.get("https://neeto-ip-lookup-web-production.neetodeployapp.com/location", {
    headers: {
      "X-ACCESS-TOKEN": IP_LOOKUP_ACCESS_TOKEN
    }
  });
};
var neetoIpLookupApi = {
  fetchLocationDetails: fetchLocationDetails$1
};

function _regenerator() { /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */ var e, t, r = "function" == typeof Symbol ? Symbol : {}, n = r.iterator || "@@iterator", o = r.toStringTag || "@@toStringTag"; function i(r, n, o, i) { var c = n && n.prototype instanceof Generator ? n : Generator, u = Object.create(c.prototype); return _regeneratorDefine2(u, "_invoke", function (r, n, o) { var i, c, u, f = 0, p = o || [], y = false, G = { p: 0, n: 0, v: e, a: d, f: d.bind(e, 4), d: function d(t, r) { return i = t, c = 0, u = e, G.n = r, a; } }; function d(r, n) { for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) { var o, i = p[t], d = G.p, l = i[2]; r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0)); } if (o || r > 1) return a; throw y = true, n; } return function (o, p, l) { if (f > 1) throw TypeError("Generator is already running"); for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) { i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u); try { if (f = 2, i) { if (c || (o = "next"), t = i[o]) { if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object"); if (!t.done) return t; u = t.value, c < 2 && (c = 0); } else 1 === c && (t = i["return"]) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1); i = e; } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break; } catch (t) { i = e, c = 1, u = t; } finally { f = 1; } } return { value: t, done: y }; }; }(r, o, i), true), u; } var a = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} t = Object.getPrototypeOf; var c = [][n] ? t(t([][n]())) : (_regeneratorDefine2(t = {}, n, function () { return this; }), t), u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c); function f(e) { return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine2(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine2(u, "constructor", GeneratorFunctionPrototype), _regeneratorDefine2(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine2(GeneratorFunctionPrototype, o, "GeneratorFunction"), _regeneratorDefine2(u), _regeneratorDefine2(u, o, "Generator"), _regeneratorDefine2(u, n, function () { return this; }), _regeneratorDefine2(u, "toString", function () { return "[object Generator]"; }), (_regenerator = function _regenerator() { return { w: i, m: f }; })(); }
function _regeneratorDefine2(e, r, n, t) { var i = Object.defineProperty; try { i({}, "", {}); } catch (e) { i = 0; } _regeneratorDefine2 = function _regeneratorDefine(e, r, n, t) { function o(r, n) { _regeneratorDefine2(e, r, function (e) { return this._invoke(r, n, e); }); } r ? i ? i(e, r, { value: n, enumerable: !t, configurable: !t, writable: !t }) : e[r] = n : (o("next", 0), o("throw", 1), o("return", 2)); }, _regeneratorDefine2(e, r, n, t); }
var isPhoneNumberValid = function isPhoneNumberValid() {
  var value = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "";
  for (var _len = arguments.length, rest = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
    rest[_key - 1] = arguments[_key];
  }
  return min.isValidPhoneNumber.apply(void 0, [value].concat(rest));
};
var validation = function validation() {
  var message = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : i18next.t("neetoMolecules.phoneNumberInput.validations.invalid");
  return yup__namespace.string().test("phoneNumber", message, function (phoneNumber) {
    return phoneNumber ? min.isValidPhoneNumber(phoneNumber) : true;
  });
};
var getPhoneData = function getPhoneData(value, defaultCountryCode) {
  try {
    var parsedValue = min.parsePhoneNumber(value, defaultCountryCode);
    return {
      phoneNumber: parsedValue.number,
      international: parsedValue.formatInternational(),
      countryCode: parsedValue.country || defaultCountryCode
    };
  } catch (_unused) {
    return {
      phoneNumber: value,
      international: min.formatIncompletePhoneNumber(value, defaultCountryCode),
      countryCode: defaultCountryCode
    };
  }
};
var fetchLocationDetails = /*#__PURE__*/function () {
  var _ref = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee() {
    var stored, _ref2, data, timestamp, isCacheValid, details, _timestamp;
    return _regenerator().w(function (_context) {
      while (1) switch (_context.p = _context.n) {
        case 0:
          stored = utils.getFromLocalStorage(IP_LOOKUP_STORAGE_KEY);
          _ref2 = stored || {}, data = _ref2.data, timestamp = _ref2.timestamp;
          isCacheValid = timestamp && Date.now() - timestamp < MAX_CACHE_AGE;
          if (!isCacheValid) {
            _context.n = 1;
            break;
          }
          return _context.a(2, data);
        case 1:
          _context.p = 1;
          _context.n = 2;
          return neetoIpLookupApi.fetchLocationDetails();
        case 2:
          details = _context.v;
          _timestamp = Date.now();
          utils.setToLocalStorage(IP_LOOKUP_STORAGE_KEY, {
            data: details,
            timestamp: _timestamp
          });
          return _context.a(2, details);
        case 3:
          _context.p = 3;
          _context.v;
          return _context.a(2, data || null);
      }
    }, _callee, null, [[1, 3]]);
  }));
  return function fetchLocationDetails() {
    return _ref.apply(this, arguments);
  };
}();
var isNumeric = function isNumeric(_char) {
  return _char >= "0" && _char <= "9";
};
var preserveCursor = function preserveCursor(callback) {
  return function (event) {
    var start = event.target.selectionStart;
    var end = event.target.selectionEnd;
    var len = event.target.value.length;
    var result = callback(event);
    var delta = event.target.value.length - len;
    event.target.setSelectionRange(start + delta, end + delta);
    return result;
  };
};

var _excluded = ["value", "onChange", "className", "error", "selectProps", "initialCountryCode"];
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var PhoneNumberInput = /*#__PURE__*/React.forwardRef(function (_ref, ref) {
  var _ref$value = _ref.value,
    value = _ref$value === void 0 ? "" : _ref$value,
    _ref$onChange = _ref.onChange,
    onChange = _ref$onChange === void 0 ? neetoCist.noop : _ref$onChange,
    className = _ref.className,
    error = _ref.error,
    selectProps = _ref.selectProps,
    initialCountryCode = _ref.initialCountryCode,
    inputProps = _objectWithoutProperties(_ref, _excluded);
  var _useState = React.useState(function () {
      return getPhoneData(value).countryCode || initialCountryCode;
    }),
    _useState2 = _slicedToArray(_useState, 2),
    countryCode = _useState2[0],
    setCountryCode = _useState2[1];
  var _useQuery = reactQuery.useQuery({
      queryKey: [IP_LOOKUP_STORAGE_KEY],
      queryFn: fetchLocationDetails,
      enabled: !countryCode,
      staleTime: Infinity,
      gcTime: Infinity,
      select: function select(data) {
        return neetoCist.findBy({
          value: data.countryCode
        }, COUNTRY_PICKER_OPTIONS);
      }
    }),
    ipCountry = _useQuery.data;
  var finalCountryCode = countryCode || (ipCountry === null || ipCountry === void 0 ? void 0 : ipCountry.value) || "US";
  var formattedValue = min.formatIncompletePhoneNumber(value, finalCountryCode);
  var onKeyDown = preserveCursor(function (event) {
    // Handles special characters in the phone number formatting like brackets and spaces.
    if (event.key !== "Backspace") return;
    var left = event.target.value.substring(0, event.target.selectionStart);
    var right = event.target.value.substring(event.target.selectionEnd);
    var index = left.length - 1;
    while (index > 0 && !isNumeric(left[index])) index--;
    var newValue = left.substring(0, index + 1) + right;
    if (newValue) event.target.value = newValue;
  });
  var onInputChange = preserveCursor(function (event) {
    var phoneData = getPhoneData(event.target.value, finalCountryCode);
    event.target.value = min.formatIncompletePhoneNumber(event.target.value);
    setCountryCode(phoneData.countryCode);
    onChange(phoneData.phoneNumber);
  });
  var onChangeCountry = function onChangeCountry(countryCode) {
    var phoneData = getPhoneData(value, finalCountryCode);
    var prevPrefix = "+".concat(min.getCountryCallingCode(phoneData.countryCode));
    var nextPrefix = "+".concat(min.getCountryCallingCode(countryCode));
    setCountryCode(countryCode);
    onChange(nextPrefix + value.replace(prevPrefix, ""));
  };
  return /*#__PURE__*/jsxRuntime.jsx("div", {
    className: className,
    children: /*#__PURE__*/jsxRuntime.jsx(Input, _objectSpread({
      error: error,
      onKeyDown: onKeyDown,
      ref: ref,
      autoComplete: "tel",
      className: "neeto-molecules-phone-number-input__input",
      "data-testid": "phonenumber-input",
      inputMode: "tel",
      type: "tel",
      value: formattedValue,
      prefix: /*#__PURE__*/jsxRuntime.jsx(CountryPicker, _objectSpread({
        countryCode: finalCountryCode,
        onChange: onChangeCountry
      }, selectProps)),
      onChange: onInputChange
    }, inputProps))
  });
});
PhoneNumberInput.displayName = "PhoneNumberInput";

var css = "@import url(\"https://fonts.googleapis.com/css2?family=Noto+Color+Emoji&display=swap\");.neeto-molecules-phone-number-input__flag{font-family:-apple-system,Noto Color Emoji,BlinkMacSystemFont,Inter,Arial,Segoe UI,Roboto,Oxygen,Ubuntu,Fira Sans,Droid Sans,Helvetica Neue,sans-serif!important;font-style:normal;font-weight:400}.neeto-molecules-phone-number{display:block!important}.neeto-molecules-phone-number-input__input .neeto-ui-react-select__indicators{padding-inline:0!important}.neeto-molecules-phone-number-input__input .neeto-ui-input input{direction:inherit}";
injectCss.n(css,{});

exports.PhoneNumberInput = PhoneNumberInput;
exports.SingleValue = SingleValue;
exports.getPhoneData = getPhoneData;
exports.isPhoneNumberValid = isPhoneNumberValid;
exports.validation = validation;
//# sourceMappingURL=phone-number-DIIlhFGA.js.map
