const loginForm = document.getElementById('login-form');
const loginCard = document.getElementById('login-card');
const loginSuccess = document.getElementById('login-success');

loginForm.addEventListener('submit', async (event) => {
  event.preventDefault();

  const formData = new FormData(loginForm);
  const data = Object.fromEntries(formData.entries());

  try {
    const response = await fetch('/api/login', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(data)
    });

    if (response.ok) {
      // localStorage.setItem('token', responseData.token);

      displayLoginSuccess();
    } else {
      const errorData = await response.json();
      alert(`Login failed: ${errorData.message}`);
    }
  } catch (error) {
    console.error('Error during login:', error);
    alert('An error occurred while trying to log in.');
  }
}
);

async function isLoggedInFunction() {
  // const token = localStorage.getItem('token');
  // if (!token) return false;

  // try {
  //   const response = await fetch('/api/loginToken', {
  //     method: 'GET',
  //     headers: {
  //       'Authorization': `Bearer ${token}`
  //     }
  //   });

  //   if (response.ok) {
  //     return true;
  //   } else {
  //     localStorage.removeItem('token');
  //     return false;
  //   }
  // } catch (error) {
  //   console.error('Error checking login status:', error);
  //   return false;
  // }

  try {
    const response = await fetch('/api/loginToken', {
      method: 'GET'
    });

    if (response.ok) {
      return true;
    } else {
      return false;
    }
  } catch (error) {
    console.error('Error checking login status:', error);
    return false;
  }
}

function displayLoginSuccess() {
  loginCard.classList.add('hidden');
  loginSuccess.classList.remove('hidden');
}

isLoggedInFunction().then((logged) => {
  if (logged) displayLoginSuccess();
});