import { LESOUBLIES_CONFIG } from "./les-oublies-config.js"
import { LesOubliesUtility } from "./les-oublies-utility.js"
import { LesOubliesActor } from "./les-oublies-actor.js"
import { LesOubliesItem } from "./les-oublies-item.js"
import { LesOubliesRolls } from "./les-oublies-rolls.js"
import * as models from "./models/index.mjs"
import * as sheets from "./applications/sheets/_module.mjs"

const DEFAULT_PERSONNAGE_TOKEN_TEXTURE = "systems/fvtt-les-oublies/assets/tokens/border_token_oublies.webp"
const UBERWALD_URL = "https://www.uberwald.me"
const XII_SINGES_URL = "https://www.les12singes.com/84-les-oublies"

function ensureSystemStyles() {
  const href = `systems/${game.system.id}/css/les-oublies.css`
  const existingLink = document.querySelector(`link[href$="${href}"]`)
  if (existingLink) return

  const link = document.createElement("link")
  link.rel = "stylesheet"
  link.type = "text/css"
  link.href = href
  link.dataset.systemStyle = game.system.id
  document.head.append(link)
}

function usesFoundryDefaultTokenTexture(actor, data) {
  const tokenTexture = foundry.utils.getProperty(data, "prototypeToken.texture.src")
    ?? foundry.utils.getProperty(actor, "prototypeToken.texture.src")
    ?? ""
  return !tokenTexture || tokenTexture === CONST.DEFAULT_TOKEN || tokenTexture === "icons/svg/mystery-man.svg"
}

function usesFoundryDefaultItemImage(item, data) {
  const image = foundry.utils.getProperty(data, "img")
    ?? foundry.utils.getProperty(item, "img")
    ?? ""
  return !image || image === "icons/svg/item-bag.svg"
}

async function getHelpJournalEntry() {
  const pack = game.packs.get(`${game.system.id}.aide-systeme`)
  if (!pack) return null

  const documents = await pack.getDocuments()
  return documents[0] ?? null
}

async function buildWelcomeMessageContent(helpJournal) {
  const helpContent = helpJournal
    ? await foundry.applications.ux.TextEditor.implementation.enrichHTML(
      `@UUID[${helpJournal.uuid}]{${game.i18n.localize("LESOUBLIES.welcome.helpLinkLabel")}}`,
      { async: true },
    )
    : game.i18n.localize("LESOUBLIES.welcome.helpUnavailable")

  return `
    <div class="les-oublies-chat-card les-oublies-welcome-chat">
      <div class="chat-card-header">
        <div>
          <p class="chat-card-eyebrow">${game.i18n.localize("LESOUBLIES.welcome.eyebrow")}</p>
          <h3>${game.i18n.localize("LESOUBLIES.welcome.title")}</h3>
        </div>
      </div>
      <div class="chat-card-body">
        <p>${game.i18n.localize("LESOUBLIES.welcome.intro")}</p>
        <p>${game.i18n.localize("LESOUBLIES.welcome.developerLabel")} <a href="${UBERWALD_URL}" target="_blank" rel="noopener noreferrer">Uberwald</a>.</p>
        <p>${game.i18n.localize("LESOUBLIES.welcome.publisherLabel")} <a href="${XII_SINGES_URL}" target="_blank" rel="noopener noreferrer">Les XII Singes</a>.</p>
        <p><strong>${game.i18n.localize("LESOUBLIES.welcome.helpLabel")}</strong> ${helpContent}</p>
      </div>
    </div>
  `
}

async function showWelcomeMessage() {
  const helpJournal = await getHelpJournalEntry()
  const content = await buildWelcomeMessageContent(helpJournal)

  await ChatMessage.create({
    speaker: {
      alias: game.system.title,
    },
    content,
    whisper: [game.user.id],
  })
}

async function ensureWelcomeScene() {
  const pack = game.packs.get(`${game.system.id}.scenes-de-base`)
  if (!pack) return

  if (game.scenes.getName("Accueil")) return

  try {
    const scenes = await pack.getDocuments()
    const accueil = scenes.find(s => s.name === "Accueil")
    if (!accueil) return

    const worldScene = await accueil.importToWorld()
    if (worldScene) await worldScene.activate()
  } catch (err) {
    console.error("Les Oubliés | Échec d'import de la scène d'accueil:", err)
  }
}

