function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function (_e) { function e(_x) { return _e.apply(this, arguments); } e.toString = function () { return _e.toString(); }; return e; }(function (e) { throw e; }), f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function (_e2) { function e(_x2) { return _e2.apply(this, arguments); } e.toString = function () { return _e2.toString(); }; return e; }(function (e) { didErr = true; err = e; }), f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
import React, { useMemo } from 'react';
import { locales } from '@pisell/utils';
import "./PhoneInput.less";

/** 国家/地区配置（后端返回格式） */

/** 手机号对象格式 */

/** 值格式类型 */

/** 手机号输入组件属性 */

/** 默认国家/地区列表 */
var DEFAULT_COUNTRIES = [{
  name: 'United States',
  code: 'US',
  calling_code: '1',
  currency_code: 'USD'
}, {
  name: 'China',
  code: 'CN',
  calling_code: '86',
  currency_code: 'CNY'
}, {
  name: 'United Kingdom',
  code: 'GB',
  calling_code: '44',
  currency_code: 'GBP'
}, {
  name: 'Australia',
  code: 'AU',
  calling_code: '61',
  currency_code: 'AUD'
}, {
  name: 'Canada',
  code: 'CA',
  calling_code: '1',
  currency_code: 'CAD'
}, {
  name: 'Japan',
  code: 'JP',
  calling_code: '81',
  currency_code: 'JPY'
}, {
  name: 'South Korea',
  code: 'KR',
  calling_code: '82',
  currency_code: 'KRW'
}, {
  name: 'Singapore',
  code: 'SG',
  calling_code: '65',
  currency_code: 'SGD'
}, {
  name: 'Hong Kong',
  code: 'HK',
  calling_code: '852',
  currency_code: 'HKD'
}, {
  name: 'Taiwan',
  code: 'TW',
  calling_code: '886',
  currency_code: 'TWD'
}, {
  name: 'Malaysia',
  code: 'MY',
  calling_code: '60',
  currency_code: 'MYR'
}, {
  name: 'Thailand',
  code: 'TH',
  calling_code: '66',
  currency_code: 'THB'
}, {
  name: 'Vietnam',
  code: 'VN',
  calling_code: '84',
  currency_code: 'VND'
}, {
  name: 'Philippines',
  code: 'PH',
  calling_code: '63',
  currency_code: 'PHP'
}, {
  name: 'Indonesia',
  code: 'ID',
  calling_code: '62',
  currency_code: 'IDR'
}, {
  name: 'India',
  code: 'IN',
  calling_code: '91',
  currency_code: 'INR'
}, {
  name: 'Germany',
  code: 'DE',
  calling_code: '49',
  currency_code: 'EUR'
}, {
  name: 'France',
  code: 'FR',
  calling_code: '33',
  currency_code: 'EUR'
}, {
  name: 'Italy',
  code: 'IT',
  calling_code: '39',
  currency_code: 'EUR'
}, {
  name: 'Spain',
  code: 'ES',
  calling_code: '34',
  currency_code: 'EUR'
}];

/**
 * 从浏览器检测用户的国家/地区
 * 优先级：
 * 1. Intl.DateTimeFormat 的 resolvedOptions
 * 2. navigator.language 的地区后缀
 * 3. 返回 null（使用默认值）
 */
function detectUserCountry() {
  try {
    // 方法 1: 使用 Intl API 获取时区对应的地区
    if (typeof Intl !== 'undefined' && Intl.DateTimeFormat) {
      var timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;

      // 常见时区到国家代码的映射
      var timeZoneMap = {
        'America/New_York': 'US',
        'America/Los_Angeles': 'US',
        'America/Chicago': 'US',
        'America/Denver': 'US',
        'America/Toronto': 'CA',
        'America/Vancouver': 'CA',
        'Europe/London': 'GB',
        'Europe/Paris': 'FR',
        'Europe/Berlin': 'DE',
        'Europe/Rome': 'IT',
        'Europe/Madrid': 'ES',
        'Asia/Shanghai': 'CN',
        'Asia/Hong_Kong': 'HK',
        'Asia/Taipei': 'TW',
        'Asia/Tokyo': 'JP',
        'Asia/Seoul': 'KR',
        'Asia/Singapore': 'SG',
        'Asia/Bangkok': 'TH',
        'Asia/Kuala_Lumpur': 'MY',
        'Asia/Jakarta': 'ID',
        'Asia/Manila': 'PH',
        'Asia/Ho_Chi_Minh': 'VN',
        'Asia/Kolkata': 'IN',
        'Australia/Sydney': 'AU',
        'Australia/Melbourne': 'AU'
      };
      if (timeZone && timeZoneMap[timeZone]) {
        return timeZoneMap[timeZone];
      }
    }

    // 方法 2: 从 navigator.language 提取国家代码
    if (typeof navigator !== 'undefined' && navigator.language) {
      var lang = navigator.language;
      // 格式可能是 "zh-CN", "en-US", "ja-JP" 等
      var parts = lang.split('-');
      if (parts.length > 1) {
        var countryCode = parts[1].toUpperCase();
        return countryCode;
      }

      // 语言到国家的映射（当只有语言代码时）
      var langMap = {
        'zh': 'CN',
        'en': 'US',
        'ja': 'JP',
        'ko': 'KR',
        'de': 'DE',
        'fr': 'FR',
        'es': 'ES',
        'it': 'IT',
        'th': 'TH',
        'vi': 'VN',
        'id': 'ID',
        'ms': 'MY'
      };
      if (langMap[parts[0]]) {
        return langMap[parts[0]];
      }
    }
  } catch (error) {
    console.warn('Failed to detect user country:', error);
  }
  return null;
}

