function imagesLoaded(container) {
  const imgs = Array.from(container.querySelectorAll('figure.wp-block-image'));

  if (imgs.length === 0) {
    return Promise.resolve();
  }

  const promises = imgs.map((img, index) => {
    if (index > 4) {
      img.style.display = "none";
    }
    return new Promise(resolve => {
      const image = new Image();
      image.onload = () => resolve();
      image.onerror = () => resolve();
      image.src = img.querySelector('img').src;
    });
  });

  return Promise.all(promises);
}

document.addEventListener('DOMContentLoaded', () => {
  const gallery = document.querySelector('.wp-block-gallery.load-more-gallery');
  if (!gallery) return;

  // Insert the "Load More" button
  const buttonWrapper = document.createElement('div');
  buttonWrapper.className = 'wp-block-buttons is-content-justification-center is-layout-flex wp-block-buttons-is-layout-flex my-4';
  const button = document.createElement('button');
  button.className = 'ucla-btn ucla-btn--primary';
  button.id = 'load-more';
  button.textContent = 'Load More';
  buttonWrapper.insertAdjacentElement('beforeend', button);
  gallery.insertAdjacentElement('afterend', buttonWrapper);

  imagesLoaded(gallery).then(() => {
    if (gallery.querySelectorAll(
      'figure.wp-block-image[style*="display: none"]'
    ).length < 1) {
      button.style.display = 'none';
    }
    button.addEventListener('click', e => {
      e.preventDefault();
      const hiddenFigures = gallery.querySelectorAll(
        'figure.wp-block-image[style*="display: none"]'
      );
      let count = 0;
      for (let i = 0; i < hiddenFigures.length && count < 4; i++) {
        hiddenFigures[i].style.display = '';
        count++;
      }
      if (gallery.querySelectorAll('figure.wp-block-image[style*="display: none"]').length === 0) {
        button.style.display = 'none';
      }
    }
  );
  });
});