Hooks.once("init", function () {
  console.info(
    "%c888                             .d88888b.           888      888 d8b                   \n%c888                            d88P\" \"Y88b          888      888 Y8P                   \n%c888                            888     888          888      888                        \n%c888      .d88b.  .d8888b       888     888 888  888 88888b.  888 888  .d88b.  .d8888b  \n%c888     d8P  Y8b 88K           888     888 888  888 888 \"88b 888 888 d8P  Y8b 88K      \n%c888     88888888 \"Y8888b.      888     888 888  888 888  888 888 888 88888888 \"Y8888b. \n%c888     Y8b.          X88      Y88b. .d88P Y88b 888 888 d88P 888 888 Y8b.          X88 \n%c88888888 \"Y8888   88888P'       \"Y88888P\"   \"Y88888 88888P\"  888 888  \"Y8888   88888P' \n%c                                                                                       \n%cSystème FoundryVTT AppV2  |  Les XII Singes / Uberwald                                 \n%c                                                                                       ",
    "color: #8b5cf6",
    "color: #8b5cf6",
    "color: #8b5cf6",
    "color: #a78bfa",
    "color: #a78bfa",
    "color: #a78bfa",
    "color: #c4b5fd",
    "color: #c4b5fd",
    "color: #c4b5fd",
    "color: #c4b5fd; font-style: italic",
    "color: #c4b5fd",
  )
  console.info("Les Oubliés | Initialisation du système")
  ensureSystemStyles()

  CONFIG.Actor.documentClass = LesOubliesActor
  CONFIG.Actor.dataModels = {
    personnage: models.PersonnageDataModel,
    compagnie: models.CompagnieDataModel,
    creature: models.CreatureDataModel,
  }

  CONFIG.Item.documentClass = LesOubliesItem
  CONFIG.Item.dataModels = {
    race: models.RaceDataModel,
    tribu: models.TribuDataModel,
    metier: models.MetierDataModel,
    competence: models.CompetenceDataModel,
    sortilege: models.SortilegeDataModel,
    arme: models.ArmeDataModel,
    armure: models.ArmureDataModel,
    equipement: models.EquipementDataModel,
    pouvoircompagnie: models.PouvoirCompagnieDataModel,
  }

  CONFIG.LESOUBLIES = LESOUBLIES_CONFIG

  game.system.lesOublies = {
    config: LESOUBLIES_CONFIG,
    models,
    sheets,
    rolls: LesOubliesRolls,
    utility: LesOubliesUtility,
  }

  foundry.documents.collections.Actors.registerSheet("fvtt-les-oublies", sheets.LesOubliesPersonnageSheet, { types: ["personnage"], makeDefault: true })
  foundry.documents.collections.Actors.registerSheet("fvtt-les-oublies", sheets.LesOubliesCompagnieSheet, { types: ["compagnie"], makeDefault: true })
  foundry.documents.collections.Actors.registerSheet("fvtt-les-oublies", sheets.LesOubliesCreatureSheet, { types: ["creature"], makeDefault: true })

  foundry.documents.collections.Items.registerSheet("fvtt-les-oublies", sheets.LesOubliesReferenceItemSheet, { types: ["race", "tribu", "metier"], makeDefault: true })
  foundry.documents.collections.Items.registerSheet("fvtt-les-oublies", sheets.LesOubliesCompetenceSheet, { types: ["competence"], makeDefault: true })
  foundry.documents.collections.Items.registerSheet("fvtt-les-oublies", sheets.LesOubliesSortilegeSheet, { types: ["sortilege"], makeDefault: true })
  foundry.documents.collections.Items.registerSheet("fvtt-les-oublies", sheets.LesOubliesArmeSheet, { types: ["arme"], makeDefault: true })
  foundry.documents.collections.Items.registerSheet("fvtt-les-oublies", sheets.LesOubliesArmureSheet, { types: ["armure"], makeDefault: true })
  foundry.documents.collections.Items.registerSheet("fvtt-les-oublies", sheets.LesOubliesEquipementSheet, { types: ["equipement"], makeDefault: true })
  foundry.documents.collections.Items.registerSheet("fvtt-les-oublies", sheets.LesOubliesPouvoirCompagnieSheet, { types: ["pouvoircompagnie"], makeDefault: true })

  LesOubliesUtility.registerHandlebarsHelpers()
})

Hooks.once("ready", function () {
  showWelcomeMessage()
  ensureWelcomeScene()
})

Hooks.on("preCreateActor", function (actor, data) {
  if (actor.type !== "personnage") return
  if (!usesFoundryDefaultTokenTexture(actor, data)) return

  actor.updateSource({
    prototypeToken: {
      texture: {
        src: DEFAULT_PERSONNAGE_TOKEN_TEXTURE,
      },
    },
  })
})

Hooks.on("preCreateItem", function (item, data) {
  if (!usesFoundryDefaultItemImage(item, data)) return

  item.updateSource({
    img: LesOubliesUtility.getDefaultItemImage(item.type),
  })
})
