// TitleScene：标题 + 名字输入（留空默认「小满」）。DOM input，不依赖 localStorage。

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

export class TitleScene extends Phaser.Scene {
  private overlay: HTMLDivElement | null = null;

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

  create(): void {
    this.cameras.main.setBackgroundColor('#8FD3FF');
    // 糖果色标题卡
    this.add.rectangle(160, 70, 240, 64, 0xfff3d6).setStrokeStyle(2, 0xf5a623);
    this.add.text(160, 58, '崩坏童话', { fontFamily: 'monospace', fontSize: '20px', color: '#8B5A2B' }).setOrigin(0.5);
    this.add.text(160, 84, '蜜 糖 村', { fontFamily: 'monospace', fontSize: '14px', color: '#F5A623' }).setOrigin(0.5);
    this.add.text(160, 120, 'WASD / 方向键移动 · E 互动', { fontFamily: 'monospace', fontSize: '8px', color: '#5c4a2e' }).setOrigin(0.5);

    // DOM 输入框（名字仅存于本次会话内存）
    const parent = document.getElementById('game') ?? document.body;
    const overlay = document.createElement('div');
    overlay.style.cssText = 'position:absolute;left:50%;top:58%;transform:translateX(-50%);display:flex;gap:6px;align-items:center;z-index:10;';
    const label = document.createElement('span');
    label.textContent = '名字：';
    label.style.cssText = 'color:#FFF3D6;font:12px monospace;';
    const input = document.createElement('input');
    input.type = 'text';
    input.maxLength = 8;
    input.placeholder = '小满';
    input.style.cssText = 'width:80px;font:12px monospace;background:#FFF3D6;border:2px solid #F5A623;color:#5c4a2e;outline:none;';
    const btn = document.createElement('button');
    btn.textContent = '开始';
    btn.style.cssText = 'font:12px monospace;background:#F5A623;border:none;color:#fff;padding:2px 8px;cursor:pointer;';
    overlay.append(label, input, btn);
    parent.appendChild(overlay);
    this.overlay = overlay;
    input.focus();

    const start = (): void => {
      const name = input.value.trim() || '小满';
      director.newGame(name);
      overlay.remove();
      this.overlay = null;
      this.scene.start('HouseScene', { spawn: 'default' });
    };
    btn.addEventListener('click', start);
    input.addEventListener('keydown', (e) => {
      if (e.key === 'Enter') start();
      e.stopPropagation();
    });

    this.events.once('shutdown', () => {
      if (this.overlay) {
        this.overlay.remove();
        this.overlay = null;
      }
    });
  }
}
