import Phaser from 'phaser';
import { audio } from '../AudioDirector';
import { director } from '../CorruptionDirector';

export class TitleScene extends Phaser.Scene {
  private form?: Phaser.GameObjects.DOMElement;

  constructor() { super('TitleScene'); }

  create(): void {
    this.cameras.main.setBackgroundColor('#79cce4');
    const background = this.add.tileSprite(160, 90, 320, 180, 'tiles', 0).setTint(0x72c85a);
    background.tileScaleX = 1; background.tileScaleY = 1;
    this.add.rectangle(160, 38, 286, 58, 0xffe8a4, 0.92).setStrokeStyle(3, 0x5b362b);
    this.add.text(160, 24, '崩坏童话：蜜糖村', {
      fontFamily: '"Courier New", "PingFang SC", monospace', fontSize: '19px', fontStyle: 'bold', color: '#57342b',
    }).setOrigin(0.5).setShadow(2, 2, '#e99a3b', 0, true, true);
    this.add.text(160, 48, '每一天都很幸福。', {
      fontFamily: '"Courier New", "PingFang SC", monospace', fontSize: '8px', fontStyle: 'bold', color: '#8d4f33',
    }).setOrigin(0.5);
    [0, 1, 2, 3, 4].forEach((index) => this.add.sprite(112 + index * 24, 76, 'characters', 37 + index).setScale(1));
    const html = `<form class="name-form"><label for="player-name">你的名字</label><input id="player-name" maxlength="12" placeholder="小满" autocomplete="off"><button type="submit">进入蜜糖村</button></form>`;
    this.form = this.add.dom(160, 119).createFromHTML(html);
    const node = this.form.node as HTMLFormElement;
    node.addEventListener('submit', (event) => {
      event.preventDefault();
      const input = node.querySelector<HTMLInputElement>('#player-name');
      this.startGame(input?.value ?? '');
    });
    this.input.keyboard?.once('keydown-ENTER', () => {
      const input = node.querySelector<HTMLInputElement>('#player-name');
      this.startGame(input?.value ?? '');
    });
  }

  private startGame(name: string): void {
    if (!this.form?.active) return;
    audio.unlock();
    director.reset(name);
    this.form.destroy();
    this.scene.start('HouseScene', { spawn: 'default' });
    this.scene.launch('UIScene');
    this.scene.bringToTop('UIScene');
  }
}
