(function(){
  function isLongJob(form){
    if(!form) return false;
    return form.classList.contains('xcvpn-long-job') ||
      form.dataset.loading === '1' ||
      !!form.querySelector('[name="install_ovpn"], [name="install_add_vpn"], [name="install_engine"], [name="refresh_provider"], [name="submit_provider_all"], [name="submit_provider_country"], [name="submit_provider"]');
  }

  function ensureLoader(message){
    var el = document.getElementById('xcvpnLoading');
    if(!el){
      el = document.createElement('div');
      el.id = 'xcvpnLoading';
      el.setAttribute('role','status');
      el.setAttribute('aria-live','polite');
      document.body.appendChild(el);
    }
    el.innerHTML = '<div class="xcvpn-loader-card">' +
      '<div class="xcvpn-loader-ring"></div>' +
      '<div class="xcvpn-loader-dot"></div>' +
      '<div class="xcvpn-loader-title">' + (message || 'Installing OpenVPN') + '</div>' +
      '<small class="xcvpn-loader-subtitle">Please keep this page open while the VPS finishes the job.</small>' +
      '<div class="xcvpn-loader-bar"><span></span></div>' +
    '</div>';
    return el;
  }

  window.xcvpnShowLoading = function(message){
    var el = ensureLoader(message);
    el.classList.add('show');
    document.body.classList.add('xcvpn-installing');
  };

  window.xcvpnHideLoading = function(){
    var el = document.getElementById('xcvpnLoading');
    if(el) el.classList.remove('show');
    document.body.classList.remove('xcvpn-installing');
  };

  document.addEventListener('submit', function(e){
    if(!isLongJob(e.target)) return;
    var submitter = e.submitter || document.activeElement;
    var txt = ((submitter && (submitter.textContent || submitter.value)) || '').toLowerCase();
    var msg = e.target.dataset.loadingMessage || 'Please wait...';
    if(txt.indexOf('refresh') !== -1) msg = 'Refreshing configs...';
    else if(txt.indexOf('add all') !== -1 || txt.indexOf('add country') !== -1 || txt.indexOf('add selected') !== -1) msg = 'Adding profiles...';
    else if(txt.indexOf('install') !== -1) msg = 'Installing OpenVPN';
    window.xcvpnShowLoading(msg);
  }, true);

  document.addEventListener('click', function(e){
    var btn = e.target.closest('button, input[type="submit"], a.btn');
    if(!btn) return;
    var text = ((btn.textContent || btn.value || '') + '').toLowerCase();
    if(text.indexOf('install') !== -1 || text.indexOf('save and install') !== -1){
      window.setTimeout(function(){ window.xcvpnShowLoading('Installing OpenVPN'); }, 30);
    }
  }, true);
})();
