/**
 * 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/
 */

const { HandlebarsApplicationMixin } = foundry.applications.api

export class CDEBaseActorSheet extends HandlebarsApplicationMixin(foundry.applications.sheets.ActorSheetV2) {
  static DEFAULT_OPTIONS = {
    classes: ["fvtt-chroniques-de-l-etrange", "actor"],
    position: { width: 920, height: 800 },
    window: { resizable: true },
    form: { submitOnChange: true },
    dragDrop: [{ dragSelector: ".item, [data-drag='true']", dropSelector: null }],
    actions: {
      create: CDEBaseActorSheet.#onItemCreate,
      edit: CDEBaseActorSheet.#onItemEdit,
      delete: CDEBaseActorSheet.#onItemDelete,
      editImage: CDEBaseActorSheet.#onEditImage,
    },
  }

  tabGroups = { primary: "description" }

  get title() {
    return this.document.name
  }

  async _prepareContext() {
    const descriptionHTML = await foundry.applications.ux.TextEditor.implementation.enrichHTML(this.document.system.description ?? "", { async: true })
    const cssClass = this.options.classes?.join(" ") ?? ""
    return {
      actor: this.document,
      system: this.document.system,
      systemData: this.document.system,
      systemFields: this.document.system.schema.fields,
      items: this.document.items.contents,
      descriptionHTML,
      editable: this.isEditable,
      cssClass,
    }
  }

  // Restore the active tab after every render (including re-renders from submitOnChange).
  // AppV2 does NOT preserve tab state natively — we must re-apply it from this.tabGroups,
  // which is dynamically updated by changeTab() when the user clicks a tab.
  _onRender(context, options) {
    super._onRender?.(context, options)
    for (const [group, tab] of Object.entries(this.tabGroups)) {
      this.changeTab(tab, group, { force: true })
    }
  }

  static async #onItemCreate(event, target) {
    const type = target.dataset.type ?? "item"
    const cls = getDocumentClass("Item")
    const labels = {
      item: "CDE.ItemNew",
      weapon: "CDE.WeaponNew",
      armor: "CDE.ArmorNew",
      sanhei: "CDE.SanheiNew",
      ingredient: "CDE.IngredientNew",
      kungfu: "CDE.KFNew",
      spell: "CDE.SpellNew",
      supernatural: "CDE.SupernaturalNew",
    }
    const name = game.i18n.localize(labels[type] ?? "CDE.ItemNew")
    const systemData = {}
    if (type === "spell" && target.dataset.discipline) {
      systemData.discipline = target.dataset.discipline
    }
    return cls.create({ name, type, system: systemData }, { parent: this.document })
  }

  static #onItemEdit(event, target) {
    const itemId = target.dataset.itemId ?? target.closest("[data-item-id]")?.dataset.itemId
    const item = this.document.items.get(itemId)
    if (item) item.sheet.render(true)
  }

  static #onItemDelete(event, target) {
    const itemId = target.dataset.itemId ?? target.closest("[data-item-id]")?.dataset.itemId
    const item = this.document.items.get(itemId)
    if (item) item.delete()
  }

  static async #onEditImage(event, target) {
    const attr = target.dataset.edit
    const current = foundry.utils.getProperty(this.document, attr)
    const { img } = this.document.constructor.getDefaultArtwork?.(this.document.toObject()) ?? {}
    const fp = new FilePicker({
      current,
      type: "image",
      redirectToRoot: img ? [img] : [],
      callback: (path) => this.document.update({ [attr]: path }),
      top: this.position.top + 40,
      left: this.position.left + 10,
    })
    return fp.browse()
  }
}
