jQuery(function ($) {
    // Populate expiry year dropdown for credit card edit form
    var $yearSelect = $('#anet-credit-card-edit-expiry-year');
    if ($yearSelect.length && $yearSelect.children('option').length === 0) {
        var currentYear = new Date().getFullYear();
        $yearSelect.append($('<option>', {
            value: '',
            text: 'Select Year',
            disabled: true,
            selected: true
        }));
        for (var i = 0; i < 10; i++) {
            var year = currentYear + i;
            $yearSelect.append($('<option>', {
                value: year,
                text: year
            }));
        }
        $yearSelect.val('');
    }
    $('#anet-credit-card-edit-expiry-month')[0].selectedIndex = 0;
    $('#anet-credit-card-save-btn').on('click', function (e) {
        e.preventDefault();
        // Validation
        var $error = $('#anet-credit-card-edit-error');
        $error.hide().text('');
        var cardNumber = $('#anet-credit-card-edit-card-number').val().replace(/\s+/g, '');
        var month = $('#anet-credit-card-edit-expiry-month').val();
        var year = $('#anet-credit-card-edit-expiry-year').val();
        // Check if card number is masked (starts with 'XXXX')
        const isCardNumberMasked = cardNumber.startsWith('XXXX');
        // Validate card number
        if (cardNumber === '' || (!isCardNumberMasked && !/^\d{13,19}$/.test(cardNumber))) {
            $error.text('Please enter a valid credit card number.').show();
            $('#anet-credit-card-edit-card-number').focus();
            return false;
        }
        // Expiry: both month and year must be selected
        if (!month || !year) {
            $error.text('Please select both expiry month and year.').show();
            if (!month) {
                $('#anet-credit-card-edit-expiry-month').focus();
            } else {
                $('#anet-credit-card-edit-expiry-year').focus();
            }
            return false;
        }
        // Expiry must not be in the past
        var now = new Date();
        var thisMonth = now.getMonth() + 1;
        var thisYear = now.getFullYear();
        var expMonth = parseInt(month, 10);
        var expYear = parseInt(year, 10);
        if (expYear < thisYear || (expYear === thisYear && expMonth < thisMonth)) {
            $error.text('The expiry date cannot be in the past.').show();
            $('#anet-credit-card-edit-expiry-month').focus();
            return false;
        }
        $('#anet-credit-card-edit-form form').submit();
    });
});