jQuery(document).ready(function($) {
    var searchInput = $('#usermorph-search-input');
    var resultsContainer = $('#usermorph-search-results');
    var typingTimer;
    var doneTypingInterval = 300;

    searchInput.on('keyup', function() {
        clearTimeout(typingTimer);
        var term = $(this).val();
        
        if (term.length < 2) {
            resultsContainer.removeClass('active').html('');
            return;
        }

        typingTimer = setTimeout(function() {
            searchUsers(term);
        }, doneTypingInterval);
    });

    function searchUsers(term) {
        $.post(usermorphVars.ajaxurl, {
            action: 'usermorph_search_users',
            nonce: usermorphVars.nonce,
            term: term
        }, function(response) {
            if (response.success && response.data.length > 0) {
                var html = '';
                $.each(response.data, function(index, user) {
                    html += '<div class="usermorph-result-item">';
                    html += '<a href="' + user.url + '">' + user.name + '</a>';
                    html += '</div>';
                });
                resultsContainer.html(html).addClass('active');
            } else {
                resultsContainer.html('<div class="usermorph-result-item">No users found</div>').addClass('active');
            }
        });
    }

    // Close on click outside
    $(document).on('click', function(e) {
        if (!$(e.target).closest('.usermorph-search-container').length) {
            resultsContainer.removeClass('active');
        }
    });

    // Handle focus to reopen if has content
    searchInput.on('focus', function() {
        if (resultsContainer.html() !== '') {
            resultsContainer.addClass('active');
        }
    });
});
