import VermineBaseActorSheet from "./base-actor-sheet.mjs"

export default class VermineGroupSheetV2 extends VermineBaseActorSheet {

  static DEFAULT_OPTIONS = {
    classes: ["group"],
    position: { width: 700, height: 600 },
    window: { contentClasses: ["group-content"] },
    actions: {
      chooseActor: VermineGroupSheetV2.#onChooseActor,
      deleteMember: VermineGroupSheetV2.#onDeleteMember,
      deleteEncounter: VermineGroupSheetV2.#onDeleteEncounter,
      deleteObjective: VermineGroupSheetV2.#onDeleteObjective,
      addObjective: VermineGroupSheetV2.#onAddObjective
    }
  }

  static PARTS = {
    main: { template: "systems/vermine2047/templates/actor/appv2/group-main.hbs" },
    tabs: { template: "templates/generic/tab-navigation.hbs" },
    info: { template: "systems/vermine2047/templates/actor/appv2/group-info.hbs" },
    gear: { template: "systems/vermine2047/templates/actor/appv2/group-gear.hbs" },
    road: { template: "systems/vermine2047/templates/actor/appv2/group-road.hbs" },
    reserve: { template: "systems/vermine2047/templates/actor/appv2/group-reserve.hbs" }
  }

  tabGroups = { sheet: "info" }

  #getTabs() {
    const tabs = {
      info: { id: "info", group: "sheet", icon: "fas fa-star", label: "VERMINE.information" },
      gear: { id: "gear", group: "sheet", icon: "fas fa-gear", label: "VERMINE.gear" },
      road: { id: "road", group: "sheet", icon: "fas fa-route", label: "VERMINE.road" },
      reserve: { id: "reserve", group: "sheet", icon: "fas fa-users", label: "VERMINE.reserve" }
    }
    for (const v of Object.values(tabs)) {
      v.active = this.tabGroups[v.group] === v.id
      v.cssClass = v.active ? "active" : ""
    }
    return tabs
  }

  async _prepareContext() {
    const context = await super._prepareContext()
    context.tabs = this.#getTabs()
    // Résoudre les IDs des membres/encounters en données acteur
    context.resolvedMembers = {}
    if (this.document.system.members?.length > 0) {
      for (const memberId of this.document.system.members) {
        const a = game.actors.get(memberId)
        if (a) context.resolvedMembers[memberId] = { name: a.name, id: a.id }
      }
    }
    context.resolvedEncounters = {}
    if (this.document.system.encounters?.length > 0) {
      for (const encId of this.document.system.encounters) {
        const a = game.actors.get(encId)
        if (a) context.resolvedEncounters[encId] = { name: a.name, id: a.id }
      }
    }
    return context
  }

  async _preparePartContext(partId, context) {
    const doc = this.document
    switch (partId) {
      case "main": break
      case "info":
        context.tab = context.tabs.info
        context.abilities = doc.itemTypes.ability
        context.specialties = doc.itemTypes.specialty
        context.backgrounds = doc.itemTypes.background
        context.traumas = doc.itemTypes.trauma
        context.evolutions = doc.itemTypes.evolution
        break
      case "gear":
        context.tab = context.tabs.gear
        context.gear = doc.itemTypes.item
        context.weapons = doc.itemTypes.weapon
        context.defenses = doc.itemTypes.defense
        break
      case "road":
        context.tab = context.tabs.road
        context.vehicles = doc.itemTypes.vehicle
        break
      case "reserve":
        context.tab = context.tabs.reserve
        break
    }
    return context
  }

  // Actions : délégation aux applications AppV1 existantes pour TotemPicker/ActorPicker
  static async #onChooseTotem(event, target) {
    const { TotemPicker } = await import("../../system/applications.mjs")
    new TotemPicker(target, this.document).render(true)
  }
  static async #onChooseActor(event, target) {
    const { ActorPicker } = await import("../../system/applications.mjs")
    new ActorPicker(target, this.document).render(true)
  }
  static #onDeleteMember(event, target) {
    const li = target.closest("li.actor")
    if (!li) return
    const actorId = li.dataset.actorId
    const idx = this.document.system.members.indexOf(actorId)
    if (idx !== -1) {
      const members = [...this.document.system.members]
      members.splice(idx, 1)
      this.document.update({ "system.members": members })
    }
  }
  static #onDeleteEncounter(event, target) {
    const li = target.closest("li.actor")
    if (!li) return
    const actorId = li.dataset.actorId
    const idx = this.document.system.encounters.indexOf(actorId)
    if (idx !== -1) {
      const encounters = [...this.document.system.encounters]
      encounters.splice(idx, 1)
      this.document.update({ "system.encounters": encounters })
    }
  }
  static #onDeleteObjective(event, target) {
    const type = target.dataset.type
    const index = parseInt(target.dataset.index)
    if (isNaN(index)) return
    const objectives = foundry.utils.duplicate(this.document.system.objectives || { major: [], minor: [] })
    objectives[type].splice(index, 1)
    this.document.update({ "system.objectives": objectives })
  }
  static #onAddObjective(event, target) {
    const type = target.dataset.type === "major_objective" ? "major" : "minor"
    const objectives = foundry.utils.duplicate(this.document.system.objectives || { major: [], minor: [] })
    objectives[type].push("")
    this.document.update({ "system.objectives": objectives })
  }
}
