import VermineBaseActorSheet from "./base-actor-sheet.mjs"

export default class VermineCreatureSheetV2 extends VermineBaseActorSheet {

  // La fiche créature s'ouvre en mode édition : Gabarit, Taille, Rôle et Meute
  // se règlent dès l'ouverture (le mode jeu reste accessible via le toggle).
  _sheetMode = this.constructor.SHEET_MODES.EDIT

  static DEFAULT_OPTIONS = {
    classes: ["creature"],
    position: { width: 700, height: 650 },
    window: { contentClasses: ["creature-content"] }
  }

  static PARTS = {
    main: { template: "systems/vermine2047/templates/actor/appv2/creature-main.hbs", scrollable: [""] },
    tabs: { template: "templates/generic/tab-navigation.hbs" },
    info: { template: "systems/vermine2047/templates/actor/appv2/creature-info.hbs", scrollable: [""] },
    stats: { template: "systems/vermine2047/templates/actor/appv2/creature-stats.hbs", scrollable: [""] },
    combat: { template: "systems/vermine2047/templates/actor/appv2/creature-combat.hbs", scrollable: [""] },
    effects: { template: "systems/vermine2047/templates/actor/appv2/creature-effects.hbs", scrollable: [""] }
  }

  tabGroups = { sheet: "info" }

  #getTabs() {
    const tabs = {
      info: { id: "info", group: "sheet", icon: "fas fa-info-circle", label: "VERMINE.information" },
      stats: { id: "stats", group: "sheet", icon: "fas fa-chart-bar", label: "VERMINE.stats" },
      combat: { id: "combat", group: "sheet", icon: "fas fa-sword", label: "VERMINE.combat" },
      effects: { id: "effects", group: "sheet", icon: "fas fa-magic", label: "UI.effects.name" }
    }
    for (const v of Object.values(tabs)) {
      v.active = this.tabGroups[v.group] === v.id
      v.cssClass = v.active ? "active" : ""
    }
    return tabs
  }

  async _prepareContext() {
    const context = await super._prepareContext()
    context.tabs = this.#getTabs()
    return context
  }

  changeTab(tab, group, options = {}) {
    super.changeTab(tab, group, options)
    if (group === "sheet") {
      const main = this.element?.querySelector('[data-group="sheet"][data-tab="main"]')
      if (main) main.classList.add("active")
    }
  }

  async _preparePartContext(partId, context) {
    const doc = this.document
    switch (partId) {
      case "main":
        context.patternOptions = CONFIG.VERMINE.creaturePatternLevels
        context.roleOptions = CONFIG.VERMINE.creatureRoleLevels
        context.sizeOptions = CONFIG.VERMINE.creatureSizeLevels
        context.packOptions = CONFIG.VERMINE.creaturePackLevels
        context.sizeLabel = doc.system.size?.value !== undefined
          ? game.i18n.localize(CONFIG.VERMINE.creatureSizeLevels[doc.system.size.value]?.label ?? "")
          : ""
        context.packLabel = doc.system.pack?.value
          ? game.i18n.localize(CONFIG.VERMINE.creaturePackLevels[doc.system.pack.value]?.label ?? "")
          : ""
        break
      case "info":
        context.tab = context.tabs.info
        context.capacities = doc.itemTypes.creaturecapacity
        break
      case "stats":
        context.tab = context.tabs.stats
        context.patternLabel = doc.system.pattern?.value ? game.i18n.localize(CONFIG.VERMINE.creaturePatternLevels[doc.system.pattern.value]?.label ?? "") : ""
        context.sizeLabel = doc.system.size?.value !== undefined ? game.i18n.localize(CONFIG.VERMINE.creatureSizeLevels[doc.system.size.value]?.label ?? "") : ""
        context.roleLabel = doc.system.role?.value ? game.i18n.localize(CONFIG.VERMINE.creatureRoleLevels[doc.system.role.value]?.label ?? "") : ""
        context.packLabel = doc.system.pack?.value
          ? `${doc.system.pack.value} (${game.i18n.localize(CONFIG.VERMINE.creaturePackLevels[doc.system.pack.value]?.label ?? "")})`
          : game.i18n.localize("VERMINE.none")
        // Contribution cumulée de la Taille (les modificateurs se cumulent : Taille N = somme 1..N)
        const sizeLevels = CONFIG.VERMINE.creatureSizeLevels || {}
        const sizeLevel = doc.system.size?.value ?? 0
        context.sizeCumulative = { attack: 0, vigor: 0, minorWound: 0, majorWound: 0, deadlyWound: 0 }
        for (let i = 1; i <= sizeLevel; i++) {
          const cfg = sizeLevels[i] || {}
          context.sizeCumulative.attack += cfg.attack || 0
          context.sizeCumulative.vigor += cfg.vigor || 0
          context.sizeCumulative.minorWound += cfg.minorWound || 0
          context.sizeCumulative.majorWound += cfg.majorWound || 0
          context.sizeCumulative.deadlyWound += cfg.deadlyWound || 0
        }
        break
      case "combat":
        context.tab = context.tabs.combat
        context.weapons = doc.itemTypes.weapon
        context.equippedWeapons = doc.itemTypes.weapon.filter(i => i.system.equipped)
        context.equippedDefenses = doc.itemTypes.defense.filter(i => i.system.equipped)
        break
      case "effects":
        context.tab = context.tabs.effects
        const { prepareActiveEffectCategories } = await import("../../system/effects.mjs")
        context.effects = prepareActiveEffectCategories(doc.effects)
        break
    }
    return context
  }

  /** @override - Les créatures n'ont pas de caractéristiques/compétences : on ouvre le dialogue d'attaque (pool calculé) ou de Réaction. */
  async _onRoll(event) {
    event.preventDefault()
    const el = event.currentTarget
    const type = el.dataset.type
    if (type === "creature-reaction") {
      const { default: NpcRollDialog } = await import("../../system/dialogs/npcRollDialog.mjs")
      const dialog = await NpcRollDialog.create({ actorId: this.document.id, rolltype: "reaction" })
      if (dialog) dialog.render(true)
      return
    }
    if (type !== "creature-attack") return super._onRoll(event)
    const { default: CombatDialog } = await import("../../system/dialogs/combatDialog.mjs")
    const dialog = await CombatDialog.create({ actorId: this.document.id })
    if (dialog) dialog.render(true)
  }
}
