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;
    }
    window.location.href = "/login";
}

function click() {
    const username = document.getElementById("username").value;
    const password = document.getElementById("password").value;

    if (username.trim().length === 0) {
        error("username cannot be empty");
        return;
    } else if (password.trim().length === 0) {
        error("password cannot be empty");
        return;
    }
    const method = "POST";
    const body = JSON.stringify({ username, password });
    const headers = new Headers({ "Content-Type": "application/json" });
    return fetch("/api/register", {
        method,
        body,
        headers,
    })
        .then(v => v.json())
        .then(displayResponse);

}

function main() {
    const submit = document.getElementById("submit");
    submit.addEventListener("click", () => click())
}

main();
