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

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

  create() {
    const { width, height } = this.scale;
    this.add.rectangle(width / 2, height / 2, width, height, 0x0d1b2a);
    this.add.text(width / 2, 40, 'Deck Builder', { fontSize: '38px', color: '#d4af37' }).setOrigin(0.5);

    const save = this.registry.get('save');

    // Working deck (copy to avoid mutating saved deck directly until Save is clicked)
    const existingDeck = save.decks[0];
    this.workingDeck = existingDeck
      ? { ...existingDeck, cards: [...existingDeck.cards] }
      : { id: 'deck_1', name: 'My Deck', commander: null, cards: [] };

    this.deckPanelGroup = [];
    this.cardListGroup = [];

    this._renderDeckPanel();
    this._renderCardList();
    this._makeButtons();
    this._makeBackButton();
  }

  _renderDeckPanel() {
    if (this.deckPanelGroup) this.deckPanelGroup.forEach(o => o.destroy());
    this.deckPanelGroup = [];

    const x0 = 1300;
    const cardManager = this.registry.get('cardManager');

    const title = this.add.text(x0 + 250, 90, 'Current Deck', { fontSize: '24px', color: '#d4af37' }).setOrigin(0.5);
    this.deckPanelGroup.push(title);

    // Commander slot
    const cmdCard = this.workingDeck.commander ? cardManager.getCard(this.workingDeck.commander) : null;
    const cmdBg = this.add.rectangle(x0 + 250, 140, 500, 50, cmdCard ? 0x1a3a5c : 0x2a1a1c).setStrokeStyle(2, 0xffd700);
    const cmdText = this.add.text(x0 + 250, 140, cmdCard ? `Commander: ${cmdCard.name}` : 'No Commander Selected', {
      fontSize: '18px', color: cmdCard ? '#ffd700' : '#888888'
    }).setOrigin(0.5);
    this.deckPanelGroup.push(cmdBg, cmdText);

    // Remove commander button
    if (cmdCard) {
      const rmCmdBtn = this.add.rectangle(x0 + 480, 140, 38, 32, 0x662222)
        .setInteractive({ useHandCursor: true }).setStrokeStyle(1, 0xff4444);
      const rmCmdTxt = this.add.text(x0 + 480, 140, 'X', { fontSize: '16px', color: '#ff4444' }).setOrigin(0.5);
      rmCmdBtn.on('pointerdown', () => {
        this.workingDeck.commander = null;
        this._renderDeckPanel();
      });
      this.deckPanelGroup.push(rmCmdBtn, rmCmdTxt);
    }

    // Card list (grouped by card id)
    const counts = {};
    this.workingDeck.cards.forEach(id => { counts[id] = (counts[id] || 0) + 1; });

    let y = 190;
    Object.entries(counts).forEach(([cardId, count]) => {
      const card = cardManager.getCard(cardId);
      if (!card) return;

      const rarityColors = { common: 0x888888, rare: 0x4488ff, epic: 0xaa44ff, legendary: 0xffaa00 };
      const bg = this.add.rectangle(x0 + 250, y, 500, 40, 0x1a3a5c).setStrokeStyle(1, rarityColors[card.rarity] || 0x336699);
      const txt = this.add.text(x0 + 20, y, `${card.name} x${count}`, { fontSize: '16px', color: '#ffffff' });
      const statsT = this.add.text(x0 + 360, y, `ATK:${card.attack}`, { fontSize: '14px', color: '#aaaaff' }).setOrigin(0.5);

      // Remove one button
      const rmBtn = this.add.rectangle(x0 + 480, y, 38, 32, 0x662222)
        .setInteractive({ useHandCursor: true }).setStrokeStyle(1, 0xff4444);
      const rmTxt = this.add.text(x0 + 480, y, '-', { fontSize: '20px', color: '#ff4444' }).setOrigin(0.5);
      rmBtn.on('pointerdown', () => {
        const idx = this.workingDeck.cards.lastIndexOf(cardId);
        if (idx !== -1) this.workingDeck.cards.splice(idx, 1);
        this._renderDeckPanel();
      });
      this.deckPanelGroup.push(bg, txt, statsT, rmBtn, rmTxt);
      y += 44;
    });

    // Filler slots
    const totalSlots = 10;
    const filledSlots = this.workingDeck.cards.length;
    for (let s = filledSlots; s < Math.min(totalSlots, filledSlots + 2); s++) {
      const slotBg = this.add.rectangle(x0 + 250, y, 500, 40, 0x111122).setStrokeStyle(1, 0x333355);
      const slotTxt = this.add.text(x0 + 250, y, '— empty slot —', { fontSize: '14px', color: '#333355' }).setOrigin(0.5);
      this.deckPanelGroup.push(slotBg, slotTxt);
      y += 44;
    }

    // Total count
    const countColor = this.workingDeck.cards.length > 10 ? '#ff4444' : this.workingDeck.cards.length >= 3 ? '#aaaaff' : '#888888';
    const total = this.add.text(x0 + 250, y + 18, `Cards: ${this.workingDeck.cards.length} / 10`, {
      fontSize: '18px', color: countColor
    }).setOrigin(0.5);
    this.deckPanelGroup.push(total);

    // Validation indicator
    const validation = DeckManager.validate(this.workingDeck, this.registry.get('cardManager'));
    const validText = this.add.text(x0 + 250, y + 46, validation.valid ? 'Valid Deck' : validation.errors[0], {
      fontSize: '16px', color: validation.valid ? '#44ff44' : '#ff6644'
    }).setOrigin(0.5);
    this.deckPanelGroup.push(validText);
  }

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

    const save = this.registry.get('save');
    const cardManager = this.registry.get('cardManager');

    // Header
    const hdr = this.add.text(500, 100, 'Your Cards — click to add to deck', { fontSize: '18px', color: '#888888' }).setOrigin(0.5);
    this.cardListGroup.push(hdr);

    const ownedIds = Object.keys(save.collection).filter(id => save.collection[id] > 0);
    const cols = 6;
    const cardW = 195;
    const cardH = 135;
    const startX = 120;
    const startY = 180;

    ownedIds.forEach((cardId, i) => {
      const card = cardManager.getCard(cardId);
      if (!card) return;
      const col = i % cols;
      const row = Math.floor(i / cols);
      const x = startX + col * (cardW + 12);
      const y = startY + row * (cardH + 12);
      if (y > 920) return; // clip

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

      const isCommander = card.type === 'commander';
      const alreadyInDeck = isCommander
        ? this.workingDeck.commander === cardId
        : this.workingDeck.cards.filter(id => id === cardId).length;
      const maxAllowed = isCommander ? 1 : 3;
      const canAdd = isCommander
        ? !this.workingDeck.commander
        : (this.workingDeck.cards.length < 10 && alreadyInDeck < maxAllowed);

      const bg = this.add.rectangle(x, y, cardW, cardH, canAdd ? (factionColors[card.faction] || 0x1a3a5c) : 0x222222)
        .setStrokeStyle(2, canAdd ? (rarityColors[card.rarity] || 0x888888) : 0x444444);

      if (canAdd) {
        bg.setInteractive({ useHandCursor: true });
        bg.on('pointerover', () => bg.setAlpha(0.75));
        bg.on('pointerout', () => bg.setAlpha(1));
        bg.on('pointerdown', () => {
          if (isCommander) {
            this.workingDeck.commander = cardId;
          } else {
            if (this.workingDeck.cards.length < 10) {
              this.workingDeck.cards.push(cardId);
            }
          }
          this._renderDeckPanel();
          this._renderCardList();
        });
      }

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

      const typeLabel = isCommander ? '[CMD]' : `[${card.rarity}]`;
      const typeT = this.add.text(x, y - 28, typeLabel, {
        fontSize: '12px', color: canAdd ? '#aaaaaa' : '#444444'
      }).setOrigin(0.5);

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

      const inDeckCount = isCommander
        ? (this.workingDeck.commander === cardId ? 1 : 0)
        : this.workingDeck.cards.filter(id => id === cardId).length;

      const countT = this.add.text(x, y + 12, `Owned:${save.collection[cardId]} In deck:${inDeckCount}`, {
        fontSize: '12px', color: canAdd ? '#44ff44' : '#444444'
      }).setOrigin(0.5);

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

      this.cardListGroup.push(bg, nameT, typeT, statsT, countT, skillT);
    });

    if (ownedIds.length === 0) {
      const t = this.add.text(500, 450, 'No cards in collection.\nVisit the Store to buy packs!', {
        fontSize: '22px', color: '#666666', align: 'center'
      }).setOrigin(0.5);
      this.cardListGroup.push(t);
    }
  }

  _makeButtons() {
    // Save deck button
    const saveBtn = this.add.rectangle(1550, 930, 200, 50, 0x224422)
      .setInteractive({ useHandCursor: true })
      .setStrokeStyle(2, 0x44aa44);
    this.add.text(1550, 930, 'Save Deck', { fontSize: '20px', color: '#ffffff' }).setOrigin(0.5);
    saveBtn.on('pointerdown', () => {
      const save = this.registry.get('save');
      const validation = DeckManager.validate(this.workingDeck, this.registry.get('cardManager'));
      if (!validation.valid) {
        this._showMsg(validation.errors[0], '#ff4444');
        return;
      }
      SaveManager.saveDeck(save, this.workingDeck);
      this.registry.set('save', save);
      this._showMsg('Deck saved!', '#44ff44');
    });

    // Clear deck button
    const clearBtn = this.add.rectangle(1550, 990, 200, 45, 0x442222)
      .setInteractive({ useHandCursor: true })
      .setStrokeStyle(2, 0xaa4444);
    this.add.text(1550, 990, 'Clear Deck', { fontSize: '18px', color: '#ffffff' }).setOrigin(0.5);
    clearBtn.on('pointerdown', () => {
      this.workingDeck.commander = null;
      this.workingDeck.cards = [];
      this._renderDeckPanel();
      this._renderCardList();
    });
  }

  _showMsg(msg, color) {
    const { width } = this.scale;
    const t = this.add.text(width / 2, 860, msg, { fontSize: '18px', color }).setOrigin(0.5);
    this.time.delayedCall(2000, () => t.destroy());
  }

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