/**
 * 手机号输入组件
 * 
 * 支持国际区号选择和手机号输入
 * 值格式：+区号+手机号，例如：+8613800138000 或 +15551234567
 */
function PhoneInput(_ref) {
  var value = _ref.value,
    onChange = _ref.onChange,
    placeholder = _ref.placeholder,
    onKeyDown = _ref.onKeyDown,
    _ref$size = _ref.size,
    size = _ref$size === void 0 ? 'large' : _ref$size,
    _ref$disabled = _ref.disabled,
    disabled = _ref$disabled === void 0 ? false : _ref$disabled,
    _ref$className = _ref.className,
    className = _ref$className === void 0 ? '' : _ref$className,
    _ref$countries = _ref.countries,
    countries = _ref$countries === void 0 ? DEFAULT_COUNTRIES : _ref$countries,
    defaultCountry = _ref.defaultCountry,
    _ref$valueFormat = _ref.valueFormat,
    valueFormat = _ref$valueFormat === void 0 ? 'string' : _ref$valueFormat;
  // 使用国际化的 placeholder
  var effectivePlaceholder = placeholder || locales.getText('pisell-phone-input-placeholder');
  // 将输入值标准化为字符串格式（内部统一使用字符串）
  var normalizedValue = useMemo(function () {
    if (!value) return '';

    // 如果是对象格式，转换为字符串
    if (_typeof(value) === 'object' && 'phone' in value) {
      var phone = value.phone,
        country_calling_code = value.country_calling_code;
      return "+".concat(country_calling_code).concat(phone);
    }

    // 已经是字符串格式
    return value;
  }, [value]);

  // 智能确定默认国家：检测到的国家 > 传入的 defaultCountry > 美国
  var effectiveDefaultCountry = useMemo(function () {
    var _countries$;
    var detectedCountry = detectUserCountry();

    // 1. 优先使用检测到的国家（如果在列表中存在）
    if (detectedCountry && countries.some(function (c) {
      return c.code === detectedCountry;
    })) {
      console.log('PhoneInput: Auto-detected country:', detectedCountry);
      return detectedCountry;
    }

    // 2. 使用传入的 defaultCountry（如果在列表中存在）
    if (defaultCountry && countries.some(function (c) {
      return c.code === defaultCountry;
    })) {
      return defaultCountry;
    }

    // 3. 默认第一个，如果没有使用 AU 澳洲
    return (countries === null || countries === void 0 || (_countries$ = countries[0]) === null || _countries$ === void 0 ? void 0 : _countries$.code) || 'AU';
  }, [countries, defaultCountry]);

  // 解析当前值，提取区号和手机号
  var _useMemo = useMemo(function () {
      if (!(countries !== null && countries !== void 0 && countries.length)) {
        return {
          dialCode: '',
          phoneNumber: ''
        };
      }
      if (!normalizedValue || !normalizedValue.startsWith('+')) {
        // 如果没有值或格式不正确，使用默认国家的区号
        var _defaultCountryOption = countries.find(function (c) {
          return c.code === effectiveDefaultCountry;
        }) || countries[0];
        return {
          dialCode: "+".concat(_defaultCountryOption.calling_code),
          phoneNumber: ''
        };
      }

      // 尝试匹配区号
      var _iterator = _createForOfIteratorHelper(countries),
        _step;
      try {
        for (_iterator.s(); !(_step = _iterator.n()).done;) {
          var country = _step.value;
          var countryDialCode = "+".concat(country.calling_code);
          if (normalizedValue.startsWith(countryDialCode)) {
            return {
              dialCode: countryDialCode,
              phoneNumber: normalizedValue.slice(countryDialCode.length)
            };
          }
        }

        // 如果没有匹配到，使用默认国家
      } catch (err) {
        _iterator.e(err);
      } finally {
        _iterator.f();
      }
      var defaultCountryOption = countries.find(function (c) {
        return c.code === effectiveDefaultCountry;
      }) || countries[0];
      return {
        dialCode: "+".concat(defaultCountryOption.calling_code),
        phoneNumber: normalizedValue.startsWith('+') ? normalizedValue.slice(1) : normalizedValue
      };
    }, [normalizedValue, countries, effectiveDefaultCountry]),
    currentDialCode = _useMemo.dialCode,
    currentPhoneNumber = _useMemo.phoneNumber;

  // 当前选中的国家/地区
  var currentCountry = useMemo(function () {
    return countries.find(function (c) {
      return "+".concat(c.calling_code) === currentDialCode;
    }) || countries[0];
  }, [currentDialCode, countries]);

  // 格式化输出值（根据 valueFormat 返回字符串或对象）
  var formatOutputValue = function formatOutputValue(dialCode, phoneNumber) {
    var fullString = "".concat(dialCode).concat(phoneNumber);
    if (valueFormat === 'object') {
      // 对象格式：{ phone: "13800138000", country_calling_code: "86" }
      // 确保返回的数据都是字符串格式
      return {
        phone: String(phoneNumber || ''),
        country_calling_code: String(dialCode.replace('+', '') || '') // 去掉 + 号并确保是字符串
      };
    }

    // 字符串格式："+8613800138000"
    return fullString;
  };

  // 处理区号变化
  var handleDialCodeChange = function handleDialCodeChange(e) {
    var newDialCode = e.target.value;
    var newValue = formatOutputValue(newDialCode, currentPhoneNumber);
    onChange === null || onChange === void 0 || onChange(newValue);
  };

  // 处理手机号输入变化
  var handlePhoneNumberChange = function handlePhoneNumberChange(e) {
    var inputValue = e.target.value;

    // 检测输入值是否包含当前区号前缀（处理浏览器自动填充的情况）
    // 情况1: 输入值以 +86 开头，当前区号也是 +86
    // 情况2: 输入值以 86 开头（无+号），当前区号是 +86
    var dialCodeWithoutPlus = currentDialCode.replace('+', ''); // 去掉 + 号，用于匹配

    // 如果输入值以 + 号开头，检查是否以当前区号开头
    if (inputValue.startsWith('+')) {
      if (inputValue.startsWith(currentDialCode)) {
        // 输入值以当前区号开头，去除区号部分
        inputValue = inputValue.slice(currentDialCode.length);
      }
    } else if (inputValue.startsWith(dialCodeWithoutPlus)) {
      // 输入值以区号数字开头（无+号），去除区号部分
      inputValue = inputValue.slice(dialCodeWithoutPlus.length);
    }

    // 只保留数字
    var newPhoneNumber = inputValue.replace(/[^\d]/g, '');
    var newValue = formatOutputValue(currentDialCode, newPhoneNumber);
    onChange === null || onChange === void 0 || onChange(newValue);
  };
  return /*#__PURE__*/React.createElement("div", {
    className: "phone-input-wrapper ".concat(className)
  }, /*#__PURE__*/React.createElement("div", {
    className: "phone-input-container"
  }, /*#__PURE__*/React.createElement("div", {
    className: "phone-input-prefix"
  }, /*#__PURE__*/React.createElement("span", {
    className: "phone-input-country-display"
  }, currentCountry === null || currentCountry === void 0 ? void 0 : currentCountry.code, "(", currentDialCode, ")"), /*#__PURE__*/React.createElement("select", {
    className: "phone-input-select",
    value: currentDialCode,
    onChange: handleDialCodeChange,
    disabled: disabled
  }, countries.map(function (country) {
    return /*#__PURE__*/React.createElement("option", {
      key: country.code,
      value: "+".concat(country.calling_code)
    }, country.code, " +", country.calling_code);
  })), /*#__PURE__*/React.createElement("svg", {
    className: "phone-input-arrow",
    width: "12",
    height: "12",
    viewBox: "0 0 12 12",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg"
  }, /*#__PURE__*/React.createElement("path", {
    d: "M3 4.5L6 7.5L9 4.5",
    stroke: "currentColor",
    strokeWidth: "1.5",
    strokeLinecap: "round",
    strokeLinejoin: "round"
  }))), /*#__PURE__*/React.createElement("div", {
    className: "phone-input-divider"
  }), /*#__PURE__*/React.createElement("input", {
    type: "tel",
    className: "phone-input-field phone-input-field-".concat(size),
    value: currentPhoneNumber,
    onChange: handlePhoneNumberChange,
    onKeyDown: onKeyDown,
    placeholder: effectivePlaceholder,
    disabled: disabled,
    autoComplete: "tel"
  })));
}
export default PhoneInput;