/**
 * Chroniques de l'Étrange — Système FoundryVTT
 *
 * Chroniques de l'Étrange est un jeu de rôle édité par Antre-Monde Éditions.
 * Ce système FoundryVTT est une implémentation indépendante et n'est pas
 * affilié à Antre-Monde Éditions,
 * mais a été réalisé avec l'autorisation d'Antre-Monde Éditions.
 *
 * @author    LeRatierBretonnien
 * @copyright 2024–2026 LeRatierBretonnien
 * @license   CC BY-NC-SA 4.0 – https://creativecommons.org/licenses/by-nc-sa/4.0/
 */

/**
 * Loksyu / TinJi settings-based helpers.
 *
 * Data is stored as world settings instead of singleton Actor documents.
 */

import { SYSTEM_ID, WU_XING_CYCLE, ASPECT_FACES } from "../../config/constants.js"

/** Read the current loksyu data object from world settings */
export function getLoksyuData() {
  return game.settings.get(SYSTEM_ID, "loksyuData") ?? {
    wood: {yin:0,yang:0}, fire: {yin:0,yang:0}, earth: {yin:0,yang:0}, metal: {yin:0,yang:0}, water: {yin:0,yang:0},
  }
}

/** Write the loksyu data object to world settings */
export async function setLoksyuData(data) {
  await game.settings.set(SYSTEM_ID, "loksyuData", data)
  Hooks.callAll("cde:loksyuUpdated", data)
}

/** Read current TinJi value from world settings */
export function getTinjiValue() {
  return game.settings.get(SYSTEM_ID, "tinjiData") ?? 0
}

/** Write TinJi value to world settings */
export async function setTinjiValue(value) {
  await game.settings.set(SYSTEM_ID, "tinjiData", Math.max(0, value))
  Hooks.callAll("cde:tinjiUpdated", Math.max(0, value))
}

/**
 * After a WuXing roll, add the loksyu faces (yin + yang) of the relevant
 * aspect to the loksyu settings data.
 *
 * @param {string} activeAspect  - e.g. "fire"
 * @param {Object} faces         - Die face counts { 0: n, 1: n, …, 9: n }
 */
export async function updateLoksyuFromRoll(activeAspect, faces) {
  const cycle = WU_XING_CYCLE[activeAspect]
  if (!cycle) return

  const lokAspect = cycle[3]
  const [yinFace, yangFace] = ASPECT_FACES[lokAspect] ?? []
  if (yinFace === undefined) return

  const yinCount  = faces[yinFace]  ?? 0
  const yangCount = faces[yangFace] ?? 0
  if (yinCount === 0 && yangCount === 0) return

  const data = getLoksyuData()
  const current = data[lokAspect] ?? { yin: 0, yang: 0 }
  data[lokAspect] = {
    yin:  (current.yin  ?? 0) + yinCount,
    yang: (current.yang ?? 0) + yangCount,
  }
  await setLoksyuData(data)
}

/**
 * After a WuXing roll, add tinji faces to the TinJi settings.
 *
 * @param {number} count - Number of tinji faces rolled
 */
export async function updateTinjiFromRoll(count) {
  if (!count || count <= 0) return
  const current = getTinjiValue()
  await setTinjiValue(current + count)
}
