/**
 * 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 DonjonEtCieActorSheet from "./base-actor-sheet.mjs";
import { DonjonEtCieUtility } from "../../donjon-et-cie-utility.mjs";

export default class DonjonEtCiePNJSheet extends DonjonEtCieActorSheet {
  static DEFAULT_OPTIONS = {
    ...super.DEFAULT_OPTIONS,
    classes: [...super.DEFAULT_OPTIONS.classes, "pnj"],
    position: { width: 840, height: 760 },
    actions: {
      ...super.DEFAULT_OPTIONS.actions,
      rollPnjArmor: DonjonEtCiePNJSheet.#onRollPnjArmor,
      rollPnjCourage: DonjonEtCiePNJSheet.#onRollPnjCourage,
      rollPnjAttackDamage: DonjonEtCiePNJSheet.#onRollPnjAttackDamage,
      createPnjAttack: DonjonEtCiePNJSheet.#onCreatePnjAttack,
      deletePnjAttack: DonjonEtCiePNJSheet.#onDeletePnjAttack
    }
  };

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

  async _prepareContext() {
    const context = await super._prepareContext();
    const system = this.document.system;
    const indexedSections = Object.fromEntries(context.sections.map((section) => [section.key, section]));
    const getSection = (key) => indexedSections[key] ?? {
      key,
      label: context.config.actorSections[key]?.label ?? key,
      createType: context.config.actorSections[key]?.createType ?? key,
      items: []
    };

    return {
      ...context,
      capacitySection: getSection("capacites"),
      spellSection: getSection("sortileges"),
      armorDisplay: Number(system.defense?.armure?.delta ?? 0) ? `Δ${system.defense.armure.delta}` : "—",
      storedArmor: Number(system.defense?.armure?.resultatProtection ?? 0) > 0 ? system.defense.armure.resultatProtection : "—",
      courageDisplay: Number(system.defense?.courage?.delta ?? 0) ? `Δ${system.defense.courage.delta}` : "—",
      pnjAttacks: this.document.getPnjAttacks()
    };
  }

  static async #onRollPnjArmor(event) {
    event.preventDefault();
    return this.document.rollPnjArmor();
  }

  static async #onRollPnjCourage(event) {
    event.preventDefault();
    return this.document.rollPnjCourage();
  }

  static async #onRollPnjAttackDamage(event) {
    event.preventDefault();
    return this.document.rollPnjAttackDamage(event.target.closest("[data-attack-index]")?.dataset.attackIndex ?? 0);
  }

  static async #onCreatePnjAttack(event) {
    event.preventDefault();
    return this.document.createPnjAttack();
  }

  static async #onDeletePnjAttack(event) {
    event.preventDefault();
    return this.document.deletePnjAttack(event.target.closest("[data-attack-index]")?.dataset.attackIndex ?? 0);
  }
}
