
function error(message) {
    const errorContainer = document.getElementById("mao-error");
    const errorElement = document.getElementById("mao-error-message");

    errorElement.innerText = message;
    errorContainer.classList.remove("hidden");
}

function displayResponse(response) {
    if (!response.ok) {
        error(response.error);
        return;
    }
    const { videos, total } = response;
    if (videos.length === 0) {
        error("search returned no results");
        return;
    }
    console.log(videos);
    const resultElement = document.getElementById("result");
    resultElement.innerHTML = `<p>Showing ${videos.length}/${total} results.</p>`
        + "<ul id='video-list'>"
        + videos
            .map(v => {
                console.log(v);
                return `
					<li>
						<div class="video-item">
							<div class="video-image">
								<img class="shadow" src="/videos/${v.id}.png" alt="">
								<img class="non-shadow" src="/videos/${v.id}.png" alt="">
							</div>
							<span class="video-info">
								<a href="/watch?id=${v.id}">${v.title}</a>
								<br>
								by ${v.author}
							</span>
						</div>
					</li>
				`;
            })
            .join("")
        + "</ul>";
}

function main() {
    const params = new URLSearchParams(window.location.search);
    const searchElement = document.getElementById("query");
    searchElement.value = params.get("query") || "";
    return fetch(`/api/search?${params.toString()}`)
        .then(v => v.json())
        .then(displayResponse);
}

main();
