import { clsx, type ClassValue } from "clsx";

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

export function currency(value: number | string) {
  return new Intl.NumberFormat("en-US", {
    style: "currency",
    currency: "USD",
    maximumFractionDigits: 2
  }).format(Number(value));
}

export function priceWithMarkup(supplierPrice: number, markupPercent = 10) {
  return Number((supplierPrice * (1 + markupPercent / 100)).toFixed(2));
}

export function parseImages(images: string): string[] {
  try {
    const parsed = JSON.parse(images);
    return Array.isArray(parsed) ? parsed : ["/products/bullion-hero.svg"];
  } catch {
    return [images || "/products/bullion-hero.svg"];
  }
}

export function productImages(product: { imageUrls?: string | null; images?: string | null; metalType?: string; productType?: string }) {
  const raw = product.imageUrls && product.imageUrls !== "[]" ? product.imageUrls : product.images || "";
  const parsed = parseImages(raw);
  return parsed.length ? parsed : [placeholderForProduct(product)];
}

export function placeholderForProduct(product: { metalType?: string; productType?: string }) {
  const metal = product.metalType === "SILVER" ? "silver" : "gold";
  const type = product.productType === "COIN" || product.productType === "ROUND" || product.productType === "COLLECTIBLE" ? "coin" : "bar";
  return `/products/${metal}-${type}.svg`;
}

export function displayPrice(product: { customerPrice?: unknown; totalSalePrice?: unknown; manualPrice?: unknown }) {
  const customerPrice = Number(product.customerPrice ?? 0);
  if (customerPrice > 0) return customerPrice;
  const totalSalePrice = Number(product.totalSalePrice ?? 0);
  if (totalSalePrice > 0) return totalSalePrice;
  return Number(product.manualPrice ?? 0);
}

export function isPriceStale(date: Date) {
  return Date.now() - new Date(date).getTime() > 24 * 60 * 60 * 1000;
}

export function priceFreshness(date: Date) {
  const hours = (Date.now() - new Date(date).getTime()) / (60 * 60 * 1000);
  if (hours > 72) return "overdue";
  if (hours > 24) return "recommended";
  return "fresh";
}

export function orderNumber() {
  return `ELIT-${Date.now().toString().slice(-8)}-${Math.floor(Math.random() * 900 + 100)}`;
}
