import { formatRating } from "@/lib/format";

/** Star rating. The numeric value stays available to screen readers. */
export function RatingStars({ rating, showValue = true }: { rating: number; showValue?: boolean }) {
  const rounded = Math.round(rating);
  const stars = Array.from({ length: 5 }, (_, index) => index < rounded);

  return (
    <span className="inline-flex items-center gap-1.5" title={`Rated ${formatRating(rating)} out of 5`}>
      <span className="flex" aria-hidden="true">
        {stars.map((filled, index) => (
          <svg
            key={index}
            viewBox="0 0 20 20"
            className={`size-4 ${filled ? "text-amber-400" : "text-slate-300"}`}
            fill="currentColor"
          >
            <path d="M10 1.5l2.6 5.27 5.82.85-4.21 4.1.99 5.79L10 14.77l-5.2 2.74.99-5.79-4.21-4.1 5.82-.85L10 1.5z" />
          </svg>
        ))}
      </span>
      {showValue ? (
        <span className="text-sm text-slate-600">
          {formatRating(rating)}
          <span className="sr-only"> out of 5 stars</span>
        </span>
      ) : (
        <span className="sr-only">Rated {formatRating(rating)} out of 5 stars</span>
      )}
    </span>
  );
}
