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

export default class HeritiersCompetenceSheet extends HeritiersItemSheet {
  /** @override */
  static DEFAULT_OPTIONS = {
    ...super.DEFAULT_OPTIONS,
    window: {
      ...super.DEFAULT_OPTIONS.window,
      title: "SHEETS.Item.competence",
    },
    actions: {
      addSpecialite: HeritiersCompetenceSheet.#onAddSpecialite,
      deleteSpecialite: HeritiersCompetenceSheet.#onDeleteSpecialite,
    }
  }

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

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

    // Attacher les écouteurs pour l'édition des spécialités
    this.element.querySelectorAll('.edit-specialite').forEach(input => {
      input.addEventListener('change', async (event) => {
        const li = event.target.closest('.specialite-item')
        const index = Number.parseInt(li?.dataset.specialiteIndex)
        if (index !== undefined && !Number.isNaN(index)) {
          const spec = foundry.utils.duplicate(this.item.system.specialites) || []
          if (spec[index]) {
            spec[index].name = event.target.value
            await this.item.update({ 'system.specialites': spec })
          }
        }
      })
    })

    this.element.querySelectorAll('.edit-specialite-description').forEach(textarea => {
      textarea.addEventListener('change', async (event) => {
        const li = event.target.closest('.specialite-item')
        const index = Number.parseInt(li?.dataset.specialiteIndex)
        if (index !== undefined && !Number.isNaN(index)) {
          const spec = foundry.utils.duplicate(this.item.system.specialites) || []
          if (spec[index]) {
            spec[index].description = event.target.value
            await this.item.update({ 'system.specialites': spec })
          }
        }
      })
    })
  }

  /* -------------------------------------------- */
  /*  Event Handlers                              */
  /* -------------------------------------------- */

  static async #onAddSpecialite(event, target) {
    let spec = foundry.utils.duplicate(this.item.system.specialites) || []
    spec.push({ name: "Nouvelle Spécialité", description: "", used: false })
    await this.item.update({ 'system.specialites': spec })
  }

  static async #onDeleteSpecialite(event, target) {
    const li = target.closest(".specialite-item")
    let index = Number.parseInt(li.dataset.specialiteIndex)
    let spec = foundry.utils.duplicate(this.item.system.specialites) || []
    spec.splice(index, 1)
    await this.item.update({ 'system.specialites': spec })
  }
}
