(function () {
  'use strict';

  var endpoint = window.puffergoContactForm && window.puffergoContactForm.endpoint
    ? window.puffergoContactForm.endpoint
    : '/wp-json/puffergo/v1/contact';

  function toPayload(form) {
    var data = new FormData(form);
    var payload = {};
    data.forEach(function (value, key) {
      if (payload[key]) {
        if (!Array.isArray(payload[key])) {
          payload[key] = [payload[key]];
        }
        payload[key].push(value);
      } else {
        payload[key] = value;
      }
    });
    payload.page_url = window.location.href;
    // Auto-detect product context from page
    var productEl = document.querySelector('[data-pg-product-name]');
    if (productEl && productEl.value) {
      payload.product_name = productEl.value;
    }
    return payload;
  }

  function findStatusEl(form) {
    var inside = form.querySelector('[data-pg-form-status]');
    if (inside) {
      return inside;
    }
    var next = form.nextElementSibling;
    return next && next.getAttribute('data-pg-form-status') !== null ? next : null;
  }

  function setStatus(form, state, message) {
    var el = findStatusEl(form);
    if (!el) {
      el = document.createElement('div');
      el.setAttribute('data-pg-form-status', '');
      el.setAttribute('role', 'status');
      form.parentNode.insertBefore(el, form.nextSibling);
    }
    el.textContent = message || '';
    el.className = 'pg-form-status pg-form-status--' + state;
  }

  function setSubmitDisabled(form, disabled) {
    var submits = form.querySelectorAll('button[type="submit"], input[type="submit"]');
    submits.forEach(function (btn) {
      btn.disabled = !!disabled;
    });
  }

  document.addEventListener('submit', function (e) {
    var form = e.target;
    if (!form || form.getAttribute('data-pg-submit') !== 'contact') {
      return;
    }
    e.preventDefault();

    if (form.getAttribute('data-pg-submitting') === 'true') {
      return;
    }
    form.setAttribute('data-pg-submitting', 'true');
    setSubmitDisabled(form, true);

    var loadingMsg = form.getAttribute('data-pg-loading-text') || '';
    var successMsg = form.getAttribute('data-pg-success-text') || '';
    var errorMsg = form.getAttribute('data-pg-error-text') || '';

    setStatus(form, 'loading', loadingMsg || '…');

    var payload = toPayload(form);
    fetch(endpoint, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload),
    })
      .then(function (res) {
        return res.json().then(function (data) {
          return { ok: res.ok, data: data };
        });
      })
      .then(function (_ref) {
        var ok = _ref.ok;
        var data = _ref.data;
        if (ok && data && data.success) {
          var successUrl = form.getAttribute('data-pg-success-url');
          if (successUrl) {
            window.location.href = successUrl;
            return;
          }
          setStatus(form, 'success', successMsg || (data.message || (window.puffergoContactForm.i18n.submitSuccess || 'Submitted successfully')));
          form.reset();
        } else {
          setStatus(form, 'error', errorMsg || (data && data.message ? data.message : (window.puffergoContactForm.i18n.submitFailed || 'Submission failed')));
        }
      })
      .catch(function () {
        setStatus(form, 'error', errorMsg || (window.puffergoContactForm.i18n.submitFailed || 'Submission failed'));
      })
      .finally(function () {
        form.removeAttribute('data-pg-submitting');
        setSubmitDisabled(form, false);
      });
  });
})();
