import { storage, KEYS } from '../utils/storage.js';

const DEFAULTS = {
  gamesPlayed: 0,
  totalJumps: 0,
  totalStomps: 0,
  totalBlocks: 0,
  bestCombo: 0,
};

/**
 * Persistent lifetime stats. One instance per run accumulates a snapshot and
 * flushes it into the stored totals at game over.
 */
export class StatsManager {
  constructor() {
    this.run = { jumps: 0, stomps: 0, bestCombo: 0 };
  }

  static load() {
    const saved = storage.getJSON(KEYS.stats, null);
    return { ...DEFAULTS, ...(saved || {}) };
  }

  static reset() {
    storage.setJSON(KEYS.stats, { ...DEFAULTS });
  }

  onJump() {
    this.run.jumps += 1;
  }

  onStomp() {
    this.run.stomps += 1;
  }

  onCombo(multiplier) {
    if (multiplier > this.run.bestCombo) this.run.bestCombo = multiplier;
  }

  /** Merge this run into lifetime totals. Call once at game over. */
  flush(blockHeight) {
    const t = StatsManager.load();
    t.gamesPlayed += 1;
    t.totalJumps += this.run.jumps;
    t.totalStomps += this.run.stomps;
    t.totalBlocks += blockHeight || 0;
    t.bestCombo = Math.max(t.bestCombo, this.run.bestCombo);
    storage.setJSON(KEYS.stats, t);
    return t;
  }
}
