import analytics from './index'
import { CONTENT_EVENTS } from '../../constants/events'

/**
 * 阅读时长追踪器
 * 精确追踪用户阅读行为，包括：
 * - 有效阅读时长（排除切后台、锁屏等无效时间）
 * - 阅读进度
 * - 阅读完成判断
 */
class ReadingTracker {
  constructor() {
    // 当前追踪的内容
    this.content = null
    // 开始阅读时间
    this.startTime = null
    // 累计阅读时长（毫秒）
    this.totalDuration = 0
    // 最后活跃时间
    this.lastActiveTime = null
    // 是否正在阅读
    this.isReading = false
    // 阅读进度（百分比）
    this.progress = 0
    // 内容总高度
    this.contentHeight = 0
    // 已滚动的最大位置
    this.maxScrollPosition = 0
    // 心跳定时器
    this.heartbeatTimer = null
    // 心跳间隔（毫秒）
    this.heartbeatInterval = 5000
  }

  /**
   * 开始阅读追踪
   * @param {object} content - 内容信息
   */
  start(content) {
    this.content = {
      id: content.id,
      title: content.title,
      category: content.category || '',
      author: content.author || '',
      publishTime: content.publishTime || '',
      wordCount: content.wordCount || 0,
    }

    this.startTime = Date.now()
    this.lastActiveTime = Date.now()
    this.totalDuration = 0
    this.isReading = true
    this.progress = 0
    this.maxScrollPosition = 0

    // 启动心跳
    this._startHeartbeat()

    console.log('[ReadingTracker] Started tracking:', this.content.title)
  }

  /**
   * 暂停阅读（切后台、跳转页面等）
   */
  pause() {
    if (!this.isReading) return

    // 累计有效阅读时长
    if (this.lastActiveTime) {
      this.totalDuration += Date.now() - this.lastActiveTime
    }

    this.isReading = false
    this._stopHeartbeat()

    console.log('[ReadingTracker] Paused, duration:', this.totalDuration)
  }

  /**
   * 恢复阅读
   */
  resume() {
    if (this.isReading) return
    if (!this.content) return

    this.lastActiveTime = Date.now()
    this.isReading = true
    this._startHeartbeat()

    console.log('[ReadingTracker] Resumed')
  }

  /**
   * 结束阅读追踪并上报
   * @param {string} exitType - 退出类型：normal/back/close
   */
  end(exitType = 'normal') {
    if (!this.content) return null

    // 如果还在阅读状态，先暂停
    if (this.isReading) {
      this.pause()
    }

    // 计算最终阅读时长（秒）
    const durationSeconds = Math.floor(this.totalDuration / 1000)

    // 判断是否完成阅读
    const isCompleted = this._isReadingCompleted(durationSeconds)

    // 上报阅读事件
    const eventData = {
      news_id: this.content.id,
      news_title: this.content.title,
      news_category: this.content.category,
      news_author: this.content.author,
      reading_duration: durationSeconds,
      reading_duration_range: this._getDurationRange(durationSeconds),
      reading_progress: this.progress,
      is_completed: isCompleted,
      exit_type: exitType,
      word_count: this.content.wordCount,
    }

    analytics.track(CONTENT_EVENTS.NEWS_VIEWED, eventData)

    // 如果完成阅读，额外上报完成事件
    if (isCompleted) {
      analytics.track(CONTENT_EVENTS.NEWS_READ_COMPLETED, eventData)
    }

    console.log('[ReadingTracker] Ended:', eventData)

    // 重置状态
    const result = { ...eventData }
    this._reset()

    return result
  }

  /**
   * 更新阅读进度
   * @param {number} scrollTop - 滚动位置
   * @param {number} viewportHeight - 可视区域高度
   */
  updateProgress(scrollTop, viewportHeight) {
    if (!this.contentHeight || !this.isReading) return

    // 更新最大滚动位置
    const currentPosition = scrollTop + viewportHeight
    if (currentPosition > this.maxScrollPosition) {
      this.maxScrollPosition = currentPosition
    }

    // 计算阅读进度
    this.progress = Math.min(100, Math.round((this.maxScrollPosition / this.contentHeight) * 100))

    // 更新活跃时间
    this.lastActiveTime = Date.now()
  }

  /**
   * 设置内容高度
   */
  setContentHeight(height) {
    this.contentHeight = height
  }

  /**
   * 获取当前阅读时长（秒）
   */
  getCurrentDuration() {
    let duration = this.totalDuration
    if (this.isReading && this.lastActiveTime) {
      duration += Date.now() - this.lastActiveTime
    }
    return Math.floor(duration / 1000)
  }

  /**
   * 启动心跳
   */
  _startHeartbeat() {
    this._stopHeartbeat()
    this.heartbeatTimer = setInterval(() => {
      if (this.isReading) {
        // 定期更新活跃时间，确保时长统计准确
        this.lastActiveTime = Date.now()
      }
    }, this.heartbeatInterval)
  }

  /**
   * 停止心跳
   */
  _stopHeartbeat() {
    if (this.heartbeatTimer) {
      clearInterval(this.heartbeatTimer)
      this.heartbeatTimer = null
    }
  }

  /**
   * 判断是否完成阅读
   * 规则：阅读进度>=80% 或 阅读时长>=预估阅读时间的60%
   */
  _isReadingCompleted(durationSeconds) {
    // 进度判断
    if (this.progress >= 80) return true

    // 时长判断（假设阅读速度为300字/分钟）
    if (this.content.wordCount) {
      const estimatedReadTime = (this.content.wordCount / 300) * 60 // 秒
      if (durationSeconds >= estimatedReadTime * 0.6) return true
    }

    // 最低阅读时长判断（超过60秒视为有效阅读）
    if (durationSeconds >= 60 && this.progress >= 50) return true

    return false
  }

  /**
   * 获取阅读时长范围
   */
  _getDurationRange(seconds) {
    if (seconds < 10) return '0-10s'
    if (seconds < 30) return '10-30s'
    if (seconds < 60) return '30-60s'
    if (seconds < 180) return '1-3min'
    if (seconds < 300) return '3-5min'
    if (seconds < 600) return '5-10min'
    return '10min+'
  }

  /**
   * 重置状态
   */
  _reset() {
    this._stopHeartbeat()
    this.content = null
    this.startTime = null
    this.totalDuration = 0
    this.lastActiveTime = null
    this.isReading = false
    this.progress = 0
    this.contentHeight = 0
    this.maxScrollPosition = 0
  }
}

// 导出单例
export default new ReadingTracker()