/**
 * 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 { DonjonEtCieRolls } from "../donjon-et-cie-rolls.mjs";
import { DonjonEtCieUtility } from "../donjon-et-cie-utility.mjs";

export class DonjonEtCieRollDialog {
  static async createInitiative(actor) {
    const content = await foundry.applications.handlebars.renderTemplate(
      "systems/fvtt-donjon-et-cie/templates/dialogs/initiative-roll.hbs",
      {
        actorName: actor.name,
        dex: actor.system.caracteristiques?.dexterite?.value ?? 0,
        initiativeBonus: actor.system.combat?.initiativeBonus ?? 0
      }
    );

    return foundry.applications.api.DialogV2.wait({
      window: { title: game.i18n.localize("DNC.Roll.Initiative"), icon: "fa-solid fa-bolt" },
      classes: ["dnc-roll-dialog"],
      content,
      modal: false,
      buttons: [
        {
          action: "roll",
          label: game.i18n.localize("DNC.UI.RollAction"),
          icon: "fa-solid fa-bolt",
          default: true,
          callback: async (event, button) => {
            const form = button.form.elements;
            return DonjonEtCieRolls.rollInitiative(actor, {
              mode: form.mode?.value ?? "normal"
            });
          }
        }
      ],
      rejectClose: false
    });
  }

  static async createCharacteristic(actor, characteristicKey) {
    const characteristic = actor.system.caracteristiques?.[characteristicKey];
    if (!characteristic) return;

    const content = await foundry.applications.handlebars.renderTemplate(
      "systems/fvtt-donjon-et-cie/templates/dialogs/characteristic-roll.hbs",
      {
        actorName: actor.name,
        characteristic,
        characteristicKey,
        favorOptions: DonjonEtCieUtility.getAvailableFavorOptions(actor),
        hasFavorOptions: DonjonEtCieUtility.getAvailableFavorOptions(actor).length > 0
      }
    );

    return foundry.applications.api.DialogV2.wait({
      window: { title: game.i18n.localize("DNC.Roll.Characteristic"), icon: "fa-solid fa-dice-d20" },
      classes: ["dnc-roll-dialog"],
      content,
      modal: false,
      buttons: [
        {
          action: "roll",
          label: game.i18n.localize("DNC.UI.RollAction"),
          icon: "fa-solid fa-dice-d20",
          default: true,
          callback: async (event, button) => {
              const form = button.form.elements;
              return DonjonEtCieRolls.rollCharacteristic(actor, characteristicKey, {
                mode: form.mode?.value ?? "normal",
                favorKey: form.favorDepartment?.value ?? ""
              });
            }
        }
      ],
      rejectClose: false
    });
  }

  static async createWeapon(actor, item) {
    const content = await foundry.applications.handlebars.renderTemplate(
      "systems/fvtt-donjon-et-cie/templates/dialogs/weapon-roll.hbs",
      {
        actorName: actor.name,
        item,
        characteristicLabel: DonjonEtCieUtility.getWeaponCharacteristicLabel(item.system.categorie),
        characteristicValue: actor.system.caracteristiques?.[DonjonEtCieUtility.getWeaponCharacteristicKey(item.system.categorie)]?.value ?? 0,
        favorOptions: DonjonEtCieUtility.getAvailableFavorOptions(actor),
        hasFavorOptions: DonjonEtCieUtility.getAvailableFavorOptions(actor).length > 0
      }
    );

    return foundry.applications.api.DialogV2.wait({
      window: { title: game.i18n.localize("DNC.Roll.Attack"), icon: "fa-solid fa-sword" },
      classes: ["dnc-roll-dialog"],
      content,
      modal: false,
      buttons: [
        {
          action: "roll",
          label: game.i18n.localize("DNC.UI.AttackAction"),
          icon: "fa-solid fa-sword",
          default: true,
          callback: async (event, button) => {
            const form = button.form.elements;
              return DonjonEtCieRolls.rollWeapon(actor, item, {
                mode: form.mode?.value ?? "normal",
                favorKey: form.favorDepartment?.value ?? ""
              });
            }
        }
      ],
      rejectClose: false
    });
  }

  static async createSpell(actor, item) {
    const characteristicKey = item.system.caracteristique || "intelligence";
    const characteristic = actor.system.caracteristiques?.[characteristicKey];
    const magicResources = DonjonEtCieUtility.getMagicResourceContext(actor);
    const content = await foundry.applications.handlebars.renderTemplate(
      "systems/fvtt-donjon-et-cie/templates/dialogs/spell-roll.hbs",
      {
        actorName: actor.name,
        item,
        characteristic,
        rank: magicResources.rank,
        currentPv: actor.system.sante?.pv?.value ?? 0,
        focusLabel: magicResources.focusLabel,
        focusDisplay: magicResources.focusDisplay,
        focusIsActive: magicResources.focusIsActive,
        chaosLabel: magicResources.chaosLabel,
        autoDisadvantage: Number(item.system.coutPv ?? 0) > magicResources.rank,
        favorOptions: DonjonEtCieUtility.getAvailableFavorOptions(actor),
        hasFavorOptions: DonjonEtCieUtility.getAvailableFavorOptions(actor).length > 0
      }
    );

    return foundry.applications.api.DialogV2.wait({
      window: { title: game.i18n.localize("DNC.Roll.Spell"), icon: "fa-solid fa-wand-magic-sparkles" },
      classes: ["dnc-roll-dialog"],
      content,
      modal: false,
      buttons: [
        {
          action: "roll",
          label: game.i18n.localize("DNC.UI.RollAction"),
          icon: "fa-solid fa-wand-magic-sparkles",
          default: true,
          callback: async (event, button) => {
              const form = button.form.elements;
              return DonjonEtCieRolls.rollSpell(actor, item, {
                mode: form.mode?.value ?? "normal",
                favorKey: form.favorDepartment?.value ?? ""
              });
            }
        }
      ],
      rejectClose: false
    });
  }

  static async createUsage(item) {
    const content = await foundry.applications.handlebars.renderTemplate(
      "systems/fvtt-donjon-et-cie/templates/dialogs/usage-roll.hbs",
      {
        item
      }
    );

    return foundry.applications.api.DialogV2.wait({
      window: { title: game.i18n.localize("DNC.Roll.Usage"), icon: "fa-solid fa-hourglass-half" },
      classes: ["dnc-roll-dialog"],
      content,
      modal: false,
      buttons: [
        {
          action: "roll",
          label: game.i18n.localize("DNC.UI.UseAction"),
          icon: "fa-solid fa-hourglass-half",
          default: true,
          callback: async (event, button) => {
            const form = button.form.elements;
            return DonjonEtCieRolls.rollUsage(item, {
              mode: form.mode?.value ?? "normal"
            });
          }
        }
      ],
      rejectClose: false
    });
  }

  static async createDamage(actor, item) {
    const damageContext = DonjonEtCieUtility.getMartialDamageContext(actor, item);
    const isMeleeTwoHanded = item.type === "arme" && item.system?.categorie === "melee" && Number(item.system?.mains ?? 1) > 1;
    const defaultMode = isMeleeTwoHanded ? "avantage" : "normal";
    const content = await foundry.applications.handlebars.renderTemplate(
      "systems/fvtt-donjon-et-cie/templates/dialogs/damage-roll.hbs",
      {
        actorName: actor?.name ?? item.actor?.name ?? "",
        item,
        damageFormula: damageContext.effectiveFormula || item.system.degats,
        damageBase: damageContext.baseFormula || item.system.degats,
        damageCapped: damageContext.capped,
        martialDvLabel: damageContext.martialDvSides ? `d${damageContext.martialDvSides}` : damageContext.martialDvFormula,
        defaultMode
      }
    );

    return foundry.applications.api.DialogV2.wait({
      window: { title: game.i18n.localize("DNC.Roll.Damage"), icon: "fa-solid fa-burst" },
      classes: ["dnc-roll-dialog"],
      content,
      modal: false,
      buttons: [
        {
          action: "roll",
          label: game.i18n.localize("DNC.UI.RollAction"),
          icon: "fa-solid fa-burst",
          default: true,
          callback: async (event, button) => {
            const form = button.form.elements;
            return DonjonEtCieRolls.rollDamage(actor, item, {
              mode: form.mode?.value ?? "normal"
            });
          }
        }
      ],
      rejectClose: false
    });
  }
}
