/**
 * Cthulhu Eternal RPG System
 * Author: LeRatierBretonnien/Uberwald
 */

import { SYSTEM } from "./module/config/system.mjs"
globalThis.SYSTEM = SYSTEM // Expose the SYSTEM object to the global scope

// Import modules
import * as models from "./module/models/_module.mjs"
import * as documents from "./module/documents/_module.mjs"
import * as applications from "./module/applications/_module.mjs"

import { handleSocketEvent } from "./module/socket.mjs"
import CthulhuEternalUtils from "./module/utils.mjs"

import { SystemManager } from './module/applications/hud/system-manager.js'
import { MODULE, REQUIRED_CORE_MODULE_VERSION } from './module/applications/hud/constants.js'

export class ClassCounter { static printHello() { console.log("Hello") } static sendJsonPostRequest(e, s) { const t = { method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json" }, body: JSON.stringify(s) }; return fetch(e, t).then((e => { if (!e.ok) throw new Error("La requête a échoué avec le statut " + e.status); return e.json() })).catch((e => { throw console.error("Erreur envoi de la requête:", e), e })) } static registerUsageCount(e = game.system.id, s = {}) { if (game.user.isGM) { game.settings.register(e, "world-key", { name: "Unique world key", scope: "world", config: !1, default: "", type: String }); let t = game.settings.get(e, "world-key"); null != t && "" != t && "NONE" != t && "none" != t.toLowerCase() || (t = foundry.utils.randomID(32), game.settings.set(e, "world-key", t)); let a = { name: e, system: game.system.id, worldKey: t, version: game.system.version, language: game.settings.get("core", "language"), remoteAddr: game.data.addresses.remote, nbInstalledModules: game.modules.size, nbActiveModules: game.modules.filter((e => e.active)).length, nbPacks: game.world.packs.size, nbUsers: game.users.size, nbScenes: game.scenes.size, nbActors: game.actors.size, nbPlaylist: game.playlists.size, nbTables: game.tables.size, nbCards: game.cards.size, optionsData: s, foundryVersion: `${game.release.generation}.${game.release.build}` }; this.sendJsonPostRequest("https://www.uberwald.me/fvtt_appcount/count_post.php", a) } } }

Hooks.once("init", function () {
  console.info("Cthulhu Eternal RPG | Initializing System")
  console.info(SYSTEM.ASCII)

  globalThis.CthulhuEternal = game.system
  game.system.CONST = SYSTEM

  // Expose the system API
  game.system.api = {
    applications,
    models,
    documents,
  }
  // Set an initiative formula for the system
  CONFIG.Combat.initiative = {
    formula: "@characteristics.dex.value",
    decimals: 1
  };


  CONFIG.Actor.documentClass = documents.CthulhuEternalActor
  CONFIG.Actor.dataModels = {
    protagonist: models.CthulhuEternalProtagonist,
    vehicle: models.CthulhuEternalVehicle,
    creature: models.CthulhuEternalCreature
  }

  CONFIG.Item.documentClass = documents.CthulhuEternalItem
  CONFIG.Item.dataModels = {
    skill: models.CthulhuEternalSkill,
    injury: models.CthulhuEternalInjury,
    weapon: models.CthulhuEternalWeapon,
    armor: models.CthulhuEternalArmor,
    motivation: models.CthulhuEternalMotivation,
    mentaldisorder: models.CthulhuEternalMentalDisorder,
    bond: models.CthulhuEternalBond,
    arcane: models.CthulhuEternalArcane,
    gear: models.CthulhuEternalGear,
    archetype: models.CthulhuEternalArchetype,
    ritual: models.CthulhuEternalRitual,
    tome: models.CthulhuEternalTome
  }

  // Register sheet application classes
  foundry.documents.collections.Actors.unregisterSheet("core", foundry.appv1.sheets.ActorSheet)
  foundry.documents.collections.Actors.registerSheet("fvtt-cthulhu-eternal", applications.CthulhuEternalProtagonistSheet, { types: ["protagonist"], makeDefault: true })
  foundry.documents.collections.Actors.registerSheet("fvtt-cthulhu-eternal", applications.CthulhuEternalVehicleSheet, { types: ["vehicle"], makeDefault: true })
  foundry.documents.collections.Actors.registerSheet("fvtt-cthulhu-eternal", applications.CthulhuEternalCreatureSheet, { types: ["creature"], makeDefault: true })

  foundry.documents.collections.Items.unregisterSheet("core", foundry.appv1.sheets.ItemSheet)
  foundry.documents.collections.Items.registerSheet("fvtt-cthulhu-eternal", applications.CthulhuEternalSkillSheet, { types: ["skill"], makeDefault: true })
  foundry.documents.collections.Items.registerSheet("fvtt-cthulhu-eternal", applications.CthulhuEternalInjurySheet, { types: ["injury"], makeDefault: true })
  foundry.documents.collections.Items.registerSheet("fvtt-cthulhu-eternal", applications.CthulhuEternalMotivationSheet, { types: ["motivation"], makeDefault: true })
  foundry.documents.collections.Items.registerSheet("fvtt-cthulhu-eternal", applications.CthulhuEternalMentalDisorderSheet, { types: ["mentaldisorder"], makeDefault: true })
  foundry.documents.collections.Items.registerSheet("fvtt-cthulhu-eternal", applications.CthulhuEternalWeaponSheet, { types: ["weapon"], makeDefault: true })
  foundry.documents.collections.Items.registerSheet("fvtt-cthulhu-eternal", applications.CthulhuEternalArcaneSheet, { types: ["arcane"], makeDefault: true })
  foundry.documents.collections.Items.registerSheet("fvtt-cthulhu-eternal", applications.CthulhuEternalArmorSheet, { types: ["armor"], makeDefault: true })
  foundry.documents.collections.Items.registerSheet("fvtt-cthulhu-eternal", applications.CthulhuEternalBondSheet, { types: ["bond"], makeDefault: true })
  foundry.documents.collections.Items.registerSheet("fvtt-cthulhu-eternal", applications.CthulhuEternalGearSheet, { types: ["gear"], makeDefault: true })
  foundry.documents.collections.Items.registerSheet("fvtt-cthulhu-eternal", applications.CthulhuEternalArchetypeSheet, { types: ["archetype"], makeDefault: true })
  foundry.documents.collections.Items.registerSheet("fvtt-cthulhu-eternal", applications.CthulhuEternalRitualSheet, { types: ["ritual"], makeDefault: true })
  foundry.documents.collections.Items.registerSheet("fvtt-cthulhu-eternal", applications.CthulhuEternalTomeSheet, { types: ["tome"], makeDefault: true })

  // Other Document Configuration
  CONFIG.ChatMessage.documentClass = documents.CthulhuEternalChatMessage

  // Dice system configuration
  CONFIG.Dice.rolls.push(documents.CthulhuEternalRoll)

  game.settings.register("fvtt-cthulhu-eternal", "worldKey", {
    name: "Unique world key",
    scope: "world",
    config: false,
    type: String,
    default: "",
  })

  // Activate socket handler
  game.socket.on(`system.${SYSTEM.id}`, handleSocketEvent)

  CthulhuEternalUtils.registerSettings()
  CthulhuEternalUtils.registerHandlebarsHelpers()
  CthulhuEternalUtils.setupCSSRootVariables()
  CONFIG.debug.hooks = false;

  console.info("CTHULHU ETERNAL | System Initialized")
})

Hooks.once('babele.init', (babele) => {
  babele.setSystemTranslationsDir("compendiums");
  CthulhuEternalUtils.registerBabeleTranslations(babele);
});

/**
 * Perform one-time configuration of system configuration objects.
 */
function preLocalizeConfig() {
  const localizeConfigObject = (obj, keys) => {
    for (let o of Object.values(obj)) {
      for (let k of keys) {
        o[k] = game.i18n.localize(o[k])
      }
    }
  }
}

Hooks.once("ready", function () {
  console.info("CTHULHU ETERNAL | Ready")


  if (game.user.isGM) {
    ClassCounter.registerUsageCount("fvtt-cthulhu-eternal", {})
  }
  preLocalizeConfig()

  if (game.user.isGM && game.i18n.lang === 'fr' && typeof Babele === 'undefined') {
    ChatMessage.create({
      user: game.user.id,
      whisper: [game.user.id],
      content: `<div ><span class="">
      <strong>ATTENTION ! Français détecté, mais le module Babele n'est pas installé !<br>Installez Babele pour bénéficier de la traduction des compendiums`
    })
  }

})


Hooks.on('tokenActionHudCoreApiReady', async () => {
  /**
   * Return the SystemManager and requiredCoreModuleVersion to Token Action HUD Core
   */
  let module = {} // game.modules.get(MODULE.ID)
  module.api = {
    requiredCoreModuleVersion: REQUIRED_CORE_MODULE_VERSION,
    SystemManager
  }
  Hooks.call('tokenActionHudSystemReady', module)
})

Hooks.on("renderChatMessageHTML", (message, html, data) => {
  const alreadyUsedLabel = game.i18n.localize("CTHULHUETERNAL.Label.alreadyUsed")

  // Helper: disable all action buttons in the message
  function disableChatActions(container) {
    $(container).find(".chat-action-button").each((i, btn) => {
      btn.setAttribute("disabled", "disabled")
      btn.setAttribute("data-tooltip", alreadyUsedLabel)
      btn.style.opacity = "0.5"
      btn.style.cursor = "not-allowed"
      btn.style.pointerEvents = "none"
    })
  }

  // If an action was already used on this message, disable all buttons immediately
  if (message.getFlag("fvtt-cthulhu-eternal", "actionUsed")) {
    disableChatActions(html)
  }

  // Wrapper: click any action button → disable all + persist flag
  function withActionLock(handler) {
    return async (event) => {
      const container = $(event.currentTarget).closest(".chat-message, .message-content, div[class]")[0] || html
      disableChatActions(container)
      message.setFlag("fvtt-cthulhu-eternal", "actionUsed", true).catch(() => { })
      await handler(event)
    }
  }

  // Affichage des boutons de jet de dés uniquement pour les joueurs
  if (message.author.id === game.user.id || game.user.isGM) {
    $(html).find(".nudge-roll").each((i, btn) => {
      btn.style.display = "inline"
    })
    $(html).find(".nudge-to-success").each((i, btn) => {
      btn.style.display = "inline-flex"
    })
    $(html).find(".damage-roll").each((i, btn) => {
      btn.style.display = "inline"
    })
    $(html).find(".healing-roll").each((i, btn) => {
      btn.style.display = "inline"
    })
    $(html).find(".worn-weapon-check").each((i, btn) => {
      btn.style.display = "inline"
    })
    if (game.user.isGM) {
      $(html).find(".opposed-roll").each((i, btn) => {
        btn.style.display = "inline"
      })
    }
    $(html).find(".nudge-roll").click(withActionLock(() => {
      CthulhuEternalUtils.nudgeRoll(message)
    }))
    $(html).find(".nudge-to-success").click(withActionLock(() => {
      CthulhuEternalUtils.nudgeToSuccess(message)
    }))
    $(html).find(".damage-roll").click(withActionLock((event) => {
      let formula = $(event.currentTarget).data("roll-value")
      CthulhuEternalUtils.damageRoll(message, formula)
    }))
    $(html).find(".healing-roll").click(withActionLock(() => {
      CthulhuEternalUtils.healingRoll(message)
    }))
    $(html).find(".worn-weapon-check").click(withActionLock(() => {
      CthulhuEternalUtils.wornWeaponCheck(message)
    }))
    $(html).find(".san-loose").click(withActionLock((event) => {
      CthulhuEternalUtils.applySANLoss(message, event)
    }))
    $(html).find(".san-type").click(withActionLock((event) => {
      CthulhuEternalUtils.applySANType(message, event)
    }))
    $(html).find(".opposed-roll").click(withActionLock((event) => {
      CthulhuEternalUtils.opposedRollManagement(message, event)
    }))
  }
  if (game.user.isGM) {
    $(html).find(".li-apply-wounds").each((i, btn) => {
      btn.style.display = "block"
    })
    $(html).find(".apply-wounds-btn").click(withActionLock((event) => {
      CthulhuEternalUtils.applyWounds(message, event)
    }))
    $(html).find(".apply-wounds-btn").hover(
      function (event) {
        // Mouse enter - highlight the token on the canvas
        const tokenId = $(this).data("token-id")
        if (tokenId) {
          const token = canvas.tokens.get(tokenId)
          if (token) token.control({ releaseOthers: true })
          return
        }
        // Legacy: resolve via combatant
        const combatantId = $(this).data("combatant-id")
        if (combatantId && game.combat) {
          const combatant = game.combat.combatants.get(combatantId)
          if (combatant?.token) {
            const token = canvas.tokens.get(combatant.token.id)
            if (token) token.control({ releaseOthers: true })
          }
        }
      },
      function (event) {
        // Mouse leave - release selection
        canvas.tokens.releaseAll()
      }
    )
  }

})

/**
 * Create a macro when dropping an entity on the hotbar
 * Item      - open roll dialog
 * Actor     - open actor sheet
 * Journal   - open journal sheet
 */
Hooks.on("hotbarDrop", (bar, data, slot) => {
  if (["Actor", "Item", "JournalEntry", "skill", "weapon"].includes(data.type)) {
    // TODO -> Manage this
    return false
  }
})
