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

    const PaychefPaymentMethods = {
        init: function() {
            this.bindEvents();
            this.loadSavedPaymentMethods();
        },

        bindEvents: function() {
            // Delete payment method
            $(document).on('click', '.delete-payment-method', this.deletePaymentMethod);
            
            // Payment method selection change
            $(document).on('change', 'input[name^="wc-"][name$="-payment-token"]', this.toggleNewPaymentFields);
            
            // Form submission validation
            $('form.checkout').on('checkout_place_order', this.validatePaymentSelection);
        },

        deletePaymentMethod: function(e) {
            e.preventDefault();
            
            if (!confirm(paychef_payment_methods_params.confirm_delete)) {
                return;
            }

            const $button = $(this);
            const tokenId = $button.data('token-id');
            
            $button.addClass('paychef-payment-method-loading');
            
            $.ajax({
                url: paychef_payment_methods_params.ajax_url,
                type: 'POST',
                data: {
                    action: 'paychef_delete_payment_method',
                    token_id: tokenId,
                    security: paychef_payment_methods_params.delete_nonce
                },
                success: function(response) {
                    if (response.success) {
                        $button.closest('.wc-saved-payment-method, .woocommerce-PaymentMethod').fadeOut(300, function() {
                            $(this).remove();
                            PaychefPaymentMethods.checkEmptyState();
                        });
                    } else {
                        alert(response.data || paychef_payment_methods_params.delete_error);
                    }
                },
                error: function() {
                    alert(paychef_payment_methods_params.delete_error);
                },
                complete: function() {
                    $button.removeClass('paychef-payment-method-loading');
                }
            });
        },

        toggleNewPaymentFields: function() {
            const $selected = $(this);
            const $container = $selected.closest('.payment_method_paychef, [class*="payment_method_paychef_"]');
            const $newPaymentFields = $container.find('.paychef-new-payment-method-form');
            
            if ($selected.val() === 'new') {
                $newPaymentFields.slideDown(200);
            } else {
                $newPaymentFields.slideUp(200);
            }
        },

        validatePaymentSelection: function() {
            const $paymentMethod = $('input[name="payment_method"]:checked');
            
            if ($paymentMethod.val() && $paymentMethod.val().indexOf('paychef') === 0) {
                const $tokenInput = $('input[name="wc-' + $paymentMethod.val() + '-payment-token"]:checked');
                
                if ($tokenInput.length === 0) {
                    return true; // No saved methods, proceed normally
                }
                
                if ($tokenInput.val() === 'new') {
                    // Validate new payment method fields if needed
                    return true;
                }
            }
            
            return true;
        },

        loadSavedPaymentMethods: function() {
            // Load saved payment methods for account page
            if ($('.woocommerce-MyAccount-payment-methods').length > 0) {
                this.enhanceAccountPaymentMethods();
            }
        },

        enhanceAccountPaymentMethods: function() {
            // Add icons and enhanced styling to payment methods
            $('.woocommerce-PaymentMethod').each(function() {
                const $method = $(this);
                const gateway = $method.find('td').first().text().trim();
                
                if (gateway.indexOf('paychef') === 0) {
                    const $details = $method.find('.woocommerce-PaymentMethod-details');
                    if ($details.length === 0) {
                        // Create enhanced details if not exist
                        PaychefPaymentMethods.createEnhancedPaymentMethodDisplay($method);
                    }
                }
            });
        },

        createEnhancedPaymentMethodDisplay: function($method) {
            const $firstCell = $method.find('td').first();
            const gateway = $firstCell.text().trim();
            const $lastCell = $method.find('td').last();
            
            // Create enhanced display
            const $details = $('<div class="woocommerce-PaymentMethod-details"></div>');
            const $brand = $('<span class="woocommerce-PaymentMethod-brand"></span>').text(gateway);
            
            $details.append($brand);
            $firstCell.empty().append($details);
            
            // Move actions to last cell
            const $actions = $('<div class="woocommerce-PaymentMethod-actions"></div>');
            $lastCell.empty().append($actions);
            
            // Add delete button
            const $deleteBtn = $('<button type="button" class="delete-payment-method button" data-token-id="' + 
                $method.data('token-id') + '">' + paychef_payment_methods_params.delete_text + '</button>');
            $actions.append($deleteBtn);
        },

        checkEmptyState: function() {
            const $container = $('.wc-saved-payment-methods, .woocommerce-MyAccount-payment-methods');
            const $methods = $container.find('.wc-saved-payment-method, .woocommerce-PaymentMethod');
            
            if ($methods.length === 0) {
                const $emptyMessage = $('<p class="paychef-no-payment-methods">' + 
                    paychef_payment_methods_params.no_methods_text + '</p>');
                $container.append($emptyMessage);
            }
        }
    };

    // Initialize when DOM is ready
    PaychefPaymentMethods.init();

    // Re-initialize after AJAX updates (for checkout)
    $(document.body).on('updated_checkout', function() {
        PaychefPaymentMethods.loadSavedPaymentMethods();
    });
});