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

export default class VermineVehicleSheetV2 extends VermineBaseActorSheet {

  static DEFAULT_OPTIONS = {
    classes: ["vehicle"],
    position: { width: 640, height: 580 },
    window: { contentClasses: ["vehicle-content"] }
  }

  static PARTS = {
    main: { template: "systems/vermine2047/templates/actor/appv2/vehicle-main.hbs", scrollable: [""] },
    tabs: { template: "templates/generic/tab-navigation.hbs" },
    specs: { template: "systems/vermine2047/templates/actor/appv2/vehicle-specs.hbs", scrollable: [""] }
  }

  tabGroups = { sheet: "specs" }

  #getTabs() {
    const tabs = {
      specs: { id: "specs", group: "sheet", icon: "fas fa-car-side", label: "VERMINE.vehicle_specs" }
    }
    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()
    // Compétences d'Entretien possibles (mécanique, technologie, artisanat, animalisme…)
    const maintenanceKeys = ["mecanical", "technology", "crafting", "animalism", "environment", "wildlife", "flora", "repulsion", "toxics"]
    const current = this.document.system.maintenance || []
    context.maintenanceSkills = maintenanceKeys.map(key => ({
      key,
      label: game.i18n.localize("SKILLS." + key + ".name"),
      checked: current.includes(key)
    }))
    // Propriétaire (groupe ou personnage) résolu
    context.resolvedOwner = null
    if (this.document.system.ownerId) {
      const owner = game.actors.get(this.document.system.ownerId)
      if (owner) context.resolvedOwner = { id: owner.id, name: owner.name }
    }
    return context
  }

  async _preparePartContext(partId, context) {
    switch (partId) {
      case "main": break
      case "specs":
        context.tab = context.tabs.specs
        break
    }
    return context
  }

  changeTab(tab, group, options = {}) {
    super.changeTab(tab, group, options)
    if (group === "sheet") {
      const main = this.element?.querySelector('[data-group="sheet"][data-tab="main"]')
      if (main) main.classList.add("active")
    }
  }

  /** @override - nettoie le tableau d'Entretien (retire les cases non cochées). */
  _prepareSubmitData(event, form, formData, updateData) {
    const result = super._prepareSubmitData(event, form, formData, updateData)
    if (Array.isArray(result?.system?.maintenance)) {
      result.system.maintenance = result.system.maintenance.filter(v => typeof v === "string" && v.trim() !== "")
    }
    return result
  }
}
