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

    var walletCheckout = {
        init: function() {
            this.bindEvents();
            this.updateWalletDisplay();
        },

        bindEvents: function() {
            // Use wallet checkbox
            $(document.body).on('change', '#use_wallet_payment', this.handleWalletToggle);
            
            // Checkout update
            $(document.body).on('updated_checkout', this.updateWalletDisplay);
        },

        // Removed payment method change handler - no longer needed

        handleWalletToggle: function() {
            var $checkbox = $(this);
            var useWallet = $checkbox.is(':checked') ? '1' : '0';
            
            // Apply/remove wallet discount via AJAX
            $.ajax({
                url: kaveh_wallet_checkout.ajax_url,
                type: 'POST',
                data: {
                    action: 'apply_wallet_discount',
                    use_wallet: useWallet,
                    nonce: kaveh_wallet_checkout.nonce
                },
                success: function(response) {
                    if (response.success) {
                        // Trigger checkout update to recalculate totals
                        $('body').trigger('update_checkout');
                    }
                },
                error: function() {
                    walletCheckout.showMessage('Error applying wallet discount', 'error');
                }
            });
        },

        // Removed partial payment toggle as it's no longer needed

        // Removed wallet amount change handler as amount is now fixed

        // Removed payment gateway related methods

        // Removed total calculation methods - now handled by WooCommerce fees system

        updateWalletDisplay: function() {
            // Update wallet balance display if it exists
            $.ajax({
                url: wc_kaveh_wallet_params.ajax_url,
                type: 'POST',
                data: {
                    action: 'get_wallet_balance',
                    nonce: wc_kaveh_wallet_params.nonce
                },
                success: function(response) {
                    try {
                        var data = JSON.parse(response);
                        if (data.success) {
                            $('.wallet-balance').html(kaveh_wallet_checkout.messages.available_balance + ' ' + data.formatted_balance);
                            $('input[name="wallet_payment_amount"]').attr('max', data.balance);
                        }
                    } catch (e) {
                        console.log(kaveh_wallet_checkout.messages.error_parsing_response);
                    }
                }
            });
        },

        // Removed wallet payment validation - no longer needed for discount system

        getCartTotal: function() {
            var totalText = $('.order-total .woocommerce-Price-amount').text();
            // Remove currency symbol and parse
            var total = totalText.replace(/[^\d.,]/g, '').replace(',', '');
            return parseFloat(total) || 0;
        },

        getWalletBalance: function() {
            var balanceText = $('.wallet-balance').text();
            // Extract balance from text
            var balance = balanceText.replace(/[^\d.,]/g, '').replace(',', '');
            return parseFloat(balance) || 0;
        },

        formatCurrency: function(amount) {
            return wc_kaveh_wallet_params.currency_symbol + amount.toFixed(2);
        },

        showMessage: function(message, type) {
            var $messageContainer = $('.woocommerce-notices-wrapper');
            
            if ($messageContainer.length === 0) {
                $messageContainer = $('<div class="woocommerce-notices-wrapper"></div>');
                $('.woocommerce-checkout').prepend($messageContainer);
            }
            
            var messageClass = 'woocommerce-message';
            if (type === 'error') {
                messageClass = 'woocommerce-error';
            } else if (type === 'warning') {
                messageClass = 'woocommerce-info';
            }
            
            var $message = $('<div class="' + messageClass + '">' + message + '</div>');
            $messageContainer.html($message);
            
            // Auto-hide after 5 seconds
            setTimeout(function() {
                $message.fadeOut();
            }, 5000);
            
            // Scroll to message
            $('html, body').animate({
                scrollTop: $messageContainer.offset().top - 20
            }, 300);
        },

        // Quick amount selection
        addQuickAmountButtons: function() {
            var $amountInput = $('input[name="wallet_payment_amount"]');
            var walletBalance = this.getWalletBalance();
            var cartTotal = this.getCartTotal();
            
            var amounts = [25, 50, 100];
            var $quickButtons = $('<div class="wallet-quick-amounts"></div>');
            
            // Add percentage buttons
            var percentages = [25, 50, 75, 100];
            $.each(percentages, function(index, percentage) {
                var amount = Math.min(walletBalance, cartTotal) * (percentage / 100);
                if (amount > 0) {
                    var $button = $('<button type="button" class="wallet-quick-btn" data-amount="' + amount.toFixed(2) + '">' + percentage + '%</button>');
                    $quickButtons.append($button);
                }
            });
            
            // Add fixed amount buttons
            $.each(amounts, function(index, amount) {
                if (amount <= walletBalance && amount <= cartTotal) {
                    var $button = $('<button type="button" class="wallet-quick-btn" data-amount="' + amount + '">' + walletCheckout.formatCurrency(amount) + '</button>');
                    $quickButtons.append($button);
                }
            });
            
            $amountInput.after($quickButtons);
            
            // Handle quick button clicks
            $(document).on('click', '.wallet-quick-btn', function() {
                var amount = $(this).data('amount');
                $amountInput.val(amount).trigger('input');
            });
        }
    };

    // Initialize wallet checkout
    walletCheckout.init();
    
    // Add quick amount buttons if wallet payment is available
    if ($('.wallet-payment-fields').length > 0) {
        walletCheckout.addQuickAmountButtons();
    }
    
    // Removed checkout form submission handler - no longer needed
    
    // Update wallet display when checkout is updated
    $(document.body).on('updated_checkout', function() {
        setTimeout(function() {
            walletCheckout.updateWalletDisplay();
        }, 100);
    });
    
    // Removed payment method visibility handler - no longer needed
    
    // CSS for quick buttons
    $('<style>').text(`
        .wallet-quick-amounts {
            margin-top: 10px;
            display: flex;
            gap: 5px;
            flex-wrap: wrap;
        }
        .wallet-quick-btn {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            padding: 5px 10px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
            transition: all 0.2s;
        }
        .wallet-quick-btn:hover {
            background: #e9ecef;
            border-color: #adb5bd;
        }
        .wallet-total-adjustment {
            color: #28a745;
            font-weight: 600;
        }
        .wallet-remaining-amount {
            margin-top: 10px;
            padding: 10px;
            background: #fff3cd;
            border: 1px solid #ffeaa7;
            border-radius: 4px;
        }
    `).appendTo('head');
});