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

export default class MournbladeCompetenceSheet extends MournbladeItemSheet {
  /** @override */
  static DEFAULT_OPTIONS = {
    classes: ["competence"],
    position: {
      width: 620,
    },
    window: {
      contentClasses: ["competence-content"],
    },
    actions: {
      ...MournbladeItemSheet.DEFAULT_OPTIONS.actions,
      addPredilection: MournbladeCompetenceSheet.#onAddPredilection,
      deletePredilection: MournbladeCompetenceSheet.#onDeletePredilection,
    },
  }

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

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

  /**
   * Prepare an array of form header tabs.
   * @returns {Record<string, Partial<ApplicationTab>>}
   */
  #getTabs() {
    const tabs = {
      details: { id: "details", group: "primary", label: "Détails" },
      description: { id: "description", group: "primary", label: "Description" }
    }
    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()
    return context
  }

  /**
   * Add a new empty predilection to the competence
   * @param {PointerEvent} event
   */
  static async #onAddPredilection(event) {
    event.preventDefault()
    const predilections = foundry.utils.duplicate(this.document.system.predilections ?? [])
    predilections.push({ name: "", used: false })
    await this.document.update({ "system.predilections": predilections })
  }

  /**
   * Delete a predilection by index
   * @param {PointerEvent} event
   * @param {HTMLElement} target
   */
  static async #onDeletePredilection(event, target) {
    event.preventDefault()
    const idx = Number(target.dataset.predictionIndex)
    const predilections = foundry.utils.duplicate(this.document.system.predilections ?? [])
    predilections.splice(idx, 1)
    await this.document.update({ "system.predilections": predilections })
  }
}