$(document).ready(function () {

    /* --------------------------------
       1. Initialize Lenis
    -------------------------------- */
    window.lenis = new Lenis({
        duration: 1.2,
        easing: (t) => Math.min(1, 1.001 - Math.pow(2, -10 * t)),
        smoothWheel: true,
        wheelMultiplier: 1,
        smoothTouch: false,
        touchMultiplier: 2,
        infinite: false,
    });

    /* --------------------------------
       2. Connect Lenis to ScrollTrigger
       All three parts are required together
    -------------------------------- */

    // a) Tell ScrollTrigger to update on every Lenis scroll event
    lenis.on('scroll', ScrollTrigger.update);

    // b) Run Lenis inside gsap.ticker so they sync on the same frame
    gsap.ticker.add((time) => {
        lenis.raf(time * 1000);
    });

    // c) Disable lag smoothing to prevent delayed updates
    gsap.ticker.lagSmoothing(0);



    // WOW.js Init
    const wow = new WOW({
        boxClass: "wow",
        animateClass: "animated",
        offset: 200,
        mobile: false,
        live: false,
    });
    wow.init();


    // Initialize Testimonials Swiper
    if ($('.testimonials-swiper').length > 0) {
        new Swiper('.testimonials-swiper', {
            slidesPerView: 3,
            spaceBetween: 10,
            loop: true,
            autoplay: {
                delay: 5000,
                disableOnInteraction: false
            },
            pagination: {
                el: '.swiper-pagination',
                clickable: true
            },
            navigation: {
                nextEl: '.testimonials-swiper-next',
                prevEl: '.testimonials-swiper-prev'
            },
            breakpoints: {
                320: {
                    slidesPerView: 1,
                    spaceBetween: 40
                },
                768: {
                    slidesPerView: 2,
                    spaceBetween: 40
                },
                992: {
                    slidesPerView: 3,
                    spaceBetween: 40
                }
            }
        });
    }

    // Initialize Partners Swiper
    if ($('.partners-swiper').length > 0) {
        new Swiper('.partners-swiper', {
            slidesPerView: 5,
            spaceBetween: 10,
            loop: false,
            autoplay: {
                delay: 3000,
                disableOnInteraction: false
            },
            navigation: {
                nextEl: '.swiper-button-next',
                prevEl: '.swiper-button-prev'
            },
            breakpoints: {
                320: {
                    slidesPerView: 2,
                    spaceBetween: 10
                },
                576: {
                    slidesPerView: 3,
                    spaceBetween: 10
                },
                768: {
                    slidesPerView: 4,
                    spaceBetween: 10
                },
                992: {
                    slidesPerView: 5,
                    spaceBetween: 10
                }
            }
        });
    }

    // Initialize Locations Swiper
    if ($('.location-swiper').length > 0) {
        new Swiper('.location-swiper', {
            slidesPerView: 3,
            spaceBetween: 10,
            loop: true,
            speed: 800,
            autoplay: {
                delay: 5000,
                disableOnInteraction: false
            },
            pagination: {
                el: '.swiper-pagination',
                clickable: true
            },
            navigation: {
                nextEl: '.location-swiper-next',
                prevEl: '.location-swiper-prev'
            },
            breakpoints: {
                320: {
                    slidesPerView: 1,
                    spaceBetween: 20
                },
                768: {
                    slidesPerView: 2,
                    spaceBetween: 20
                },
                992: {
                    slidesPerView: 3,
                    spaceBetween: 10
                }
            }
        });
    }

    // Initialize Amenities Swiper
    if ($('.amenities-swiper').length > 0) {
        new Swiper('.amenities-swiper', {
            slidesPerView: 1,
            spaceBetween: 30,
            loop: false,
            speed: 1000,
            autoplay: {
                delay: 3500,
                disableOnInteraction: false
            },
            pagination: {
                el: '.amenities-swiper .swiper-pagination',
                clickable: true
            },
            breakpoints: {
                320: {
                    slidesPerView: 1,
                    spaceBetween: 20
                },
                576: {
                    slidesPerView: 1,
                    spaceBetween: 20
                },
                768: {
                    slidesPerView: 1,
                    spaceBetween: 20
                },
                992: {
                    slidesPerView: 1,
                    spaceBetween: 30
                }
            }
        });
    }


    // Initialize singleRommSwiper
    if ($('.singleRommSwiper').length > 0) {
        new Swiper('.singleRommSwiper', {
            slidesPerView: 1.7,
            spaceBetween: 30,
            centeredSlides: true,
            loop: true,
            //   autoplay: {
            //     delay: 3500,
            //     disableOnInteraction: false
            //   },
            pagination: {
                el: '.singleRommSwiper .swiper-pagination',
                clickable: true
            },
            breakpoints: {
                320: {
                    slidesPerView: 1.2,
                    spaceBetween: 20
                },
                992: {
                    slidesPerView: 1.7,
                    spaceBetween: 30,
                }
            }
        });
    }

    // Add/remove 'nav-scroll' class to header on scroll
    window.onscroll = function () {
        const header = document.querySelector('header');
        if (header) {
            if (window.scrollY > 50) {
                header.classList.add('nav-scroll');
            } else {
                header.classList.remove('nav-scroll');
            }
        }
    };

    // Scroll to top button
    $('.to-top').click(function () {
        $('html, body').animate({ scrollTop: 0 }, 1000);
        return false;
    });

    // Counter animation when numbers section enters viewport
    var startedBlocks = [];

    $(".numbers-section, .numbers-block").each(function (index, section) {
        var $section = $(section);

        $(window).on("scroll", function () {
            var sectionOffset = $section.offset().top - window.innerHeight + 200;

            if (!startedBlocks[index] && $(window).scrollTop() > sectionOffset) {
                startedBlocks[index] = true;

                $section.find(".counter").each(function () {
                    var $this = $(this);
                    var countTo = $this.attr("data-count");

                    $({ countNum: 0 }).animate(
                        { countNum: countTo },
                        {
                            duration: 4000,
                            easing: "swing",
                            step: function () {
                                $this.text("+" + Math.floor(this.countNum));
                            },
                            complete: function () {
                                $this.text("+" + this.countNum);
                            }
                        }
                    );
                });
            }
        });

        // Fancybox Video Popup initialization
        console.log('Initializing fancybox for video');
        $(".fancybox-video").fancybox({
            type: 'iframe',
            maxWidth: 800,
            maxHeight: 600,
            fitToView: false,
            width: '70%',
            height: '70%',
            autoSize: false,
            closeClick: false,
            helpers: {
                title: {
                    type: 'float'
                },
                media: {}
            }
        });
    });


    // Example for safely using IntersectionObserver
    const observedElement = document.querySelector(".observe-me");

    if (observedElement) {
        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    // Add your custom logic here
                    console.log("Element is in view:", entry.target);
                }
            });
        }, {
            threshold: 0.5
        });

        observer.observe(observedElement);
    }
});
// var swiper = new Swiper(".mySwiper.clients-slider", {
//   slidesPerView: 2,
//   spaceBetween: 25,
//   autoplay: {
//     delay: 2500,
//     disableOnInteraction: false,
//   },
//   breakpoints: { 0: { slidesPerView: 1 }, 480: { slidesPerView: 1 }, 787: { slidesPerView: 2 }, 991: { slidesPerView: 2 } },
//   //   pagination: {
//   //     el: ".swiper-pagination",
//   //     clickable: true,
//   //   },
//   navigation: {
//     nextEl: ".swiper-button-next",
//     prevEl: ".swiper-button-prev",
//   },
// });


