import { cn } from "@/lib/cn";

interface StarRatingProps {
  /** `null` renders nothing — we never show a rating we don't have. */
  rating: number | null;
  count?: number | null;
  className?: string;
}

export function StarRating({ rating, count, className }: StarRatingProps) {
  if (rating === null) return null;

  const pct = Math.max(0, Math.min(100, (rating / 5) * 100));

  return (
    <span
      className={cn("inline-flex items-center gap-2 leading-none", className)}
      // Only ratings that carry a count come from an App Store listing; our own
      // rating has no count and must not claim a source it doesn't have.
      aria-label={
        count
          ? `Rated ${rating} out of 5 on the App Store from ${count.toLocaleString("en-US")} ratings`
          : `Rated ${rating} out of 5`
      }
    >
      <span className="relative inline-block text-[0.9rem] tracking-[0.12em]" aria-hidden="true">
        <span className="text-border">★★★★★</span>
        <span
          className="absolute top-0 left-0 overflow-hidden whitespace-nowrap text-gold"
          style={{ width: `${pct}%` }}
        >
          ★★★★★
        </span>
      </span>
      {/* The count stays in the aria-label for provenance, but isn't shown. */}
      <span className="text-[0.8rem] font-semibold text-muted">{rating.toFixed(1)}</span>
    </span>
  );
}
