document.addEventListener("DOMContentLoaded", function () {
    const shareUsernameInput = document.getElementById("share-username");
    const suggestionsBox = document.getElementById("user-suggestions");
    const shareSubmitButton = document.getElementById("share-submit");

    if (!shareUsernameInput || !suggestionsBox || !shareSubmitButton) {
        console.warn("Autocomplete: Required elements not found.");
        return;
    }

    // Función para buscar usuarios
    async function fetchUsers(query) {
        try {
            const response = await fetch(`/api/users/search?q=${encodeURIComponent(query)}`);
            if (!response.ok) throw new Error("API error");
            return await response.json();
        } catch (error) {
            console.error("Error fetching users:", error);
            return [];
        }
    }

    // Mostrar sugerencias en el dropdown
    function showSuggestions(users) {
        suggestionsBox.innerHTML = "";
        if (users.length === 0) {
            suggestionsBox.classList.add("d-none");
            return;
        }

        users.forEach((user) => {
            const item = document.createElement("button");
            item.type = "button";
            item.classList.add("list-group-item", "list-group-item-action");
            item.textContent = user.username;
            item.addEventListener("click", () => {
                shareUsernameInput.value = user.username;
                suggestionsBox.classList.add("d-none");
            });
            suggestionsBox.appendChild(item);
        });

        suggestionsBox.classList.remove("d-none");
    }

    // Evento de entrada para mostrar sugerencias dinámicamente
    shareUsernameInput.addEventListener("input", async function () {
        const query = this.value.trim();
        if (query.length >= 2) {
            const users = await fetchUsers(query);
            showSuggestions(users);
        } else {
            suggestionsBox.classList.add("d-none");
        }
    });

    // Ocultar sugerencias si se hace clic fuera
    document.addEventListener("click", function (event) {
        if (!shareUsernameInput.contains(event.target) && !suggestionsBox.contains(event.target)) {
            suggestionsBox.classList.add("d-none");
        }
    });
});

