import Phaser from 'phaser';

const MAPS = ['home', 'plaza', 'bakery', 'grocery', 'clinic', 'lake', 'field', 'well', 'fog', 'white'];
const NPCS = ['afu', 'yuan', 'dabao', 'mimi', 'fu', 'gui'];

export class BootScene extends Phaser.Scene {
  constructor() { super('Boot'); }

  preload() {
    const g = this.add.graphics();
    const bar = this.add.graphics();
    this.add.text(160, 78, '蜜糖村加载中……', { fontFamily: 'monospace', fontSize: '10px', color: '#ffe9b0' }).setOrigin(0.5);
    this.load.on('progress', (p: number) => {
      bar.clear(); bar.fillStyle(0xffd27a, 1); bar.fillRect(90, 96, 140 * p, 6);
    });
    g.lineStyle(1, 0x8a6a3a).strokeRect(90, 96, 140, 6);

    this.load.image('tiles', 'assets/sprites/tileset.png');
    this.load.spritesheet('player', 'assets/sprites/player.png', { frameWidth: 16, frameHeight: 24 });
    this.load.spritesheet('portraits', 'assets/sprites/portraits.png', { frameWidth: 32, frameHeight: 32 });
    this.load.spritesheet('birds', 'assets/sprites/birds.png', { frameWidth: 16, frameHeight: 24 });
    this.load.spritesheet('extras', 'assets/sprites/extras.png', { frameWidth: 16, frameHeight: 16 });
    this.load.image('sparrow', 'assets/sprites/sparrow.png');
    for (const n of NPCS) this.load.spritesheet('npc_' + n, `assets/sprites/npc_${n}.png`, { frameWidth: 16, frameHeight: 24 });
    for (const m of MAPS) this.load.tilemapTiledJSON('map_' + m, `assets/maps/${m}.json`);
  }

  create() {
    // player walk anims (rows: 0 down,1 left,2 right,3 up; 4 frames each)
    const mk = (key: string, row: number) =>
      this.anims.create({ key, frames: this.anims.generateFrameNumbers('player', { start: row * 4, end: row * 4 + 3 }), frameRate: 8, repeat: -1 });
    mk('walk-down', 0); mk('walk-left', 1); mk('walk-right', 2); mk('walk-up', 3);
    // bird mouth
    this.anims.create({ key: 'bird-flap', frames: this.anims.generateFrameNumbers('birds', { start: 0, end: 1 }), frameRate: 3, repeat: -1 });
    // extras: 5 critters x 2 frames
    for (let k = 0; k < 5; k++)
      this.anims.create({ key: 'extra' + (k + 1), frames: this.anims.generateFrameNumbers('extras', { start: k * 2, end: k * 2 + 1 }), frameRate: 3, repeat: -1 });

    this.scene.start('Title');
  }
}
