<?php
function kpy_web_slider($atts) {
    $atts = shortcode_atts([
        'posts_per_page' => 9,
        'heading'        => 'Our Solutions',
        'subheading'     => 'Bakla Ltd ensures that organizations communicate clearly, engage effectively with their audiences, and operate efficiently in the digital space.',
    ], $atts);

    $args = array(
        'post_type'      => 'page',
        'posts_per_page' => intval($atts['posts_per_page']),
        'tax_query'      => [
            [
                'taxonomy' => 'page_category',
                'field'    => 'slug',
                'terms'    => 'web',
            ],
        ],
    );

    $query = new WP_Query($args);

    ob_start();
    ?>

    <div class="kpy-slider-wrapper" 
         data-aos="fade-up" 
         data-aos-duration="900" 
         data-aos-offset="100">
        
        <div class="kpy-section-heading">
            <div class="kpy-heading-badge" 
                 data-aos="fade-up" 
                 data-aos-duration="600" 
                 data-aos-offset="50">
                <span>Our Expertise</span>
            </div>
            <h2 data-aos="fade-up" 
                data-aos-duration="700" 
                data-aos-delay="100"
                data-aos-offset="50">
                <?php echo esc_html($atts['heading']); ?>
            </h2>
            <?php if (!empty($atts['subheading'])) : ?>
                <p class="kpy-subheading" 
                   data-aos="fade-up" 
                   data-aos-duration="700" 
                   data-aos-delay="200"
                   data-aos-offset="50">
                    <?php echo esc_html($atts['subheading']); ?>
                </p>
            <?php endif; ?>
        </div>

        <div class="kpy-slider-container" 
             data-aos="fade-up" 
             data-aos-duration="800" 
             data-aos-delay="300"
             data-aos-offset="100">
            
            <div class="kpy-slider">
                <?php 
                $slide_index = 0;
                while ($query->have_posts()) : $query->the_post(); 
                    $delay = 0.4 + ($slide_index * 0.05);
                ?>
                    <div class="kpy-slide" 
                         data-aos="fade-up" 
                         data-aos-duration="600" 
                         data-aos-delay="<?php echo $delay * 1000; ?>"
                         data-aos-offset="50">
                        <a href="<?php the_permalink(); ?>" class="kpy-slide-inner">
                            <div class="kpy-slide-img">
                                <?php if (has_post_thumbnail()) {
                                    the_post_thumbnail('large');
                                } else { ?>
                                    <img src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 400 250'%3E%3Crect width='400' height='250' fill='%23ddd'/%3E%3Ctext x='50%25' y='50%25' text-anchor='middle' dy='.3em' fill='%23999'%3ENo Image%3C/text%3E%3C/svg%3E" alt="Placeholder">
                                <?php } ?>
                            </div>
                            <div class="kpy-slide-overlay">
                                <div class="kpy-overlay-content">
                                    <div class="kpy-icon" 
                                         data-aos="zoom-in" 
                                         data-aos-duration="400" 
                                         data-aos-delay="<?php echo ($delay + 0.1) * 1000; ?>">
                                        <i class="fa-solid fa-arrow-right"></i>
                                    </div>
                                    <h3 data-aos="fade-up" 
                                        data-aos-duration="500" 
                                        data-aos-delay="<?php echo ($delay + 0.15) * 1000; ?>">
                                        <?php the_title(); ?>
                                    </h3>
                                    <p data-aos="fade-up" 
                                       data-aos-duration="600" 
                                       data-aos-delay="<?php echo ($delay + 0.2) * 1000; ?>">
                                        <?php echo wp_trim_words(get_the_excerpt(), 16); ?>
                                    </p>
                                </div>
                            </div>
                        </a>
                    </div>
                <?php 
                $slide_index++;
                endwhile; 
                wp_reset_postdata(); 
                ?>
            </div>

            <button class="kpy-prev" aria-label="Previous slide" 
                    data-aos="fade-right" 
                    data-aos-duration="500" 
                    data-aos-delay="600">
                <i class="fa-solid fa-chevron-left"></i>
            </button>
            <button class="kpy-next" aria-label="Next slide" 
                    data-aos="fade-left" 
                    data-aos-duration="500" 
                    data-aos-delay="600">
                <i class="fa-solid fa-chevron-right"></i>
            </button>
        </div>

        <div class="kpy-dots" 
             data-aos="fade-up" 
             data-aos-duration="500" 
             data-aos-delay="700"></div>
    </div>

    <style>
        /* AOS initial state fixes for slider */
        .kpy-slide {
            opacity: 0;
            transition: opacity 0.3s ease;
        }
        
        .kpy-slide.aos-animate {
            opacity: 1;
        }
        
        /* Prevent slider jump during AOS initialization */
        .aos-init {
            opacity: 0;
        }
        
        .aos-animate {
            opacity: 1;
        }
        
        /* Ensure slider controls are visible */
        .kpy-prev, .kpy-next {
            transition: all 0.3s ease;
        }
    </style>

    <script>
        document.addEventListener("DOMContentLoaded", function () {
            const slider = document.querySelector(".kpy-slider");
            const nextBtn = document.querySelector(".kpy-next");
            const prevBtn = document.querySelector(".kpy-prev");
            const dotsContainer = document.querySelector(".kpy-dots");
            
            if (!slider || !nextBtn || !prevBtn) return;
            
            const slides = document.querySelectorAll(".kpy-slide");
            let slideWidth = 0;
            let gap = 25;
            let currentIndex = 0;
            let totalSlides = slides.length;
            let slidesPerView = 3;
            let autoPlayInterval;
            let isDragging = false;
            let startPos = 0;
            let currentTranslate = 0;
            
            function updateSlidesPerView() {
                if (window.innerWidth <= 768) {
                    slidesPerView = 1;
                } else if (window.innerWidth <= 1024) {
                    slidesPerView = 2;
                } else {
                    slidesPerView = 3;
                }
                updateSlideWidth();
            }
            
            function updateSlideWidth() {
                if (slides.length > 0) {
                    const slideRect = slides[0].getBoundingClientRect();
                    const containerRect = document.querySelector(".kpy-slider-container").getBoundingClientRect();
                    if (slidesPerView === 1) {
                        slideWidth = containerRect.width;
                        gap = 0;
                    } else {
                        slideWidth = slideRect.width;
                        gap = 25;
                    }
                }
            }
            
            function updateSlider() {
                const maxIndex = Math.max(0, totalSlides - slidesPerView);
                if (currentIndex > maxIndex) currentIndex = maxIndex;
                if (currentIndex < 0) currentIndex = 0;
                const scrollAmount = currentIndex * (slideWidth + gap);
                slider.style.transform = `translateX(-${scrollAmount}px)`;
                updateDots();
                updateButtons();
            }
            
            function updateDots() {
                if (!dotsContainer) return;
                const maxIndex = Math.max(0, totalSlides - slidesPerView);
                const dotCount = maxIndex + 1;
                dotsContainer.innerHTML = '';
                for (let i = 0; i < dotCount; i++) {
                    const dot = document.createElement('button');
                    dot.classList.add('kpy-dot');
                    if (i === currentIndex) dot.classList.add('active');
                    
                    // Add AOS attributes to new dots
                    dot.setAttribute('data-aos', 'zoom-in');
                    dot.setAttribute('data-aos-duration', '300');
                    dot.setAttribute('data-aos-delay', String(700 + (i * 50)));
                    
                    dot.addEventListener('click', () => {
                        currentIndex = i;
                        updateSlider();
                        resetAutoPlay();
                    });
                    dotsContainer.appendChild(dot);
                }
                
                // Reinitialize AOS for dynamically added dots
                if (typeof AOS !== 'undefined') {
                    AOS.refresh();
                }
            }
            
            function updateButtons() {
                const maxIndex = Math.max(0, totalSlides - slidesPerView);
                prevBtn.disabled = currentIndex === 0;
                nextBtn.disabled = currentIndex >= maxIndex;
                
                // Update button styles based on disabled state
                if (prevBtn.disabled) {
                    prevBtn.style.opacity = '0.5';
                    prevBtn.style.cursor = 'not-allowed';
                } else {
                    prevBtn.style.opacity = '1';
                    prevBtn.style.cursor = 'pointer';
                }
                
                if (nextBtn.disabled) {
                    nextBtn.style.opacity = '0.5';
                    nextBtn.style.cursor = 'not-allowed';
                } else {
                    nextBtn.style.opacity = '1';
                    nextBtn.style.cursor = 'pointer';
                }
            }
            
            function nextSlide() {
                const maxIndex = Math.max(0, totalSlides - slidesPerView);
                if (currentIndex < maxIndex) {
                    currentIndex++;
                    updateSlider();
                }
            }
            
            function prevSlide() {
                if (currentIndex > 0) {
                    currentIndex--;
                    updateSlider();
                }
            }
            
            function startAutoPlay() {
                if (autoPlayInterval) clearInterval(autoPlayInterval);
                autoPlayInterval = setInterval(() => {
                    const maxIndex = Math.max(0, totalSlides - slidesPerView);
                    if (currentIndex >= maxIndex) {
                        currentIndex = 0;
                        updateSlider();
                    } else {
                        nextSlide();
                    }
                }, 5000);
            }
            
            function resetAutoPlay() {
                if (autoPlayInterval) {
                    clearInterval(autoPlayInterval);
                    startAutoPlay();
                }
            }
            
            function stopAutoPlay() {
                if (autoPlayInterval) {
                    clearInterval(autoPlayInterval);
                    autoPlayInterval = null;
                }
            }
            
            // Drag functionality
            function dragStart(e) {
                if (window.innerWidth <= 768) return;
                stopAutoPlay();
                isDragging = true;
                startPos = e.type === 'mousedown' ? e.pageX : e.touches[0].clientX;
                slider.style.transition = 'none';
            }
            
            function dragMove(e) {
                if (!isDragging) return;
                const currentPos = e.type === 'mousemove' ? e.pageX : e.touches[0].clientX;
                const diff = currentPos - startPos;
                const currentTranslateX = currentIndex * (slideWidth + gap);
                slider.style.transform = `translateX(-${currentTranslateX - diff}px)`;
            }
            
            function dragEnd(e) {
                if (!isDragging) return;
                isDragging = false;
                slider.style.transition = 'transform 0.5s cubic-bezier(0.2, 0, 0, 1)';
                const endPos = e.type === 'mouseup' ? e.pageX : (e.changedTouches ? e.changedTouches[0].clientX : 0);
                const diff = endPos - startPos;
                const threshold = 50;
                if (Math.abs(diff) > threshold) {
                    if (diff > 0) {
                        prevSlide();
                    } else {
                        nextSlide();
                    }
                } else {
                    updateSlider();
                }
                startAutoPlay();
            }
            
            nextBtn.addEventListener("click", () => { nextSlide(); resetAutoPlay(); });
            prevBtn.addEventListener("click", () => { prevSlide(); resetAutoPlay(); });
            
            slider.addEventListener('mousedown', dragStart);
            slider.addEventListener('mousemove', dragMove);
            slider.addEventListener('mouseup', dragEnd);
            slider.addEventListener('touchstart', dragStart);
            slider.addEventListener('touchmove', dragMove);
            slider.addEventListener('touchend', dragEnd);
            
            let resizeTimer;
            window.addEventListener("resize", function() {
                clearTimeout(resizeTimer);
                resizeTimer = setTimeout(function() {
                    updateSlidesPerView();
                    updateSlider();
                }, 250);
            });
            
            updateSlidesPerView();
            updateSlider();
            startAutoPlay();
            
            // Pause autoplay on hover
            const wrapper = document.querySelector(".kpy-slider-wrapper");
            if (wrapper) {
                wrapper.addEventListener("mouseenter", stopAutoPlay);
                wrapper.addEventListener("mouseleave", startAutoPlay);
            }
            
            // Refresh AOS after slider is initialized
            if (typeof AOS !== 'undefined') {
                setTimeout(() => {
                    AOS.refresh();
                }, 100);
            }
        });
    </script>

    <?php
    return ob_get_clean();
}
add_shortcode('kpy_web_slider', 'kpy_web_slider');
?>