export const getInitials = (name: string): string => {
  if (!name) return "";

  return name
    .trim()
    .split(/\s+/)
    .map((part) => part.charAt(0))
    .join("")
    .toUpperCase();
};

export const formatLabel = (text?: string): string => {
  if (!text) return "";

  const withSpaces = text
    .replace(/([a-z])([A-Z])/g, "$1 $2")
    .replace(/([A-Z])([A-Z][a-z])/g, "$1 $2");

  return withSpaces.charAt(0).toUpperCase() + withSpaces.slice(1);
};

export const cleanString = (value: string): string => {
  return value.trim().replace(/\s+/g, "");
};

export const slugify = (text: string) =>
  text
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-+|-+$/g, "");

export const isObjectEmpty = (obj: object): boolean => {
  return obj && Object.keys(obj).length === 0;
};

/**
 * Utility function to safely retrieve a deeply nested value from an object.
 * It only performs path traversal (splitting by '.') if the path contains "customFields".
 * Otherwise, it assumes the path is a top-level key.
 *
 * @param obj The object to traverse (e.g., the 'errors' object from RHF).
 * @param path The path string (e.g., "customFields.fieldName" or "topLevelField").
 * @returns The value at the specified path, or undefined if the path does not exist.
 */
export const getNestedValue = <T = any>(
  obj: Record<string, any>,
  path: string
): T | undefined => {
  if (!path || typeof path !== "string") {
    return undefined;
  }

  if (path.includes("customFields")) {
    const pathParts = path.split(".");

    let currentValue: any = obj;

    for (const part of pathParts) {
      if (
        currentValue &&
        typeof currentValue === "object" &&
        part in currentValue
      ) {
        currentValue = currentValue[part];
      } else {
        return undefined;
      }
    }

    return currentValue as T;
  }

  if (obj && typeof obj === "object" && path in obj) {
    return obj[path] as T;
  }

  return undefined;
};

export const capitalizeFirst = (value: string) =>
  value ? value.charAt(0).toUpperCase() + value.slice(1) : value;
