import Phaser from 'phaser';
import { DEFAULT_PLAYER_NAME, SCENE_KEYS } from '../data/constants';
import { Director } from '../systems/CorruptionDirector';
import { audio } from '../audio/ProceduralAudio';

export class NameScene extends Phaser.Scene {
  private nameValue = '';
  private nameText!: Phaser.GameObjects.Text;

  constructor() {
    super(SCENE_KEYS.NAME);
  }

  create(): void {
    void audio.unlock();
    const { width, height } = this.cameras.main;
    this.cameras.main.setBackgroundColor('#f5e6c8');

    this.add
      .text(width / 2, 40, '你的名字是？', {
        fontFamily: 'monospace',
        fontSize: '14px',
        color: '#503020',
      })
      .setOrigin(0.5);

    this.add
      .text(width / 2, 58, `（留空默认为「${DEFAULT_PLAYER_NAME}」）`, {
        fontFamily: 'monospace',
        fontSize: '9px',
        color: '#806050',
      })
      .setOrigin(0.5);

    this.add.rectangle(width / 2, 90, 160, 22, 0xfffaf0).setStrokeStyle(2, 0xc08040);

    this.nameText = this.add
      .text(width / 2, 90, '', {
        fontFamily: 'monospace',
        fontSize: '12px',
        color: '#302010',
      })
      .setOrigin(0.5);

    this.add
      .text(width / 2, 130, '输入名字后按 Enter 进入蜜糖村', {
        fontFamily: 'monospace',
        fontSize: '9px',
        color: '#705040',
      })
      .setOrigin(0.5);

    this.input.keyboard?.on('keydown', (ev: KeyboardEvent) => {
      if (ev.key === 'Enter') {
        this.confirm();
        return;
      }
      if (ev.key === 'Backspace') {
        this.nameValue = this.nameValue.slice(0, -1);
        this.nameText.setText(this.nameValue);
        return;
      }
      if (ev.key.length === 1 && this.nameValue.length < 12) {
        // Allow CJK and basic latin
        this.nameValue += ev.key;
        this.nameText.setText(this.nameValue);
      }
    });
  }

  private confirm(): void {
    Director.resetSession(this.nameValue);
    audio.syncFromDirector();
    this.scene.start(SCENE_KEYS.HOUSE, { spawn: 'spawn' });
    this.scene.launch(SCENE_KEYS.UI);
  }
}
