(function() {
  function tKey(key) {
    return window.t ? t(key) : key;
  }

  function showError(message) {
    var errorElement = document.getElementById('login-error');
    errorElement.style.display = 'block';
    errorElement.textContent = message;
  }

  function hideError() {
    var errorElement = document.getElementById('login-error');
    errorElement.style.display = 'none';
  }

  document.addEventListener('DOMContentLoaded', function() {
    window.CrankAuth.guardLoginPage().catch(function(error) {
      console.error(error);
    });

    document.getElementById('login-form').addEventListener('submit', async function(event) {
      event.preventDefault();

      var email = document.getElementById('email').value.trim();
      var password = document.getElementById('password').value;

      if (!email || !password) {
        showError(tKey('login.error.required'));
        return;
      }

      hideError();

      try {
        await window.CrankAuth.login(email, password);
      } catch (error) {
        if (error && error.status === 401) {
          showError(tKey('login.error.invalid'));
          return;
        }
        showError(tKey('login.error.generic'));
      }
    });
  });
}());
