/**
 * Donjon & Cie - Systeme FoundryVTT
 *
 * Donjon & Cie est un jeu de role edite par John Doe.
 * Ce systeme FoundryVTT est une implementation independante et n'est pas
 * affilie a John Doe.
 *
 * @author    LeRatierBretonnien
 * @copyright 2025–2026 LeRatierBretonnien
 * @license   CC BY-NC-SA 4.0 – https://creativecommons.org/licenses/by-nc-sa/4.0/
 */

import { DonjonEtCieUtility } from "../../donjon-et-cie-utility.mjs";

const { HandlebarsApplicationMixin } = foundry.applications.api;

export default class DonjonEtCieItemSheet extends HandlebarsApplicationMixin(foundry.applications.sheets.ItemSheetV2) {
  static DEFAULT_OPTIONS = {
    classes: ["fvtt-donjon-et-cie", "sheet", "item"],
    position: { width: 640, height: 700 },
    form: {
      submitOnChange: true,
      closeOnSubmit: false
    },
    window: {
      resizable: true
    },
    actions: {
      editImage: DonjonEtCieItemSheet.#onEditImage,
      postItem: DonjonEtCieItemSheet.#onPostItem,
      rollItem: DonjonEtCieItemSheet.#onRollItem,
      rollDamageItem: DonjonEtCieItemSheet.#onRollDamageItem,
      resetUsageItem: DonjonEtCieItemSheet.#onResetUsageItem
    }
  };

  static PARTS = {
    main: { template: "systems/fvtt-donjon-et-cie/templates/items/item-sheet.hbs" }
  };

  async _prepareContext() {
    const item = this.document;
    return {
      item,
      system: item.system,
      source: item.toObject(),
      config: game.system.donjonEtCie.config,
      fields: item.schema.fields,
      systemFields: item.system.schema.fields,
      isWeapon: item.type === "arme",
      isArmor: item.type === "armure",
      isConsumable: item.type === "consommable",
      isTraining: item.type === "entrainement",
      isSpell: item.type === "sortilege",
      canRollDamage: Boolean(item.system.degats),
      isEquipment: item.type === "equipement",
      isCapacity: item.type === "capacite",
      isLanguage: item.type === "langue",
      isTrait: item.type === "trait",
      ammunitionUsageLabel: item.type === "arme" && Number(item.system.munitionsDelta ?? 0) > 0
        ? DonjonEtCieUtility.formatUsageDie(item.system.munitionsDelta)
        : "—",
      canResetUsage: item.type === "entrainement" && Number(item.system.deltaMax ?? 0) > 0 && Number(item.system.delta ?? 0) !== Number(item.system.deltaMax ?? 0),
      armorProtectionDisplay: Number(item.system.resultatProtection ?? 0) > 0 ? item.system.resultatProtection : "—",
      weaponCharacteristicLabel: item.type === "arme" ? DonjonEtCieUtility.getWeaponCharacteristicLabel(item.system.categorie) : null,
      enrichedDescription: await foundry.applications.ux.TextEditor.implementation.enrichHTML(item.system.description ?? "", { async: true }),
      enrichedNotes: await foundry.applications.ux.TextEditor.implementation.enrichHTML(item.system.notes ?? "", { async: true })
    };
  }

  _onRender(context, options) {
    super._onRender(context, options);
    this.#fixWindowShell();
  }

  #fixWindowShell() {
    const content = this.element?.closest(".window-content") ?? this.element?.parentElement;
    const app = content?.closest(".application") ?? this.element?.closest(".application");
    const header = app?.querySelector(".window-header");

    if (app) {
      app.style.display = "flex";
      app.style.flexDirection = "column";
      app.style.paddingTop = "0";
      app.style.overflow = "hidden";
    }

    if (header) {
      header.style.width = "100%";
      header.style.flex = "0 0 auto";
      header.style.position = "relative";
      header.style.zIndex = "3";
    }

    if (content) {
      content.style.width = "100%";
      content.style.flex = "1 1 auto";
      content.style.minHeight = "0";
      content.style.overflowY = "auto";
      content.style.overflowX = "hidden";
    }
  }

  static async #onEditImage(event) {
    event.preventDefault();
    const picker = new FilePicker({
      type: "image",
      current: this.document.img,
      callback: (path) => this.document.update({ img: path })
    });
    return picker.browse();
  }

  static async #onPostItem(event) {
    event.preventDefault();
    return this.document.postToChat();
  }

  static async #onRollItem(event) {
    event.preventDefault();
    return this.document.roll();
  }

  static async #onRollDamageItem(event) {
    event.preventDefault();
    return this.document.rollDamage();
  }

  static async #onResetUsageItem(event) {
    event.preventDefault();
    return this.document.resetUsageDie();
  }
}
