// retoor <retoor@molodetz.nl>

import { Http } from "./Http.js";
import { Avatar } from "./Avatar.js";
import { DomUtils } from "./DomUtils.js";

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 = "";
                DomUtils.hide(dropdown);
                return;
            }
            debounceTimer = setTimeout(async () => {
                try {
                    const data = await Http.getJson(`/messages/search?q=${encodeURIComponent(q)}`);
                    const results = data.results || [];
                    if (results.length === 0) {
                        DomUtils.hide(dropdown);
                        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}`;
                        const label = document.createElement("span");
                        label.textContent = r.username;
                        item.append(Avatar.imgElement(r.username), label);
                        dropdown.appendChild(item);
                    }
                    DomUtils.show(dropdown);
                } 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)) {
                DomUtils.hide(dropdown);
            }
        });
    }
}
