jQuery(function ($) {
    $(document).ready(function () {
        // Check if we're on add payment method page
        var isAddPaymentPage = window.location.pathname.includes('add-payment-method') ||
            $('body').hasClass('woocommerce-add-payment-method');
        // Always show credit card form on add payment method page
        if (isAddPaymentPage) {
            $('.woocommerce-billing-fields__field-wrapper_credit_card').show();
        }
        // Set up validation
        setupValidation();
        // Set up input formatting
        setupInputFormatting();
        // Set up payment token handling (only if elements exist)
        if ($('input[name="wc-anet-payment-token"]').length > 0) {
            setupPaymentTokenHandling();
        }
    });
    // Validate Card Number on blur
    function setupValidation() {
        // Use event delegation for all validation events
        $(document).on('blur', '#anet-card-number', function () {
            const value = $(this).val();
            const isValid = /^\d{13,19}$/.test(value);
            toggleValidation('#anet-card-number-div', isValid);
        });
        // Validate CVV on blur
        $(document).on('blur', '#anet-card-cvc', function () {
            const value = $(this).val();
            const isValid = /^\d{3,4}$/.test(value);
            toggleValidation('#anet-card-cvc-div', isValid);
        });
        // Validate Expiry Month on blur/change
        $(document).on('blur change', '#anet-card-expiry-month', function () {
            const value = $(this).val();
            const isValid = value !== '';
            toggleValidation('#anet-card-expiry-month-div', isValid);
        });
        // Validate Expiry Year on blur/change
        $(document).on('blur change', '#anet-card-expiry-year', function () {
            const value = $(this).val();
            const isValid = value !== '';
            toggleValidation('#anet-card-expiry-year-div', isValid);
        });
    }
    // Utility function to toggle validation classes   
    function toggleValidation(selector, isValid) {
        const $field = $(selector);
        if (isValid) {
            $field.removeClass('woocommerce-invalid woocommerce-invalid-required-field');
            $field.addClass('woocommerce-validated');
        } else {
            $field.removeClass('woocommerce-validated');
            $field.addClass('woocommerce-invalid woocommerce-invalid-required-field');
        }
    }
    // Set up input formatting
    function setupInputFormatting() {
        // Use event delegation - this will work even if elements are added later
        $(document).on('input', '#anet-card-number', function (e) {
            // Remove any non-numeric characters
            this.value = this.value.replace(/[^0-9]/g, '');
            // Update card type logo and validate length
            var cardNumber = this.value;
            var maxLength = getCardMaxLength(cardNumber);
            if (cardNumber.length > maxLength) {
                this.value = cardNumber.slice(0, maxLength);
            }
            updateCardTypeLogo(cardNumber);
        });
        // CVV formatting with delegation
        $(document).on('input', '#anet-card-cvc', function (e) {
            // Remove any non-numeric characters
            this.value = this.value.replace(/[^0-9]/g, '');
        });
    }
    // Payment token handling (only for checkout page)
    function setupPaymentTokenHandling() {
        function toggleFields() {
            const selectedToken = $('input[name="wc-anet-payment-token"]:checked').val();
            const isNewPayment = $('#wc-anet-payment-token-new').is(':checked');
            if (isNewPayment || !selectedToken) {
                $('.woocommerce-billing-fields__field-wrapper_credit_card').show();
                $('#wc-anet-subscription-notice').show();
            } else {
                $('.woocommerce-billing-fields__field-wrapper_credit_card').hide();
                $('#wc-anet-subscription-notice').hide();
            }
        }
        // If no radio button is selected, select the "new payment method" by default
        if ($('input[name="wc-anet-payment-token"]:checked').length === 0) {
            $('#wc-anet-payment-token-new').prop('checked', true);
        }
        // Initial check on page load
        toggleFields();
        // Bind change event to all token radio buttons
        $(document).on('change', 'input[name="wc-anet-payment-token"]', function () {
            toggleFields();
        });
    }
    // Card type detection functions.
    function getCardMaxLength(cardNumber) {
        if (/^4/.test(cardNumber)) {
            return 16; // Visa
        } else if (/^5[1-5]/.test(cardNumber)) {
            return 16; // MasterCard
        } else if (/^3[47]/.test(cardNumber)) {
            return 15; // American Express
        } else if (/^6(?:011|5)/.test(cardNumber)) {
            return 16; // Discover
        } else if (/^3(?:0[0-5]|[68])/.test(cardNumber)) {
            return 14; // Diners Club
        } else if (/^35/.test(cardNumber)) {
            return 16; // JCB
        } else {
            return 19; // Default max length
        }
    }
    // Card type logo detection functions.
    function updateCardTypeLogo(cardNumber) {
        var inputField = document.getElementById('anet-card-number');
        if (!inputField) return;
        var cardType = '';
        if (/^4/.test(cardNumber)) {
            cardType = 'card-visa';
        } else if (/^5[1-5]/.test(cardNumber)) {
            cardType = 'card-mastercard';
        } else if (/^3[47]/.test(cardNumber)) {
            cardType = 'card-amex';
        } else if (/^6(?:011|5)/.test(cardNumber)) {
            cardType = 'card-discover';
        } else if (/^3(?:0[0-5]|[68])/.test(cardNumber)) {
            cardType = 'card-dinersclub';
        } else if (/^35/.test(cardNumber)) {
            cardType = 'card-jcb';
        }
        if (cardType && typeof anetCreditCardVars !== 'undefined') {
            inputField.style.backgroundImage = `url('${anetCreditCardVars.pluginUrl}../../assets/img/${cardType}.png')`;
            inputField.style.backgroundRepeat = 'no-repeat';
            inputField.style.backgroundPosition = 'right 10px center';
            inputField.style.backgroundSize = '30px auto';
        } else {
            inputField.style.backgroundImage = '';
        }
    }
});