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

  create() {
    const cardManager = this.registry.get('cardManager');
    const save = this.registry.get('save');
    const { width, height } = this.scale;

    this.add.rectangle(width / 2, height / 2, width, height, 0x0d1b2a);
    this.add.text(width / 2, 40, 'Card Collection', {
      fontSize: '38px', color: '#d4af37'
    }).setOrigin(0.5);

    // Stats
    const totalCards = cardManager.getAllCards().length;
    const ownedCards = Object.keys(save.collection).length;
    this.add.text(width - 20, 20, `Owned: ${ownedCards}/${totalCards}`, {
      fontSize: '20px', color: '#aaaaaa'
    }).setOrigin(1, 0);

    this.filter = { faction: 'all', rarity: 'all' };
    this.cardGroup = [];
    this._buildFilters();
    this._renderCards();
    this._makeBackButton();
  }

  _buildFilters() {
    const factions = ['all', 'imperial', 'raider'];
    const rarities = ['all', 'common', 'rare', 'epic', 'legendary'];

    this.add.text(20, 90, 'Faction:', { fontSize: '16px', color: '#888888' });
    let x = 130;
    factions.forEach(f => {
      const btn = this.add.rectangle(x + 55, 97, 110, 34, 0x1a3a5c)
        .setInteractive({ useHandCursor: true })
        .setStrokeStyle(1, 0x4488ff);
      this.add.text(x + 55, 97, f, { fontSize: '15px', color: '#ffffff' }).setOrigin(0.5);
      btn.on('pointerdown', () => { this.filter.faction = f; this._renderCards(); });
      x += 120;
    });

    this.add.text(20, 128, 'Rarity:', { fontSize: '16px', color: '#888888' });
    x = 130;
    rarities.forEach(r => {
      const btn = this.add.rectangle(x + 55, 135, 110, 34, 0x1a3a5c)
        .setInteractive({ useHandCursor: true })
        .setStrokeStyle(1, 0x4488ff);
      this.add.text(x + 55, 135, r, { fontSize: '15px', color: '#ffffff' }).setOrigin(0.5);
      btn.on('pointerdown', () => { this.filter.rarity = r; this._renderCards(); });
      x += 120;
    });
  }

  _renderCards() {
    // Clear previous cards
    if (this.cardGroup) this.cardGroup.forEach(c => c.destroy());
    this.cardGroup = [];

    const cardManager = this.registry.get('cardManager');
    const save = this.registry.get('save');
    const allCards = cardManager.getAllCards()
      .filter(c => this.filter.faction === 'all' || c.faction === this.filter.faction)
      .filter(c => this.filter.rarity === 'all' || c.rarity === this.filter.rarity);

    const cols = 8;
    const cardW = 195;
    const cardH = 135;
    const startX = 110;
    const startY = 190;
    const padX = 15;
    const padY = 15;

    allCards.forEach((card, i) => {
      const col = i % cols;
      const row = Math.floor(i / cols);
      const x = startX + col * (cardW + padX);
      const y = startY + row * (cardH + padY);
      if (y > 970) return; // clip overflow

      const owned = save.collection[card.id] || 0;
      const rarityColors = { common: 0x888888, rare: 0x4488ff, epic: 0xaa44ff, legendary: 0xffaa00 };
      const factionColors = { imperial: 0x2244aa, raider: 0xaa2222 };

      const bg = this.add.rectangle(x, y, cardW, cardH,
        owned > 0 ? (factionColors[card.faction] || 0x1a3a5c) : 0x1a1a1a)
        .setStrokeStyle(2, owned > 0 ? (rarityColors[card.rarity] || 0x888888) : 0x333333);
      this.cardGroup.push(bg);

      const nameT = this.add.text(x, y - 45, card.name, {
        fontSize: '14px', color: owned > 0 ? '#ffffff' : '#555555',
        wordWrap: { width: cardW - 6 }, align: 'center'
      }).setOrigin(0.5);
      this.cardGroup.push(nameT);

      const typeT = this.add.text(x, y - 28, `[${card.type}]`, {
        fontSize: '12px', color: owned > 0 ? '#aaaaaa' : '#444444'
      }).setOrigin(0.5);
      this.cardGroup.push(typeT);

      const statsT = this.add.text(x, y - 8, `ATK:${card.attack} HP:${card.health}${card.armor > 0 ? ' ARM:' + card.armor : ''}`, {
        fontSize: '14px', color: owned > 0 ? '#aaaaff' : '#444455'
      }).setOrigin(0.5);
      this.cardGroup.push(statsT);

      const skillsT = this.add.text(x, y + 12, card.skills.map(s => s.name).join(', '), {
        fontSize: '12px', color: owned > 0 ? '#ffcc44' : '#443300',
        wordWrap: { width: cardW - 6 }, align: 'center'
      }).setOrigin(0.5);
      this.cardGroup.push(skillsT);

      const ownedT = this.add.text(x, y + 38, `x${owned}`, {
        fontSize: '16px', color: owned > 0 ? '#44ff44' : '#333333'
      }).setOrigin(0.5);
      this.cardGroup.push(ownedT);

      const rarityT = this.add.text(x + cardW / 2 - 4, y - cardH / 2 + 6, card.rarity[0].toUpperCase(), {
        fontSize: '13px',
        color: '#' + (rarityColors[card.rarity] || 0x888888).toString(16).padStart(6, '0')
      }).setOrigin(1, 0);
      this.cardGroup.push(rarityT);
    });

    if (allCards.length === 0) {
      const t = this.add.text(960, 540, 'No cards match the current filter.', {
        fontSize: '22px', color: '#666666'
      }).setOrigin(0.5);
      this.cardGroup.push(t);
    }
  }

  _makeBackButton() {
    const bg = this.add.rectangle(80, 1040, 160, 45, 0x333333)
      .setInteractive({ useHandCursor: true })
      .setStrokeStyle(1, 0x888888);
    this.add.text(80, 1040, 'Back', { fontSize: '18px', color: '#ffffff' }).setOrigin(0.5);
    bg.on('pointerdown', () => this.scene.start('MainMenuScene'));
  }
}
