// Utility shim - uses WordPress global "_" (lodash) when available, with local fallbacks.
const wpUtils = window.lodash || window._;

export const debounce = wpUtils?.debounce || function(func, wait) {
  let timeout;
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout);
      func(...args);
    };
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
  };
};

export const throttle = wpUtils?.throttle || function(func, limit) {
  let inThrottle;
  return function executedFunction(...args) {
    if (!inThrottle) {
      func(...args);
      inThrottle = true;
      setTimeout(() => inThrottle = false, limit);
    }
  };
};

export const get = wpUtils?.get || function(obj, path, defaultValue) {
  const travel = (regexp) =>
    String.prototype.split
      .call(path, regexp)
      .filter(Boolean)
      .reduce((res, key) => (res !== null && res !== undefined ? res[key] : res), obj);
  const result = travel(/[,[\]]+?/) || travel(/[,[\].]+?/);
  return result === undefined || result === obj ? defaultValue : result;
};

export const cloneDeep = wpUtils?.cloneDeep || function(obj) {
  return JSON.parse(JSON.stringify(obj));
};

export const isEqual = wpUtils?.isEqual || function(a, b) {
  return JSON.stringify(a) === JSON.stringify(b);
};

export const isEmpty = wpUtils?.isEmpty || function(obj) {
  if (obj == null) return true;
  if (Array.isArray(obj) || typeof obj === "string") return obj.length === 0;
  if (typeof obj === "object") return Object.keys(obj).length === 0;
  return false;
};

export default wpUtils;
