"use client";

import Image from "next/image";
import {
  Carousel,
  CarouselContent,
  CarouselItem,
  CarouselNext,
  CarouselPrevious,
} from "@/components/ui/carousel";
import { useTestimonials } from "@/hooks/useData";
import { Star, Quote } from "lucide-react";

// --- ENHANCED cleanText Function ---
// This handles ALL problematic Unicode characters that cause "No Glyph" errors
const cleanText = (text) => {
  if (!text) return "";

  return (
    text
      // Remove control characters (0x00-0x1F and 0x7F-0x9F) - these cause "No Glyph" errors
      .replace(/[\x00-\x1F\x7F-\x9F]/g, "")
      // Replace smart quotes
      .replace(/[\u2018\u2019]/g, "'")
      .replace(/[\u201C\u201D]/g, '"')
      // Replace dashes
      .replace(/[\u2013\u2014]/g, "-")
      // Replace ellipsis
      .replace(/\u2026/g, "...")
      // Replace other common problematic characters
      .replace(/\u00A0/g, " ") // Non-breaking space
      .replace(/\u2022/g, "•") // Bullet point
      .replace(/\u00AB/g, "«") // Left guillemet
      .replace(/\u00BB/g, "»") // Right guillemet
      // Normalize Unicode to decomposed form
      .normalize("NFKD")
      // Remove any remaining non-ASCII characters that might cause issues
      .replace(/[^\x00-\x7F]/g, (char) => {
        // Keep common safe characters
        const safeChars = "•";
        return safeChars.includes(char) ? char : "";
      })
  );
};

// Elegant Star Component
const StarRating = ({ rating }) => {
  return (
    <div className="flex gap-1 mb-4">
      {[1, 2, 3, 4, 5].map((star) => (
        <Star
          key={star}
          className={`w-3 h-3 ${
            star <= rating
              ? "fill-brand-gold text-brand-gold"
              : "fill-stone-200 text-stone-200"
          }`}
        />
      ))}
    </div>
  );
};

export default function TestimonialsCarousel() {
  const { data } = useTestimonials();
  const allTestimonials = data?.rows || [];
  const activeTestimonials = allTestimonials.filter((t) => t.status === 1);

  if (!activeTestimonials.length) return null;

  return (
    <section className="py-20 px-4 bg-stone-50/50 relative overflow-hidden">
      {/* Background Decorative Blob */}
      <div className="absolute top-0 left-0 w-full h-full overflow-hidden pointer-events-none">
        <div className="absolute top-0 right-0 w-[500px] h-[500px] bg-brand-gold/5 rounded-full blur-3xl -translate-y-1/2 translate-x-1/2" />
        <div className="absolute bottom-0 left-0 w-[500px] h-[500px] bg-primary/5 rounded-full blur-3xl translate-y-1/2 -translate-x-1/2" />
      </div>

      <div className="max-w-[1600px] mx-auto relative z-10">
        {/* Header */}
        <div className="text-center mb-16 space-y-3">
          <span className="uppercase tracking-[0.2em] text-xs font-medium text-brand-gold">
            Client Stories
          </span>
          <h2 className="text-4xl md:text-5xl font-cormorant text-primary">
            Love Notes
          </h2>
          <div className="w-16 h-[1px] bg-primary/20 mx-auto mt-4" />
        </div>

        <Carousel
          opts={{
            align: "center",
            loop: true,
            slidesToScroll: 1,
          }}
          className="w-full"
        >
          <CarouselContent className="-ml-4 md:-ml-6 pb-10">
            {activeTestimonials.map((testimonial) => (
              <CarouselItem
                key={testimonial.id}
                className="pl-4 md:pl-6 md:basis-1/2 lg:basis-1/3"
              >
                {/* Testimonial Card */}
                <div className="h-full bg-white p-8 md:p-10 border border-stone-100 shadow-sm hover:shadow-md transition-all duration-500 group relative overflow-hidden">
                  {/* Decorative Background Quote Mark */}
                  <Quote className="absolute top-8 right-8 w-24 h-24 text-stone-50 fill-stone-50 -z-0 rotate-180" />

                  <div className="relative z-10 flex flex-col h-full">
                    {/* Rating */}
                    {testimonial.visibility.show_rating === 1 && (
                      <StarRating rating={testimonial.rating} />
                    )}

                    {/* Review Text - Using enhanced cleanText() */}
                    {testimonial.visibility.show_description === 1 && (
                      <div className="flex-grow">
                        <p className="text-primary/80 font-cormorant text-xl md:text-2xl italic leading-relaxed">
                          "{cleanText(testimonial.description)}"
                        </p>
                      </div>
                    )}

                    {/* Footer / Profile */}
                    <div className="mt-8 pt-8 border-t border-stone-100 flex items-center gap-4">
                      {/* Avatar */}
                      {testimonial.visibility.show_image === 1 && (
                        <div className="relative w-12 h-12 shrink-0">
                          <div className="absolute inset-0 rounded-full border border-brand-gold/30" />
                          <Image
                            src={
                              testimonial.image?.replace("/api", "") ||
                              "/placeholder-avatar.png"
                            }
                            alt={testimonial.name}
                            fill
                            className="object-cover rounded-full p-[2px]"
                          />
                        </div>
                      )}

                      <div className="flex flex-col">
                        <span className="font-lato uppercase tracking-widest text-xs font-bold text-primary">
                          {cleanText(testimonial.name)}
                        </span>

                        <div className="flex flex-col sm:flex-row sm:gap-2 text-xs text-stone-500 mt-1 font-lato">
                          {testimonial.visibility.show_designation === 1 &&
                            testimonial.designation && (
                              <span>{cleanText(testimonial.designation)}</span>
                            )}

                          {testimonial.visibility.show_designation === 1 &&
                            testimonial.designation &&
                            testimonial.visibility.show_product === 1 &&
                            testimonial.product_name && (
                              <span className="hidden sm:inline">•</span>
                            )}

                          {testimonial.visibility.show_product === 1 &&
                            testimonial.product_name && (
                              <span className="text-brand-gold font-medium">
                                Purchased {cleanText(testimonial.product_name)}
                              </span>
                            )}
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </CarouselItem>
            ))}
          </CarouselContent>

          {/* Navigation Buttons */}
          <div className="flex justify-center md:block gap-4 mt-6 md:mt-0">
            <CarouselPrevious className="static md:absolute h-12 w-12 border-brand-gold/30 text-primary hover:bg-primary hover:text-brand-gold transition-all duration-300 md:-left-12 bg-white" />
            <CarouselNext className="static md:absolute h-12 w-12 border-brand-gold/30 text-primary hover:bg-primary hover:text-brand-gold transition-all duration-300 md:-right-12 bg-white" />
          </div>
        </Carousel>
      </div>
    </section>
  );
}
