"use client";

import { parseServiceRating } from "@/lib/serviceRating";

export function ServiceStarRow({
  value,
  className = "",
}: {
  value: number;
  className?: string;
}) {
  const rounded = Math.round(Math.min(5, Math.max(0, value)));
  return (
    <span
      className={`inline-flex text-amber-500 leading-none ${className}`}
      aria-hidden
    >
      {[1, 2, 3, 4, 5].map((i) => (
        <span key={i}>{i <= rounded ? "★" : "☆"}</span>
      ))}
    </span>
  );
}

/** Interactive 1–5 stars for review forms (LTR star order is conventional). */
export function ServiceStarRatingInput({
  value,
  onChange,
  starAriaLabel,
  className = "",
}: {
  value: number;
  onChange: (rating: number) => void;
  starAriaLabel: (n: number) => string;
  className?: string;
}) {
  const v = Math.min(5, Math.max(1, Math.round(value)));
  return (
    <div
      className={`flex flex-wrap items-center gap-0.5 ${className}`}
      role="radiogroup"
      dir="ltr"
    >
      {[1, 2, 3, 4, 5].map((i) => (
        <button
          key={i}
          type="button"
          role="radio"
          aria-checked={v === i}
          onClick={() => onChange(i)}
          aria-label={starAriaLabel(i)}
          className={`min-h-11 min-w-11 grid place-items-center rounded-lg text-2xl leading-none transition hover:bg-amber-50 focus:outline-none focus-visible:ring-2 focus-visible:ring-amber-400 focus-visible:ring-offset-1 ${
            i <= v ? "text-amber-500" : "text-slate-300"
          }`}
        >
          <span aria-hidden>{i <= v ? "★" : "☆"}</span>
        </button>
      ))}
    </div>
  );
}

/** Card / compact summary */
export function ServiceRatingSummary({
  ratingRaw,
  textLabel,
  className = "",
}: {
  ratingRaw: unknown;
  textLabel: string | null | undefined;
  className?: string;
}) {
  const n = parseServiceRating(ratingRaw);
  if (n == null || textLabel == null || !String(textLabel).trim()) {
    return null;
  }
  return (
    <div
      className={`flex items-center gap-2 border-t border-slate-100 pt-2.5 ${className}`}
      dir="rtl"
    >
      <ServiceStarRow value={n} className="text-[15px]" />
      <span className="text-sm font-bold text-slate-800">{textLabel}</span>
    </div>
  );
}
