// 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");
        });
    });
}


// Input Date and time Placeholder
const input = document.querySelector('.datetime-wrapper input');

if (input) {
    const placeholder = input.nextElementSibling;

    const toggle = () => {
        if (!placeholder) return;

        if (input.value) {
            placeholder.style.display = 'none';
            input.style.color = 'rgba(0,0,0,0.5)';
        } else {
            placeholder.style.display = 'block';
            input.style.color = 'transparent';
        }
    };

    input.addEventListener('input', toggle);
    toggle();
}

const form = document.getElementById('whatsapp-form');
const phoneNumber = '+971529856007'; // WhatsApp number
const datetimeError = document.getElementById('datetime-error');

form.addEventListener('submit', function (e) {
    e.preventDefault(); // prevent normal submission

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

    if (!datetimeInput) return; // safety check

    const selectedDate = new Date(datetimeInput);
    const now = new Date();

    // Check if date is in the past
    if (selectedDate < now) {
        datetimeError.style.display = 'block';
        return;
    } else {
        datetimeError.style.display = 'none';
    }

    // Format datetime nicely: 27 Feb 2026, 14:30
    const options = { day: 'numeric', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit' };
    const formattedDate = selectedDate.toLocaleString('en-GB', options).replace(',', '');

    // Create WhatsApp message
    let text = `*New Consultation Request*%0A`;
    text += `*Name:* ${name}%0A`;
    text += `*Phone:* ${phone}%0A`;
    text += `*Email:* ${email}%0A`;
    text += `*Preferred Contact:* ${contact}%0A`;
    text += `*Preferred Time:* ${formattedDate}%0A`;
    text += `*Message:* ${message}`;

    // Open WhatsApp chat
    const url = `https://wa.me/${phoneNumber.replace(/\D/g, '')}?text=${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();