// AJAX shop settings — progressive enhancement.
// When JS is available, intercepts settings form POSTs and submits
// via fetch so the page does not reload. Flash messages are rendered
// inline into the #alerts div. When JS is disabled, forms fall back
// to the normal POST + redirect flow.
(function() {
  var forms = document.querySelectorAll('form[action*="/settings"]');
  if (!forms.length) return;

  forms.forEach(function(form) {
    // Skip file upload forms — they POST directly to S3, not /settings
    if (form.querySelector('input[type="file"]')) return;

    form.addEventListener('submit', function(e) {
      e.preventDefault();
      var formData = new FormData(form);
      var submitBtn = form.querySelector('input[type="submit"], button[type="submit"]');
      if (!submitBtn) return;
      var originalLabel = submitBtn.value;
      submitBtn.disabled = true;
      submitBtn.value = 'Saving...';

      fetch(form.action, {
        method: 'POST',
        body: formData,
        redirect: 'manual',
        headers: { 'X-Requested-With': 'XMLHttpRequest' }
      })
      .then(function(response) {
        if (!response.ok) {
          // Auth redirect or server error — fall back to regular form submit
          submitBtn.disabled = false;
          submitBtn.value = originalLabel;
          form.submit();
          return;
        }
        return response.json();
      })
      .then(function(data) {
        if (!data) return;
        showFlashMessages(data.messages);
      })
      .catch(function() {
        // Network error — fall back to regular form submit
        submitBtn.disabled = false;
        submitBtn.value = originalLabel;
        form.submit();
      })
      .finally(function() {
        submitBtn.disabled = false;
        submitBtn.value = originalLabel;
      });
    });
  });

  function showFlashMessages(messages) {
    var alerts = document.getElementById('alerts');
    if (!alerts) return;
    alerts.innerHTML = '';
    if (!messages || !messages.length) return;
    messages.forEach(function(msg) {
      var text = msg[0], level = msg[1];
      var div = document.createElement('div');
      div.className = 'alert alert-' + level;
      div.setAttribute('onclick', "this.style.display='none'");
      div.innerHTML = '<p class="alert-message">' + escapeHtml(text) + '</p>'
        + '<label class="close" alt="dismiss" title="Mark as read">X</label>';
      alerts.appendChild(div);
    });
    alerts.scrollIntoView({ behavior: 'smooth', block: 'start' });
  }

  function escapeHtml(str) {
    var div = document.createElement('div');
    div.textContent = str;
    return div.innerHTML;
  }
})();
