// Preload — load assets with a progress bar.
window.PreloadScene = class PreloadScene extends Phaser.Scene {
  constructor() { super('Preload'); }

  preload() {
    const W = window.GAME.WIDTH, H = window.GAME.HEIGHT;
    const accent = Phaser.Display.Color.HexStringToColor(window.GAME.ACCENT).color;

    // ---- progress bar UI ----
    const barW = W * 0.6, barH = 22;
    const barX = (W - barW) / 2, barY = H / 2;
    const box = this.add.graphics();
    const bar = this.add.graphics();
    box.fillStyle(0x222233, 0.9).fillRoundedRect(barX - 4, barY - 4, barW + 8, barH + 8, 8);
    const label = this.add.text(W / 2, barY - 36, 'LOADING', {
      fontFamily: 'Arial', fontSize: '20px', color: '#ffffff', fontStyle: 'bold',
    }).setOrigin(0.5);
    const pct = this.add.text(W / 2, barY + barH + 24, '0%', {
      fontFamily: 'Arial', fontSize: '16px', color: '#9aa',
    }).setOrigin(0.5);

    this.load.on('progress', (v) => {
      bar.clear();
      bar.fillStyle(accent, 1).fillRoundedRect(barX, barY, barW * v, barH, 6);
      pct.setText(Math.round(v * 100) + '%');
    });
    this.load.on('complete', () => { box.destroy(); bar.destroy(); label.destroy(); pct.destroy(); });

    // =========================================================
    // ASSET LIST  ——  EDIT POINT #1 (assets)
    // Real fal.ai art (run tools/gen-assets.mjs to (re)generate).
    // If a file is missing (e.g. art not generated yet) we silence
    // the loader error and the Game scene draws a styled fallback
    // shape, so the game NEVER errors and is always playable.
    // =========================================================
    // window.GAME.assets lists the art keys this game expects.
    // We probe each file with a HEAD-style fetch BEFORE asking
    // Phaser to load it, so a missing file never produces a 404 /
    // console error — the Game scene just uses its styled fallback.
    // After running tools/gen-assets.mjs the PNGs appear and load
    // automatically with ZERO code changes.
    this.load.on('loaderror', (file) => {
      // Should not fire (main.js pre-checks), but stay quiet just in case.
      console.warn('[asset skipped]', file && file.key);
    });
    // Queue loads only for assets that actually exist on disk
    // (probed in main.js -> window.GAME.availableAssets).
    (window.GAME.availableAssets || []).forEach((key) => {
      this.load.image(key, 'assets/' + key + '.png');
    });

    // Tiny fake load so the bar always animates even with no assets.
    for (let i = 0; i < 8; i++) {
      this.load.image('__warm' + i,
        'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+M8AAAMBAQDJ/pLvAAAAAElFTkSuQmCC');
    }
  }

  create() {
    this.scene.start('Menu');
  }
};
