/**
 * Dialog for spending Luck Points after a roll result is known.
 * Called from the "🍀 Luck" button on chat cards.
 */
export default class OathHammerLuckRollDialog {

  /**
   * Prompt the actor's owner to spend luck points after seeing a roll result.
   * @param {Actor} actor
   * @returns {Promise<{luckSpend: number, luckIsHuman: boolean}|null>}
   */
  static async prompt(actor) {
    const actorSys     = actor.system
    const availableLuck = actorSys.luck?.value ?? 0
    if (availableLuck <= 0) {
      ui.notifications.warn(game.i18n.localize("OATHHAMMER.Roll.NoLuckLeft"))
      return null
    }

    const isHuman          = (actorSys.lineage?.name ?? "").toLowerCase() === "human"
    const luckDicePerPoint = isHuman ? 3 : 2

    const luckOptions = Array.from({ length: availableLuck + 1 }, (_, i) => ({
      value:    i,
      label:    i === 0 ? "0" : `${i} LP (+${i * luckDicePerPoint}d)`,
      selected: i === 1,
    }))

    const content = await foundry.applications.handlebars.renderTemplate(
      "systems/fvtt-oath-hammer/templates/luck-roll-dialog.hbs",
      { availableLuck, isHuman, luckOptions }
    )

    const result = await foundry.applications.api.DialogV2.wait({
      window:      { title: game.i18n.format("OATHHAMMER.Dialog.LuckPostRollTitle", { name: actor.name }) },
      classes:     ["fvtt-oath-hammer"],
      content,
      rejectClose: false,
      buttons: [{
        label:    game.i18n.localize("OATHHAMMER.Dialog.LuckPostRollConfirm"),
        callback: (_ev, btn) => {
          const spend = parseInt(btn.form.elements.luckSpend?.value) || 0
          const isH   = btn.form.elements.luckIsHuman?.checked ?? false
          return { luckSpend: spend, luckIsHuman: isH }
        },
      }],
    })

    if (!result || result.luckSpend <= 0) return null
    return result
  }
}
