import { SaveManager } from '../managers/SaveManager.js';

const FUSION_RECIPES = {
  common: { count: 3, result_rarity: 'rare' },
  rare: { count: 3, result_rarity: 'epic' },
  epic: { count: 3, result_rarity: 'legendary' }
};

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

  create() {
    const { width, height } = this.scale;
    this.add.rectangle(width / 2, height / 2, width, height, 0x0d1b2a);
    this.add.text(width / 2, 40, 'Fusion Lab', { fontSize: '38px', color: '#d4af37' }).setOrigin(0.5);
    this.add.text(width / 2, 80, 'Combine 3 copies of a card to upgrade it to the next rarity tier', {
      fontSize: '18px', color: '#888888'
    }).setOrigin(0.5);

    // Recipe reference
    const recipeX = width - 300;
    this.add.text(recipeX, 155, 'Fusion Recipes', { fontSize: '20px', color: '#d4af37' }).setOrigin(0.5);
    const recipeLines = [
      '3x Common  ->  1x Rare',
      '3x Rare    ->  1x Epic',
      '3x Epic    ->  1x Legendary'
    ];
    recipeLines.forEach((line, i) => {
      this.add.text(recipeX, 195 + i * 28, line, { fontSize: '16px', color: '#aaaaaa' }).setOrigin(0.5);
    });

    this.listGroup = [];
    this._renderCardList();
    this._makeBackButton();
  }

  _renderCardList() {
    if (this.listGroup) this.listGroup.forEach(o => o.destroy());
    this.listGroup = [];

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

    const fusibleCards = Object.entries(save.collection)
      .filter(([id, count]) => {
        const card = cardManager.getCard(id);
        return card && card.type !== 'commander' && FUSION_RECIPES[card.rarity] && count >= 3;
      });

    if (fusibleCards.length === 0) {
      const t = this.add.text(width / 2, 480, 'No cards available for fusion.\nCollect 3 or more copies of the same card to fuse them.', {
        fontSize: '22px', color: '#888888', align: 'center'
      }).setOrigin(0.5);
      this.listGroup.push(t);

      // Show progress toward next fusion
      this.add.text(width / 2, 610, 'Your collection progress:', { fontSize: '18px', color: '#666666' }).setOrigin(0.5);
      const nearFusion = Object.entries(save.collection)
        .filter(([id, count]) => {
          const card = cardManager.getCard(id);
          return card && card.type !== 'commander' && FUSION_RECIPES[card.rarity] && count >= 1 && count < 3;
        })
        .sort((a, b) => b[1] - a[1])
        .slice(0, 5);

      nearFusion.forEach(([id, count], i) => {
        const card = cardManager.getCard(id);
        if (!card) return;
        const recipe = FUSION_RECIPES[card.rarity];
        const t2 = this.add.text(width / 2, 650 + i * 30,
          `${card.name} (${card.rarity}): ${count}/${recipe.count}`,
          { fontSize: '18px', color: '#555555' }
        ).setOrigin(0.5);
        this.listGroup.push(t2);
      });
      return;
    }

    fusibleCards.forEach(([cardId, count], i) => {
      const card = cardManager.getCard(cardId);
      const recipe = FUSION_RECIPES[card.rarity];
      const cols = 4;
      const x = 270 + (i % cols) * 380;
      const y = 280 + Math.floor(i / cols) * 265;

      if (y > 940) return;

      const rarityColors = { common: 0x888888, rare: 0x4488ff, epic: 0xaa44ff, legendary: 0xffaa00 };
      const factionColors = { imperial: 0x2244aa, raider: 0xaa2222 };

      const bg = this.add.rectangle(x, y, 340, 230, factionColors[card.faction] || 0x1a3a5c)
        .setStrokeStyle(2, rarityColors[card.rarity] || 0x888888);

      const nameT = this.add.text(x, y - 85, card.name, {
        fontSize: '20px', color: '#ffffff', wordWrap: { width: 320 }, align: 'center'
      }).setOrigin(0.5);
      const rarityT = this.add.text(x, y - 56, card.rarity.toUpperCase(), {
        fontSize: '16px', color: '#' + (rarityColors[card.rarity] || 0x888888).toString(16).padStart(6, '0')
      }).setOrigin(0.5);
      const statsT = this.add.text(x, y - 32, `ATK:${card.attack} HP:${card.health} ARM:${card.armor}`, {
        fontSize: '16px', color: '#aaaaff'
      }).setOrigin(0.5);
      const countT = this.add.text(x, y - 8, `You have: ${count}  (need ${recipe.count})`, {
        fontSize: '16px', color: '#44ff44'
      }).setOrigin(0.5);
      const resultT = this.add.text(x, y + 18, `Result: ${recipe.result_rarity.toUpperCase()}`, {
        fontSize: '18px', color: '#ffd700'
      }).setOrigin(0.5);

      const fuseBtn = this.add.rectangle(x, y + 68, 220, 48, 0x553300)
        .setInteractive({ useHandCursor: true })
        .setStrokeStyle(2, 0xffaa00);
      const fuseTxt = this.add.text(x, y + 68, 'FUSE (3x)', { fontSize: '18px', color: '#ffd700' }).setOrigin(0.5);

      fuseBtn.on('pointerover', () => fuseBtn.setFillStyle(0x775500));
      fuseBtn.on('pointerout', () => fuseBtn.setFillStyle(0x553300));
      fuseBtn.on('pointerdown', () => this._fuse(cardId, card, recipe));

      this.listGroup.push(bg, nameT, rarityT, statsT, countT, resultT, fuseBtn, fuseTxt);
    });
  }

  _fuse(cardId, card, recipe) {
    const save = this.registry.get('save');
    const cardManager = this.registry.get('cardManager');

    if ((save.collection[cardId] || 0) < recipe.count) {
      this._showMsg('Not enough copies!', '#ff4444');
      return;
    }

    // Remove source cards
    for (let i = 0; i < recipe.count; i++) {
      SaveManager.removeCard(save, cardId);
    }

    // Find a card of the same faction with target rarity
    const candidates = cardManager.getAllCards().filter(c =>
      c.faction === card.faction &&
      c.rarity === recipe.result_rarity &&
      c.type !== 'commander'
    );

    if (candidates.length === 0) {
      this._showMsg('No higher rarity card available in this faction!', '#ff8800');
      // Refund
      for (let i = 0; i < recipe.count; i++) SaveManager.addCard(save, cardId);
      return;
    }

    // Give random result card from the same faction
    const result = candidates[Math.floor(Math.random() * candidates.length)];
    SaveManager.addCard(save, result.id);
    this.registry.set('save', save);

    this._showMsg(`Fusion successful! You got: ${result.name}!`, '#ffd700');
    this.time.delayedCall(400, () => this._renderCardList());
  }

  _showMsg(msg, color) {
    const { width } = this.scale;
    if (this._msgText) this._msgText.destroy();
    this._msgText = this.add.text(width / 2, 960, msg, { fontSize: '24px', color }).setOrigin(0.5);
    this.time.delayedCall(2500, () => {
      if (this._msgText) this._msgText.destroy();
      this._msgText = null;
    });
  }

  _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'));
  }
}
