jQuery(document).ready(function($) {
    
    // =====================
    // Notification System
    // =====================
    function showNotification(message, type) {
        type = type || 'success';
        var icons = { success: '✅', error: '❌', info: 'ℹ️' };
        var $notif = $('<div class="dima-notification ' + type + '">' + (icons[type] || '') + ' ' + message + '</div>');
        $('body').append($notif);
        
        setTimeout(function() { $notif.addClass('show'); }, 50);
        setTimeout(function() {
            $notif.removeClass('show');
            setTimeout(function() { $notif.remove(); }, 300);
        }, 3000);
    }
    window.showNotification = showNotification;
    
    // =====================
    // Add to Cart
    // =====================
    $(document).on('click', '.add-to-cart-btn:not(.disabled)', function(e) {
        e.preventDefault();
        var $btn = $(this);
        var productId = $btn.data('product-id');
        var originalText = $btn.html();
        
        $btn.prop('disabled', true).html('<span class="dashicons dashicons-update" style="animation:spin 1s linear infinite"></span> در حال افزودن...');
        
        $.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) {
                    showNotification(response.data.message, 'success');
                    $('.cart-count-badge').text(response.data.cart_count);
                    $btn.html('✓ اضافه شد!');
                    setTimeout(function() {
                        $btn.html(originalText).prop('disabled', false);
                    }, 1500);
                } else {
                    showNotification(response.data.message || 'خطا', 'error');
                    $btn.html(originalText).prop('disabled', false);
                }
            },
            error: function() {
                showNotification('خطا در ارتباط با سرور', 'error');
                $btn.html(originalText).prop('disabled', false);
            }
        });
    });
    
    // =====================
    // Wishlist Toggle
    // =====================
    $(document).on('click', '.wishlist-btn, .floating-action-btn.wishlist-btn', function(e) {
        e.preventDefault();
        e.stopPropagation();
        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) {
                    if (response.data.action === 'added') {
                        $btn.addClass('active');
                        $btn.find('.heart-icon').text('♥');
                        showNotification('به علاقه‌مندی‌ها اضافه شد ❤️', 'success');
                    } else {
                        $btn.removeClass('active');
                        $btn.find('.heart-icon').text('♡');
                        showNotification('از علاقه‌مندی‌ها حذف شد', 'info');
                    }
                    $('.wishlist-count-badge').text(response.data.count);
                }
            }
        });
    });
    
    // =====================
    // Compare Toggle
    // =====================
    $(document).on('click', '.compare-btn, .floating-action-btn.compare-btn, .compare-mobile-btn', function(e) {
        e.preventDefault();
        e.stopPropagation();
        var $btn = $(this);
        var productId = $btn.data('product-id');
        
        $.ajax({
            url: dima_shop.ajax_url,
            type: 'POST',
            data: {
                action: 'dima_toggle_compare',
                product_id: productId,
                nonce: dima_shop.nonce
            },
            success: function(response) {
                if (response.success) {
                    showNotification(
                        response.data.action === 'added' ? 'به لیست مقایسه اضافه شد ⚖️' : 'از لیست مقایسه حذف شد',
                        response.data.action === 'added' ? 'success' : 'info'
                    );
                } else {
                    showNotification(response.data.message, 'error');
                }
            }
        });
    });
    
    // =====================
    // Quick View
    // =====================
    $(document).on('click', '.quick-view-btn', function(e) {
        e.preventDefault();
        e.stopPropagation();
        var productId = $(this).data('product-id');
        
        $.ajax({
            url: dima_shop.ajax_url,
            type: 'POST',
            data: {
                action: 'dima_quick_view',
                product_id: productId,
                nonce: dima_shop.nonce
            },
            success: function(response) {
                if (response.success) {
                    $('#quick-view-content').html(response.data.html);
                    $('#quick-view-overlay').addClass('active');
                    $('body').css('overflow', 'hidden');
                }
            }
        });
    });
    
    $('#quick-view-close, #quick-view-overlay').on('click', function(e) {
        if (e.target === this || $(this).is('#quick-view-close')) {
            $('#quick-view-overlay').removeClass('active');
            $('body').css('overflow', '');
        }
    });
    
    // ESC to close
    $(document).on('keydown', function(e) {
        if (e.key === 'Escape') {
            $('#quick-view-overlay').removeClass('active');
            $('body').css('overflow', '');
        }
    });
    
    // =====================
    // Search
    // =====================
    var searchTimer;
    $('#dima-live-search-input').on('input', function() {
        var query = $(this).val();
        clearTimeout(searchTimer);
        
        if (query.length < 2) {
            $('#dima-search-results').hide().empty();
            return;
        }
        
        searchTimer = setTimeout(function() {
            $.ajax({
                url: dima_shop.ajax_url,
                type: 'POST',
                data: { action: 'dima_live_search', query: query, nonce: dima_shop.nonce },
                success: function(response) {
                    if (response.success && response.data.products.length > 0) {
                        var html = '<ul class="search-results-list">';
                        response.data.products.forEach(function(p) {
                            html += '<li><a href="' + p.url + '">';
                            if (p.image) html += '<img src="' + p.image + '" alt="">';
                            html += '<div class="search-result-info"><strong>' + p.title + '</strong><span>' + parseInt(p.price).toLocaleString('fa-IR') + ' تومان</span></div>';
                            html += '</a></li>';
                        });
                        html += '</ul>';
                        $('#dima-search-results').html(html).show();
                    } else {
                        $('#dima-search-results').html('<p class="no-results">نتیجه‌ای یافت نشد</p>').show();
                    }
                }
            });
        }, 300);
    });
    
    $(document).on('click', function(e) {
        if (!$(e.target).closest('.dima-live-search').length) {
            $('#dima-search-results').hide();
        }
    });
    
    // =====================
    // Sort
    // =====================
    $('#dima-sort-select').on('change', function() {
        var url = new URL(window.location);
        url.searchParams.set('orderby', $(this).val());
        window.location = url.toString();
    });
    
    // =====================
    // Review Form
    // =====================
    // Star rating input
    $('.rate-star').on('click', function() {
        var val = $(this).data('value');
        $('#rating-value').val(val);
        $('.rate-star').removeClass('active');
        $(this).addClass('active').prevAll().addClass('active');
    });
    
    // Hover effect
    $('.rate-star').on('mouseenter', function() {
        $(this).addClass('active').prevAll().addClass('active');
    }).on('mouseleave', function() {
        if (!$('#rating-value').val()) {
            $('.rate-star').removeClass('active');
        }
    });
    
    // Submit review
    $('#review-form').on('submit', function(e) {
        e.preventDefault();
        var $form = $(this);
        var $btn = $form.find('.submit-review-btn');
        
        $btn.prop('disabled', true).text('در حال ارسال...');
        
        $.ajax({
            url: dima_shop.ajax_url,
            type: 'POST',
            data: $form.serialize() + '&action=dima_submit_review',
            success: function(response) {
                if (response.success) {
                    showNotification(response.data.message, 'success');
                    $form[0].reset();
                    $('.rate-star').removeClass('active');
                } else {
                    showNotification(response.data.message, 'error');
                }
            },
            complete: function() {
                $btn.prop('disabled', false).text('ارسال نظر');
            }
        });
    });
    
    // =====================
    // Cart Page Update
    // =====================
    $('.cart-quantity').on('change', function() {
        var productId = $(this).closest('tr').data('product-id');
        var quantity = $(this).val();
        
        $.ajax({
            url: dima_shop.ajax_url,
            type: 'POST',
            data: { action: 'dima_update_cart', product_id: productId, quantity: quantity, nonce: dima_shop.nonce },
            success: function(response) {
                if (response.success) location.reload();
            }
        });
    });
    
    $('.remove-from-cart').on('click', function(e) {
        e.preventDefault();
        var productId = $(this).data('product-id');
        if (!confirm('حذف این محصول؟')) return;
        
        $.ajax({
            url: dima_shop.ajax_url,
            type: 'POST',
            data: { action: 'dima_update_cart', product_id: productId, quantity: 0, nonce: dima_shop.nonce },
            success: function(response) {
                if (response.success) location.reload();
            }
        });
    });
    
    // Coupon
    $('#apply-coupon-btn').on('click', function() {
        var code = $('#coupon-code').val().trim();
        if (!code) return showNotification('کد تخفیف را وارد کنید', 'error');
        
        $.ajax({
            url: dima_shop.ajax_url,
            type: 'POST',
            data: { action: 'dima_apply_coupon', coupon_code: code, nonce: dima_shop.nonce },
            success: function(response) {
                if (response.success) {
                    showNotification(response.data.message, 'success');
                    setTimeout(function() { location.reload(); }, 1000);
                } else {
                    showNotification(response.data.message, 'error');
                }
            }
        });
    });
});
// اضافه کردن انیمیشن با JavaScript
element.classList.add('dima-fade-in-up');

// حذف انیمیشن بعد از اتمام
element.addEventListener('animationend', function() {
    this.classList.remove('dima-fade-in-up');
});

// Scroll Reveal
const observer = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
        if (entry.isIntersecting) {
            entry.target.classList.add('dima-visible');
        }
    });
});

document.querySelectorAll('.dima-scroll-reveal').forEach(el => {
    observer.observe(el);
});