jQuery(document).ready(function($) {
    function initializeCarousel(selector) {
        var totalItems = $(selector).find('.item').length; // Count available items

        // Add AOS animation to the carousel container
        $(selector).attr("data-aos", "fade-up"); // Apply animation to the entire carousel container

        $(selector).owlCarousel({
            loop: totalItems > 4,  
            rewind: totalItems <= 4,
            margin: 15, 
            nav: true,   
            dots: true,  
            autoplay: false,  
            smartSpeed: 600, 
            stagePadding: 20, 
            lazyLoad: false,
            animateOut: false, 
            animateIn: false, 
            navText: [
                '<span class="custom-prev">&#9665;</span>', 
                '<span class="custom-next">&#9655;</span>'
            ],
            responsive: {
                0: { items: 1, stagePadding: 10 },  
                600: { items: 2, stagePadding: 15 },  
                1000: { items: Math.min(4, totalItems), stagePadding: 20 }  
            },
            onInitialized: function() {
                AOS.refresh(); // Refresh AOS after carousel initializes
            },
            onTranslated: function() {
                AOS.refresh(); // Refresh AOS when slides change
            }
        });

        // Equalize heights after carousel loads
        function equalizeHeights() {
            let maxHeight = 0;
            $(selector + " .card").each(function() {
                let thisHeight = $(this).outerHeight();
                if (thisHeight > maxHeight) {
                    maxHeight = thisHeight;
                }
            });
            $(selector + " .card").css("height", maxHeight + "px");
        }

        $(selector).on('initialized.owl.carousel resized.owl.carousel', function() {
            equalizeHeights();
            AOS.refresh(); // Refresh AOS when resizing
        });
    }

    // Initialize Owl Carousel for all tabs when the page loads
    initializeCarousel('#newsCarousel');
    initializeCarousel('#eventsCarousel');
    initializeCarousel('#mediaCarousel');

    // Reinitialize Owl Carousel when switching tabs
    $('#myTab a').on('shown.bs.tab', function (e) {
        var target = $(e.target).attr('href'); // Activated tab
        if (target === '#news-tab-pane') {
            initializeCarousel('#newsCarousel');
        } else if (target === '#events-tab-pane') {
            initializeCarousel('#eventsCarousel');
        } else if (target === '#media-tab-pane') {
            initializeCarousel('#mediaCarousel');
        }
    });

    // Initialize AOS after everything loads
    AOS.init({
        duration: 1000, // Animation duration
        easing: "ease-in-out",
        once: true // Only animate once
    });
});
