import Phaser from "phaser";
import { GAME_CONFIG } from "../core/config/GameConfig";

export class PreloadScene extends Phaser.Scene {
  constructor() {
    super("PreloadScene");
  }

  preload() {
    const { width, height } = this.scale;

    // Loading UI
    const progressLimit = 300;
    const progressBar = this.add.graphics();
    const progressBox = this.add.graphics();
    progressBox.fillStyle(0x222222, 0.8);
    progressBox.fillRect(width / 2 - progressLimit / 2 - 10, height / 2 - 25, progressLimit + 20, 50);

    const loadingText = this.make.text({
      x: width / 2,
      y: height / 2 - 50,
      text: "Loading Assets...",
      style: {
        font: "20px monospace",
        color: "#ffffff"
      }
    });
    loadingText.setOrigin(0.5, 0.5);

    this.load.on("progress", (value: number) => {
      progressBar.clear();
      progressBar.fillStyle(0xff2266, 1);
      progressBar.fillRect(width / 2 - progressLimit / 2, height / 2 - 15, progressLimit * value, 30);
    });

    this.load.on("complete", () => {
      // Create Global Animations
      GAME_CONFIG.animations.forEach(anim => {
        this.anims.create({
          key: anim.key,
          frames: this.anims.generateFrameNumbers(anim.textureKey, { frames: [...anim.frames] }), // Spread to make mutable
          frameRate: anim.frameRate,
          repeat: anim.repeat
        });
      });

      progressBar.destroy();
      progressBox.destroy();
      loadingText.destroy();
      this.scene.start("MenuScene");
    });

    // Load Spritesheets
    GAME_CONFIG.assets.spritesheets.forEach(asset => {
      this.load.spritesheet(asset.key, asset.path, asset.frameConfig);
    });

    // Load Images
    GAME_CONFIG.assets.images.forEach(asset => {
      this.load.image(asset.key, asset.path);
    });
  }
}
