export class ChessClock {
  constructor(timeMs, incrementMs = 0) {
    this.initial = timeMs;
    this.increment = incrementMs;
    this.white = timeMs;
    this.black = timeMs;
    this.running = null;
    this.interval = null;
    this.lastTick = null;
    this.onTick = null;
    this.onFlag = null;
  }

  start(color) {
    this.stop();
    this.running = color;
    this.lastTick = performance.now();
    const tick = () => {
      const now = performance.now();
      const elapsed = now - this.lastTick;
      this.lastTick = now;
      if (this.running === 'w') {
        this.white -= elapsed;
        if (this.white <= 0) { this.white = 0; this.stop(); this.onFlag?.('w'); return; }
      } else {
        this.black -= elapsed;
        if (this.black <= 0) { this.black = 0; this.stop(); this.onFlag?.('b'); return; }
      }
      this.onTick?.(this.white, this.black);
    };
    this.interval = setInterval(tick, 100);
  }

  switch() {
    if (!this.running) return;
    if (this.running === 'w') {
      this.white += this.increment;
      this.start('b');
    } else {
      this.black += this.increment;
      this.start('w');
    }
  }

  stop() {
    if (this.interval) {
      clearInterval(this.interval);
      this.interval = null;
    }
    this.running = null;
  }

  getTime(color) {
    return color === 'w' ? this.white : this.black;
  }

  format(ms) {
    if (ms <= 0) return '0:00';
    const totalSec = Math.ceil(ms / 1000);
    const m = Math.floor(totalSec / 60);
    const s = totalSec % 60;
    if (m >= 60) {
      const h = Math.floor(m / 60);
      return `${h}:${(m % 60).toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`;
    }
    return `${m}:${s.toString().padStart(2, '0')}`;
  }

  isLowTime(color, thresholdMs = 30000) {
    return this.getTime(color) < thresholdMs;
  }

  destroy() {
    this.stop();
    this.onTick = null;
    this.onFlag = null;
  }
}

export function parseTimeControl(key) {
  const match = key.match(/(\w+)_(\d+)_(\d+)/);
  if (!match) return { time: 600000, increment: 0 };
  const minutes = parseInt(match[2]);
  const inc = parseInt(match[3]);
  return { time: minutes * 60 * 1000, increment: inc * 1000 };
}
