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

/** Tailwind-aware className combiner (shadcn convention). */
export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs));
}

/** Format a number with thousands separators and optional unit. */
export function formatMetric(value: number, unit?: string): string {
  const n = Number.isInteger(value)
    ? value.toLocaleString("en-MY")
    : value.toLocaleString("en-MY", { maximumFractionDigits: 2 });
  if (!unit) return n;
  // Currency-style units lead, symbolic/count units trail.
  if (/^(rm|usd|myr|\$)$/i.test(unit)) return `${unit} ${n}`;
  return `${n}${unit === "%" ? "%" : ` ${unit}`}`;
}

/** Clamp a value between min and max. */
export function clamp(v: number, min: number, max: number): number {
  return Math.min(Math.max(v, min), max);
}

/** Percentage of target met, clamped 0-100 for progress bars. */
export function progressPct(current: number, target: number): number {
  if (!target) return 0;
  return clamp(Math.round((current / target) * 100), 0, 100);
}

/** Threshold colour band for a KPI: green / yellow / red. */
export function thresholdBand(pct: number): "green" | "yellow" | "red" {
  if (pct >= 90) return "green";
  if (pct >= 60) return "yellow";
  return "red";
}

export function initials(name = ""): string {
  return (
    name
      .trim()
      .split(/\s+/)
      .map((w) => w[0] || "")
      .join("")
      .toUpperCase()
      .slice(0, 2) || "?"
  );
}
