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); }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
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 _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
/**
 * 注册登录工具函数
 */

import { VerificationCodeType, OAuthProvider } from "./types";

/**
 * 验证邮箱格式
 */
export function validateEmail(email) {
  var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailRegex.test(email);
}

/**
 * 验证手机号格式（支持多种国际格式）
 */
export function validatePhone(phone) {
  // 移除所有非数字字符（除了 + 号）
  var cleanPhone = phone.replace(/[^\d+]/g, '');

  // 基本的手机号验证规则
  var phoneRegex = /^(\+\d{1,3}[- ]?)?\d{10,14}$/;
  return phoneRegex.test(cleanPhone);
}

/**
 * 验证密码强度
 */
export function validatePassword(password) {
  var errors = [];
  if (password.length < 8) {
    errors.push('密码长度至少为8位');
  }
  if (password.length > 128) {
    errors.push('密码长度不能超过128位');
  }
  if (!/[a-z]/.test(password)) {
    errors.push('密码必须包含至少一个小写字母');
  }
  if (!/[A-Z]/.test(password)) {
    errors.push('密码必须包含至少一个大写字母');
  }
  if (!/\d/.test(password)) {
    errors.push('密码必须包含至少一个数字');
  }
  if (!/[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(password)) {
    errors.push('密码必须包含至少一个特殊字符');
  }
  return {
    isValid: errors.length === 0,
    errors: errors
  };
}

/**
 * 验证验证码格式
 */
export function validateVerificationCode(code, type) {
  // 移除所有空格
  var cleanCode = code.replace(/\s/g, '');
  switch (type) {
    case VerificationCodeType.EMAIL:
    case VerificationCodeType.SMS:
      // 通常是4-8位数字
      return /^\d{4,8}$/.test(cleanCode);
    default:
      return false;
  }
}

/**
 * 格式化手机号显示
 */
export function formatPhoneDisplay(phone) {
  // 移除所有非数字字符（除了 + 号）
  var cleanPhone = phone.replace(/[^\d+]/g, '');

  // 如果是中国手机号（11位数字）
  if (/^\d{11}$/.test(cleanPhone)) {
    return cleanPhone.replace(/(\d{3})(\d{4})(\d{4})/, '$1 $2 $3');
  }

  // 如果是国际号码（以 + 开头）
  if (cleanPhone.startsWith('+')) {
    return cleanPhone;
  }

  // 其他格式保持原样
  return phone;
}

/**
 * 格式化邮箱显示（隐藏部分字符）
 */
export function formatEmailDisplay(email) {
  var maskLength = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 3;
  var _email$split = email.split('@'),
    _email$split2 = _slicedToArray(_email$split, 2),
    localPart = _email$split2[0],
    domain = _email$split2[1];
  if (!localPart || !domain) {
    return email;
  }
  if (localPart.length <= maskLength * 2) {
    return email;
  }
  var visibleStart = localPart.substring(0, maskLength);
  var visibleEnd = localPart.substring(localPart.length - maskLength);
  var maskedPart = '*'.repeat(localPart.length - maskLength * 2);
  return "".concat(visibleStart).concat(maskedPart).concat(visibleEnd, "@").concat(domain);
}

/**
 * 生成随机字符串（用于状态参数等）
 */
export function generateRandomString() {
  var length = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 32;
  var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  var result = '';
  for (var i = 0; i < length; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return result;
}

/**
 * 获取 OAuth 提供商的显示名称
 */
export function getOAuthProviderDisplayName(provider) {
  var displayNames = _defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({}, OAuthProvider.FACEBOOK, 'Facebook'), OAuthProvider.APPLE, 'Apple'), OAuthProvider.GOOGLE, 'Google'), OAuthProvider.WECHAT, '微信'), OAuthProvider.GITHUB, 'GitHub');
  return displayNames[provider] || provider;
}

/**
 * 获取 OAuth 提供商的图标 URL
 */
export function getOAuthProviderIconUrl(provider) {
  var iconUrls = _defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({}, OAuthProvider.FACEBOOK, 'https://cdn.jsdelivr.net/npm/simple-icons@v9/icons/facebook.svg'), OAuthProvider.APPLE, 'https://cdn.jsdelivr.net/npm/simple-icons@v9/icons/apple.svg'), OAuthProvider.GOOGLE, 'https://cdn.jsdelivr.net/npm/simple-icons@v9/icons/google.svg'), OAuthProvider.WECHAT, 'https://cdn.jsdelivr.net/npm/simple-icons@v9/icons/wechat.svg'), OAuthProvider.GITHUB, 'https://cdn.jsdelivr.net/npm/simple-icons@v9/icons/github.svg');
  return iconUrls[provider] || '';
}

