import { SaveManager } from '../managers/SaveManager.js';
import { CardManager } from '../managers/CardManager.js';
import { PackManager } from '../managers/PackManager.js';
import { DeckManager } from '../managers/DeckManager.js';

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

  preload() {
    // Load all JSON data files
    this.load.image('vs', 'assets/images/ui/vs.png');
    this.load.image('attacksFirst', 'assets/images/ui/attacksFirst.png');
    this.load.spritesheet('attacks', 'assets/images/spritesheets/attacks.png', { frameWidth: 460, frameHeight: 460 });
    this.load.json('cards', 'data/cards.json');
    this.load.json('packs', 'data/packs.json');
    this.load.json('missions', 'data/missions.json');
    this.load.json('skills', 'data/skills.json');

    // Once cards.json finishes, queue card art images and resume loading
    this.load.once('filecomplete-json-cards', (_key, _type, data) => {
      data.forEach(card => {
        if (card.artKey && !this.textures.exists(card.artKey)) {
          this.load.image(card.artKey, `assets/images/cards/${card.artKey}.png`);
        }
      });
      this.load.start();
    });

    // Loading text
    const loadText = this.add.text(this.scale.width / 2, this.scale.height / 2, 'Loading...', {
      fontSize: '28px', color: '#ffffff'
    }).setOrigin(0.5);

    this.load.on('progress', (value) => {
      loadText.setText(`Loading... ${Math.floor(value * 100)}%`);
    });
  }

  create() {
    // Initialize managers
    const cardsData = this.cache.json.get('cards');
    const packsData = this.cache.json.get('packs');
    const missionsData = this.cache.json.get('missions');

    const cardManager = new CardManager(cardsData);
    const packManager = new PackManager(packsData, cardManager);

    // Load save
    const save = SaveManager.load();

    // Give starter deck on first run
    if (!save.starterDeckReceived) {
      const starterDeck = DeckManager.createStarterDeck(cardManager);
      save.decks.push(starterDeck);
      // Add starter cards to collection
      for (const cardId of starterDeck.cards) {
        save.collection[cardId] = (save.collection[cardId] || 0) + 1;
      }
      save.collection[starterDeck.commander] = (save.collection[starterDeck.commander] || 0) + 1;
      save.starterDeckReceived = true;
      SaveManager.save(save);
    }

    // Store managers on game registry for global access
    this.registry.set('cardManager', cardManager);
    this.registry.set('packManager', packManager);
    this.registry.set('missions', missionsData);
    this.registry.set('save', save);

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