document.addEventListener('DOMContentLoaded', function () {
    const dashpostsApiEndpoint = fleximp_dashposts_ajax_object.apiEndpoint;
    let isFetching = false;
    let swiper; // declare globally

    function fetchPosts() {
        if (isFetching) return;
        isFetching = true;

        fetch(dashpostsApiEndpoint, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                action: 'getLatestPosts'
            })
        })
            .then(response => response.json())
            .then(data => {
                if (data.code == 200 && Array.isArray(data.data)) {
                    displayPosts(data.data);
                    initSwiper();
                } else {
                    console.error('Error fetching plugins:', data);
                }
            })
            .catch(error => {
                console.error('Error:', error);
            })
            .finally(() => {
                isFetching = false;
            });
    }

    function displayPosts(posts) {
        const swiperWrapper = document.querySelector('.swiper-container-2 .swiper-wrapper');
        swiperWrapper.innerHTML = '';

        posts.forEach(post => {
            const postHTML = `
            <div class="swiper-slide">
                <div class="plugin-item">
                    <div class="flex-imp-sidebar-image-box">
                        <img src="${post.image}" alt="img" style="max-height:75px; max-width:75px;" class="video-img">
                        <a href="${post.url}" target="_blank">
                            <h3 class="plugin-post-title pb-2 pt-2">${post.title}</h3>  
                        </a>   
                        <a href="${post.url}"
                            class="fleximp-dash-btn fleximp-dash-btn-review flex-demo-btn mb-4 flex-contact-btn"
                            target="_blank" rel="noopener">Read More</a>
                    </div>
                </div>
            </div>`;

            swiperWrapper.insertAdjacentHTML('beforeend', postHTML);
        });
    }

    function initSwiper() {

        const container = document.querySelector('.swiper-container-2');

        // If already initialized → destroy first
        if (container.swiper) {
            container.swiper.destroy(true, true);
        }

        swiper = new Swiper('.swiper-container-2', {
            loop: true,
            slidesPerView: 4, // default fallback
            spaceBetween: 30,
            slidesPerGroup: 1,
            navigation: {
                nextEl: '.swiper-button-next',
                prevEl: '.swiper-button-prev'
            },

            breakpoints: {
                0: {
                    slidesPerView: 1,
                    spaceBetween: 20
                },
                768: {
                    slidesPerView: 2,
                    spaceBetween: 25
                },
                1024: {
                    slidesPerView: 4,
                    spaceBetween: 30
                }
            },

            observer: true,
            observeParents: true
        });
    }

    // Initialization function for dashboard tab
    let initialised = false;

    function initDashboard() {
        if (initialised) return;
        initialised = true;
        fetchPosts();
    }

    // Check if Dashboard tab is already active on page load
    if (jQuery('#dashboard').hasClass('active') || jQuery('#dashboard').hasClass('show')) {
        initDashboard();
    }

    // Bootstrap 3/4 tab shown event
    jQuery(document).on('shown.bs.tab', 'a[href="#dashboard"]', function () {
        initDashboard();
    });
});