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

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs));
}

/**
 * Format currency in Nigerian Naira (NGN)
 */
export function formatNaira(amount: number | string, options?: { showDecimal?: boolean }) {
  const num = typeof amount === "string" ? parseFloat(amount) : amount;
  if (isNaN(num)) return "₦0";

  return new Intl.NumberFormat("en-NG", {
    style: "currency",
    currency: "NGN",
    minimumFractionDigits: options?.showDecimal ? 2 : 0,
    maximumFractionDigits: options?.showDecimal ? 2 : 0,
  }).format(num);
}

/**
 * Format large numbers for Nigerian Real Estate (e.g. ₦45M, ₦1.2B)
 */
export function formatCompactNaira(amount: number | string) {
  const num = typeof amount === "string" ? parseFloat(amount) : amount;
  if (isNaN(num)) return "₦0";

  if (num >= 1_000_000_000) {
    return `₦${(num / 1_000_000_000).toFixed(1).replace(/\.0$/, "")}B`;
  }
  if (num >= 1_000_000) {
    return `₦${(num / 1_000_000).toFixed(1).replace(/\.0$/, "")}M`;
  }
  if (num >= 1_000) {
    return `₦${(num / 1_000).toFixed(0)}k`;
  }
  return formatNaira(num);
}

/**
 * Normalizes an agent name or id into a clean URL-friendly slug
 */
export function normalizeAgentSlug(nameOrId: string): string {
  if (!nameOrId) return "agent";
  return nameOrId
    .toLowerCase()
    .trim()
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-+|-+$/g, "");
}

/**
 * Formats a listing timestamp (e.g. "Jul 16, 11:10" or "Aug 22, 14:30")
 */
export function formatListingTimestamp(dateInput?: string | Date | null): string {
  if (!dateInput) return "Jul 16, 11:10";

  try {
    const date = typeof dateInput === "string" ? new Date(dateInput) : dateInput;
    if (isNaN(date.getTime())) {
      return String(dateInput);
    }

    const dateStr = date.toLocaleDateString("en-US", {
      month: "short",
      day: "numeric",
    });

    const timeStr = date.toLocaleTimeString("en-US", {
      hour: "2-digit",
      minute: "2-digit",
      hour12: false,
    });

    return `${dateStr}, ${timeStr}`;
  } catch {
    return "Jul 16, 11:10";
  }
}


