<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Login page</title>
  </head>
  <body>
    <div id="errors"></div>
    <h3>Login page</h3>
    <form action="/login" method="post" name="login">
      <label for="login">Login</label>
      <input type="text" name="login" id="login" required />
      <br />
      <label for="password">Password</label>
      <input type="password" name="password" id="password" required />
    </form>
    <br />
    <button id="login">Login</button>
    <br />
    <a href="/register">No accoount? Register here!</a>
  </body>
  <script>
    const init = function () {
      const btn = document.querySelector("button#login");
      btn.addEventListener("click", async () => {
        btn.textContent = "Loading...";
        let formData = Array.from(document.forms.login, e => [e.name, encodeURIComponent(e.value)].join("=")).join("&");
        try {
          const jsonData = await (
            await fetch("/login", {
              method: "post",
              body: formData,
            })
          ).json();
          if (jsonData.ok) {
            location = "/dashboard";
          } else {
            alert(jsonData.message);
            btn.textContent = "Login";
          }
        } catch (e) {
          alert(e.message);
          btn.textContent = "Login";
        }
      });
    };

    document.addEventListener("DOMContentLoaded", init);
  </script>
</html>
