'use client'
import { useEffect, useState } from "react";
import Link from "next/link";
import { Autoplay } from "swiper/modules";
import { Swiper, SwiperSlide } from "swiper/react";

import "swiper/css";
import "swiper/css/autoplay";

const swiperOptions = {
    modules: [Autoplay],
    slidesPerView: 3,
    spaceBetween: 20,
    loop: true,
    autoplay: {
        delay: 2000,
        disableOnInteraction: false,
        pauseOnMouseEnter: false,
    },
    breakpoints: {
        0: { slidesPerView: 1 },
        768: { slidesPerView: 2 },
        1024: { slidesPerView: 3 },
    },
};

export default function Testimonial() {
    const [reviews, setReviews] = useState([]);
    const [loading, setLoading] = useState(true);
    const [expandedReview, setExpandedReview] = useState(null);
    const [isClient, setIsClient] = useState(false);

    useEffect(() => {
        setIsClient(true);
    }, []);

    useEffect(() => {
        async function loadReviews() {
            try {
                const res = await fetch("/api/reviews");
                const data = await res.json();

                const cleaned = (data.reviews || []).filter(r =>
                    (r.text ||
                        r.description ||
                        r.snippet ||
                        r.review_text ||
                        r.body ||
                        r.content) &&
                    r.rating >= 4
                );

                setReviews(cleaned);
            } catch (error) {
                console.error("Failed to fetch reviews", error);
            } finally {
                setLoading(false);
            }
        }
        loadReviews();
    }, []);

    const displayedReviews = reviews.length > 0 && reviews.length < 3
        ? [...reviews, ...reviews, ...reviews]
        : reviews;

    function renderStars(rating) {
        return [...Array(5)].map((_, i) => (
            <span key={i} className={`fa fa-star ${i < rating ? "text-warning" : ""}`}></span>
        ));
    }

    function getReviewText(r) {
        return r.text || r.description || r.snippet || r.review_text || r.body || r.content || "";
    }

    function truncateText(text) {
        return text.length > 150 ? text.substring(0, 150) + "..." : text;
    }

    function getProfileImage(r) {
        // Normalize profile photo URLs
        const url = r.profile_photo_url || r.author_profile_photo_url || r.user?.thumbnail;
        if (!url) return "/default-user.png";
        return url.startsWith("http") ? url : `https://lh3.googleusercontent.com/${url}`;
    }

    return (
        <section className="testimonial-section-two pb-0">
            <div
                className="icon-layer-two"
                style={{ backgroundImage: "url(/assets/images/home/review-right-bottom-element-home.webp)" }}
            ></div>

            <div className="auto-container">
                <div className="sec-title centered">
                    <div className="title">Google Reviews</div>
                    <h2>Hear from our happy customers</h2>
                    <div className="separate"></div>
                </div>

                <div className="inner-container">
                    {loading && <p className="text-center">Loading reviews...</p>}

                    {!loading && isClient && displayedReviews.length > 0 && (
                        <Swiper {...swiperOptions} className="single-item-carousel">
                            {displayedReviews.map((r, index) => {
                                const fullText = getReviewText(r);
                                const isExpanded = expandedReview === index;

                                return (
                                    <SwiperSlide key={index}>
                                        <div className="google-review-card equal-height">
                                            <div className="google-review-header">
                                                <div className="google-avatar">
                                                    <img
                                                        src={getProfileImage(r)}
                                                        alt={r.author_name || r.user?.name || "User"}
                                                        onError={(e) => (e.target.src = "/default-user.png")}
                                                    />
                                                </div>

                                                <div className="google-user-info">
                                                    <h4 className="google-name">
                                                        {r.author_name || r.user?.name || "Customer"}
                                                    </h4>
                                                    <div className="google-stars">{renderStars(r.rating)}</div>
                                                </div>
                                            </div>

                                            <p className="google-text">
                                                {isExpanded ? fullText : truncateText(fullText)}
                                            </p>

                                            {r.images &&
                                                r.images.length > 0 &&
                                                r.images.some(img => img && img !== "ky") && (
                                                    <div className="google-review-images">
                                                        {r.images.map((img, i) => {
                                                            if (!img || img === "ky") return null;
                                                            const fixedImg = img.startsWith("http")
                                                                ? img
                                                                : `https://lh3.googleusercontent.com/${img}`;
                                                            return (
                                                                <img
                                                                    key={i}
                                                                    src={fixedImg}
                                                                    alt="Review image"
                                                                    className="google-review-photo"
                                                                    onError={(e) => (e.target.style.display = "none")}
                                                                />
                                                            );
                                                        })}
                                                    </div>
                                                )}

                                            {fullText.length > 150 && (
                                                <button
                                                    className="read-more-btn mt-3"
                                                    onClick={(e) => {
                                                        e.stopPropagation();
                                                        setExpandedReview(isExpanded ? null : index);
                                                    }}
                                                >
                                                    {isExpanded ? "Read Less" : "Read More"}
                                                </button>
                                            )}
                                        </div>
                                    </SwiperSlide>
                                );
                            })}
                        </Swiper>
                    )}

                    <div className="btns-box text-center mt-4">
                        <Link
                            href="https://www.google.com/search?sca_esv=0fe16c1f02c217b7&sxsrf=AE3TifOLptPQLUmmtN31E_3elXLW6TFOQw:1762618049873&si=AMgyJEtREmoPL4P1I5IDCfuA8gybfVI2d5Uj7QMwYCZHKDZ-E-aY0flGiK9jtBbvWKno0yJxYW9CK-ZYgm0G70i4ON2SMlNBNsid-fMvQPqNzI7FcY1u8NR67M0xsy1G8HMAZhtgOP2m&q=Sixty5+Street+Reviews&sa=X&ved=2ahUKEwjY5_L19-KQAxW89DgGHdw0AesQ0bkNegQILRAE&biw=1366&bih=633&dpr=1&sei=MHYRadbjFKWo4-EPlrjFkAs&zx=1762752154509&no_sw_cr=1#lrd=0x882b3dbb0e18ed73:0xbdb3783d6e6393c9,3,,,," 
                            target="_blank"
                            className="theme-btn btn-style-one clearfix"
                        >
                            <span className="icon"></span> Review us on Google
                        </Link>
                    </div>
                </div>
            </div>
        </section>
    );
}
