import PrismRPGItemSheet from "./base-item-sheet.mjs"

export default class PrismRPGWeaponSheet extends PrismRPGItemSheet {
  /** @override */
  static DEFAULT_OPTIONS = {
    classes: ["weapon"],
    position: {
      width: 620,
    },
    window: {
      contentClasses: ["weapon-content"],
    },
  }

  /** @override */
  static PARTS = {
    main: {
      template: "systems/fvtt-prism-rpg/templates/weapon.hbs",
    },
  }

  /** @override */
  tabGroups = {
    primary: "details",
  }

  /**
   * Prepare an array of form header tabs.
   * @returns {Record<string, Partial<ApplicationTab>>}
   */
  #getTabs() {
    const tabs = {
      details: { id: "details", group: "primary", label: "PRISMRPG.Label.details" },
      description: { id: "description", group: "primary", label: "PRISMRPG.Label.description" },
      effects: { id: "effects", group: "primary", label: "PRISMRPG.Label.effects" },
    }
    for (const v of Object.values(tabs)) {
      v.active = this.tabGroups[v.group] === v.id
      v.cssClass = v.active ? "active" : ""
    }
    return tabs
  }

  /** @override */
  async _prepareContext() {
    const context = await super._prepareContext()
    context.tabs = this.#getTabs()
    context.enrichedDescription = await foundry.applications.ux.TextEditor.implementation.enrichHTML(this.document.system.description, { async: true })

    // Enrich descriptions for all passives
    context.enrichedPassives = await Promise.all(
      this.document.system.passives.map(async (passive) => ({
        ...passive,
        enrichedDescription: await foundry.applications.ux.TextEditor.implementation.enrichHTML(passive.description, { async: true })
      }))
    )

    // Enrich descriptions for all maneuvers
    context.enrichedManeuvers = await Promise.all(
      this.document.system.maneuvers.map(async (maneuver) => ({
        ...maneuver,
        enrichedDescription: await foundry.applications.ux.TextEditor.implementation.enrichHTML(maneuver.description, { async: true })
      }))
    )

    return context
  }

  /** @override */
  _onRender(context, options) {
    super._onRender(context, options)

    // Add event listeners for passive management
    this.element.querySelectorAll('[data-action="add-passive"]').forEach(el => {
      el.addEventListener("click", this._onAddPassive.bind(this))
    })

    this.element.querySelectorAll('[data-action="delete-passive"]').forEach(el => {
      el.addEventListener("click", this._onDeletePassive.bind(this))
    })

    // Add event listeners for maneuver management
    this.element.querySelectorAll('[data-action="add-maneuver"]').forEach(el => {
      el.addEventListener("click", this._onAddManeuver.bind(this))
    })

    this.element.querySelectorAll('[data-action="delete-maneuver"]').forEach(el => {
      el.addEventListener("click", this._onDeleteManeuver.bind(this))
    })
  }

  async _onAddPassive(event) {
    event.preventDefault()
    const passives = [...this.document.system.passives]
    passives.push({ name: "", description: "" })
    await this.document.update({ "system.passives": passives })
  }

  async _onDeletePassive(event) {
    event.preventDefault()
    const index = parseInt(event.currentTarget.closest("[data-passive-index]").dataset.passiveIndex)
    const passives = this.document.system.passives.filter((_, i) => i !== index)
    await this.document.update({ "system.passives": passives })
  }

  async _onAddManeuver(event) {
    event.preventDefault()
    const maneuvers = [...this.document.system.maneuvers]
    maneuvers.push({ name: "", description: "" })
    await this.document.update({ "system.maneuvers": maneuvers })
  }

  async _onDeleteManeuver(event) {
    event.preventDefault()
    const index = parseInt(event.currentTarget.closest("[data-maneuver-index]").dataset.maneuverIndex)
    const maneuvers = this.document.system.maneuvers.filter((_, i) => i !== index)
    await this.document.update({ "system.maneuvers": maneuvers })
  }

}