document.querySelectorAll('.fav_butn').forEach(btn => {

    btn.addEventListener('click', function () {

        this.classList.toggle('active');

        const icon = this.querySelector('i');

        icon.classList.toggle('fa-solid');
        icon.classList.toggle('fa-light');

    });

});

document.querySelectorAll(".password_group").forEach(group => {

    const btn = group.querySelector(".show_pass");
    const input = group.querySelector("input");
    const icon = btn.querySelector("i");

    btn.addEventListener("click", () => {

        if (input.type === "password") {
            input.type = "text";
            icon.classList.replace("fa-eye", "fa-eye-slash");
        } else {
            input.type = "password";
            icon.classList.replace("fa-eye-slash", "fa-eye");
        }

    });

});


document.addEventListener("DOMContentLoaded", function () {

    const features = document.querySelectorAll(".feature_item");
    const btn = document.querySelector(".more_features_btn .txt");

    let expanded = false;

    features.forEach((item, index) => {
        if (index >= 10) {
            item.style.display = "none";
        }
    });

    if (btn) {
        btn.addEventListener("click", function (e) {
            e.preventDefault();

            expanded = !expanded;

            features.forEach((item, index) => {
                if (index >= 10) {
                    item.style.display = expanded ? "block" : "none";
                }
            });

            btn.textContent = expanded
                ? "عرض أقل من المرافق"
                : "عرض المزيد من المرافق";
        });
    }

});


