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

export default class MGNECompanionSheet extends MGNEActorSheet {
  static DEFAULT_OPTIONS = {
    classes: ["companion"],
    position: {
      width: 820,
      height: 700,
    },
    actions: {
      rollAdventuringBehavior: MGNECompanionSheet.prototype._rollAdventuringBehavior,
      clearAdventuringBehavior: MGNECompanionSheet.prototype._clearAdventuringBehavior,
      openAdventuringBehavior: MGNECompanionSheet.prototype._openAdventuringBehavior,
      rollCombatBehavior: MGNECompanionSheet.prototype._rollCombatBehavior,
      clearCombatBehavior: MGNECompanionSheet.prototype._clearCombatBehavior,
      openCombatBehavior: MGNECompanionSheet.prototype._openCombatBehavior,
    },
  }

  static PARTS = {
    main: { template: "systems/fvtt-machine-gods-noxian-expanse/templates/companion-main.hbs" },
  }

  async _prepareContext() {
    const context = await super._prepareContext()

    const resolveTable = async (uuid) => {
      if (!uuid) return null
      const table = await fromUuid(uuid).catch(() => null)
      return table ? { name: table.name, uuid } : null
    }

    context.adventuringTable = await resolveTable(this.document.system.adventuringBehaviorUuid)
    context.combatTable = await resolveTable(this.document.system.combatBehaviorUuid)

    return context
  }

  async _onDrop(event) {
    const data = foundry.applications.ux.TextEditor.implementation.getDragEventData(event)
    if (data?.type === "RollTable") {
      const table = await fromUuid(data.uuid)
      if (!table) return super._onDrop(event)

      // Determine drop target by proximity to each section
      const target = event.target.closest("[data-behavior-slot]")
      const slot = target?.dataset.behaviorSlot
      if (slot === "adventuring") {
        await this.document.update({ "system.adventuringBehaviorUuid": data.uuid })
        return
      }
      if (slot === "combat") {
        await this.document.update({ "system.combatBehaviorUuid": data.uuid })
        return
      }
      // Fallback: first empty slot, then adventuring
      const sys = this.document.system
      if (!sys.adventuringBehaviorUuid) {
        await this.document.update({ "system.adventuringBehaviorUuid": data.uuid })
      } else {
        await this.document.update({ "system.combatBehaviorUuid": data.uuid })
      }
      return
    }
    return super._onDrop(event)
  }

  async _rollAdventuringBehavior() { await this._rollTable("adventuringBehaviorUuid") }
  async _clearAdventuringBehavior() { await this.document.update({ "system.adventuringBehaviorUuid": "" }) }
  async _openAdventuringBehavior() { await this._openTable("adventuringBehaviorUuid") }

  async _rollCombatBehavior() { await this._rollTable("combatBehaviorUuid") }
  async _clearCombatBehavior() { await this.document.update({ "system.combatBehaviorUuid": "" }) }
  async _openCombatBehavior() { await this._openTable("combatBehaviorUuid") }

  async _rollTable(uuidField) {
    const uuid = this.document.system[uuidField]
    if (!uuid) return ui.notifications.warn(game.i18n.localize("MGNE.Companion.NoTableLinked"))
    const table = await fromUuid(uuid).catch(() => null)
    if (!table) return ui.notifications.warn(game.i18n.localize("MGNE.Companion.TableNotFound"))
    await table.draw()
  }

  async _openTable(uuidField) {
    const uuid = this.document.system[uuidField]
    if (!uuid) return
    const table = await fromUuid(uuid).catch(() => null)
    if (table) table.sheet.render(true)
  }
}
