$(document).ready(function() {
    // Cache the email input field and status element
    const $emailInput = $('input[name="email"]');
    const $emailStatus = $('<small class="form-text text-muted float-right"></small>');
    
    // Insert status message after the email field
    $emailInput.after($emailStatus);
    
    // Debounce function to prevent excessive AJAX calls
    let debounceTimer;
    $emailInput.on('input', function() {
        clearTimeout(debounceTimer);
        debounceTimer = setTimeout(() => {
            const email = $(this).val().trim();
            
            // Only check if email is valid and not empty
            if (email.length > 3 && email.includes('@')) {
                checkEmailAvailability(email);
            } else {
                $emailStatus.removeClass('text-success text-danger').text('');
            }
        }, 500); // 0.5 second delay after typing stops
    });
    
    function checkEmailAvailability(email) {
        $emailStatus.removeClass('text-success text-danger').html('<div class="spinner-border" role="status">  <span class="visually-hidden">Checking...</span></div> ');
        
        $.ajax({
            url: base_url + 'check-user-email', // Your CI4 endpoint
            method: 'POST',
            data: { email: email },
            headers: {
                'X-Requested-With': 'XMLHttpRequest' // Identify as AJAX request
            },
            success: function(response) {
                if (response.available) {
                    $emailStatus.removeClass('text-danger').addClass('text-success')
                        .html('<span class="text-success"><i class="bi bi-check-circle"></i> Email is available</span>');
                } else {
                    $emailStatus.removeClass('text-success').addClass('text-danger')
                        .html('<span class="text-danger"><i class="bi bi bi-x-circle"></i> Email already registered</span>');
                }
            },
            error: function() {
                $emailStatus.removeClass('text-success text-danger').text('Error checking email');
            }
        });
    }
});