(function () {
  function closestForm(el) {
    return el && el.closest ? el.closest('form[data-wpps-magic-login-form="1"]') : null;
  }
  function setMessage(form, text, ok) {
    var card = form.closest('.wpps-magic-login');
    var header = card ? card.querySelector('.wpps-magic-login__header') : null;
    if (!header) { return; }
    header.innerHTML =
      '<p class="wpps-magic-login__msg ' +
      (ok ? 'wpps-magic-login__msg--ok' : 'wpps-magic-login__msg--err') +
      '" role="' +
      (ok ? 'status' : 'alert') +
      '">' +
      escapeHtml(text) +
      '</p>';
  }
  function escapeHtml(s) {
    var d = document.createElement('div');
    d.textContent = s;
    return d.innerHTML;
  }
  function captchaReady(form) {
    var scope = form.querySelector('.wpps-magic-login__form') || form;
    var hasWidget = scope.querySelector(
      '.wpps-simple-captcha-wrap, .wpps-captcha-cushion, .g-recaptcha, .cf-turnstile, .wpps-turnstile-wrap, .wpps-recaptcha-v3-token'
    );
    if (!hasWidget) {
      return true;
    }
    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')) {
      var turnstile = scope.querySelector('[name="cf-turnstile-response"]');
      return !!(turnstile && (turnstile.value || '').trim());
    }
    return true;
  }
  document.addEventListener('submit', function (e) {
    var form = closestForm(e.target);
    if (!form || !window.wppsMagicLogin || !window.FormData) { return; }
    /* No-AJAX fallback for full wp-login POST */
    if (form.getAttribute('action') && form.getAttribute('action').indexOf('wp-login.php') !== -1) {
      return;
    }
    if (!captchaReady(form)) {
      e.preventDefault();
      setMessage(form, (window.wppsMagicLogin.captchaError || 'Please complete the CAPTCHA.'), false);
      return;
    }
    e.preventDefault();
    var card = form.closest('.wpps-magic-login');
    var btn = form.querySelector('.wpps-magic-login__submit');
    var data = new FormData(form);
    data.append('action', window.wppsMagicLogin.action || 'wpps_request_magic_link');
    if (card) { card.classList.add('is-sending'); }
    if (btn) { btn.disabled = true; }
    form.dispatchEvent(new CustomEvent('wpps-magic-login:before-send', { bubbles: true }));
    fetch(window.wppsMagicLogin.ajaxUrl, { method: 'POST', credentials: 'same-origin', body: data })
      .then(function (r) { return r.json(); })
      .then(function (res) {
        var ok = !!(res && res.success);
        var d = res && res.data ? res.data : {};
        var title = d.title || '';
        var subtitle = d.subtitle || '';
        var msg = d.message || '';
        if (ok && (title || subtitle)) {
          var cardInner = form.closest('.wpps-magic-login');
          var head = cardInner ? cardInner.querySelector('.wpps-magic-login__header') : null;
          if (head) {
            head.innerHTML =
              '<p class="wpps-magic-login__msg wpps-magic-login__msg--ok" role="status"><strong>' +
              escapeHtml(title) +
              '</strong><br>' +
              escapeHtml(subtitle) +
              '</p>';
          }
        } else if (msg) {
          setMessage(form, msg, ok);
        }
        if (ok && d.show_form === false) { form.reset(); }
        form.dispatchEvent(new CustomEvent(ok ? 'wpps-magic-login:success' : 'wpps-magic-login:error', { bubbles: true, detail: res }));
      })
      .catch(function (err) {
        form.dispatchEvent(new CustomEvent('wpps-magic-login:error', { bubbles: true, detail: err }));
      })
      .finally(function () {
        if (card) { card.classList.remove('is-sending'); }
        if (btn) { btn.disabled = false; }
        form.dispatchEvent(new CustomEvent('wpps-magic-login:complete', { bubbles: true }));
      });
  });
})();
