import Phaser from 'phaser';
import { Director } from '../core/Director';
import { Audio } from '../core/Audio';
import { activateDay } from '../core/quests';

export class TitleScene extends Phaser.Scene {
  private nameInput?: HTMLInputElement;
  constructor() { super('Title'); }

  create() {
    const W = 320, H = 180;
    this.cameras.main.setBackgroundColor('#f6e7b8');
    // sky / ground bands
    const g = this.add.graphics();
    g.fillStyle(0x8fd3f0, 1).fillRect(0, 0, W, 110);
    g.fillStyle(0x7bc86c, 1).fillRect(0, 110, W, 70);
    g.fillStyle(0xf2a94e, 1).fillCircle(260, 40, 22); // sun
    // title
    this.add.text(160, 44, '崩坏童话', { fontFamily: 'serif', fontSize: '30px', color: '#c85850', fontStyle: 'bold' }).setOrigin(0.5);
    this.add.text(160, 74, '蜜 糖 村', { fontFamily: 'serif', fontSize: '18px', color: '#8a5a3a' }).setOrigin(0.5);
    this.add.text(160, 150, 'WASD/方向键移动 · E 交互 · ` 调试面板', { fontFamily: 'monospace', fontSize: '8px', color: '#5a4a3a' }).setOrigin(0.5);

    // DOM name input (centered overlay)
    const inp = document.createElement('input');
    inp.type = 'text'; inp.maxLength = 8; inp.placeholder = '小满';
    inp.style.cssText = 'position:fixed;left:50%;top:58%;transform:translate(-50%,-50%);width:160px;padding:6px 8px;font-size:16px;text-align:center;border:2px solid #8a5a3a;border-radius:6px;background:#fffbe9;color:#5a4a3a;font-family:sans-serif;outline:none;';
    document.body.appendChild(inp); this.nameInput = inp; setTimeout(() => inp.focus(), 50);
    this.add.text(160, 96, '请输入名字（留空默认 小满）：', { fontFamily: 'monospace', fontSize: '8px', color: '#5a4a3a' }).setOrigin(0.5);

    const btn = this.add.text(160, 124, '▶ 开始疗程', { fontFamily: 'monospace', fontSize: '12px', color: '#ffffff', backgroundColor: '#c85850', padding: { x: 8, y: 4 } })
      .setOrigin(0.5).setInteractive({ useHandCursor: true });
    btn.on('pointerover', () => btn.setStyle({ backgroundColor: '#e0736b' }));
    btn.on('pointerout', () => btn.setStyle({ backgroundColor: '#c85850' }));
    btn.on('pointerdown', () => this.begin());
    inp.addEventListener('keydown', (e) => { if (e.key === 'Enter') this.begin(); });
  }

  private begin() {
    const name = (this.nameInput?.value || '').trim() || '小满';
    if (this.nameInput) { this.nameInput.remove(); this.nameInput = undefined; }
    Audio.start();
    Director.reset(name);
    activateDay(1);
    this.scene.launch('UI');
    this.scene.start('World', { map: 'home', spawn: 'start' });
  }
}
