/** Presentation helpers. Kept free of React so both server and client code can use them. */

const currency = new Intl.NumberFormat("en-US", {
  style: "currency",
  currency: "USD",
});

export function formatPrice(value: number): string {
  return currency.format(value);
}

export function formatRating(rating: number): string {
  return rating.toFixed(1);
}

export type StockLevel = "in-stock" | "low-stock" | "out-of-stock";

export function getStockLevel(stock: number): StockLevel {
  if (stock <= 0) return "out-of-stock";
  if (stock <= 5) return "low-stock";
  return "in-stock";
}

export const STOCK_LABELS: Record<StockLevel, string> = {
  "in-stock": "In stock",
  "low-stock": "Low stock",
  "out-of-stock": "Out of stock",
};

/** Trim a long product name to a predictable card-height length. */
export function truncate(value: string, maxLength: number): string {
  return value.length > maxLength ? `${value.slice(0, maxLength - 1).trimEnd()}…` : value;
}

/** Percentage of the query's top score, for the "match strength" bar. */
export function toMatchPercent(similarity: number): number {
  return Math.round(Math.max(0, Math.min(1, similarity)) * 100);
}