/**
 * 检查是否在移动设备上
 */
export function isMobileDevice() {
  if (typeof window === 'undefined') {
    return false;
  }
  return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
}

/**
 * 检查是否支持 WebAuthn
 */
export function isWebAuthnSupported() {
  if (typeof window === 'undefined') {
    return false;
  }
  return !!(navigator.credentials && navigator.credentials.create);
}

/**
 * 检查是否在 iOS 设备上
 */
export function isIOSDevice() {
  if (typeof window === 'undefined') {
    return false;
  }
  return /iPad|iPhone|iPod/.test(navigator.userAgent);
}

/**
 * 检查是否在 Android 设备上
 */
export function isAndroidDevice() {
  if (typeof window === 'undefined') {
    return false;
  }
  return /Android/.test(navigator.userAgent);
}

/**
 * 获取设备类型
 */
export function getDeviceType() {
  if (typeof window === 'undefined') {
    return 'desktop';
  }
  var userAgent = navigator.userAgent;
  if (/iPad/.test(userAgent)) {
    return 'tablet';
  }
  if (/Android|webOS|iPhone|iPod|BlackBerry|IEMobile|Opera Mini/i.test(userAgent)) {
    return 'mobile';
  }
  return 'desktop';
}

/**
 * 防抖函数
 */
export function debounce(func, wait) {
  var timeout = null;
  return function () {
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    if (timeout) {
      clearTimeout(timeout);
    }
    timeout = setTimeout(function () {
      func.apply(void 0, args);
    }, wait);
  };
}

/**
 * 节流函数
 */
export function throttle(func, wait) {
  var lastTime = 0;
  return function () {
    var now = Date.now();
    if (now - lastTime >= wait) {
      lastTime = now;
      func.apply(void 0, arguments);
    }
  };
}

/**
 * 深拷贝对象
 */
export function deepClone(obj) {
  if (obj === null || _typeof(obj) !== 'object') {
    return obj;
  }
  if (obj instanceof Date) {
    return new Date(obj.getTime());
  }
  if (obj instanceof Array) {
    return obj.map(function (item) {
      return deepClone(item);
    });
  }
  if (_typeof(obj) === 'object') {
    var cloned = {};
    for (var key in obj) {
      if (obj.hasOwnProperty(key)) {
        cloned[key] = deepClone(obj[key]);
      }
    }
    return cloned;
  }
  return obj;
}

/**
 * 安全的 JSON 解析
 */
export function safeJsonParse(jsonString, defaultValue) {
  try {
    return JSON.parse(jsonString);
  } catch (error) {
    console.warn('JSON 解析失败:', error);
    return defaultValue;
  }
}

/**
 * 安全的 JSON 字符串化
 */
export function safeJsonStringify(obj) {
  var defaultValue = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '{}';
  try {
    return JSON.stringify(obj);
  } catch (error) {
    console.warn('JSON 字符串化失败:', error);
    return defaultValue;
  }
}

/**
 * 格式化时间戳为可读时间
 */
export function formatTimestamp(timestamp) {
  var format = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'YYYY-MM-DD HH:mm:ss';
  var date = new Date(timestamp);
  var year = date.getFullYear();
  var month = String(date.getMonth() + 1).padStart(2, '0');
  var day = String(date.getDate()).padStart(2, '0');
  var hours = String(date.getHours()).padStart(2, '0');
  var minutes = String(date.getMinutes()).padStart(2, '0');
  var seconds = String(date.getSeconds()).padStart(2, '0');
  return format.replace('YYYY', year.toString()).replace('MM', month).replace('DD', day).replace('HH', hours).replace('mm', minutes).replace('ss', seconds);
}

/**
 * 计算两个时间戳之间的差值（秒）
 */
export function getTimeDifference(timestamp1, timestamp2) {
  return Math.abs(timestamp1 - timestamp2) / 1000;
}

/**
 * 检查时间戳是否过期
 */
export function isTimestampExpired(timestamp) {
  var expirationTime = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 5 * 60 * 1000;
  return Date.now() - timestamp > expirationTime;
}