// Image Slider
const sliderEl = document.getElementById('image-slider');
if (sliderEl) {
    const splide = new Splide('#image-slider', {
        type: 'loop',
        perPage: 2,
        focus: 'left',
        gap: '20px',
        autoplay: true,
        pauseOnHover: false,
        pauseOnFocus: false,
        interval: 3000,
        padding: window.innerWidth <= 767 ? { left: '20px', right: '20px' } : { left: '12%', right: '12%' },
        arrows: true,
        pagination: false,
        speed: 600,
        breakpoints: {
            768: {
                perPage: 1,
            },
        }
    });

    splide.mount();
}

// FAQ Section
const faq = document.querySelectorAll(".faq");
if (faq) {
    faq.forEach(faq => {
        faq.addEventListener("click", () => {

            document.querySelectorAll(".faq").forEach(item => {
                if (item !== faq) item.classList.remove("active");
            });

            faq.classList.toggle("active");
        });
    });
}

// Consultation Form
const form = document.getElementById('whatsapp-form');
const phoneNumber = '+971529856007';

if (form) {
    form.addEventListener('submit', function (e) {
        e.preventDefault();

        const name = form.elements['name'].value;
        const phone = form.elements['phone'].value;
        const email = form.elements['email'].value;
        const datetime = form.elements['datetime'].value;
        const message = form.elements['message'].value;

        let text = `*New Consultation Request*\n`;
        text += `*Name:* ${name}\n`;
        text += `*Phone:* ${phone}\n`;
        text += `*Email:* ${email}\n`;
        text += `*Preferred Time:* ${datetime}\n`;
        text += `*Message:* ${message}`;

        const url = `https://wa.me/${phoneNumber.replace(/\D/g, '')}?text=${encodeURIComponent(text)}`;

        window.open(url, '_blank');
    });
}


// FadeIn Animation
gsap.registerPlugin(ScrollTrigger);

gsap.utils.toArray("section").forEach((sec) => {

    gsap.utils.toArray(sec.children).forEach((child) => {

        if (child.classList.contains("hero-overlay")) return;

        gsap.from(child, {
            opacity: 0,
            y: 40,
            duration: 1.2,
            ease: "power2.out",
            scrollTrigger: {
                trigger: child,
                start: "top 82%",
            }
        });
    });

});

gsap.from("footer > *", {
    opacity: 0,
    y: 40,
    duration: 1.6,
    ease: "power2.out",
    stagger: 0.15,
    scrollTrigger: {
        trigger: "footer",
        start: "top 70%",
        toggleActions: "play none none none",
    }
});

// Google Reviews

async function fetchReviews() {
    const res = await fetch("reviews.php");
    const data = await res.json();

    const reviews = data.reviews || [];
    const list = document.querySelector("#google-reviews .splide__list");
    list.innerHTML = "";

    reviews.forEach((review, index) => {
        const author = review.authorAttribution?.displayName || "Anonymous";
        const photo = review.authorAttribution?.photoUri || "./assets/images/default-user.jpg";
        const rating = review.rating || 0;
        const publishTime = new Date(review.publishTime).toDateString();
        const fullText = review.text?.text || "";

        const limit = 180;
        let displayText = fullText;
        let toggleHTML = "";

        if (fullText.length > limit) {
            const shortText = fullText.substring(0, limit);
            displayText = shortText;

            toggleHTML = `
                <span class="show-toggle" 
                      data-short="${shortText}" 
                      data-full="${fullText}">
                      ... show more
                </span>
            `;
        }

        // ⭐ Stars
        let starsHTML = "";
        for (let i = 1; i <= 5; i++) {
            starsHTML += `<img src="./assets/images/${i <= rating ? "star" : "star-empty"}.svg" alt="star icon">`;
        }

        list.innerHTML += `
        <div class="splide__slide">
            <div class="review-wrapper">
                <div class="user-details">
                    <img src="${photo}" alt="user profile img">
                    <div>
                        <h6>${author}</h6>
                        <p>${publishTime}</p>
                    </div>
                    <img src="./assets/images/google-icon.svg" alt="icon">
                </div>

                <div class="rating">
                    ${starsHTML}
                </div>

                <p class="review-text">
                    ${displayText}${toggleHTML}
                </p>
            </div>
        </div>`;
    });

    // ✅ Show More Toggle (Loop Compatible)
    document.addEventListener("click", function (e) {
        if (e.target.classList.contains("show-toggle")) {
            const wrapper = e.target.closest(".review-wrapper");
            const p = wrapper.querySelector(".review-text");

            const isExpanded = e.target.classList.contains("expanded");
            const full = e.target.dataset.full;
            const short = e.target.dataset.short;

            if (isExpanded) {
                p.innerHTML = short + `<span class="show-toggle" data-short="${short}" data-full="${full}">... show more</span>`;
            } else {
                p.innerHTML = full + `<span class="show-toggle expanded" data-short="${short}" data-full="${full}"> show less</span>`;
            }
        }
    });

    // ✅ Initialize Splide
    const reviewsSlider = document.querySelector('#google-reviews');
    if (reviewsSlider) {
        new Splide('#google-reviews', {
            type: 'loop',
            perPage: 3,
            gap: 20,
            autoplay: true,
            interval: 3000,
            pagination: false,
            arrows: true,
            breakpoints: {
                992: { perPage: 2 },
                768: { perPage: 1 },
            }
        }).mount();
    }
}
fetchReviews();