import { SYSTEM } from "../../config/system.mjs"

function normalizeMax(max, current) {
  return Math.max(max ?? 0, Number.isFinite(current) ? current : 0)
}

export function numericOptions(min, max, current = null) {
  const resolvedMin = Math.min(min, Number.isFinite(current) ? current : min)
  const resolvedMax = normalizeMax(max, current)
  return Array.from({ length: Math.max(0, resolvedMax - resolvedMin) + 1 }, (_, index) => {
    const value = resolvedMin + index
    return { value, label: String(value) }
  })
}

export function objectOptions(choices) {
  return Object.entries(choices).map(([value, label]) => ({ value, label }))
}

export function dieMax(die) {
  if (typeof die !== "string" || !die.startsWith("d")) return 0
  const faces = Number.parseInt(die.slice(1), 10)
  return Number.isFinite(faces) ? faces : 0
}

export function buildSharedSelectOptions() {
  return {
    abilityValues: numericOptions(-3, 6),
    conditionValues: numericOptions(0, 12),
    moraleValues: numericOptions(2, 12),
    armorPenalties: numericOptions(0, 6),
    shieldPenalties: numericOptions(0, 4),
    weaponCategories: objectOptions(SYSTEM.weaponCategories),
    usageDice: objectOptions(SYSTEM.usageDieChoices),
    armorDice: objectOptions(SYSTEM.armorDieChoices),
    omenDice: objectOptions(SYSTEM.omenDieChoices),
    resonanceList: objectOptions(SYSTEM.resonanceList),
    equipmentSubtypes: objectOptions(SYSTEM.equipmentSubtypes),
    artifactIds: objectOptions(SYSTEM.artifactChoices),
    featureIds: objectOptions(SYSTEM.featureChoices),
  }
}

export function buildCharacterSelectOptions(system) {
  return {
    omenCurrent: numericOptions(0, dieMax(system.omens?.die), system.omens?.current),
    resonanceUsed: numericOptions(0, system.resonance?.max ?? 0, system.resonance?.used),
    artifactSyncUsed: numericOptions(0, system.syncLimit ?? 0, system.artifactSync?.used),
  }
}
