<%- include('partials/header'); -%>

<form action="/signup" class="form">
  <h2>Login</h2>
  <label for="email" class="labelT">Email</label>
  <input type="text" name="email" class="inputT" />
  <div class="email error"></div>
  <label for="password" class="labelT">Password</label>
  <input type="password" name="password"  class="inputT"/>
  <div class="password error"></div>
  <button class="button">login</button>
</form>

<%- include('partials/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(`/home/${data.username}`);
      }
    }
    catch (err) {
      console.log(err);
    }
  });
</script>