<!DOCTYPE html>
<html lang="en">
  <head>
    <%- include('../partials/head'); %>
  </head>
  <body class="container" id="users-index">
    <header><%- include('../partials/header'); %></header>

    <main class="row d-flex justify-content-center">
      <section class="col-sm-8 py-4">
        <form action="/login">
          <label for="email" class="form-label">Email</label>
          <input type="text" name="email" class="form-control" />
          <div class="email error text-info"></div>
          <label for="password" class="form-label">Password</label>
          <input type="password" class="form-control" name="password" />
          <div class="password error text-info"></div>
          <button class="btn btn-primary mt-3">login</button>
        </form>
      </section>
    </main>

    <footer><%- include('../partials/footer'); %></footer>
    <script>
      const form = document.querySelector("form");
      const emailError = document.querySelector(".email.error");
      const passwordError = document.querySelector(".password.error");
      form.addEventListener("submit", async (e) => {
        e.preventDefault();
        // reset errors
        emailError.textContent = "";
        passwordError.textContent = "";
        // get values
        const email = form.email.value;
        const password = form.password.value;
        try {
          const res = await fetch("/login", {
            method: "POST",
            body: JSON.stringify({ email, password }),
            headers: { "Content-Type": "application/json" },
          });
          const data = await res.json();
          if (data.errors) {
            emailError.textContent = data.errors.email;
            passwordError.textContent = data.errors.password;
          }
          if (data.user) {
            location.assign("/users");
          }
        } catch (err) {
          console.log(err);
        }
      });
    </script>
  </body>
</html>
