// GameOver — score + best + restart.
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);
    }
    this.cameras.main.setBackgroundColor(window.GAME.BG_COLOR);
    this.add.rectangle(W / 2, H / 2, W, H, 0x000000, 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 = this.add.text(W / 2, H * 0.3, 'GAME OVER', {
      fontFamily: 'Arial', fontSize: '44px', fontStyle: 'bold', color: '#fff',
      stroke: '#000', strokeThickness: 6,
    }).setOrigin(0.5);
    title.setScale(0);
    this.tweens.add({ targets: title, scale: 1, duration: 400, ease: 'Back.easeOut' });

    this.add.text(W / 2, H * 0.45, 'SCORE  ' + this.finalScore, {
      fontFamily: 'Arial', fontSize: '30px', color: '#fff',
    }).setOrigin(0.5);

    this.add.text(W / 2, H * 0.52, (isNewBest ? 'NEW BEST!  ' : 'BEST  ') + best, {
      fontFamily: 'Arial', fontSize: '24px', fontStyle: 'bold',
      color: isNewBest ? window.GAME.ACCENT : '#9aa',
    }).setOrigin(0.5);

    if (isNewBest) Juice.burstParticles(this, W / 2, H * 0.52, Phaser.Display.Color.HexStringToColor(window.GAME.ACCENT).color, 26);

    const btn = this.add.rectangle(W / 2, H * 0.7, 240, 64, 0xffffff, 0.08)
      .setStrokeStyle(3, Phaser.Display.Color.HexStringToColor(window.GAME.ACCENT).color)
      .setInteractive({ useHandCursor: true });
    const btnText = this.add.text(W / 2, H * 0.7, 'PLAY AGAIN', {
      fontFamily: 'Arial', fontSize: '26px', fontStyle: 'bold', color: '#fff',
    }).setOrigin(0.5);
    this.tweens.add({ targets: [btn, btnText], scale: 1.06, duration: 800, yoyo: true, repeat: -1, ease: 'Sine.easeInOut' });

    const restart = () => {
      window.Audio.sfx('start');
      this.cameras.main.fade(220, 0, 0, 0);
      this.time.delayedCall(230, () => this.scene.start('Game'));
    };
    btn.on('pointerdown', restart);
    this.input.keyboard.on('keydown-SPACE', restart);
    this.input.keyboard.on('keydown-ENTER', restart);

    this.add.text(W / 2, H * 0.85, 'Space / Enter / tap to retry', {
      fontFamily: 'Arial', fontSize: '14px', color: '#778',
    }).setOrigin(0.5);
  }
};
