<!DOCTYPE html>
<html lang="en">
  <head>
    <%- include('../partials/head'); %>
  </head>
  <body class="body-signin">
    <a class="page-title" href="/"><h1>Sign in</h1></a>
    <main class="main-signin">
      <form action="/signup">
        <label for="email">Email</label>
        <input type="text" name="email" />
        <div class="email error"></div>
        <label for="password">Password</label>
        <input type="password" name="password" />
        <div class="password error"></div>
        <button>login</button>
      </form>
    </main>
    <script src="../dist/js/visibility.js"></script>

    <script src="/socket.io/socket.io.js"></script>
    <script>
      const form = document.querySelector('form');
      const emailError = document.querySelector('.email.error');
      const passwordError = document.querySelector('.password.error');

      // Establish a connection to the Socket.io server
      const socket = io();

      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('/series');
          }
        } catch (err) {
          console.log(err);
        }
      });

      socket.on('loginSuccess', (data) => {
        console.log('Login success:', data);
      });

      socket.on('loginFailure', (data) => {
        console.log('Login failure:', data);
      });
    </script>
  </body>
</html>
