// BootScene：加载全部素材（CONTRACT §1 文件名）并创建全局动画。

import Phaser from 'phaser';

const NAMED = ['afu', 'yuanyuan', 'dabao', 'mimi', 'fuyisheng', 'guiyeye'];
const EXTRAS = ['squirrel', 'hedgehog', 'fox', 'pig', 'chick'];
const MAPS = ['house', 'plaza', 'bakery', 'shop', 'clinic', 'lake', 'field', 'well', 'fog', 'white'];

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

  preload(): void {
    // 瓦片集（image + 16×16 spritesheet 双注册，后者用于装饰小图）
    this.load.image('tileset', 'assets/tileset.png');
    this.load.spritesheet('tiles16', 'assets/tileset.png', { frameWidth: 16, frameHeight: 16 });

    // 主角：4 列 × 4 行，帧 16×24
    this.load.spritesheet('player', 'assets/sprites/player.png', { frameWidth: 16, frameHeight: 24 });

    // 具名 NPC：3 帧横排 smile/flat/off
    for (const id of NAMED) {
      this.load.spritesheet(`npc_${id}`, `assets/sprites/npc_${id}.png`, { frameWidth: 16, frameHeight: 24 });
    }
    // 双子鸟：2 帧
    this.load.spritesheet('npc_bird', 'assets/sprites/npc_bird.png', { frameWidth: 16, frameHeight: 24 });
    // 群演：2 帧循环
    for (const id of EXTRAS) {
      this.load.spritesheet(`extra_${id}`, `assets/sprites/extra_${id}.png`, { frameWidth: 16, frameHeight: 24 });
    }

    // 头像
    this.load.image('portrait_player_smile', 'assets/portraits/player_smile.png');
    this.load.image('portrait_player_real', 'assets/portraits/player_real.png');
    for (const id of [...NAMED, 'bird']) {
      this.load.image(`portrait_${id}`, `assets/portraits/${id}.png`);
    }

    // 地图
    for (const m of MAPS) {
      this.load.tilemapTiledJSON(`map_${m}`, `assets/maps/${m}.json`);
    }

    // 简易进度
    const t = this.add.text(160, 90, '加载中……', { fontFamily: 'monospace', fontSize: '10px', color: '#fff' }).setOrigin(0.5);
    this.load.on('progress', (v: number) => t.setText(`加载中 ${Math.round(v * 100)}%`));
  }

  create(): void {
    // 主角四向动画：行 0=down 1=up 2=left 3=right，每行 4 帧，第 0 帧兼待机
    const rows: [string, number][] = [['down', 0], ['up', 4], ['left', 8], ['right', 12]];
    for (const [dir, start] of rows) {
      if (!this.anims.exists(`walk-${dir}`)) {
        this.anims.create({
          key: `walk-${dir}`,
          frames: this.anims.generateFrameNumbers('player', { start, end: start + 3 }),
          frameRate: 8,
          repeat: -1,
        });
      }
    }
    // 双子鸟张嘴循环（S4 照张）
    if (!this.anims.exists('bird-sing')) {
      this.anims.create({
        key: 'bird-sing',
        frames: this.anims.generateFrameNumbers('npc_bird', { start: 0, end: 1 }),
        frameRate: 3,
        repeat: -1,
      });
    }
    // 群演走动循环
    for (const id of EXTRAS) {
      const key = `extra_${id}-walk`;
      if (!this.anims.exists(key)) {
        this.anims.create({
          key,
          frames: this.anims.generateFrameNumbers(`extra_${id}`, { start: 0, end: 1 }),
          frameRate: 4,
          repeat: -1,
        });
      }
    }

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