export function formatStringWithUppercase(str: string): string {
  if (!str) return "";

  // Handle camelCase -> space separated
  let formatted = str.replace(/([a-z])([A-Z])/g, "$1 $2");

  // Normalize multiple spaces
  formatted = formatted.replace(/\s+/g, " ").trim();

  // Special handling for common field names written without spaces
  formatted = formatted.replace(/\bmobilenumber\b/gi, "mobile number");

  // Capitalize first letter only
  return formatted.charAt(0).toUpperCase() + formatted.slice(1).toLowerCase();
}

export function convertDateStringToDate(
  dateStr?: string | null,
  fallback = "-",
): string {
  if (!dateStr?.trim()) return fallback;

  const date = new Date(dateStr);

  if (Number.isNaN(date.getTime())) {
    console.error(`Invalid date string: ${dateStr}`);
    return fallback;
  }

  return date.toLocaleString("en-US", {
    month: "short",
    day: "numeric",
    year: "numeric",
    hour: "numeric",
    minute: "2-digit",
    hour12: true,
    timeZone: "America/New_York",
  });
}

export function formatFullName(firstName: string, lastName: string) {
  return `${firstName} ${lastName}`.trim();
}

export function getImagePath(url: string) {
  const appMode = process.env.NEXT_PUBLIC_APP_MODE;
  type APP_TYPES = "development" | "production";

  const URL: Record<APP_TYPES, string> = {
    development: process.env.NEXT_PUBLIC_IMAGE_URL_LOCAL,
    production: process.env.NEXT_PUBLIC_IMAGE_URL_PROD,
  };

  if (!url) return "";

  // If it already has the full URL, return it as is
  if (url.startsWith("http")) return url;

  // Return the image with the CDN base URL
  return `${URL[appMode]}/${url}`;
}

export function resolveImagePath(src?: string | null) {
  if (!src) return null;

  if (
    src.startsWith("http://") ||
    src.startsWith("https://") ||
    src.startsWith("blob:") ||
    src.startsWith("data:") ||
    src.startsWith("/")
  ) {
    return src;
  }

  return getImagePath(src);
}
