import BoLBaseActorSheet from "./base-actor-sheet.mjs"
import { BoLUtility } from "../../system/bol-utility.js"

/**
 * Actor Sheet for BoL characters and encounters using AppV2
 */
export default class BoLActorSheet extends BoLBaseActorSheet {
  /** @override */
  static DEFAULT_OPTIONS = {
    ...super.DEFAULT_OPTIONS,
    classes: [...super.DEFAULT_OPTIONS.classes],
    actions: {
      ...super.DEFAULT_OPTIONS.actions,
    },
  }

  /** @override */
  static PARTS = {
    sheet: {
      template: "systems/bol/templates/actor/actor-sheet.hbs",
    },
  }

  /** @override */
  tabGroups = { primary: "stats" }

  /** @override */
  async _prepareContext() {
    const context = await super._prepareContext()
    const actor = this.document

    context.data = actor.toObject()
    context.details = actor.details
    context.attributes = actor.attributes
    context.aptitudes = actor.aptitudes
    context.resources = actor.getResourcesFromType()
    context.xp = actor.system.xp
    context.equipment = actor.equipment
    context.equipmentCreature = actor.equipmentCreature
    context.weapons = actor.weapons
    context.protections = actor.protections
    context.spells = actor.spells
    context.alchemy = actor.alchemy
    context.containers = actor.containers
    context.treasure = actor.treasure
    context.boleffects = actor.boleffects
    context.alchemyrecipe = actor.alchemyrecipe
    context.horoscopes = actor.horoscopes
    context.vehicles = actor.vehicles
    context.fightoptions = actor.fightoptions
    context.ammos = actor.ammos
    context.misc = actor.misc
    context.xplog = actor.xplog
    context.combat = actor.buildCombat()
    context.initiativeRank = actor.getInitiativeRank()
    context.features = actor.buildFeatures()
    context.options = this.options
    context.editScore = this.options.editScore
    context.useBougette = (actor.type === "character" && BoLUtility.getUseBougette()) || false
    context.bougette = actor.getBougette()
    context.charType = actor.getCharType()
    context.villainy = actor.getVillainy()
    context.isUndead = actor.isUndead()
    context.biography = await foundry.applications.ux.TextEditor.implementation.enrichHTML(
      actor.system.details?.biography || "", { async: true }
    )
    context.notes = await foundry.applications.ux.TextEditor.implementation.enrichHTML(
      actor.system.details?.notes || "", { async: true }
    )
    context.isSorcerer = actor.isSorcerer()
    context.isAlchemist = actor.isAlchemist()
    context.isAstrologer = actor.isAstrologer()
    context.isMysteries = context.isSorcerer || context.isAlchemist || context.isAstrologer
    context.isPriest = actor.isPriest()
    context.horoscopeGroupList = game.settings.get("bol", "horoscope-group")

    console.log("ACTORDATA (AppV2)", context)
    return context
  }

  /** @override */
  _activateListeners() {
    super._activateListeners()
    if (!this.isEditable) return

    // Create generic item
    this.element.querySelectorAll(".create-item").forEach((el) => {
      el.addEventListener("click", () => {
        this.actor.createEmbeddedDocuments("Item", [{ name: game.i18n.localize("BOL.ui.newEquipment"), type: "item" }], { renderSheet: true })
      })
    })

    // Create natural weapon
    this.element.querySelectorAll(".create-natural-weapon").forEach((el) => {
      el.addEventListener("click", () => {
        const system = foundry.utils.duplicate(game.bol.config.defaultNaturalWeapon)
        this.actor.createEmbeddedDocuments("Item", [{ name: game.i18n.localize("BOL.ui.newNaturalWeapon"), type: "item", system }], { renderSheet: true })
      })
    })

    // Create natural protection
    this.element.querySelectorAll(".create-natural-protection").forEach((el) => {
      el.addEventListener("click", () => {
        const system = foundry.utils.duplicate(game.bol.config.defaultNaturalProtection)
        this.actor.createEmbeddedDocuments("Item", [{ name: game.i18n.localize("BOL.ui.newNaturalProtection"), type: "item", system }], { renderSheet: true })
      })
    })

    // Item create via header dataset (type-based creation)
    this.element.querySelectorAll(".item-create").forEach((el) => {
      el.addEventListener("click", (ev) => {
        ev.preventDefault()
        const header = ev.currentTarget
        const type = header.dataset.type
        const data = foundry.utils.duplicate(header.dataset)
        const name = `New ${type}`
        delete data.type
        this.actor.createEmbeddedDocuments("Item", [{ name, type, data }])
      })
    })

    // Add XP Log entry
    this.element.querySelectorAll(".xplog-add").forEach((el) => {
      el.addEventListener("click", (ev) => {
        ev.preventDefault()
        this.actor.addXPLog("other", "Nouveau", 0, 0)
      })
    })

    // Add item by category/subtype (equipment tab headers)
    this.element.querySelectorAll(".item-add").forEach((el) => {
      el.addEventListener("click", (ev) => {
        ev.preventDefault()
        const { itemType, category, subtype } = ev.currentTarget.dataset
        const system = { category, subtype }
        this.actor.createEmbeddedDocuments("Item", [{
          name: game.i18n.localize("BOL.ui.newEquipment"),
          type: itemType || "item",
          system,
        }], { renderSheet: true })
      })
    })
  }
}
