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

export class ScoreManager {
  constructor(scene) {
    this.scene = scene;
    this.score = 0;
    this.blockHeight = 0;
    this.combo = 0;
    this.comboMultiplier = 1;
    this.genesisActive = false;
    this.genesisJumps = 0;

    this.hudBg = scene.add.rectangle(10, 10, 200, 90, 0x000000, 0.5)
      .setOrigin(0)
      .setScrollFactor(0)
      .setDepth(200);

    this.hudScore = scene.add.text(16, 16, 'Gas: 0', {
      fontFamily: '"Press Start 2P", monospace',
      fontSize: '14px',
      color: '#d8b4fe',
    }).setOrigin(0).setScrollFactor(0).setDepth(200).setShadow(1, 1, '#000000', 2, false, true);

    this.hudBlocks = scene.add.text(16, 42, 'Block: 0', {
      fontFamily: '"Press Start 2P", monospace',
      fontSize: '12px',
      color: '#a855f7',
    }).setOrigin(0).setScrollFactor(0).setDepth(200).setShadow(1, 1, '#000000', 2, false, true);

    this.hudCombo = scene.add.text(16, 66, '', {
      fontFamily: '"Press Start 2P", monospace',
      fontSize: '10px',
      color: '#22c55e',
    }).setOrigin(0).setScrollFactor(0).setDepth(200).setShadow(1, 1, '#000000', 2, false, true);

    this.hudBest = scene.add.text(scene.scale.width - 16, 16, 'Best: 0', {
      fontFamily: '"Press Start 2P", monospace',
      fontSize: '9px',
      color: '#aaa',
    }).setOrigin(1, 0).setScrollFactor(0).setDepth(200).setShadow(1, 1, '#000000', 2, false, true);

    // Powerup duration bar (hidden until active)
    this.powerupBarBg = scene.add.rectangle(scene.scale.width / 2, scene.scale.height - 24, 200, 12, 0x000000, 0.6)
      .setStrokeStyle(2, 0xa855f7)
      .setScrollFactor(0).setDepth(200).setVisible(false);
    this.powerupBarFill = scene.add.rectangle(scene.scale.width / 2 - 99, scene.scale.height - 24, 196, 8, 0xa855f7)
      .setOrigin(0, 0.5).setScrollFactor(0).setDepth(201).setVisible(false);
    this.powerupBarLabel = scene.add.text(scene.scale.width / 2, scene.scale.height - 40, '', {
      fontFamily: '"Press Start 2P", monospace',
      fontSize: '9px',
      color: '#d8b4fe',
    }).setOrigin(0.5).setScrollFactor(0).setDepth(201).setVisible(false);

    this.updateBestDisplay();
  }

  update(playerY) {
    const blocks = Math.max(0, Math.floor((this.scene.scale.height - playerY) / 100));
    if (blocks > this.blockHeight) {
      this.blockHeight = blocks;
      this.hudBlocks.setText(`Block: ${this.blockHeight}`);
      if (this.scene.achievements) this.scene.achievements.onBlockHeight(this.blockHeight);

      if (this.blockHeight % 100 === 0 && this.blockHeight > 0) {
        this.showMilestone(this.blockHeight);
      }
    }

    this._updatePowerupBar();
  }

  _updatePowerupBar() {
    const player = this.scene.player;
    if (!player) return;

    let active = null;
    let remaining = 0;
    let total = 0;
    let color = 0xa855f7;
    let label = '';

    if (player.state === 'propeller') {
      active = 'propeller';
      remaining = Math.max(0, player.propellerTimer);
      total = 3500;
      color = 0x44aaff;
      label = 'PROPELLER';
    } else if (player.state === 'rocket') {
      active = 'rocket';
      remaining = Math.max(0, player.rocketTimer);
      total = 3000;
      color = 0xff4444;
      label = 'ROCKET';
    }

    if (active) {
      const pct = remaining / total;
      this.powerupBarBg.setVisible(true);
      this.powerupBarFill.setVisible(true).setFillStyle(color);
      this.powerupBarFill.scaleX = pct;
      this.powerupBarLabel.setVisible(true).setText(label);
    } else {
      this.powerupBarBg.setVisible(false);
      this.powerupBarFill.setVisible(false);
      this.powerupBarLabel.setVisible(false);
    }
  }

