<!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>Registration page</title>
  </head>
  <body>
    <div id="errors"></div>
    <h3>Registration page</h3>
    <form action="/register" method="post" name="register">
      <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 />

      <label for="passwordRepeated">Repeat password</label>
      <input
        type="password"
        name="passwordRepeated"
        id="passwordRepeated"
        required
      />
    </form>
    <br />
    <button id="register">Register</button>
    <br />
    <a href="/login">Already have an accoount? Login here!</a>
  </body>
  <script>
    const init = function () {
      const btn = document.querySelector("button#register");
      btn.addEventListener("click", async () => {
        btn.textContent = "Loading...";
        let formData = Array.from(document.forms.register, e => [e.name, encodeURIComponent(e.value)].join("=")).join("&");
        try {
          const jsonData = await (
            await fetch("/register", {
              body: formData,
              method: "post",
            })
          ).json();
          if (jsonData.ok) {
            location = "/login";
          } else {
            alert(jsonData.message);
            btn.textContent = "Register";
          }
        } catch (e) {
          alert(e.message);
          btn.textContent = "Register";
        }
      });
    };

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