/**
 * Safely parse JSON values with null handling
 * @param {*} val - Value to parse
 * @returns {*} Parsed value or original value
 */
export function globalJsonParse(val) {
  if (
    val === null ||
    val === "null" ||
    val === "undefined" ||
    val === undefined
  )
    return null;
  if (typeof val === "object") return val;

  if (typeof val === "string") {
    try {
      return JSON.parse(val);
    } catch {
      return val;
    }
  }

  return val;
}

// Also attach to globalThis for backward compatibility
if (typeof globalThis !== "undefined" && !globalThis.globalJsonParse) {
  globalThis.globalJsonParse = globalJsonParse;
}
