/**
 * Chroniques de l'Étrange — Système FoundryVTT
 *
 * Chroniques de l'Étrange est un jeu de rôle édité par Antre-Monde Éditions.
 * Ce système FoundryVTT est une implémentation indépendante et n'est pas
 * affilié à Antre-Monde Éditions,
 * mais a été réalisé avec l'autorisation d'Antre-Monde Éditions.
 *
 * @author    LeRatierBretonnien
 * @copyright 2024–2026 LeRatierBretonnien
 * @license   CC BY-NC-SA 4.0 – https://creativecommons.org/licenses/by-nc-sa/4.0/
 */

import { getTinjiValue, setTinjiValue } from "./singletons.js"
import { SYSTEM_ID } from "../../config/constants.js"

export class CDETinjiApp extends foundry.applications.api.HandlebarsApplicationMixin(
  foundry.applications.api.ApplicationV2
) {
  static DEFAULT_OPTIONS = {
    id: "cde-tinji-app",
    tag: "div",
    window: {
      title: "CDE.TinJi2",
      icon: "fas fa-star",
      resizable: false,
    },
    classes: ["cde-app", "cde-tinji-standalone"],
    position: { width: 380, height: "auto" },
    actions: {
      increment: CDETinjiApp.#onIncrement,
      decrement: CDETinjiApp.#onDecrement,
      reset:     CDETinjiApp.#onReset,
      spend:     CDETinjiApp.#onSpend,
    },
  }

  static PARTS = {
    main: {
      template: `systems/${SYSTEM_ID}/templates/apps/cde-tinji-app.html`,
    },
  }

  /** @type {Function|null} */
  _updateHook = null

  /** @type {Function|null} */
  _settingHook = null

  static open() {
    const existing = Array.from(foundry.applications.instances.values()).find(
      (app) => app instanceof CDETinjiApp
    )
    if (existing) { existing.bringToFront(); return existing }
    const app = new CDETinjiApp()
    app.render(true)
    return app
  }

  async _prepareContext() {
    return {
      canEdit: game.user.isGM,
      value:   getTinjiValue(),
    }
  }

  _onRender(context, options) {
    super._onRender(context, options)
    this.#bindDirectInput()
    if (!this._updateHook) {
      this._updateHook = Hooks.on("cde:tinjiUpdated", () => this.render())
    }
    if (!this._settingHook) {
      this._settingHook = Hooks.on("updateSetting", (setting) => {
        if (setting.key === `${SYSTEM_ID}.tinjiData`) this.render()
      })
    }
  }

  _onClose(options) {
    if (this._updateHook !== null) {
      Hooks.off("cde:tinjiUpdated", this._updateHook)
      this._updateHook = null
    }
    if (this._settingHook !== null) {
      Hooks.off("updateSetting", this._settingHook)
      this._settingHook = null
    }
    super._onClose(options)
  }

  #bindDirectInput() {
    const input = this.element?.querySelector("input.cde-tinji-direct")
    if (!input) return
    input.addEventListener("change", async (ev) => {
      const val = parseInt(ev.currentTarget.value, 10)
      if (!isNaN(val)) await setTinjiValue(val)
    })
  }

  static async #onIncrement() {
    await setTinjiValue(getTinjiValue() + 1)
  }

  static async #onDecrement() {
    const current = getTinjiValue()
    if (current <= 0) return
    await setTinjiValue(current - 1)
  }

  static async #onReset() {
    await setTinjiValue(0)
  }

  static async #onSpend() {
    const current = getTinjiValue()
    if (current <= 0) {
      ui.notifications.warn(game.i18n.localize("CDE.TinjiEmpty"))
      return
    }
    await setTinjiValue(current - 1)
    await ChatMessage.create({
      user:    game.user.id,
      content: `<div class="cde-tinji-spend-msg">
        <i class="fas fa-star"></i>
        <strong>${game.i18n.localize("CDE.TinJi2")}</strong>
        ${game.i18n.format("CDE.TinjiSpent", { name: game.user.name })}
        <span class="cde-tinji-remain">(${current - 1} ${game.i18n.localize("CDE.TinjiRemaining")})</span>
      </div>`,
    })
  }
}
