Post counter in Listing Builder query with paged pages

<?php
// Add an element that shows the post number and total, e.g. 1 of 28
// to the top of each Listing Builder listing post item.
// This code works for "Page numbers" and "Load More" Pager facets. 
// Make sure your page does not include both Pager facet types.

// Note: if you are using the Listing Builder in Dev mode, it would be better to do this directly in the template code like this:
// https://gist.facetwp.com/gist/post-counter-in-query-with-paged-pages/

add_action( 'facetwp_scripts', function() {
  ?>

  <script>

    document.addEventListener('facetwp-loaded', function() {

      // Calculate the first post number on the page:
      let page = FWP.settings.pager.page;
      let per_page = FWP.settings.pager.per_page;
      let total = FWP.settings.pager.total_rows;
      let firstofpage = 1;

      // Check for "Load more" Pager facets
      let is_loadmore = document.querySelector('.facetwp-load-more') !== null;

      if (is_loadmore) {
        // For "Load more" Pager facets
        firstofpage = 1;
      } else {
        // For "Page numbers" Pager facets
        if (per_page < total) {
          firstofpage = (1 + ((page - 1) * per_page));
        } else {
          firstofpage = (0 < total) ? 1 : 0;
        }
      }

      // Select all post elements with class .fwpl-col
      let posts = document.querySelectorAll('.fwpl-col');

      // Loop through each post element:
      posts.forEach((post, index) => {

        // Check if the post already has the item-number element (for when using a Load more Pager facet)
        if (!post.querySelector('.item-number')) {

          // Set the actual post number, which is the number of the first plus the index that starts at 0:
          let postnumber = index + firstofpage;

          let textDiv = document.createElement('div');
          textDiv.classList.add('item-number');
          textDiv.textContent = (postnumber) + ' of ' + total;

          // Get the first child of the post element
          var firstChild = post.firstChild;

          // Prepend 'textDiv' before the first child element
          post.insertBefore(textDiv, firstChild);

        }

      });

    });

  </script>

  <?php
}, 100 );