jQuery(document).ready(function($) {
    'use strict';

    // Wallet Add Funds Form Handler
    $('#wallet-add-funds-form').on('submit', function(e) {
        e.preventDefault();
        
        var $form = $(this);
        var $button = $form.find('button[type="submit"]');
        var originalText = $button.text();
        
        var amount = parseFloat($('#wallet-amount').val());
        var paymentMethod = $('#wallet-payment-method').val();
        
        // Validation
        if (!amount || amount <= 0) {
            showWalletMessage('Please enter a valid amount.', 'error');
            return;
        }
        
        if (!paymentMethod) {
            showWalletMessage('Please select a payment method.', 'error');
            return;
        }
        
        // Show loading state
        $button.prop('disabled', true).text('Processing...');
        $form.addClass('wallet-loading');
        
        // AJAX request
        $.ajax({
            url: kaveh_wallet_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'add_wallet_funds',
                amount: amount,
                payment_method: paymentMethod,
                nonce: kaveh_wallet_ajax.nonce
            },
            success: function(response) {
                var data = JSON.parse(response);
                
                if (data.success) {
                    // Redirect to checkout
                    window.location.href = data.redirect_url;
                } else {
                    showWalletMessage(data.message || 'An error occurred. Please try again.', 'error');
                }
            },
            error: function() {
                showWalletMessage('Network error. Please try again.', 'error');
            },
            complete: function() {
                $button.prop('disabled', false).text(originalText);
                $form.removeClass('wallet-loading');
            }
        });
    });
    

    
    // Checkout wallet payment toggle
    $(document).on('change', '#use_wallet_payment', function() {
        var $amountSelector = $('.wallet-amount-selector');
        if ($(this).is(':checked')) {
            $amountSelector.slideDown();
        } else {
            $amountSelector.slideUp();
        }
    });
    
    // Wallet amount input validation
    $(document).on('input', '#wallet_payment_amount', function() {
        var amount = parseFloat($(this).val());
        var max = parseFloat($(this).attr('max'));
        var min = parseFloat($(this).attr('min'));
        
        if (amount > max) {
            $(this).val(max);
            showWalletMessage('Amount cannot exceed maximum wallet balance.', 'info');
        } else if (amount < min) {
            $(this).val(min);
        }
    });
    
    // Partial wallet payment checkbox
    $(document).on('change', '#wallet_use_partial', function() {
        var $amountInput = $('input[name="wallet_payment_amount"]');
        if ($(this).is(':checked')) {
            $amountInput.prop('disabled', false);
        } else {
            $amountInput.prop('disabled', true);
        }
    });
    
    // Transaction table pagination (if implemented)
    $(document).on('click', '.wallet-pagination a', function(e) {
        e.preventDefault();
        
        var page = $(this).data('page');
        loadWalletTransactions(page);
    });
    
    function loadWalletTransactions(page) {
        var $container = $('.wallet-transactions');
        $container.addClass('wallet-loading');
        
        $.ajax({
            url: kaveh_wallet_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'get_wallet_transactions',
                page: page || 1,
                nonce: kaveh_wallet_ajax.nonce
            },
            success: function(response) {
                var data = JSON.parse(response);
                if (data.success) {
                    $container.html(data.html);
                }
            },
            complete: function() {
                $container.removeClass('wallet-loading');
            }
        });
    }
    
    // Quick add amounts
    $(document).on('click', '.wallet-quick-amount', function(e) {
        e.preventDefault();
        var amount = $(this).data('amount');
        $('#wallet-amount').val(amount);
    });
    
    // Format currency inputs
    $(document).on('input', 'input[type="number"][data-currency]', function() {
        var value = parseFloat($(this).val());
        if (!isNaN(value)) {
            $(this).next('.currency-display').text(formatCurrency(value));
        }
    });
    
    // Utility Functions
    function showWalletMessage(message, type) {
        var $messageContainer = $('.wallet-messages');
        
        if ($messageContainer.length === 0) {
            $messageContainer = $('<div class="wallet-messages"></div>');
            $('.wallet-dashboard, .wallet-add-funds').first().prepend($messageContainer);
        }
        
        var $message = $('<div class="wallet-message ' + type + '">' + message + '</div>');
        $messageContainer.html($message);
        
        // Auto-hide after 5 seconds
        setTimeout(function() {
            $message.fadeOut(function() {
                $(this).remove();
            });
        }, 5000);
        
        // Scroll to message
        $('html, body').animate({
            scrollTop: $messageContainer.offset().top - 20
        }, 300);
    }
    
    function formatCurrency(amount) {
        return kaveh_wallet_ajax.currency_symbol + amount.toFixed(2);
    }
    
    // Admin wallet management
    if ($('body').hasClass('wp-admin')) {
        // Admin user profile wallet management
        $(document).on('input', '#wallet_add_amount', function() {
            var amount = parseFloat($(this).val());
            var $preview = $('#wallet_amount_preview');
            
            if ($preview.length === 0) {
                $preview = $('<span id="wallet_amount_preview" style="margin-left: 10px; font-weight: bold;"></span>');
                $(this).after($preview);
            }
            
            if (!isNaN(amount)) {
                if (amount > 0) {
                    $preview.text('(+' + formatCurrency(amount) + ')').css('color', '#28a745');
                } else if (amount < 0) {
                    $preview.text('(' + formatCurrency(amount) + ')').css('color', '#dc3545');
                } else {
                    $preview.text('');
                }
            } else {
                $preview.text('');
            }
        });
    }
    
    // Checkout integration
    if ($('body').hasClass('woocommerce-checkout')) {
        // Update checkout when wallet payment is selected
        $(document).on('change', 'input[name="payment_method"]', function() {
            if ($(this).val() === 'kaveh_wallet') {
                updateCheckoutWithWallet();
            }
        });
        
        function updateCheckoutWithWallet() {
            $('body').trigger('update_checkout');
        }
        
        // Handle wallet partial payment
        $(document).on('checkout_place_order_kaveh_wallet', function() {
            var walletAmount = parseFloat($('input[name="wallet_payment_amount"]').val());
            var usePartial = $('#wallet_use_partial').is(':checked');
            
            if (!walletAmount || walletAmount <= 0) {
                showWalletMessage('Please enter a valid wallet payment amount.', 'error');
                return false;
            }
            
            return true;
        });
    }
    


    
    // Initialize tooltips if available
    if (typeof $.fn.tooltip === 'function') {
        $('.wallet-dashboard [data-toggle="tooltip"]').tooltip();
    }
    
    // Initialize wallet dashboard if present
    if ($('.wallet-dashboard').length > 0) {
        initializeWalletDashboard();
    }
    
    function initializeWalletDashboard() {
        // Add quick amount buttons
        var $quickAmountContainer = $('<div class="wallet-quick-amounts"></div>');
        var quickAmounts = []
        $.each(quickAmounts, function(index, amount) {
            var $button = $('<button type="button" class="wallet-quick-amount btn btn-outline-secondary btn-sm" data-amount="' + amount + '">' + formatCurrency(amount) + '</button>');
            $quickAmountContainer.append($button);
        });
        
        $('#wallet-amount').after($quickAmountContainer);
        
        // Add loading states to transaction table
        $('.wallet-transactions-table').wrap('<div class="wallet-table-container"></div>');
    }
    
    // Handle form validation
    $('.wallet-add-funds input[required]').on('invalid', function() {
        var field = $(this).attr('name');
        var message = 'This field is required.';
        
        if (field === 'amount') {
            message = 'Please enter a valid amount.';
        } else if (field === 'payment_method') {
            message = 'Please select a payment method.';
        }
        
        showWalletMessage(message, 'error');
    });
    
    // Auto-save form data to localStorage
    $('.wallet-add-funds input, .wallet-add-funds select').on('change', function() {
        var formData = {};
        $('.wallet-add-funds input, .wallet-add-funds select').each(function() {
            if ($(this).attr('name') && $(this).val()) {
                formData[$(this).attr('name')] = $(this).val();
            }
        });
        localStorage.setItem('kaveh_wallet_form_data', JSON.stringify(formData));
    });
    
    // Restore form data from localStorage
    var savedFormData = localStorage.getItem('kaveh_wallet_form_data');
    if (savedFormData) {
        try {
            var formData = JSON.parse(savedFormData);
            $.each(formData, function(name, value) {
                $('.wallet-add-funds [name="' + name + '"]').val(value);
            });
        } catch (e) {
            // Invalid JSON, ignore
        }
    }
    
    // Clear saved form data on successful submission
    $(document).on('wallet_funds_added_successfully', function() {
        localStorage.removeItem('kaveh_wallet_form_data');
    });
});