/**
 * 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 CDEBaseItemSheet extends HandlebarsApplicationMixin(foundry.applications.sheets.ItemSheetV2) {
  static DEFAULT_OPTIONS = {
    classes: ["fvtt-chroniques-de-l-etrange", "item"],
    position: { width: 520, height: "auto" },
    window: { resizable: true },
    form: { submitOnChange: true },
    actions: {
      editImage: CDEBaseItemSheet.#onEditImage,
    },
  }

  tabGroups = { primary: "details" }

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

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

  // Restore the active tab after every render (including re-renders from submitOnChange).
  _onRender(context, options) {
    super._onRender?.(context, options)
    for (const [group, tab] of Object.entries(this.tabGroups)) {
      this.changeTab(tab, group, { force: true })
    }
  }

  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()
  }
}
