/**
 * Mini Cart Drawer functionality
 * 
 * @package storzen
 * @since 1.0.3
 */

(function($) {
    'use strict';

    // Check if drawer should auto-open after page load (for non-AJAX add to cart)
    $(document).ready(function() {
        var urlParams = new URLSearchParams(window.location.search);
        if (urlParams.get('open_mini_cart') === '1') {
            // Wait a bit for page to fully load
            setTimeout(function() {
                openMiniCart();
                // Clean URL without reloading page
                if (window.history && window.history.replaceState) {
                    var cleanUrl = window.location.pathname + window.location.search.replace(/[?&]open_mini_cart=1/, '').replace(/^&/, '?');
                    window.history.replaceState({}, document.title, cleanUrl);
                }
            }, 300);
        }
    });

    // Open mini cart drawer
    $(document).on('click', '.szp-open-mini-cart, .cart-icon, .mini-cart-trigger', function(e) {
        e.preventDefault();
        openMiniCart();
    });

    // Also handle cart links
    $(document).on('click', 'a[href*="cart"]', function(e) {
        if ($(this).attr('href') && $(this).attr('href').indexOf('cart') !== -1 && $('.szp-mini-cart-drawer').length) {
            // Only intercept if not in admin and drawer exists
            if (!$(this).closest('.woocommerce-message').length) {
                return; // Let normal cart links work
            }
            e.preventDefault();
            openMiniCart();
        }
    });

    // Handle WooCommerce's "View Cart" messages
    $(document).on('click', '.woocommerce-message a.button', function(e) {
        if ($(this).attr('href') && $(this).attr('href').indexOf('cart') !== -1 && $('.szp-mini-cart-drawer').length) {
            e.preventDefault();
            openMiniCart();
        }
    });

    // Close mini cart drawer
    $(document).on('click', '.szp-mini-cart-close, .szp-mini-cart-overlay', function(e) {
        e.preventDefault();
        closeMiniCart();
    });

    // Close on ESC key
    $(document).on('keyup', function(e) {
        if (e.key === 'Escape' && $('.szp-mini-cart-drawer').hasClass('open')) {
            closeMiniCart();
        }
    });

    // Open mini cart
    function openMiniCart() {
        $('.szp-mini-cart-drawer').addClass('open');
        $('.szp-mini-cart-overlay').addClass('active');
        $('body').addClass('szp-mini-cart-active');
    }

    // Close mini cart
    function closeMiniCart() {
        $('.szp-mini-cart-drawer').removeClass('open');
        $('.szp-mini-cart-overlay').removeClass('active');
        $('body').removeClass('szp-mini-cart-active');
    }

    // Update mini cart on cart update
    $(document.body).on('wc_fragments_refreshed added_to_cart removed_from_cart', function() {
        // Cart fragments are automatically updated by WooCommerce
    });

    // Handle remove item from mini cart
    $(document).on('click', '.szp-mini-cart-drawer .remove_from_cart_button', function(e) {
        e.preventDefault();
        
        var $button = $(this);
        var cartItemKey = $button.data('cart_item_key');

        // Add loading state
        $button.closest('.woocommerce-mini-cart-item').addClass('removing');

        // Remove item via AJAX
        $.ajax({
            type: 'POST',
            url: wc_add_to_cart_params.wc_ajax_url.toString().replace('%%endpoint%%', 'remove_from_cart'),
            data: {
                cart_item_key: cartItemKey
            },
            success: function(response) {
                if (response && response.fragments) {
                    // Trigger fragments refresh
                    $(document.body).trigger('wc_fragment_refresh');
                    $(document.body).trigger('removed_from_cart', [response.fragments, response.cart_hash]);
                }
            },
            error: function() {
                $button.closest('.woocommerce-mini-cart-item').removeClass('removing');
            }
        });
    });

})(jQuery);
