import Phaser from 'phaser';
import { SCENE_KEYS } from '../data/constants';

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

  preload(): void {
    const W = this.cameras.main.width;
    const H = this.cameras.main.height;
    const bar = this.add.rectangle(W / 2, H / 2, 120, 8, 0xffc850);
    bar.setOrigin(0.5);
    this.load.on('progress', (p: number) => {
      bar.width = 120 * p;
    });

    this.load.image('tiles', 'assets/tilesets/village.png');
    this.load.spritesheet('player', 'assets/sprites/player.png', {
      frameWidth: 16,
      frameHeight: 24,
    });
    this.load.spritesheet('npcs', 'assets/sprites/npcs.png', {
      frameWidth: 16,
      frameHeight: 24,
    });
    this.load.spritesheet('birds', 'assets/sprites/birds.png', {
      frameWidth: 16,
      frameHeight: 16,
    });
    this.load.spritesheet('extras', 'assets/sprites/extras.png', {
      frameWidth: 16,
      frameHeight: 24,
    });
    this.load.spritesheet('portraits', 'assets/sprites/portraits.png', {
      frameWidth: 32,
      frameHeight: 32,
    });
    this.load.spritesheet('sunflower', 'assets/sprites/sunflower.png', {
      frameWidth: 16,
      frameHeight: 16,
    });
    this.load.image('dialog_panel', 'assets/sprites/dialog_panel.png');

    const maps = [
      'house',
      'plaza',
      'bakery',
      'shop',
      'clinic',
      'lake',
      'field',
      'well',
      'fog',
      'white',
    ];
    for (const m of maps) {
      this.load.tilemapTiledJSON(m, `assets/maps/${m}.json`);
    }
  }

  create(): void {
    // Player animations: sheet is 4 cols (frames) x 4 rows (dirs)
    // frame index = dir * 4 + walkFrame
    const mk = (key: string, dir: number) => {
      this.anims.create({
        key,
        frames: this.anims.generateFrameNumbers('player', {
          start: dir * 4,
          end: dir * 4 + 3,
        }),
        frameRate: 8,
        repeat: -1,
      });
    };
    mk('walk-down', 0);
    mk('walk-up', 1);
    mk('walk-left', 2);
    mk('walk-right', 3);

    this.anims.create({
      key: 'bird-beak',
      frames: this.anims.generateFrameNumbers('birds', { start: 0, end: 1 }),
      frameRate: 4,
      repeat: -1,
    });

    for (let i = 0; i < 5; i++) {
      this.anims.create({
        key: `extra-${i}`,
        frames: [
          { key: 'extras', frame: i * 2 },
          { key: 'extras', frame: i * 2 + 1 },
        ],
        frameRate: 3,
        repeat: -1,
      });
    }

    this.scene.start(SCENE_KEYS.TITLE);
  }
}
