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

export default class OathHammerClassSheet extends OathHammerItemSheet {
  /** @override */
  static DEFAULT_OPTIONS = {
    classes: ["class"],
    position: {
      width: 640,
    },
    window: {
      contentClasses: ["class-content"],
    },
  }

  /** @override */
  static PARTS = {
    main: {
      template: "systems/fvtt-oath-hammer/templates/item/class-sheet.hbs",
    },
  }

  /** @override */
  async _prepareContext() {
    const context = await super._prepareContext()
    context.enrichedFeatures = await foundry.applications.ux.TextEditor.implementation.enrichHTML(
      this.document.system.features ?? "", { async: true }
    )
    return context
  }

  /** @override */
  _onRender(context, options) {
    super._onRender(context, options)
    // Handle proficiency checkboxes directly — FormDataExtended mishandles
    // multiple same-named checkboxes, so we intercept the change event,
    // collect all checked values ourselves, and stop propagation to prevent
    // the generic submitOnChange handler from clobbering the data.
    for (const cb of this.element.querySelectorAll('.proficiency-checkboxes input[type="checkbox"]')) {
      cb.addEventListener("change", this.#onProficiencyChange.bind(this))
    }
  }

  async #onProficiencyChange(event) {
    event.stopPropagation()
    const root = this.element
    const armorProficiency  = [...root.querySelectorAll('input[name="system.armorProficiency"]:checked')].map(e => e.value)
    const weaponProficiency = [...root.querySelectorAll('input[name="system.weaponProficiency"]:checked')].map(e => e.value)
    await this.document.update({
      "system.armorProficiency":  armorProficiency,
      "system.weaponProficiency": weaponProficiency,
    })
  }
}
