import { renderTemplate } from "../constants.js"

export class DialogNouveauReposCD {
  static async prompt(actor) {
    const date = game.system.rdd.calendrier.dateCourante()
    let moralChoisi = actor.system.sommeil?.moral ?? "neutre"
    const data = { name: actor.name, moral: moralChoisi }
    const content = await renderTemplate(
      "systems/foundryvtt-reve-de-dragon/templates/sommeil/dialog-nouveau-repos-cd.hbs",
      data
    )
    const result = await foundry.applications.api.DialogV2.wait({
      title: "Château Dormant — " + actor.name,
      content,
      position: { width: 400, height: "fit-content" },
      buttons: [
        {
          label: "Valider le Château Dormant",
          action: "valider",
          callback: (event, btn, dialog) => {
            const stress = Number(dialog.element.querySelector('input[name="cd-stress"]')?.value) || 0
            return { stress: { valeur: stress, motif: `Nuit du ${date}` }, moral: moralChoisi }
          }
        }
      ],
      render: (event, dialog) => {
        dialog.element.querySelectorAll(".sommeil-actor-moral a").forEach(a =>
          a.addEventListener("click", clickEvent => {
            const target = clickEvent.currentTarget
            moralChoisi = target.dataset.moral
            dialog.element.querySelectorAll(".sommeil-actor-moral a i").forEach(i => {
              i.classList.remove("fa-solid")
              i.classList.add("fa-regular")
            })
            const icon = target.querySelector("i")
            if (icon) {
              icon.classList.remove("fa-regular")
              icon.classList.add("fa-solid")
            }
          })
        )
      }
    })
    return result ?? { stress: { valeur: 0, motif: "" }, moral: "neutre" }
  }
}
