/**
 * H5 对话页纯展示工具函数（无副作用、无 DOM 依赖，便于单测）。
 */

/** 相对时间格式化 */
export function formatRelativeTime(iso: string): string {
  const date = new Date(iso)
  const now = new Date()
  const diffMs = now.getTime() - date.getTime()
  const diffSec = Math.floor(diffMs / 1000)
  const diffMin = Math.floor(diffSec / 60)
  const diffHour = Math.floor(diffMin / 60)
  const diffDay = Math.floor(diffHour / 24)

  if (diffDay >= 7) {
    const month = date.getMonth() + 1
    const day = date.getDate()
    return `${month}-${day}`
  }
  if (diffDay === 1) return '昨天'
  if (diffDay > 1) return `${diffDay}天前`
  if (diffHour > 0) return `${diffHour}小时前`
  if (diffMin > 0) return `${diffMin}分钟前`
  return '刚刚'
}

/**
 * Format file size bytes → human-readable string.
 * Returns empty string for 0 (user uploads without size info).
 */
export function formatFileSize(size: number): string {
  if (!size || size <= 0) return ''
  if (size > 1024 * 1024) return `${(size / 1024 / 1024).toFixed(1)} MB`
  if (size > 1024) return `${(size / 1024).toFixed(0)} KB`
  return `${size} B`
}

/** parseStreamingMedia 的返回结构。 */
export interface ParsedStreamingMedia {
  displayText: string
  pendingFiles: { name: string }[]
}

/**
 * Parse streaming text: strip MEDIA: lines (they'll become file cards on done)
 * and extract pending file names for loading placeholders.
 * Prevents raw "MEDIA:/path" flicker during streaming.
 */
export function parseStreamingMedia(text: string): ParsedStreamingMedia {
  const pendingFiles: { name: string }[] = []
  const cleanedLines: string[] = []
  for (const line of text.split('\n')) {
    const trimmed = line.trim()
    if (trimmed.startsWith('MEDIA:')) {
      const filePath = trimmed.slice(6).trim()
      if (filePath) {
        pendingFiles.push({ name: filePath.replace(/^.*[\\/]/, '') })
      }
    } else {
      cleanedLines.push(line)
    }
  }
  const displayText = cleanedLines.join('\n').replace(/\n{3,}/g, '\n\n').trimEnd()
  return { displayText, pendingFiles }
}

/**
 * 判断智能体头像值是否为图片 URL（http(s)://、站点相对路径 /、data:image）。
 * 非 URL（如 emoji 字符）返回 false，用于在欢迎卡片里区分 <img> 与文本渲染。
 */
export function isImageUrl(v: string): boolean {
  const s = v.trim()
  return (
    s.startsWith('http://') ||
    s.startsWith('https://') ||
    s.startsWith('/') ||
    s.startsWith('data:image')
  )
}
