const { HandlebarsApplicationMixin } = foundry.applications.api

export default class HamalronTarotDeckManager extends HandlebarsApplicationMixin(foundry.applications.api.ApplicationV2) {
  constructor(options = {}) {
    super(options)
    this.deck = []
    this.drawnCards = []
    this.resetDeck()
  }

  /** @override */
  static DEFAULT_OPTIONS = {
    id: "tarot-deck-manager",
    classes: ["fvtt-hamalron", "tarot-deck-manager"],
    tag: "div",
    window: {
      title: "HAMALRON.TarotDeck.Title",
      icon: "fas fa-cards",
      resizable: true,
    },
    position: {
      width: 600,
      height: 700,
    },
    actions: {
      resetDeck: HamalronTarotDeckManager.#onResetDeck,
      drawCard: HamalronTarotDeckManager.#onDrawCard,
      drawMultiple: HamalronTarotDeckManager.#onDrawMultiple,
    },
  }

  /** @override */
  static PARTS = {
    main: {
      template: "systems/fvtt-hamalron/templates/tarot-deck-manager.hbs",
    },
  }

  /**
   * Reset the deck to a full tarot deck
   */
  resetDeck() {
    this.deck = []
    this.drawnCards = []

    // Créer toutes les cartes du jeu de tarot
    const items = game.items.filter(i => i.type === "tarot")

    if (items.length > 0) {
      // Utiliser les items existants
      this.deck = items.map(item => ({
        id: item.id,
        name: item.name,
        img: item.img,
        symbole: item.system.symbole,
        valeur: item.system.valeur,
        type: item.system.type,
        description: item.system.description,
      }))
    } else {
      ui.notifications.warn("HAMALRON.TarotDeck.NoCardsFound", { localize: true })
    }

    // Mélanger le deck
    this.shuffleDeck()
    this.render()
  }

  /**
   * Shuffle the deck using Fisher-Yates algorithm
   */
  shuffleDeck() {
    for (let i = this.deck.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [this.deck[i], this.deck[j]] = [this.deck[j], this.deck[i]]
    }
  }

  /**
   * Draw a card from the deck
   * @param {number} count - Number of cards to draw
   * @returns {Array} - Drawn cards
   */
  drawCards(count = 1) {
    if (this.deck.length === 0) {
      ui.notifications.warn("HAMALRON.TarotDeck.DeckEmpty", { localize: true })
      return []
    }

    const drawn = []
    for (let i = 0; i < count && this.deck.length > 0; i++) {
      const card = this.deck.shift()
      this.drawnCards.push(card)
      drawn.push(card)
    }

    return drawn
  }

  /**
   * Send drawn cards to chat
   * @param {Array} cards - Cards to send to chat
   */
  async sendCardsToChat(cards) {
    if (cards.length === 0) return

    const speaker = ChatMessage.getSpeaker({ alias: "Maître du Jeu" })

    for (const card of cards) {
      const content = await foundry.applications.handlebars.renderTemplate(
        "systems/fvtt-hamalron/templates/chat-tarot-draw.hbs",
        {
          card: card,
          symboleLabel: game.i18n.localize(`HAMALRON.Tarot.FIELDS.symbole.${card.symbole}`),
          valeurLabel: game.i18n.localize(`HAMALRON.Tarot.FIELDS.valeur.${card.valeur}`),
          typeLabel: game.i18n.localize(`HAMALRON.Tarot.FIELDS.type.${card.type}`),
        }
      )

      await ChatMessage.create({
        speaker: speaker,
        content: content,
        type: CONST.CHAT_MESSAGE_TYPES.OTHER,
      })
    }
  }

  /** @override */
  async _prepareContext(options) {
    const context = await super._prepareContext(options)

    context.deckCount = this.deck.length
    context.drawnCount = this.drawnCards.length
    context.totalCards = this.deck.length + this.drawnCards.length
    context.hasCards = this.deck.length > 0
    context.drawnCards = this.drawnCards.slice(-5).reverse() // Show last 5 drawn cards

    return context
  }

  /**
   * Handle reset deck action
   * @param {Event} event
   * @param {HTMLElement} target
   */
  static async #onResetDeck(event, target) {
    const confirmed = await foundry.applications.api.DialogV2.confirm({
      window: { title: "HAMALRON.TarotDeck.ResetConfirm" },
      content: `<p>${game.i18n.localize("HAMALRON.TarotDeck.ResetWarning")}</p>`,
      rejectClose: false,
      modal: true,
    })

    if (confirmed) {
      this.resetDeck()
      ui.notifications.info("HAMALRON.TarotDeck.DeckReset", { localize: true })
    }
  }

  /**
   * Handle draw single card action
   * @param {Event} event
   * @param {HTMLElement} target
   */
  static async #onDrawCard(event, target) {
    const cards = this.drawCards(1)
    if (cards.length > 0) {
      await this.sendCardsToChat(cards)
      this.render()
    }
  }

  /**
   * Handle draw multiple cards action
   * @param {Event} event
   * @param {HTMLElement} target
   */
  static async #onDrawMultiple(event, target) {
    const count = parseInt(target.dataset.count || "1")
    const cards = this.drawCards(count)
    if (cards.length > 0) {
      await this.sendCardsToChat(cards)
      this.render()
    }
  }

  /**
   * Open the Tarot Deck Manager application
   * @returns {HamalronTarotDeckManager}
   */
  static openManager() {
    if (!game.user.isGM) {
      ui.notifications.warn("HAMALRON.TarotDeck.GMOnly", { localize: true })
      return
    }

    // Singleton pattern - reuse existing instance or create new one
    if (!HamalronTarotDeckManager._instance) {
      HamalronTarotDeckManager._instance = new HamalronTarotDeckManager()
    }

    HamalronTarotDeckManager._instance.render(true, { focus: true })
    return HamalronTarotDeckManager._instance
  }
}
