// Story Shop AJAX functionality
jQuery(document).ready(function($) {
    'use strict';
    
    // Handle story click to open modal
    $(document).on('click', '.story-shop__item', function() {
        var storyId = $(this).data('story-id');
        var storyIndex = $(this).data('story-index');
        
        // Store current story index
        window.currentStoryIndex = storyIndex;
        
        // Load all stories in swiper structure
        loadAllStoriesContent(storyId);
    });
    
    // Function to load all stories content via AJAX
    function loadAllStoriesContent(currentStoryId) {
        // Show loading spinner
        $('#story-modal-content').html('<div class="swiper-wrapper"><div class="swiper-slide"><div class="story-shop__story position-relative h-100 d-flex align-items-center justify-content-center"><div class="spinner-border text-white" role="status"><span class="visually-hidden">' + storylmTranslations.loading + '</span></div></div></div></div>');
        
        $.post(story_shop_ajax.ajax_url, {
            action: 'story_shop_load_all_stories',
            current_story_id: currentStoryId,
            nonce: story_shop_ajax.nonce
        }, function(response) {
            if (response.success) {
                // Replace modal content with all stories
                $('#story-modal-content').html(response.data.html);
                
                // Wait for DOM to be ready before initializing swiper
                setTimeout(() => {
                    initializeStorySwiper(response.data.current_index);
                }, 100);
                
                // Initialize product swipers for all stories
                initializeAllProductSwipers();
            } else {
                $('#story-modal-content').html('<div class="swiper-wrapper"><div class="swiper-slide"><div class="story-shop__story position-relative h-100 d-flex align-items-center justify-content-center"><div class="text-white">Error loading stories: ' + response.data + '</div></div></div></div>');
            }
        }).fail(function() {
            $('#story-modal-content').html('<div class="swiper-wrapper"><div class="swiper-slide"><div class="story-shop__story position-relative h-100 d-flex align-items-center justify-content-center"><div class="text-white">Error loading stories</div></div></div></div>');
        });
    }
    
    // Function to load story content via AJAX (kept for backward compatibility)
    function loadStoryContent(storyId) {
        // Show loading spinner
        $('#story-modal-content').html('<div class="swiper-slide"><div class="story-shop__story position-relative h-100 d-flex align-items-center justify-content-center"><div class="spinner-border text-white" role="status"><span class="visually-hidden">' + storylmTranslations.loading + '</span></div></div></div>');
        
        $.post(story_shop_ajax.ajax_url, {
            action: 'story_shop_load_story',
            story_id: storyId,
            nonce: story_shop_ajax.nonce
        }, function(response) {
            if (response.success) {
                // Replace modal content with loaded story
                $('#story-modal-content').html('<div class="swiper-slide" data-story-id="' + storyId + '">' + response.data.html + '</div>');
                
                // Reinitialize swiper with navigation
                reinitializeStorySwiper();
                
                // Initialize product swiper if products exist
                initializeProductSwiper();
            } else {
                $('#story-modal-content').html('<div class="swiper-slide"><div class="story-shop__story position-relative h-100 d-flex align-items-center justify-content-center"><div class="text-white">Error loading story: ' + response.data + '</div></div></div>');
            }
        }).fail(function() {
            $('#story-modal-content').html('<div class="swiper-slide"><div class="story-shop__story position-relative h-100 d-flex align-items-center justify-content-center"><div class="text-white">Error loading story</div></div></div>');
        });
    }
    
    // Function to initialize product swiper
    function initializeProductSwiper() {
        if ($('.swiper-products-story').length) {
            new Swiper('.swiper-products-story', {
                slidesPerView: 'auto',
                spaceBetween: 10,
                freeMode: true
            });
        }
    }
    
    // Function to initialize story swiper with navigation
    function initializeStorySwiper(initialSlide = 0) {
        // Destroy existing swiper if it exists
        if (window.storyModalSwiper) {
            window.storyModalSwiper.destroy(true, true);
        }
        
        // Initialize swiper with navigation
        let optionEffect = {
            effect: "slide"
        };
        
        window.storyModalSwiper = new Swiper(".swiper-story-items", {
            slidesPerView: 1,
            allowTouchMove: window.innerWidth > 767 ? false : true,
            spaceBetween: 0,
            initialSlide: initialSlide,
            loop: false,
            ...optionEffect,
            navigation: {
                nextEl: ".swiper-story-items .swiper-button-next",
                prevEl: ".swiper-story-items .swiper-button-prev",
            },
            on: {
                init: (s) => s.update(),
            },
        });
    }
    
    // Function to reinitialize story swiper with navigation (kept for backward compatibility)
    function reinitializeStorySwiper() {
        initializeStorySwiper(0);
    }
    
    // Function to initialize all product swipers
    function initializeAllProductSwipers() {
        $('.swiper-products-story').each(function() {
            if (!$(this).hasClass('swiper-initialized')) {
                new Swiper(this, {
                    slidesPerView: 'auto',
                    spaceBetween: 10,
                    freeMode: true
                });
            }
        });
    }
    
    // Navigation is handled by Swiper's built-in navigation
    // Removed manual click handlers to prevent conflicts
    
    // Handle comments button click
    $(document).on('click', '.btn-comments-story', function() {
        var storyId = $(this).data('story-id');
        $('#current-story-id').val(storyId);
        
        // Load comments
        loadComments(storyId);
        
        // Show comments modal
        $('#modal-comments-story').modal('show');
    });
    
    // Load comments via AJAX
    function loadComments(storyId) {
        $.post(story_shop_ajax.ajax_url, {
            action: 'story_shop_load_comments',
            story_id: storyId,
            nonce: story_shop_ajax.nonce
        }, function(response) {
            if (response.success) {
                $('#story-comments-list').html(response.data.html);
                
                // Update comment count
                $('.btn-comments-story[data-story-id="' + storyId + '"] .comment-count').text(response.data.count);
                
                // Show/hide empty state
                if (response.data.count === 0) {
                    $('.empty-comments-story').removeClass('d-none').addClass('d-flex');
                    $('#story-comments-list').hide();
                } else {
                    $('.empty-comments-story').addClass('d-none').removeClass('d-flex');
                    $('#story-comments-list').show();
                }
            }
        });
    }
    
    // Handle story likes
    $(document).on('click', '.story-like', function(e) {
        e.preventDefault();
        
        var $likeButton = $(this);
        var storyId = $likeButton.data('story-id');
        
        // Prevent multiple clicks
        if ($likeButton.hasClass('processing')) {
            return;
        }
        
        $likeButton.addClass('processing');
        
        $.post(story_shop_ajax.ajax_url, {
            action: 'story_shop_toggle_like',
            story_id: storyId,
            nonce: story_shop_ajax.nonce
        }, function(response) {
            console.log('Like response:', response);
            if (response.success) {
                // Update count
                $likeButton.find('.like-count').text(response.data.count);
                
                // Toggle liked class
                if (response.data.liked) {
                    $likeButton.addClass('liked');
                } else {
                    $likeButton.removeClass('liked');
                }
            } else {
                // Show error message
                if (response.data === storylmTranslations.pleaseLogin) {
                    alert(storylmTranslations.pleaseLogin);
                } else {
                    alert(response.data);
                }
            }
            
            $likeButton.removeClass('processing');
        }).fail(function() {
            $likeButton.removeClass('processing');
            alert(storylmTranslations.requestError);
        });
    });

    // Handle comment form submission
    $('.send-comment-story__form').on('submit', function(e) {
        e.preventDefault();
        
        var $form = $(this);
        var comment = $form.find('input[name="comment"]').val();
        var storyId = $('#current-story-id').val();
        
        if (!comment.trim()) {
            alert(storylmTranslations.emptyComment);
            return;
        }
        
        $.post(story_shop_ajax.ajax_url, {
            action: 'story_shop_post_comment',
            story_id: storyId,
            comment: comment,
            nonce: story_shop_ajax.nonce
        }, function(response) {
            if (response.success) {
                // Clear the input
                $form.find('input[name="comment"]').val('');
                
                // Reload comments
                loadComments(storyId);
            } else {
                alert(response.data);
            }
        });
    });
    
    // Show/hide send button based on input
    $('.send-comment-story__input').on('input', function() {
        var $btn = $(this).siblings('.send-comment-story__btn');
        if ($(this).val().trim()) {
            $btn.removeClass('d-none');
        } else {
            $btn.addClass('d-none');
        }
    });
    
    // Handle product click in story
    $(document).on('click', '.story-shop__story__product', function() {
        var productId = $(this).data('product-id');
        
        // Load product details
        $.post(story_shop_ajax.ajax_url, {
            action: 'story_shop_load_product',
            product_id: productId,
            nonce: story_shop_ajax.nonce
        }, function(response) {
            if (response.success) {
                $('#product-story-content').html(response.data.html);
                $('#modal-product-story').modal('show');
            } else {
                alert(response.data);
            }
        });
    });
    
    // Handle video playback controls
    $(document).on('click', '.video__box', function() {
        var $video = $(this).find('video');
        if ($video.length) {
            if ($video[0].paused) {
                $video[0].play();
            } else {
                $video[0].pause();
            }
        }
    });
    
    // Update video progress bar
    $(document).on('timeupdate', '.video__box video', function() {
        var $video = $(this);
        var $progress = $video.siblings('.video__box__control-bar').find('.video__box__control-bar__progress span');
        var $time = $video.siblings('.video__box__control-bar').find('.video__box__control-bar__current-time');
        
        var percent = ($video[0].currentTime / $video[0].duration) * 100;
        $progress.css('width', percent + '%');
        
        // Update time display
        var minutes = Math.floor($video[0].currentTime / 60);
        var seconds = Math.floor($video[0].currentTime - minutes * 60);
        $time.text(('0' + minutes).slice(-2) + ':' + ('0' + seconds).slice(-2));
    });
});