/* -------------------------------------------- */
// Import Modules
import { BoLActor } from "./actor/actor.js"
// AppV1 actor sheets kept for reference only (AppV2 used via sheets.* below)
import { BoLItem } from "./item/item.js"
// Note: Old BoLItemSheet (AppV1) is now replaced by AppV2 sheets
import { System, BOL } from "./system/config.js"
import { preloadHandlebarsTemplates } from "./system/templates.js"
import { registerHandlebarsHelpers } from "./system/helpers.js"
import registerHooks from "./system/hooks.js"
import { Macros } from "./system/macros.js"
import { BoLUtility } from "./system/bol-utility.js"
import { BoLCombatManager } from "./system/bol-combat.js"
import { BoLTokenHud } from "./system/bol-action-hud.js"
import { BoLHotbar } from "./system/bol-hotbar.js"
import { BoLCommands } from "./system/bol-commands.js"
import { BoLRoll } from "./controllers/bol-rolls.js"

// Import DataModels
import * as models from "./models/_module.mjs"

// Import AppV2 Sheets
import * as sheets from "./applications/sheets/_module.mjs"

/* -------------------------------------------- */
Hooks.once('init', async function () {

  game.bol = {
    BoLActor,
    BoLItem,
    BoLHotbar,
    BoLRoll,
    BoLUtility,
    macros: Macros,
    config: BOL,
    models,
    sheets
  };

  // Game socket
  game.socket.on("system.bol", sockmsg => {
    BoLUtility.onSocketMessage(sockmsg);
  })

  /**
   * Set an initiative formula for the system
   * @type {String}
   */
  CONFIG.Combat.initiative = {
    formula: "2d6+@attributes.mind.value+@aptitudes.init.value",
    decimals: 2
  };

  // Define custom Entity classes
  CONFIG.Actor.documentClass = BoLActor;
  CONFIG.Actor.dataModels = {
    character: models.BoLCharacter,
    encounter: models.BoLEncounter,
    horde: models.BoLHorde,
    vehicle: models.BoLVehicle
  }

  CONFIG.Item.documentClass = BoLItem;
  CONFIG.Item.dataModels = {
    item: models.BoLItem,
    feature: models.BoLFeature
  }

  CONFIG.Combat.documentClass = BoLCombatManager;

  // Register sheet application classes
  foundry.documents.collections.Actors.unregisterSheet("core", foundry.appv1.sheets.ActorSheet);
  foundry.documents.collections.Actors.registerSheet("bol", sheets.BoLActorSheet, { types: ["character", "encounter"], makeDefault: true })
  foundry.documents.collections.Actors.registerSheet("bol", sheets.BoLVehicleSheet, { types: ["vehicle"], makeDefault: true })
  foundry.documents.collections.Actors.registerSheet("bol", sheets.BoLHordeSheet, { types: ["horde"], makeDefault: true })

  // Register AppV2 Item Sheets
  foundry.documents.collections.Items.unregisterSheet("core", foundry.appv1.sheets.ItemSheet);
  foundry.documents.collections.Items.registerSheet("bol", sheets.BoLItemSheet, { types: ["item"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("bol", sheets.BoLFeatureSheet, { types: ["feature"], makeDefault: true });

  // Debug: Verify AppV2 sheets are loaded
  console.log("BoL Item Sheets registered:", {
    BoLItemSheet: sheets.BoLItemSheet.name,
    BoLFeatureSheet: sheets.BoLFeatureSheet.name,
    extendsApplicationV2: sheets.BoLItemSheet.prototype instanceof foundry.applications.api.ApplicationV2
  });

  // Inot useful stuff
  BoLUtility.init()
  BoLTokenHud.init()
  BoLHotbar.init()
  BoLCommands.init()

  // Preload Handlebars Templates
  await preloadHandlebarsTemplates();

  // Register Handlebars helpers
  registerHandlebarsHelpers();

  // Register hooks
  registerHooks()

});

/* -------------------------------------------- */
Hooks.once("babele.init", (babele) => {
  console.log("Initializing Babele translations")
  babele.setSystemTranslationsDir("compendiums");
});


/* -------------------------------------------- */
async function welcomeMessage() {
  const noRulebook = !game.modules.find(m => m.id === "bol-rulebook")
  const content = await foundry.applications.handlebars.renderTemplate(
    "systems/bol/templates/chat/chat-welcome.hbs",
    { noRulebook }
  )
  ChatMessage.create({ user: game.user.id, whisper: [game.user.id], content })

  if (game.user.isGM && game.i18n.lang == 'en' && !game.modules.find(m => m.id == "babele")) {
    ChatMessage.create({
      user: game.user.id,
      whisper: [game.user.id],
      content: `<div class="bol-welcome-card"><div class="welcome-body"><p class="welcome-warning">⚠ WARNING ! English language selected, but Babele module is not installed !<br>Please install babele from the module tab in Foundry interface.</p></div></div>`
    })
    ui.notifications.warn("WARNING ! English language selected, but babele module is not installed !<br>Please install babele from the module tab in Foundry interface.")
  }
}

/* -------------------------------------------- */
Hooks.once('ready', async function () {

  BoLUtility.ready()

  import("https://www.uberwald.me/fvtt_appcount/count-class-ready.js").then(moduleCounter => {
    console.log("ClassCounter loaded", moduleCounter)
    moduleCounter.ClassCounter.registerUsageCount()
  }).catch(err =>
    console.log("No stats available, giving up.")
  )

  welcomeMessage()

  // User warning
  if (!game.user.isGM && game.user.character == undefined) {
    ui.notifications.info(game.i18n.localize("BOL.chat.pcwarning"));
    ChatMessage.create({
      content: game.i18n.localize("BOL.chat.pcwarningmsg") + game.user.name,
      user: game.user._id
    });
  }
  if (!game.user.isGM && game.user.character && !game.user.character.prototypeToken.actorLink) {
    ui.notifications.info(game.i18n.localize("BOL.chat.pcnotlinked"));
    ChatMessage.create({
      content: game.i18n.localize("BOL.chat.pcnotlinkedmsg") + game.user.name,
      user: game.user._id
    });
  }

  const damageFR = {
    "0": "0",
    "1": "1",
    "2": "2",
    "3": "3",
    "d3": "d3",
    "d6M": "d6M (Malus)",
    "d6": "d6",
    "d6B": "d6B (Bonus)",
    "d6BB": "d6B + dé bonus",
  }
  const damageEN = {
    "0": "0",
    "1": "1",
    "2": "2",
    "3": "3",
    "d3": "d3",
    "d6M": "d6L (Penalty)",
    "d6": "d6",
    "d6B": "d6H (Bonus)",
    "d6BB": "d6H + Bonus die",
  }

  if (game.i18n.lang === "fr") {
    game.bol.config.damageValues = damageFR;
  } else {
    game.bol.config.damageValues = damageEN;
  }

})
