(function($) {
  'use strict';

  window.MindwecoNonceRefresh = window.MindwecoNonceRefresh || {};

  MindwecoNonceRefresh.refreshInterval = 60 * 60 * 1000;
  MindwecoNonceRefresh.lastRefresh = null;
  MindwecoNonceRefresh.pendingRefresh = null;

  MindwecoNonceRefresh.refresh = function() {
    if (typeof mindwecoFrontend === 'undefined' || !mindwecoFrontend.ajax_url) {
      return $.Deferred().reject('mindwecoFrontend is unavailable').promise();
    }

    if (MindwecoNonceRefresh.pendingRefresh) {
      return MindwecoNonceRefresh.pendingRefresh;
    }

    MindwecoNonceRefresh.pendingRefresh = $.ajax({
      url: mindwecoFrontend.ajax_url,
      type: 'POST',
      data: {
        action: 'mindweco_refresh_nonce'
      },
      dataType: 'json',
      success: function(response) {
        if (response.success && response.data.nonce) {
          mindwecoFrontend.nonce = response.data.nonce;
          MindwecoNonceRefresh.lastRefresh = new Date();
        }
      },
      complete: function() {
        MindwecoNonceRefresh.pendingRefresh = null;
      }
    });

    return MindwecoNonceRefresh.pendingRefresh;
  };

  MindwecoNonceRefresh.init = function() {
    MindwecoNonceRefresh.refresh();
    setInterval(function() {
      MindwecoNonceRefresh.refresh();
    }, MindwecoNonceRefresh.refreshInterval);

    document.addEventListener('visibilitychange', function() {
      if (!document.hidden) {
        MindwecoNonceRefresh.refresh();
      }
    });

    return true;
  };

  MindwecoNonceRefresh.getNonce = function() {
    return mindwecoFrontend.nonce || null;
  };

  $(document).on('ajaxError', function(event, xhr, settings, thrownError) {
    if (xhr.status === 419 || xhr.status === 403) {
      MindwecoNonceRefresh.refresh();
    }
  });

  $(document).ready(function() {
    MindwecoNonceRefresh.init();
  });

})(jQuery);
