Add show more/less links for child levels in a hierarchical Checkboxes facet

<?php
// See: 
// https://facetwp.com/help-center/facets/facet-types/checkboxes/#add-show-more-less-toggle-links-for-child-levels-in-a-hierarchical-checkboxes-facet

add_action('facetwp_scripts', function () {
  // Change "4" in both style (3x) and script (1x) to customize from what number of choices they are hidden.
  // "4" means only the first 3 choices show, then a 'show more' link.
  ?>
  <style>
    .facetwp-depth.visible > div:nth-child(n+4 of .facetwp-checkbox),
    .facetwp-depth.visible:not(.showmore) > div:nth-child(n+4 of .facetwp-checkbox) + .facetwp-depth.visible {
      display: none; /* Hide from the 4th choice */
    }
    .facetwp-depth.visible.showmore > div:nth-child(n+4 of .facetwp-checkbox) {
      display: block; /* Show from the 4th choice */
    }
    .facetwp-type-checkboxes a.show-more-link {
      display: block;
      margin-bottom: 4px;
    }
  </style>
 
  <script>
    (function($) {
      document.addEventListener('facetwp-loaded', function() {
        document.querySelectorAll('.facetwp-depth').forEach((node) => {
 
          // Filter out children that have the 'facetwp-depth' class
          const relevantChildren = Array.from(node.children).filter(
            (child) => !child.classList.contains('facetwp-depth')
          );
 
          // Set the label texts
          let showmore_label_more = 'Show more';
          let showmore_label_less = 'Show less';
 
          let showmore_class = 'showmore';
 
          if (relevantChildren.length >= 4) {
 
            // Add show more/less links
            let show = document.createElement('a');
            show.href = 'javascript:;';
            show.textContent = showmore_label_more;
            show.classList.add('show-more-link');
            node.append(show);
 
            // Show hide on click of more/less links
            show.addEventListener('click', function(e) {
              let showmore = e.target;
              let depth = e.target.parentNode;
              if (depth.classList.contains(showmore_class)) {
                depth.classList.remove(showmore_class);
                showmore.textContent = showmore_label_more;
              } else {
                depth.classList.add(showmore_class);
                showmore.textContent = showmore_label_less;
              }
            });
          }
        });
      });
    })(fUtil);
  </script>
  <?php
}, 100);