  onLand(platformY, platformType) {
    this.combo += 1;
    this.comboMultiplier = Math.min(1 + (this.combo - 1) * SCORE.comboStep, SCORE.comboMax);

    let basePoints = SCORE.basePoints;
    if (platformType === 'genesis') {
      this.genesisActive = true;
      this.genesisJumps = SCORE.genesisJumps;
      basePoints = SCORE.genesisBonus;
    }

    let multiplier = this.comboMultiplier;
    if (this.genesisActive) {
      multiplier *= SCORE.genesisMultiplier;
      this.genesisJumps--;
      if (this.genesisJumps <= 0) this.genesisActive = false;
    }

    const gained = Math.floor(basePoints * multiplier);
    this.addPoints(gained);
    this._spawnScorePopup(gained, platformType === 'genesis');

    if (this.scene.achievements) {
      this.scene.achievements.onPlatformLand(platformType, this.comboMultiplier);
    }
    if (this.scene.stats) {
      this.scene.stats.onCombo(this.comboMultiplier);
    }

    if (this.combo > 1) {
      this.hudCombo.setText(`Combo x${this.comboMultiplier.toFixed(1)}`);
      this.scene.tweens.add({ targets: this.hudCombo, scale: 1.3, duration: 100, yoyo: true });
    }
  }

  _spawnScorePopup(amount, big) {
    const player = this.scene.player;
    if (!player) return;
    const txt = this.scene.add.text(player.x, player.y - 30, `+${amount}`, {
      fontFamily: '"Press Start 2P", monospace',
      fontSize: big ? '14px' : '10px',
      color: big ? '#ffd700' : '#22c55e',
    }).setOrigin(0.5).setDepth(150);
    this.scene.tweens.add({
      targets: txt,
      y: txt.y - 35,
      alpha: 0,
      duration: 700,
      ease: 'Quad.easeOut',
      onComplete: () => txt.destroy(),
    });
  }

  addPoints(amount) {
    this.score += amount;
    this.hudScore.setText(`Gas: ${this.score}`);
    if (this.scene.achievements) this.scene.achievements.onScore(this.score);
  }

  onFall() {
    if (this.combo > 0) {
      this.combo = 0;
      this.comboMultiplier = 1;
      this.hudCombo.setText('');
    }
  }

  showMilestone(blocks) {
    const { width, height } = this.scene.scale;
    const txt = this.scene.add.text(width / 2, height * 0.35, `EPOCH ${blocks} REACHED!`, {
      fontFamily: '"Press Start 2P", monospace',
      fontSize: '20px',
      color: '#ffd700',
    }).setOrigin(0.5).setScrollFactor(0).setDepth(200).setShadow(2, 2, '#7c2d12', 0, false, true);

    this.scene.tweens.add({
      targets: txt,
      scale: 1.5,
      alpha: 0,
      duration: 1800,
      ease: 'Quad.easeOut',
      onComplete: () => txt.destroy(),
    });

    if (this.scene.onMilestone) this.scene.onMilestone(blocks);
  }

  updateBestDisplay() {
    const best = storage.getInt(KEYS.best, 0);
    this.hudBest.setText(`Best: ${best}`);
  }

  saveBest() {
    const best = storage.getInt(KEYS.best, 0);
    if (this.score > best) {
      storage.setItem(KEYS.best, this.score);
      return true;
    }
    return false;
  }

  destroy() {
    this.hudBg.destroy();
    this.hudScore.destroy();
    this.hudBlocks.destroy();
    this.hudCombo.destroy();
    this.hudBest.destroy();
    this.powerupBarBg.destroy();
    this.powerupBarFill.destroy();
    this.powerupBarLabel.destroy();
  }
}
