/**
 * 倒计时触发器工具类 (终极修复版)
 */
export default class CountdownTimer {
  constructor(options) {
    this.targetSeconds = options.targetSeconds || 0;
    this.onTargetReached = options.onTargetReached || (() => {});

    this.elapsedTime = 0;
    this.isRunning = false;
    this.isTriggered = false;
    this.isPageVisible = true;
    this.isManualPaused = false;
    this.timerId = null;
    this.startTimeStamp = 0;

    this._handleVisibilityChange = this._handleVisibilityChange.bind(this);
    document.addEventListener('visibilitychange', this._handleVisibilityChange);
  }

  getElapsedSeconds() {
    return this.elapsedTime;
  }

  /**
   * 内部核心：启动定时器 (仅处理定时器引擎，不处理状态守卫)
   */
  _startEngine() {
    this.startTimeStamp = Date.now() - this.elapsedTime * 1000;
    this.timerId = setInterval(() => {
      const now = Date.now();
      const rawElapsed = (now - this.startTimeStamp) / 1000;
      const newElapsed = Math.floor(rawElapsed);

      if (rawElapsed >= this.targetSeconds) {
        this.elapsedTime = this.targetSeconds;
        this._trigger();
      } else {
        this.elapsedTime = newElapsed;
      }
    }, 1000);
  }

  /**
   * 内部核心：停止定时器 (仅处理定时器引擎)
   */
  _stopEngine() {
    clearInterval(this.timerId);
    this.timerId = null;
  }

  /**
   * 启动/继续计时
   */
  start() {
    if (this.isTriggered || this.isRunning) return;
    if (!this.isManualPaused && !this.isPageVisible) return;

    this.isRunning = true;
    this.isManualPaused = false;
    this._startEngine();
  }

  /**
   * 手动暂停计时
   */
  pause() {
    if (!this.isRunning) return;
    this.isRunning = false;
    this.isManualPaused = true;
    this._stopEngine();
  }

  /**
   * ⚠️ 终极修复：切换暂停/继续状态（二合一）
   * 直接操作底层状态，绕过 start/pause 的守卫逻辑，确保 100% 生效
   */
  toggle() {
    if (this.isTriggered) return;

    if (this.isRunning) {
      // 强制暂停
      this.isRunning = false;
      this.isManualPaused = true;
      this._stopEngine();
    } else {
      // 强制继续
      this.isRunning = true;
      this.isManualPaused = false;
      this._startEngine();
    }
  }

  resetAndStart(newOptions) {
    this._stopEngine();
    this.isRunning = false;
    this.isManualPaused = false;

    document.removeEventListener('visibilitychange', this._handleVisibilityChange);

    this.targetSeconds = newOptions.targetSeconds || 0;
    this.onTargetReached = newOptions.onTargetReached || (() => {});

    this.elapsedTime = 0;
    this.isTriggered = false;
    this.isPageVisible = true;

    document.addEventListener('visibilitychange', this._handleVisibilityChange);

    this.isRunning = true;
    this._startEngine();
  }

  clear() {
    this._stopEngine();
    this.isRunning = false;
    this.isManualPaused = false;
    this.elapsedTime = 0;
    this.isTriggered = false;

    document.removeEventListener('visibilitychange', this._handleVisibilityChange);
    this.onTargetReached = null;
  }

  _trigger() {
    this._stopEngine();
    this.isRunning = false;
    this.isManualPaused = false;
    this.isTriggered = true;
    this.onTargetReached(this.elapsedTime);
  }

  _handleVisibilityChange() {
    if (this.isTriggered) return;

    if (document.hidden) {
      this.isPageVisible = false;
      if (this.isRunning) {
        this.isRunning = false;
        this._stopEngine();
      }
    } else {
      this.isPageVisible = true;
      if (!this.isManualPaused && !this.isRunning) {
        this.isRunning = true;
        this._startEngine();
      }
    }
  }

  destroy() {
    this.clear();
  }
}
