let specs = [];

const MAX_RESULTS = 3;

const searchInput =
    document.getElementById("search");

const results =
    document.getElementById("results");

async function loadSpecs() {
    try {
        const res = await fetch("/api/specs");
        const rawSpecs = await res.json();

        specs = await Promise.all(
            rawSpecs.map(async (spec) => {
                try {
                    const configRes =
                        await fetch(spec.config);

                    const metadata =
                        await configRes.json();

                    return {
                        ...spec,
                        metadata
                    };

                } catch (err) {
                    console.error(
                        "Failed to load config:",
                        spec.config
                    );

                    return {
                        ...spec,
                        metadata: {}
                    };
                }
            })
        );

    } catch (err) {
        console.error(err);

        results.innerHTML =
            '<div class="item empty">Failed to load specs</div>';
    }
}

function getDisplayName(spec) {
    return (
        spec.metadata?.name ||
        spec.name
            .split("/")
            .pop()
            .replace(/\.ya?ml$/i, "")
    );
}

function getLink(spec) {
    return (
        spec.metadata?.url ||
        "/"
    );
}

function getDescription(spec) {
    return (
        spec.metadata?.description ||
        "No description available."
    );
}

function getDocPath(spec) {
    return spec.name.replace(/\.ya?ml$/i, "");
}

function getIcon(spec) {
    return (
        spec.metadata?.icon_url ||
        "/favicon.ico"
    );
}

function render(list) {
    results.innerHTML = "";

    if (
        searchInput.value.trim() === ""
    ) {
        return;
    }

    if (list.length === 0) {
        results.innerHTML =
            '<div class="item empty">No results found</div>';

        return;
    }

    list.forEach(spec => {
        const item = document.createElement("div");

        item.className = "item";

        item.onclick = () => {
            window.location.href =
                `/docs/${getDocPath(spec)}`;
        };

        const icon = document.createElement("img");
        icon.className = "item-icon";

        icon.src = getIcon(spec);
        icon.alt = getDisplayName(spec);

        icon.onerror = () => {
            icon.src = "/favicon.ico";
        };

        const content = document.createElement("div");
        content.className = "item-content";



        const title = document.createElement("div");
        title.className = "item-title";
        //title.textContent = getDisplayName(spec);

        const link = document.createElement("a");
        link.href = getLink(spec);
        link.textContent = getDisplayName(spec);

        link.target = "_blank";
        link.rel = "noopener noreferrer";

        title.appendChild(link);

        const description = document.createElement("div");

        description.className = "item-description";

        description.textContent = getDescription(spec);

        content.appendChild(title);
        content.appendChild(description);

        item.appendChild(icon);
        item.appendChild(content);

        results.appendChild(item);
    });
}

searchInput.addEventListener(
    "input",
    (e) => {
        const value =
            e.target.value
                .toLowerCase()
                .trim();

        // input leer
        if (value === "") {
            results.innerHTML = "";
            return;
        }

        const filtered = specs
            .filter(spec => {
                const name =
                    getDisplayName(spec)
                        .toLowerCase();

                const description =
                    getDescription(spec)
                        .toLowerCase();

                return (
                    name.includes(value) ||
                    description.includes(value)
                );
            })
            .slice(0, MAX_RESULTS);

        render(filtered);
    }
);

loadSpecs().then();