(function($){
  'use strict';
  $(document).on('click', '.spar-pagination-btn:not([disabled])', function(e){
    e.preventDefault();
    var $btn = $(this);
    var page = parseInt($btn.data('page'), 10);
    if (!page || page < 1) return;
    var $container = $('#spar-points-history-container');
    var $loading = $container.find('.spar-pagination-loading');
    var $controls = $container.find('.spar-pagination-controls');
    $loading.show();
    $controls.find('.spar-pagination-btn').prop('disabled', true);
    var ajaxUrl = (window.sparPointsHistory && sparPointsHistory.ajaxUrl) || (typeof ajaxurl !== 'undefined' ? ajaxurl : '');
    var nonce = window.sparPointsHistory && sparPointsHistory.nonce;
    $.ajax({
      url: ajaxUrl,
      type: 'POST',
      data: { action: 'spar_load_points_history', page: page, nonce: nonce }
    }).done(function(resp){
      if (resp && resp.success && resp.data){
        if (resp.data.table_html){ $('#spar-points-history-tbody').html(resp.data.table_html); }
        if (resp.data.pagination_html){ $('#spar-points-history-pagination').html(resp.data.pagination_html); }
        else { $('#spar-points-history-pagination').hide(); }
        var $target = $('#spar-points-history-container');
        if ($target.length){ $('html, body').animate({ scrollTop: $target.offset().top - 20 }, 300); }
      } else {
        var msg = (resp && resp.data) ? (resp.data.message || resp.data) : (window.sparPointsHistory && sparPointsHistory.i18n && sparPointsHistory.i18n.error) || 'Error';
        alert(msg);
      }
    }).fail(function(){
      var msg = (window.sparPointsHistory && sparPointsHistory.i18n && sparPointsHistory.i18n.error) || 'Error';
      alert(msg);
    }).always(function(){
      $loading.hide();
      $controls.find('.spar-pagination-btn').prop('disabled', false);
    });
  });
})(jQuery);
