import { useQuery } from "@tanstack/react-query";
import { useTenant } from "@/contexts/TenantContext";
import { Star } from "lucide-react";

interface Testimonial {
  id: string;
  author_name: string;
  author_role: string | null;
  content: string;
  rating: number;
}

const LocktelTestimonials = ({ limit }: { limit?: number }) => {
  const { branding } = useTenant();

  const { data: testimonials = [] } = useQuery<Testimonial[]>({
    queryKey: ["locktel-testimonials", branding?.company_id, limit],
    queryFn: async () => {
      if (!branding) return [];
      const params = new URLSearchParams({ company_id: branding.company_id });
      if (limit) params.set("limit", String(limit));
      try {
        const res = await fetch(`/api/locktel/testimonials?${params.toString()}`);
        if (!res.ok) return [];
        const data = await res.json();
        return Array.isArray(data) ? data : [];
      } catch {
        return [];
      }
    },
    enabled: !!branding,
  });

  if (testimonials.length === 0) return null;

  return (
    <section className="container mx-auto px-4 py-16">
      <h2 className="text-3xl font-bold text-foreground mb-2 text-center">What Our Clients Say</h2>
      <p className="text-muted-foreground text-center mb-10">Real feedback from our training delegates</p>
      <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
        {testimonials.map((t) => (
          <div key={t.id} className="bg-card border border-border rounded-xl p-6">
            <div className="flex gap-1 mb-3">
              {Array.from({ length: 5 }).map((_, i) => (
                <Star
                  key={i}
                  className={`h-4 w-4 ${i < t.rating ? "text-yellow-500 fill-yellow-500" : "text-muted-foreground/30"}`}
                />
              ))}
            </div>
            <p className="text-sm text-card-foreground/80 mb-4 italic">"{t.content}"</p>
            <div>
              <p className="text-sm font-semibold text-card-foreground">{t.author_name}</p>
              {t.author_role && (
                <p className="text-xs text-muted-foreground">{t.author_role}</p>
              )}
            </div>
          </div>
        ))}
      </div>
    </section>
  );
};

export default LocktelTestimonials;
