(function() {
  'use strict';

  window.MindwecoSafeAjax = window.MindwecoSafeAjax || {};

  MindwecoSafeAjax.request = function(options) {
    const defaults = {
      action: '',
      method: 'POST',
      timeout: 30000,
      retries: 3,
      debug: false,
      headers: {},
      data: {}
    };

    const config = Object.assign({}, defaults, options);

    return new Promise((resolve, reject) => {
      const attemptRequest = (attempt = 1) => {
        const ajaxUrl = MindwecoSafeAjax.getAjaxUrl();
        if (!ajaxUrl) {
          reject('AJAX URL not found');
          return;
        }

        const formData = new URLSearchParams();
        formData.append('action', config.action);

        if (MindwecoSafeAjax.getNonce()) {
          formData.append('nonce', MindwecoSafeAjax.getNonce());
        }

        Object.keys(config.data).forEach(key => {
          formData.append(key, config.data[key]);
        });

        fetch(ajaxUrl, {
            method: config.method,
            headers: {
              'X-Requested-With': 'XMLHttpRequest',
              ...config.headers
            },
            body: formData.toString(),
            timeout: config.timeout,
            credentials: 'same-origin'
          })
          .then(response => {
            if (!response.ok) {
              throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }
            return response.json();
          })
          .then(data => {
            resolve(data);
          })
          .catch(error => {
            if (attempt < config.retries) {
              setTimeout(() => attemptRequest(attempt + 1), 1000 * attempt);
            } else {
              reject(error);
            }
          });
      };

      attemptRequest();
    });
  };

  MindwecoSafeAjax.getAjaxUrl = function() {
    if (typeof mindwecoFrontend !== 'undefined' && mindwecoFrontend.ajax_url) {
      return mindwecoFrontend.ajax_url;
    }
    if (window.ajaxurl) {
      return window.ajaxurl;
    }
    return null;
  };

  MindwecoSafeAjax.getNonce = function() {
    if (typeof mindwecoFrontend !== 'undefined' && mindwecoFrontend.nonce) {
      return mindwecoFrontend.nonce;
    }
    const nonceElement = document.querySelector('[name="mindweco_nonce"]');
    if (nonceElement) {
      return nonceElement.value;
    }
    return null;
  };

  MindwecoSafeAjax.checkJQuery = function() {
    return (typeof jQuery !== 'undefined' && jQuery.fn.jquery);
  };

  MindwecoSafeAjax.post = function(action, data) {
    return MindwecoSafeAjax.request({
      action: action,
      method: 'POST',
      data: data
    });
  };

  MindwecoSafeAjax.init = function() {
    MindwecoSafeAjax.checkJQuery();

    const ajaxUrl = MindwecoSafeAjax.getAjaxUrl();
    const nonce = MindwecoSafeAjax.getNonce();

    return {
      ajaxUrl: ajaxUrl,
      nonce: nonce,
      jQueryAvailable: MindwecoSafeAjax.checkJQuery()
    };
  };

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', MindwecoSafeAjax.init);
  } else {
    MindwecoSafeAjax.init();
  }

})();