/**
 * 安全中心相关纯函数
 *
 * 从 security-center-card.tsx 抽出，便于单元测试。
 */

/**
 * 解析 User-Agent 字符串，返回设备类型和浏览器类型
 */
export function parseUserAgent(ua: string | null): {
  device: string
  browser: string
} {
  if (!ua) return { device: "Unknown", browser: "Unknown" }
  const device = /Mobile|Android|iPhone/i.test(ua)
    ? "Mobile"
    : /iPad|Tablet/i.test(ua)
      ? "Tablet"
      : "Desktop"
  let browser = "Unknown"
  if (/Edg\//i.test(ua)) browser = "Edge"
  else if (/Chrome\//i.test(ua)) browser = "Chrome"
  else if (/Firefox\//i.test(ua)) browser = "Firefox"
  else if (/Safari\//i.test(ua)) browser = "Safari"
  return { device, browser }
}

/**
 * 将 ISO 时间字符串格式化为相对时间（如"刚刚"、"5 分钟前"）
 */
export function formatRelativeTime(iso: string, locale: string): string {
  const date = new Date(iso)
  const now = Date.now()
  const diffMs = now - date.getTime()
  const diffMin = Math.floor(diffMs / 60000)
  const diffHour = Math.floor(diffMin / 60)
  const diffDay = Math.floor(diffHour / 24)

  const rtf = new Intl.RelativeTimeFormat(locale, { numeric: "auto" })
  if (diffMin < 1) return locale === "zh" ? "刚刚" : "just now"
  if (diffMin < 60) return rtf.format(-diffMin, "minute")
  if (diffHour < 24) return rtf.format(-diffHour, "hour")
  if (diffDay < 30) return rtf.format(-diffDay, "day")
  return date.toLocaleDateString(locale)
}
