import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";

// Combines Tailwind classes safely — avoids conflicting class names
export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs));
}

// ── Safe numeric formatters ────────────────────────────────────────
// Wrap any value that might be null/undefined before formatting. New
// API endpoints (AiAttribution, AiCitation, AiRecommendation, ROI)
// often return partial payloads when the underlying tables are empty,
// and a bare `value.toLocaleString()` on undefined crashes the whole
// page. Use these helpers at every display site.

/** Safely formats a number with commas. Returns "0" for null/undefined/NaN. */
export function nfmt(n: number | null | undefined): string {
  if (n == null || typeof n !== "number" || !Number.isFinite(n)) return "0";
  return n.toLocaleString();
}

/** Safely formats a fixed-decimal number. Returns "0.00" (or custom default) for null/undefined/NaN. */
export function nfixed(n: number | null | undefined, decimals = 2): string {
  if (n == null || typeof n !== "number" || !Number.isFinite(n)) return (0).toFixed(decimals);
  return n.toFixed(decimals);
}

/** Safely formats a number as currency. Returns "$0" for null/undefined/NaN. */
export function nmoney(n: number | null | undefined, opts?: { decimals?: number }): string {
  if (n == null || typeof n !== "number" || !Number.isFinite(n)) {
    return opts?.decimals != null ? `$${(0).toFixed(opts.decimals)}` : "$0";
  }
  return opts?.decimals != null ? `$${n.toFixed(opts.decimals)}` : `$${n.toLocaleString()}`;
}

/** Safely gets the length of a possibly-undefined array. */
export function safeLen(arr: unknown): number {
  return Array.isArray(arr) ? arr.length : 0;
}
