import { Scene } from 'phaser';
import { sound } from '../managers/SoundManager.js';
import { createButton } from '../utils/ui.js';
import { todaySeed } from '../utils/random.js';
import { currentBgTexture } from '../utils/background.js';

export class GameOverScene extends Scene {
  constructor() {
    super({ key: 'GameOverScene' });
  }

  init(data) {
    this.finalScore = data.score || 0;
    this.blockHeight = data.blockHeight || 0;
    this.isNewBest = data.isNewBest || false;
    this.mode = data.mode || 'normal';
    this.dailyBest = data.dailyBest;
  }

  retry() {
    sound.click();
    if (this.mode === 'daily') {
      this.scene.start('GameScene', { mode: 'daily', seed: todaySeed() });
    } else {
      this.scene.start('GameScene', { mode: 'normal' });
    }
  }

  create() {
    const { width, height } = this.scale;

    this.add.tileSprite(width / 2, height / 2, width, height, currentBgTexture());

    const naddie = this.add.image(width / 2, height * 0.22, 'player_dead').setScale(0.32);
    this.tweens.add({ targets: naddie, angle: -10, duration: 2000, yoyo: true, repeat: -1, ease: 'Sine.easeInOut' });

    this.add.text(width / 2, height * 0.38, 'GAME OVER', {
      fontFamily: '"Press Start 2P", monospace',
      fontSize: '32px',
      color: '#ef4444',
      align: 'center',
    }).setOrigin(0.5).setShadow(3, 3, '#7f1d1d', 0, false, true);

    if (this.isNewBest) {
      const best = this.add.text(width / 2, height * 0.46, 'NEW BEST!', {
        fontFamily: '"Press Start 2P", monospace',
        fontSize: '14px',
        color: '#22c55e',
      }).setOrigin(0.5);
      this.tweens.add({ targets: best, scale: 1.15, duration: 600, yoyo: true, repeat: -1, ease: 'Sine.easeInOut' });
    }

    this.add.text(width / 2, height * 0.54, `Block Height: ${this.blockHeight}`, {
      fontFamily: '"Press Start 2P", monospace',
      fontSize: '13px',
      color: '#d8b4fe',
    }).setOrigin(0.5);

    this.add.text(width / 2, height * 0.61, `Gas Score: ${this.finalScore}`, {
      fontFamily: '"Press Start 2P", monospace',
      fontSize: '16px',
      color: '#a855f7',
    }).setOrigin(0.5);

    if (this.mode === 'daily') {
      this.add.text(width / 2, height * 0.665, `DAILY · Today's Best: ${this.dailyBest ?? this.finalScore}`, {
        fontFamily: '"Press Start 2P", monospace',
        fontSize: '10px',
        color: '#ffd700',
      }).setOrigin(0.5);
    }

    createButton(this, width / 2, height * 0.72, 'RETRY', () => this.retry());
    createButton(this, width / 2, height * 0.82, 'MAIN MENU', () => this.scene.start('MenuScene'));

    this.add.text(width / 2, height * 0.92, 'ON-CHAIN SUBMIT — COMING SOON', {
      fontFamily: '"Press Start 2P", monospace',
      fontSize: '9px',
      color: '#666',
      align: 'center',
    }).setOrigin(0.5);

    this.input.keyboard.once('keydown-ENTER', () => this.retry());
    this.input.keyboard.once('keydown-SPACE', () => this.retry());
  }
}
