export class MessageSearch {
    constructor() {
        this.initMessageSearch();
    }

    initMessageSearch() {
        const searchInput = document.getElementById("message-search");
        if (!searchInput) {
            return;
        }

        const wrap = searchInput.parentElement;
        const dropdown = document.createElement("div");
        dropdown.className = "search-dropdown";
        wrap.appendChild(dropdown);

        let debounceTimer = null;

        searchInput.addEventListener("input", () => {
            clearTimeout(debounceTimer);
            const q = searchInput.value.trim();
            if (q.length < 1) {
                dropdown.innerHTML = "";
                dropdown.style.display = "none";
                return;
            }
            debounceTimer = setTimeout(async () => {
                try {
                    const resp = await fetch(`/messages/search?q=${encodeURIComponent(q)}`);
                    const data = await resp.json();
                    const results = data.results || [];
                    if (results.length === 0) {
                        dropdown.style.display = "none";
                        return;
                    }
                    dropdown.innerHTML = "";
                    for (const r of results) {
                        const item = document.createElement("a");
                        item.className = "search-dropdown-item";
                        item.href = `/messages?with_uid=${r.uid}`;
                        item.innerHTML = `<img src="/avatar/multiavatar/${encodeURIComponent(r.username)}?size=24" class="avatar-img" style="width:24px;height:24px;border-radius:50%" alt="" loading="lazy"><span>${r.username}</span>`;
                        dropdown.appendChild(item);
                    }
                    dropdown.style.display = "block";
                } catch (e) {
                    // silently fail - no suggestions
                }
            }, 200);
        });

        searchInput.addEventListener("keydown", (e) => {
            if (e.key === "Enter") {
                const first = dropdown.querySelector(".search-dropdown-item");
                if (first) {
                    window.location.href = first.href;
                }
            }
        });

        document.addEventListener("click", (e) => {
            if (!wrap.contains(e.target)) {
                dropdown.style.display = "none";
            }
        });
    }
}
