let idSeed = 0

function clampInteger(value, minValue, maxValue, fallback) {
  const numberValue = Number(value)
  if (!Number.isFinite(numberValue)) return fallback

  return Math.min(Math.max(Math.round(numberValue), minValue), maxValue)
}

function createId(prefix = 'id') {
  idSeed += 1

  return `${prefix}-${Date.now()}-${idSeed}`
}

function delay(ms) {
  return new Promise((resolve) => {
    setTimeout(resolve, ms)
  })
}

function parseHexInteger(value, fallback = 0) {
  const text = String(value === undefined || value === null ? '' : value).trim()
  if (!text) return fallback

  const parsed = parseInt(text, 16)
  return Number.isFinite(parsed) ? parsed : fallback
}

function normalizeTextValue(value) {
  return String(value === undefined || value === null ? '' : value)
}

function padHex(value, length = 4) {
  return Number(value || 0).toString(16).toUpperCase().padStart(length, '0')
}

module.exports = {
  clampInteger,
  createId,
  delay,
  normalizeTextValue,
  padHex,
  parseHexInteger
}
