// GameOver — score + best + restart, built with the UI.* design system.
window.GameOverScene = class GameOverScene extends Phaser.Scene {
  constructor() { super('GameOver'); }

  init(data) { this.finalScore = data.score || 0; }

  create() {
    const W = window.GAME.WIDTH, H = window.GAME.HEIGHT;

    if (this.textures.exists('bg')) {
      this.add.image(W / 2, H / 2, 'bg').setDisplaySize(W, H).setAlpha(0.5);
    } else {
      this.cameras.main.setBackgroundColor(window.GAME.BG_COLOR);
    }
    UI.scrim(this, 0.55);

    // Best score in localStorage
    const prevBest = parseInt(localStorage.getItem(window.GAME.BEST_KEY) || '0', 10);
    const isNewBest = this.finalScore > prevBest;
    const best = Math.max(prevBest, this.finalScore);
    if (isNewBest) localStorage.setItem(window.GAME.BEST_KEY, String(best));

    const title = UI.title(this, W / 2, H * 0.30, 'GAME OVER').setScale(0);
    this.tweens.add({ targets: title, scale: 1, duration: 400, ease: 'Back.easeOut' });

    // Stats in a single frosted panel — aligned, on the grid.
    UI.panel(this, W / 2, H * 0.50, 280, 132, {});
    UI.label(this, W / 2, H * 0.50 - 44, 'SCORE');
    UI.value(this, W / 2, H * 0.50 - 18, this.finalScore, { style: { fontSize: '34px' } });
    UI.label(this, W / 2, H * 0.50 + 16, isNewBest ? 'NEW BEST' : 'BEST');
    UI.value(this, W / 2, H * 0.50 + 40, best, {
      style: { fontSize: '22px', color: isNewBest ? window.GAME.ACCENT : UI.palette.muted },
    });

    if (isNewBest) Juice.burstParticles(this, W / 2, H * 0.50 + 40, UI.hex(window.GAME.ACCENT), 26);

    const restart = () => {
      window.Audio.sfx('start');
      this.cameras.main.fade(220, 0, 0, 0);
      this.time.delayedCall(230, () => this.scene.start('Game'));
    };
    UI.button(this, W / 2, H * 0.70, 240, 64, 'PLAY AGAIN', restart);

    UI.body(this, W / 2, H * 0.84, 'Space / Enter / tap to retry', { style: { fontSize: '13px' } });

    this.input.keyboard.on('keydown-SPACE', restart);
    this.input.keyboard.on('keydown-ENTER', restart);
  }
};
