jQuery(document).ready(function($) {
    
    // 1. Search Widget - Live Search
    var searchTimer;
    $('.dima-widget-search-input').on('input', function() {
        var $input = $(this);
        var query = $input.val();
        var $results = $input.closest('.dima-search-widget').find('.dima-widget-search-results');
        var $loader = $input.closest('.search-input-wrapper').find('.search-loader');
        var category = $input.closest('form').find('.dima-search-category').val();
        
        clearTimeout(searchTimer);
        
        if (query.length < 2) {
            $results.removeClass('active').empty();
            return;
        }
        
        $loader.show();
        
        searchTimer = setTimeout(function() {
            $.ajax({
                url: dima_shop.ajax_url,
                type: 'POST',
                data: {
                    action: 'dima_live_search',
                    query: query,
                    category: category,
                    nonce: dima_shop.nonce
                },
                success: function(response) {
                    $loader.hide();
                    
                    if (response.success && response.data.products.length > 0) {
                        var html = '';
                        response.data.products.forEach(function(product) {
                            html += '<a href="' + product.url + '" class="search-result-item">';
                            if (product.image) {
                                html += '<img src="' + product.image + '" alt="' + product.title + '">';
                            }
                            html += '<div class="search-result-info">';
                            html += '<div class="search-result-title">' + product.title + '</div>';
                            html += '<div class="search-result-price">' + parseInt(product.price).toLocaleString('fa-IR') + ' تومان</div>';
                            html += '</div>';
                            html += '</a>';
                        });
                        $results.html(html).addClass('active');
                    } else {
                        $results.html('<div class="search-result-item"><div class="search-result-info">نتیجه‌ای یافت نشد</div></div>').addClass('active');
                    }
                }
            });
        }, 300);
    });
    
    // Close search results on outside click
    $(document).on('click', function(e) {
        if (!$(e.target).closest('.dima-search-widget').length) {
            $('.dima-widget-search-results').removeClass('active');
        }
    });
    
    // Popular tags click
    $('.popular-tag').on('click', function(e) {
        e.preventDefault();
        var search = $(this).data('search');
        $(this).closest('.dima-search-widget').find('.dima-widget-search-input').val(search).trigger('input');
    });
    
    // 2. Mini Cart - AJAX updates
    $(document).on('dima_cart_updated', function() {
        // Reload mini cart widget via AJAX if needed
        $('.dima-mini-cart-widget').each(function() {
            var $widget = $(this);
            // Could add AJAX reload here
        });
    });
    
    // 7. Flash Sale Timer
    function updateFlashTimers() {
        $('.flash-item').each(function() {
            var $item = $(this);
            var endTime = new Date($item.data('end-time')).getTime();
            var now = new Date().getTime();
            var diff = endTime - now;
            
            if (diff <= 0) {
                $item.fadeOut();
                return;
            }
            
            var days = Math.floor(diff / (1000 * 60 * 60 * 24));
            var hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
            var minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
            var seconds = Math.floor((diff % (1000 * 60)) / 1000);
            
            $item.find('.days').text(String(days).padStart(2, '0'));
            $item.find('.hours').text(String(hours).padStart(2, '0'));
            $item.find('.minutes').text(String(minutes).padStart(2, '0'));
            $item.find('.seconds').text(String(seconds).padStart(2, '0'));
        });
    }
    
    if ($('.flash-item').length > 0) {
        updateFlashTimers();
        setInterval(updateFlashTimers, 1000);
    }
    
    // 9. Rewards - Redeem points
    $('.redeem-btn').on('click', function() {
        var $btn = $(this);
        var points = $btn.data('points');
        
        if (!confirm('آیا از تبدیل ' + points + ' امتیاز به کوپن تخفیف مطمئن هستید؟')) {
            return;
        }
        
        $btn.prop('disabled', true).text('در حال پردازش...');
        
        $.ajax({
            url: dima_shop.ajax_url,
            type: 'POST',
            data: {
                action: 'dima_redeem_rewards',
                points: points,
                nonce: dima_shop.nonce
            },
            success: function(response) {
                if (response.success) {
                    alert('✅ ' + response.data.message + '\n\nکد کوپن: ' + response.data.coupon_code);
                    location.reload();
                } else {
                    alert('❌ ' + response.data.message);
                    $btn.prop('disabled', false).text('🎁 تبدیل به کوپن تخفیف');
                }
            }
        });
    });
    
    // 10. Wishlist - Remove from widget
    $('.remove-from-wishlist').on('click', function() {
        var $btn = $(this);
        var productId = $btn.data('product-id');
        
        $.ajax({
            url: dima_shop.ajax_url,
            type: 'POST',
            data: {
                action: 'dima_toggle_wishlist',
                product_id: productId,
                nonce: dima_shop.nonce
            },
            success: function(response) {
                if (response.success) {
                    $btn.closest('.wishlist-item').fadeOut(300, function() {
                        $(this).remove();
                        
                        // Update count badge
                        $('.wishlist-count-badge').text(response.data.count);
                        
                        if ($('.wishlist-item').length === 0) {
                            location.reload();
                        }
                    });
                }
            }
        });
    });
    
    // Mini add to cart from widgets
    $(document).on('click', '.mini-add-to-cart', function(e) {
        e.preventDefault();
        var $btn = $(this);
        var productId = $btn.data('product-id');
        
        $btn.addClass('loading');
        
        $.ajax({
            url: dima_shop.ajax_url,
            type: 'POST',
            data: {
                action: 'dima_add_to_cart',
                product_id: productId,
                quantity: 1,
                nonce: dima_shop.nonce
            },
            success: function(response) {
                if (response.success) {
                    // Update cart count badges
                    $('.cart-count-badge').text(response.data.cart_count);
                    
                    // Animation
                    $btn.addClass('added');
                    setTimeout(function() {
                        $btn.removeClass('loading added');
                    }, 1000);
                    
                    // Trigger cart update event
                    $(document).trigger('dima_cart_updated');
                    
                    // Show notification
                    if (typeof showNotification === 'function') {
                        showNotification(response.data.message, 'success');
                    }
                }
            }
        });
    });
});