/**
 * AJAX Add to Cart functionality
 * 
 * @package storzen
 * @since 1.0.3
 */

(function($) {
    'use strict';

    // Handle AJAX add to cart
    $(document).on('click', '.ajax_add_to_cart', function(e) {
        var $button = $(this);
        
        // Don't prevent default for variable products
        if ($button.hasClass('product_type_variable')) {
            return;
        }

        e.preventDefault();

        var productId = $button.data('product_id');
        var quantity = $button.data('quantity') || 1;

        // Add loading state
        $button.addClass('loading').removeClass('added');

        // AJAX request
        $.ajax({
            type: 'POST',
            url: wc_add_to_cart_params.wc_ajax_url.toString().replace('%%endpoint%%', 'add_to_cart'),
            data: {
                product_id: productId,
                quantity: quantity
            },
            success: function(response) {
                if (!response) {
                    return;
                }

                if (response.error && response.product_url) {
                    window.location = response.product_url;
                    return;
                }

                // Trigger event for cart fragments refresh
                $(document.body).trigger('added_to_cart', [response.fragments, response.cart_hash, $button]);

                // Show success message
                if (typeof storzenCart !== 'undefined') {
                    showAddedMessage($button);

                    // Priority 1: Redirect to cart (highest priority)
                    if (storzenCart.redirectToCart) {
                        setTimeout(function() {
                            window.location = storzenCart.cartUrl;
                        }, 500);
                        return; // Exit early, don't open drawer
                    }

                    // Priority 2: Open mini cart drawer (only if redirect is not enabled)
                    if (storzenCart.miniCartEnabled && $('.szp-mini-cart-drawer').length) {
                        setTimeout(function() {
                            $('.szp-mini-cart-drawer').addClass('open');
                            $('.szp-mini-cart-overlay').addClass('active');
                            $('body').addClass('szp-mini-cart-active');
                        }, 300);
                    }
                }
            },
            error: function() {
                $button.removeClass('loading');
            }
        });
    });

    // Show added to cart message
    function showAddedMessage($button) {
        var $product = $button.closest('.product, .shop-card-items, .shop-list-sidebar');
        
        // Remove loading state and add success state
        $button.removeClass('loading').addClass('added');

        // Show notification
        var message = '<div class="szp-cart-notification">' +
            '<i class="fas fa-check-circle"></i> ' +
            '<span>Product added to cart!</span>' +
            '</div>';

        if ($('.szp-cart-notification').length === 0) {
            $('body').append(message);
            
            setTimeout(function() {
                $('.szp-cart-notification').addClass('show');
            }, 100);

            setTimeout(function() {
                $('.szp-cart-notification').removeClass('show');
                setTimeout(function() {
                    $('.szp-cart-notification').remove();
                }, 300);
            }, 3000);
        }

        // Reset button state after animation
        setTimeout(function() {
            $button.removeClass('added');
        }, 2000);
    }

    // Update cart count in header (if exists)
    $(document.body).on('added_to_cart', function(event, fragments, cart_hash, $button) {
        // Update any cart count elements
        if (fragments && fragments['.cart-count']) {
            $('.cart-count').html(fragments['.cart-count']);
        }
        
        // Replace "Add to Cart" button with "View Cart" button
        if ($button && $button.length) {
            replaceWithViewCartButton($button);
        }
    });

    // Replace add to cart button with view cart button
    function replaceWithViewCartButton($button) {
        // Get cart URL
        var cartUrl = typeof storzenCart !== 'undefined' ? storzenCart.cartUrl : '/cart/';
        
        // Create view cart button (icon only, no text)
        var $viewCartBtn = $('<a>')
            .attr('href', cartUrl)
            .attr('aria-label', 'View Cart')
            .attr('title', 'View Cart')
            .addClass('button added_to_cart wc-forward')
            .html('<i class="fas fa-cart-shopping" aria-hidden="true"></i>');
        
        // Replace the button
        $button.replaceWith($viewCartBtn);
        
        // Animate the new button
        $viewCartBtn.hide().fadeIn(300);
    }

})(jQuery);
