jQuery(function ($) {
  $(document).on('click', '.ss-save-button', function (e) {
    e.preventDefault();

    var $btn = $(this);
    var postId = $btn.data('post-id');

    if (!saveamsuBookmark.is_logged_in) {
      alert('Please log in to save items.');
      return;
    }

    $.ajax({
      url: saveamsuBookmark.ajax_url,
      method: 'POST',
      dataType: 'json',
      data: {
        action: 'saveamsu_toggle_bookmark',
        nonce: saveamsuBookmark.nonce,
        post_id: postId
      },
      success: function (response) {
        if (!response?.success) return;

        var status = response.data.status;

        // ✔ Do NOT replace innerHTML — only change the text part
        var label = $btn.find('.ss-main-label');

        if (status === 'added') {
          $btn.removeClass('ss-not-saved').addClass('ss-saved');
          label.text("Saved for later");
        } else {
          $btn.removeClass('ss-saved').addClass('ss-not-saved');
          label.text("Save for later");
        }
      }
    });
  });
});
