// TitleScene.ts: title screen + name entry (default 小满).
import Phaser from 'phaser';
import { director } from '../systems/CorruptionDirector';
import { DEFAULT_NAME } from '../data/gamedata';
import { audio } from '../systems/AudioEngine';

export class TitleScene extends Phaser.Scene {
  nameText = '';
  constructor() { super('TitleScene'); }

  create() {
    director.reset();
    this.cameras.main.setBackgroundColor('#1a1410');

    const cx = 160;
    // title
    this.add.text(cx, 50, '崩坏童话', { fontFamily: 'monospace', fontSize: '20px', color: '#ffd86b' }).setOrigin(0.5);
    this.add.text(cx, 74, '蜜糖村', { fontFamily: 'monospace', fontSize: '14px', color: '#ffe9b0' }).setOrigin(0.5);
    this.add.text(cx, 100, '—— 纯单机网页游戏 ——', { fontFamily: 'monospace', fontSize: '8px', color: '#9a8f80' }).setOrigin(0.5);

    // name prompt
    this.add.text(cx, 124, '输入你的名字（留空默认 小满）：', { fontFamily: 'monospace', fontSize: '9px', color: '#d8d0c0' }).setOrigin(0.5);
    const nameBox = this.add.text(cx, 140, DEFAULT_NAME, { fontFamily: 'monospace', fontSize: '12px', color: '#ffffff' }).setOrigin(0.5);
    this.add.rectangle(cx, 140, 120, 14).setStrokeStyle(1, 0x6a5a48).setOrigin(0.5);

    const startHint = this.add.text(cx, 162, '按 回车 开始 · 退格删除', { fontFamily: 'monospace', fontSize: '8px', color: '#7a7060' }).setOrigin(0.5);

    this.nameText = '';

    this.input.keyboard!.on('keydown', (e: KeyboardEvent) => {
      if (e.key === 'Enter') {
        const name = this.nameText.trim() || DEFAULT_NAME;
        director.playerName = name;
        audio.init(); audio.startMusic();
        this.scene.start('HouseScene', { spawn: 'default' });
        this.scene.launch('UIScene');
        this.scene.launch('DebugScene');
        return;
      }
      if (e.key === 'Backspace') {
        this.nameText = this.nameText.slice(0, -1);
      } else if (e.key.length === 1 && this.nameText.length < 8) {
        // accept printable; allow CJK via composition not supported simply, but single chars ok
        this.nameText += e.key;
      }
      nameBox.setText(this.nameText || DEFAULT_NAME);
    });

    // blink hint
    this.time.addEvent({ delay: 600, loop: true, callback: () => { startHint.alpha = startHint.alpha > 0.5 ? 0.3 : 1; } });
  }
}
