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

const DEFS = [
  { id: 'genesis_block', title: 'Genesis Block', desc: 'Land on a gold platform' },
  { id: 'chain_reaction', title: 'Chain Reaction', desc: 'Reach combo x3.0' },
  { id: 'bug_hunter', title: 'Bug Hunter', desc: 'Stomp 5 enemies in one run' },
  { id: 'first_flight', title: 'First Flight', desc: 'Use the propeller' },
  { id: 'liftoff', title: 'Liftoff', desc: 'Use the rocket' },
  { id: 'power_trip', title: 'Power Trip', desc: 'Use all 3 power-ups in one run' },
  { id: 'survivor', title: 'Survivor', desc: 'Reach block height 500' },
  { id: 'skyscraper', title: 'Skyscraper', desc: 'Reach block height 1000' },
  { id: 'speedrun', title: 'Speedrun', desc: 'Reach block 100 in under 60s' },
  { id: 'gas_baron', title: 'Gas Baron', desc: 'Score 50,000 in one run' },
];

export class AchievementsManager {
  constructor(scene) {
    this.scene = scene;
    this.unlocked = this._load();
    this.popupQueue = [];
    this.popupActive = false;

    // Per-run counters
    this.bugsStomped = 0;
    this.powerupsUsed = new Set();
    this.startTime = Date.now();
  }

  static getAll() {
    return DEFS;
  }

  _load() {
    return storage.getJSON(KEYS.achievements, {}) || {};
  }

  _save() {
    storage.setJSON(KEYS.achievements, this.unlocked);
  }

  isUnlocked(id) {
    return !!this.unlocked[id];
  }

  unlock(id) {
    if (this.unlocked[id]) return;
    const def = DEFS.find((d) => d.id === id);
    if (!def) return;
    this.unlocked[id] = Date.now();
    this._save();
    this.popupQueue.push(def);
    this._processQueue();
    sound.powerup();
  }

  _processQueue() {
    if (this.popupActive || this.popupQueue.length === 0) return;
    this.popupActive = true;
    const def = this.popupQueue.shift();
    this._showPopup(def, () => {
      this.popupActive = false;
      this._processQueue();
    });
  }

  _showPopup(def, onDone) {
    const { width } = this.scene.scale;
    const y = 110;
    const panel = this.scene.add.rectangle(width / 2, y, 320, 70, 0x1a0533, 0.92)
      .setStrokeStyle(2, 0xffd700)
      .setScrollFactor(0)
      .setDepth(800);
    const title = this.scene.add.text(width / 2, y - 14, `ACHIEVEMENT: ${def.title}`, {
      fontFamily: '"Press Start 2P", monospace',
      fontSize: '10px',
      color: '#ffd700',
    }).setOrigin(0.5).setScrollFactor(0).setDepth(801);
    const desc = this.scene.add.text(width / 2, y + 10, def.desc, {
      fontFamily: '"Press Start 2P", monospace',
      fontSize: '8px',
      color: '#d8b4fe',
    }).setOrigin(0.5).setScrollFactor(0).setDepth(801);

    panel.setAlpha(0);
    title.setAlpha(0);
    desc.setAlpha(0);

    this.scene.tweens.add({
      targets: [panel, title, desc],
      alpha: 1,
      y: `+=10`,
      duration: 250,
      ease: 'Quad.easeOut',
    });

    this.scene.time.delayedCall(2500, () => {
      this.scene.tweens.add({
        targets: [panel, title, desc],
        alpha: 0,
        duration: 350,
        onComplete: () => {
          panel.destroy(); title.destroy(); desc.destroy();
          onDone();
        },
      });
    });
  }

  // --- Game event hooks ---

  onPlatformLand(type, combo) {
    if (type === 'genesis') this.unlock('genesis_block');
    if (combo >= 3) this.unlock('chain_reaction');
  }

  onEnemyStomp() {
    this.bugsStomped += 1;
    if (this.bugsStomped >= 5) this.unlock('bug_hunter');
  }

  onPowerup(name) {
    this.powerupsUsed.add(name);
    if (name === 'propeller') this.unlock('first_flight');
    if (name === 'rocket') this.unlock('liftoff');
    if (this.powerupsUsed.size >= 3) this.unlock('power_trip');
  }

  onBlockHeight(blocks) {
    if (blocks >= 500) this.unlock('survivor');
    if (blocks >= 1000) this.unlock('skyscraper');
    if (blocks >= 100) {
      const elapsed = (Date.now() - this.startTime) / 1000;
      if (elapsed <= 60) this.unlock('speedrun');
    }
  }

  onScore(score) {
    if (score >= 50000) this.unlock('gas_baron');
  }
}
