// 解析版本号为数组，便于比较
function parseVersion(versionString) {
  return versionString.split('.').map(Number);
}

// 比较版本号 (a > b 返回1, a == b返回0, a < b返回-1)
function compareVersions(versionA, versionB) {
  const aParts = parseVersion(versionA);
  const bParts = parseVersion(versionB);
  const maxLength = Math.max(aParts.length, bParts.length);
  
  for (let i = 0; i < maxLength; i++) {
    const a = aParts[i] || 0;
    const b = bParts[i] || 0;
    
    if (a > b) return 1;
    if (a < b) return -1;
  }
  
  return 0;
}

// 获取浏览器信息
function getBrowserInfo() {
  const userAgent = 'mozilla/5.0 (windows nt 10.0; win64; x64) applewebkit/537.36 (khtml, like gecko) chrome/109.0.0.0 safari/537.36' || navigator.userAgent.toLowerCase();
  let browserInfo = {
    name: 'Unknown',
    version: 'Unknown',
    versionParts: []
  };

  // 检测浏览器类型和版本
  if (/edge\/([\d.]+)/.test(userAgent)) {
    browserInfo.name = 'Edge';
    browserInfo.version = userAgent.match(/edge\/([\d.]+)/)[1];
  } else if (/chrome\/([\d.]+)/.test(userAgent) && !/edge/.test(userAgent)) {
    browserInfo.name = 'Chrome';
    browserInfo.version = userAgent.match(/chrome\/([\d.]+)/)[1];
  } else if (/firefox\/([\d.]+)/.test(userAgent)) {
    browserInfo.name = 'Firefox';
    browserInfo.version = userAgent.match(/firefox\/([\d.]+)/)[1];
  } else if (/safari\/([\d.]+)/.test(userAgent) && !/chrome/.test(userAgent)) {
    browserInfo.name = 'Safari';
    // Safari的版本号在version/后面
    browserInfo.version = userAgent.match(/version\/([\d.]+)/)[1];
  } else if (/msie ([\d.]+)/.test(userAgent) || /rv:([\d.]+)/.test(userAgent)) {
    browserInfo.name = 'Internet Explorer';
    browserInfo.version = userAgent.match(/(msie |rv:)([\d.]+)/)[2];
  }

  // 解析版本号为数组
  if (browserInfo.version !== 'Unknown') {
    browserInfo.versionParts = parseVersion(browserInfo.version);
  }
  
  // 添加版本比较方法
  browserInfo.isGreaterThan = function(version) {
    return compareVersions(this.version, version) > 0;
  };
  
  browserInfo.isLessThan = function(version) {
    return compareVersions(this.version, version) < 0;
  };
  
  browserInfo.isEqual = function(version) {
    return compareVersions(this.version, version) === 0;
  };
  
  browserInfo.isGreaterOrEqual = function(version) {
    return compareVersions(this.version, version) >= 0;
  };
  
  browserInfo.isLessOrEqual = function(version) {
    return compareVersions(this.version, version) <= 0;
  };

  return browserInfo;
}

// 使用示例
export const browser = getBrowserInfo();
console.log(`浏览器: ${browser.name} ${browser.version}`);

// 版本比较示例
if (browser.name === 'Chrome') {
  if (browser.isLessThan('90.0.0')) {
    console.log('你的Chrome浏览器版本过低，请升级到90.0.0或更高版本');
  } else {
    console.log('你的Chrome浏览器版本符合要求');
  }
}

if (browser.name === 'Firefox') {
  if (browser.isGreaterOrEqual('88.0')) {
    console.log('你的Firefox浏览器支持最新特性');
  }
}