// Loop through all cards
document.querySelectorAll(".property-card").forEach((card, index) => {

    // Main slider
    const mainSlider = card.querySelector(".main-swiper");
    const thumbsSlider = card.querySelector(".thumbs-swiper");

    // Create thumbs swiper
    const thumbs = new Swiper(thumbsSlider, {
        spaceBetween: 5,
        slidesPerView: 3,
        watchSlidesProgress: true,
        // centeredSlides: true,
    });

    // Create main swiper
    new Swiper(mainSlider, {
        spaceBetween: 10,
        loop: true,

        navigation: {
            nextEl: card.querySelector(".swiper-button-next"),
            prevEl: card.querySelector(".swiper-button-prev"),
        },

        thumbs: {
            swiper: thumbs,
        },
    });

});


// info-section marq slider 
var swiper = new Swiper('.info-section .marq-slider', {
    slidesPerView: "auto",
    spaceBetween: 0,
    centeredSlides: true,
    pagination: false,
    navigation: false,
    mousewheel: false,
    keyboard: true,
    speed: 40000,
    allowTouchMove: false,
    a11y: false,
    loop: true,
    autoplay: {
        delay: 1,
    },
});



/* --------------------------------
   [ GSAP Scripts ]
   -------------------------------- */

$(function () {
    gsap.registerPlugin(ScrollTrigger, SplitText);
    gsap.config({ nullTargetWarn: false });


    /* --------------------------------
       Image parallax on scroll
    -------------------------------- */
    gsap.utils.toArray(".img-parallax img").forEach((img) => {

        gsap.fromTo(
            img,
            {
                yPercent: -20,
                scale: 1.3,
            },
            {
                yPercent: 20,
                scale: 1,
                ease: "none",
                scrollTrigger: {
                    trigger: img,
                    start: "top bottom",
                    end: "bottom top",
                    scrub: 1.5,
                }
            }
        );

    });


    /* --------------------------------
       Reveal animation
    -------------------------------- */
    function initRevealAnimation(scope = document) {
        gsap.utils
            .toArray(scope.querySelectorAll(".reveal-parent"))
            .forEach((parent) => {
                if (parent.dataset.revealInit) return;
                parent.dataset.revealInit = "true";

                const cards = parent.querySelectorAll(".reveal-card");

                gsap.set(cards, {
                    opacity: 0,
                    scale: 0.5,
                    filter: "blur(10px)",
                });

                ScrollTrigger.create({
                    trigger: parent,
                    start: "top 80%",
                    once: true,
                    onEnter: () => {
                        gsap.to(cards, {
                            scale: 1,
                            opacity: 1,
                            filter: "blur(0px)",
                            duration: 1.2,
                            stagger: {
                                amount: 1.2,
                                from: "random",
                            },
                            ease: "back.out(1.5)",
                        });
                    },
                });
            });
    }

    // Initialize Reveal Animation
    initRevealAnimation();

    if (typeof Swiper !== "undefined") {
        const mySwiper = new Swiper(".swiper", {
            loop: true,
            slidesPerView: 3,
            spaceBetween: 30,

            on: {
                init: function () {
                    initRevealAnimation(this.el);
                },
            },
        });
    }

    // Refresh ScrollTrigger to ensure correct positions
    ScrollTrigger.refresh();


    /* --------------------------------
       fade hero animation
    -------------------------------- */
    gsap.utils.toArray(".fade-scale-hero").forEach((section) => {
        const content = section.querySelector(".content");

        gsap.fromTo(
            content,
            {
                opacity: 1,
                scale: 1,
                yPercent: 0,
                transformOrigin: "center top",
            },
            {
                opacity: 0.4,
                scale: 0.90,
                yPercent: 50,
                // rotate3d: [1, 0, 0, 30],
                ease: "none",
                scrollTrigger: {
                    trigger: section,
                    start: "30% top",
                    end: "bottom top",
                    scrub: 1,
                }
            }
        );
    });

    // flipScroll1 animation
    const flipScrollCards = document.querySelectorAll('.flip-scroll-st1');

    flipScrollCards.forEach((card) => {
        gsap.to(card,
            {
                y: 0,
                rotateX: 0,
                scale: 1,
                opacity: 1,
                ease: "power1.out",
                scrollTrigger: {
                    trigger: card,
                    start: "top 90%",
                    end: "bottom 50%",
                    scrub: 1,
                    invalidateOnRefresh: true,
                }
            }
        );
    });

});