(function () {
  var loginForm = document.querySelector('.js-login-form');
  var accountPanel = document.getElementById('accountPanel');
  var accountLabel = document.getElementById('accountLabel');
  var accountActions = document.getElementById('accountActions');
  var adminLink = document.getElementById('adminLink');
  var logoutLink = document.getElementById('logoutLink');
  var loginStatus = document.getElementById('loginStatus');
  var loginModal = document.getElementById('modal-Login');
  var overlay = document.querySelector('.md-overlay');

  if (!loginForm || !accountPanel || !accountLabel || !accountActions || !logoutLink) {
    return;
  }

  function setStatus(message, isError) {
    if (!loginStatus) {
      return;
    }

    loginStatus.textContent = message || '';
    loginStatus.classList.toggle('is-error', !!isError);
    loginStatus.classList.toggle('is-success', !isError && !!message);
  }

  function closeModal() {
    if (loginModal) {
      loginModal.classList.remove('md-show');
    }
    if (document.documentElement) {
      document.documentElement.classList.remove('md-perspective');
    }
    if (overlay) {
      overlay.removeEventListener('click', closeModal);
    }
  }

  function renderAuthenticated(user, role, adminUrl, logoutUrl) {
    accountPanel.classList.add('is-authenticated');
    accountPanel.classList.remove('md-trigger');
    accountPanel.removeAttribute('data-modal');
    accountLabel.textContent = user;
    accountActions.hidden = false;

    if (role === 'admin' && adminUrl) {
      adminLink.href = adminUrl;
      adminLink.hidden = false;
    } else {
      adminLink.hidden = true;
    }

    if (logoutUrl) {
      logoutLink.href = logoutUrl;
    }
  }

  function renderLoggedOut(defaultLabel) {
    accountPanel.classList.remove('is-authenticated');
    accountPanel.classList.add('md-trigger');
    accountPanel.setAttribute('data-modal', 'modal-Login');
    accountLabel.textContent = defaultLabel;
    accountActions.hidden = true;
    adminLink.hidden = true;
  }

  accountPanel.addEventListener('click', function (event) {
    if (!accountPanel.classList.contains('is-authenticated')) {
      return;
    }

    event.stopImmediatePropagation();
  }, true);

  loginForm.addEventListener('submit', function (event) {
    event.preventDefault();
    setStatus('', false);

    var formData = new FormData(loginForm);

    fetch('login.php', {
      method: 'POST',
      headers: {
        'X-Requested-With': 'XMLHttpRequest'
      },
      body: formData
    })
      .then(function (response) {
        return response.json().then(function (payload) {
          return {
            ok: response.ok,
            payload: payload
          };
        });
      })
      .then(function (result) {
        if (!result.ok || !result.payload.success) {
          throw new Error(result.payload.message || 'Connexion impossible.');
        }

        renderAuthenticated(result.payload.user, result.payload.role, result.payload.adminUrl, result.payload.logoutUrl);
        setStatus(result.payload.message || 'Connexion réussie.', false);
        loginForm.reset();
        window.setTimeout(function () {
          closeModal();
          window.location.reload();
        }, 250);
      })
      .catch(function (error) {
        setStatus(error.message || 'Connexion impossible.', true);
      });
  });

  logoutLink.addEventListener('click', function (event) {
    event.preventDefault();

    fetch(logoutLink.href, {
      method: 'POST',
      headers: {
        'X-Requested-With': 'XMLHttpRequest'
      }
    })
      .then(function (response) {
        return response.json();
      })
      .then(function () {
        renderLoggedOut(accountPanel.dataset.loginLabel || 'Connexion');
        setStatus('', false);
        window.location.reload();
      })
      .catch(function () {
        window.location.href = logoutLink.href;
      });
  });
})();
