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

  function showError(message) {
    var errorElement = document.getElementById('login-error');
    errorElement.classList.add('is-visible');
    errorElement.textContent = message;
  }

  function hideError() {
    var errorElement = document.getElementById('login-error');
    errorElement.classList.remove('is-visible');
  }

  function initLoginPage() {
    window.CrankAuth.guardLoginPage().catch(function(error) {
      if (window.CrankDiagnostics && typeof window.CrankDiagnostics.report === 'function') {
        window.CrankDiagnostics.report('guard-login-page', error, 'login');
      }
    });

    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'));
      }
    });
  }

  if (window.CrankDiagnostics && typeof window.CrankDiagnostics.bootstrap === 'function') {
    window.CrankDiagnostics.bootstrap('login', initLoginPage);
    return;
  }
  document.addEventListener('DOMContentLoaded', initLoginPage);
}());
