(function () {
  var cfg = window.wppsMagicLoginWp || {};
  var form = document.getElementById('loginform');
  var extras = document.getElementById('wpps-magic-login-extras');
  if (!form || !extras) {
    return;
  }

  var intro = document.getElementById('wpps-magic-link-intro');
  var emailStep = document.getElementById('wpps-magic-email-step');
  var result = document.getElementById('wpps-magic-result');
  var btn = document.getElementById('wpps-magic-link-btn');
  var sendBtn = document.getElementById('wpps-magic-send-btn');
  var backBtn = document.getElementById('wpps-magic-back-btn');
  var emailInput = document.getElementById('wpps-magic-email-input');
  var captchaWrap = document.getElementById('wpps-magic-captcha-wrap');

  if (!intro || !emailStep || !result || !btn || !sendBtn || !backBtn || !emailInput) {
    return;
  }

  var submitBtn = form.querySelector('#wp-submit');
  var submitP = submitBtn ? submitBtn.closest('p.submit') : null;
  if (submitP && submitP.nextSibling !== extras) {
    form.insertBefore(extras, submitP.nextSibling);
  }
  extras.classList.add('wpps-magic-login-extras--placed');

  var LOGIN_CAPTCHA_SEL =
    '.wpps-captcha-cushion, .wpps-simple-captcha-wrap, .wpps-turnstile-embed';
  var captchaRestore = null;

  function getRedirectTo() {
    var h = form.querySelector('input[name="redirect_to"]');
    return h && h.value ? h.value : '';
  }

  function getLoginCaptchaRoot() {
    var nodes = form.querySelectorAll(LOGIN_CAPTCHA_SEL);
    var i;
    for (i = 0; i < nodes.length; i++) {
      if (extras.contains(nodes[i])) {
        continue;
      }
      return nodes[i];
    }
    return null;
  }

  function getCaptchaScope() {
    if (
      captchaWrap &&
      captchaWrap.querySelector(
        LOGIN_CAPTCHA_SEL +
          ', [name="g-recaptcha-response"], [name="cf-turnstile-response"], [name="wpps_simple_captcha_answer"]'
      )
    ) {
      return captchaWrap;
    }
    return form;
  }

  function isCaptchaRequired() {
    return !!cfg.captchaRequired || !!getLoginCaptchaRoot();
  }

  function hasCaptchaWidget(scope) {
    var root = scope || getCaptchaScope();
    return !!root.querySelector(
      '.wpps-simple-captcha-wrap, .wpps-captcha-cushion, .g-recaptcha, .cf-turnstile, .wpps-turnstile-wrap, .wpps-turnstile-embed, .wpps-recaptcha-v3-token'
    );
  }

  function initCaptchaWidgets() {
    window.setTimeout(function () {
      if (typeof window.wppsGrecaptchaV2Init === 'function') {
        window.wppsGrecaptchaV2Init();
      }
      var scope = getCaptchaScope();
      scope.querySelectorAll('.cf-turnstile:not([data-wpps-turnstile-done])').forEach(function (el) {
        if (window.turnstile && typeof window.turnstile.render === 'function') {
          try {
            window.turnstile.render(el);
            el.setAttribute('data-wpps-turnstile-done', '1');
          } catch (e) {
            /* already rendered */
          }
        }
      });
    }, 60);
  }

  function moveCaptchaToMagicStep() {
    if (!captchaWrap) {
      return;
    }
    var cap = getLoginCaptchaRoot();
    if (!cap || captchaWrap.contains(cap)) {
      initCaptchaWidgets();
      return;
    }
    captchaRestore = { parent: cap.parentNode, next: cap.nextSibling };
    captchaWrap.appendChild(cap);
    initCaptchaWidgets();
  }

  function restoreCaptchaToLoginForm() {
    if (!captchaRestore || !captchaRestore.parent || !captchaWrap) {
      captchaRestore = null;
      return;
    }
    var cap = captchaWrap.querySelector(LOGIN_CAPTCHA_SEL);
    if (cap) {
      captchaRestore.parent.insertBefore(cap, captchaRestore.next);
    }
    captchaRestore = null;
  }

  function appendCaptchaFields(fd) {
    var scope = getCaptchaScope();
    scope.querySelectorAll('input, textarea, select').forEach(function (el) {
      if (!el.name || el.disabled) {
        return;
      }
      if (el.type === 'checkbox' || el.type === 'radio') {
        if (el.checked) {
          fd.append(el.name, el.value);
        }
      } else {
        fd.append(el.name, el.value);
      }
    });
    var g = scope.querySelector('[name="g-recaptcha-response"]');
    if (g && g.value) {
      fd.append('g-recaptcha-response', g.value);
    }
    var t = scope.querySelector('[name="cf-turnstile-response"]');
    if (t && t.value) {
      fd.append('cf-turnstile-response', t.value);
    }
  }

  function ensureRecaptchaV3Token() {
    return new Promise(function (resolve) {
      var scope = getCaptchaScope();
      var tokenInp = scope.querySelector('.wpps-recaptcha-v3-token');
      if (!tokenInp) {
        resolve(true);
        return;
      }
      if ((tokenInp.value || '').trim()) {
        resolve(true);
        return;
      }
      if (typeof grecaptcha === 'undefined' || !grecaptcha.execute || !cfg.recaptchaSiteKey) {
        resolve(false);
        return;
      }
      var action = tokenInp.getAttribute('data-action') || 'login';
      grecaptcha.ready(function () {
        grecaptcha
          .execute(cfg.recaptchaSiteKey, { action: action })
          .then(function (tok) {
            tokenInp.value = tok || '';
            resolve(!!(tok || '').trim());
          })
          .catch(function () {
            resolve(false);
          });
      });
    });
  }

  function captchaReady() {
    if (!isCaptchaRequired()) {
      return true;
    }
    if (!hasCaptchaWidget()) {
      return false;
    }
    var scope = getCaptchaScope();
    var simple = scope.querySelector('[name="wpps_simple_captcha_answer"]');
    if (simple) {
      return !!(simple.value || '').trim();
    }
    if (scope.querySelector('.g-recaptcha, .wpps-g-recaptcha-v2, .wpps-recaptcha-v3-token')) {
      var g = scope.querySelector('[name="g-recaptcha-response"]');
      return !!(g && (g.value || '').trim());
    }
    if (scope.querySelector('.cf-turnstile, .wpps-turnstile-wrap, .wpps-turnstile-embed')) {
      var turnstile = scope.querySelector('[name="cf-turnstile-response"]');
      return !!(turnstile && (turnstile.value || '').trim());
    }
    return false;
  }

  function showCaptchaError(message) {
    intro.hidden = true;
    emailStep.hidden = false;
    result.hidden = false;
    result.innerHTML = '';
    result.className = 'wpps-magic-result wpps-magic-error';
    var captchaMsg = document.createElement('p');
    captchaMsg.textContent = message || cfg.captchaError || 'Please complete the CAPTCHA.';
    result.appendChild(captchaMsg);
  }

  function showEmailFlow() {
    form.classList.add('wpps-magic-email-active');
    intro.hidden = true;
    emailStep.hidden = false;
    result.hidden = true;
    result.innerHTML = '';
    result.className = 'wpps-magic-result';
    moveCaptchaToMagicStep();
    emailInput.focus();
    if (isCaptchaRequired() && !hasCaptchaWidget()) {
      showCaptchaError(cfg.captchaError);
    }
  }

  function showIntro() {
    restoreCaptchaToLoginForm();
    form.classList.remove('wpps-magic-email-active');
    intro.hidden = false;
    emailStep.hidden = true;
    result.hidden = true;
    result.innerHTML = '';
    result.className = 'wpps-magic-result';
  }

  function showResult(ok, title, text, errMsg, codeUrl) {
    intro.hidden = true;
    emailStep.hidden = true;
    result.hidden = false;
    result.innerHTML = '';
    result.className = 'wpps-magic-result' + (ok ? ' wpps-magic-success' : ' wpps-magic-error');
    var h = document.createElement('h3');
    h.textContent = ok ? title : errMsg || title;
    result.appendChild(h);
    if (ok && text) {
      var p = document.createElement('p');
      p.className = 'wpps-magic-result-lead';
      p.textContent = text;
      result.appendChild(p);
    } else if (!ok && text) {
      var pe = document.createElement('p');
      pe.className = 'wpps-magic-result-lead';
      pe.textContent = text;
      result.appendChild(pe);
    }
    if (ok && codeUrl) {
      var actions = document.createElement('div');
      actions.className = 'wpps-magic-result-actions';
      var codeA = document.createElement('a');
      codeA.href = codeUrl;
      codeA.className = 'button button-primary button-large wpps-magic-link-cta';
      codeA.textContent = cfg.enterCodeLabel || 'Enter one-time code';
      actions.appendChild(codeA);
      result.appendChild(actions);
    }
    var retry = document.createElement('p');
    retry.className = 'wpps-magic-retry';
    var rb = document.createElement('button');
    rb.type = 'button';
    rb.className = 'button' + (ok ? ' button-secondary' : '');
    rb.textContent = ok ? (cfg.backToSignIn || 'Back to sign in') : (cfg.tryAgain || 'Try again');
    rb.addEventListener('click', function () {
      if (ok) {
        showIntro();
      } else {
        emailInput.value = '';
        showEmailFlow();
      }
    });
    retry.appendChild(rb);
    result.appendChild(retry);
  }

  btn.addEventListener('click', function (e) {
    e.preventDefault();
    showEmailFlow();
  });
  backBtn.addEventListener('click', function (e) {
    e.preventDefault();
    showIntro();
  });
  sendBtn.addEventListener('click', function (e) {
    e.preventDefault();
    var email = (emailInput.value || '').trim();
    if (!email) {
      emailInput.focus();
      return;
    }
    sendBtn.disabled = true;
    sendBtn.classList.add('is-busy');
    moveCaptchaToMagicStep();
    ensureRecaptchaV3Token()
      .then(function (v3ok) {
        if (!v3ok) {
          throw new Error('captcha_v3');
        }
        if (!captchaReady()) {
          throw new Error('captcha_ready');
        }
        var fd = new FormData();
        fd.append('action', cfg.action || 'wpps_request_magic_link');
        fd.append('email', email);
        fd.append('nonce', cfg.nonce || '');
        fd.append('redirect_to', getRedirectTo());
        fd.append('mode', cfg.mode || 'auto');
        if (cfg.honeypotName) {
          var hp = document.getElementById('wpps-magic-hp');
          fd.append(cfg.honeypotName, hp && hp.value ? hp.value : '');
        }
        appendCaptchaFields(fd);
        return fetch(cfg.ajaxUrl || '', { method: 'POST', credentials: 'same-origin', body: fd }).then(function (r) {
          return r.json();
        });
      })
      .then(function (res) {
        sendBtn.disabled = false;
        sendBtn.classList.remove('is-busy');
        if (res && res.success) {
          var t = (res.data && res.data.title) || cfg.successTitle || '';
          var st = (res.data && res.data.subtitle) || '';
          var codeUrl = (res.data && res.data.code_url) || '';
          showResult(true, t, st, '', codeUrl);
        } else {
          var msg =
            (res && res.data && res.data.message) || cfg.requestFailed || 'Request failed.';
          showResult(false, cfg.errorTitle || 'Something went wrong', '', msg);
        }
      })
      .catch(function (err) {
        sendBtn.disabled = false;
        sendBtn.classList.remove('is-busy');
        if (err && err.message === 'captcha_v3') {
          showCaptchaError(cfg.captchaError);
          return;
        }
        if (err && err.message === 'captcha_ready') {
          showCaptchaError(cfg.captchaError);
          return;
        }
        showResult(false, '', '', cfg.networkError || 'Network error. Please try again.');
      });
  });
})();
