import './paragraph.photo-gallery.scss';

document.addEventListener('DOMContentLoaded', () => {
  const photoGalleries = document.querySelectorAll('.photo-gallery');
  if (!photoGalleries.length) return;

  let resizeTimeout;

  const updateEmptyCellHeight = (photoGallery) => {
    const emptyCell = photoGallery.querySelector('.photo-gallery__empty-cell');
    if (!emptyCell) return;

    const lastEmptyCellHeight = parseFloat(photoGallery.style.getPropertyValue('--empty-cell-height')) || 0;
    const emptyCellHeight = emptyCell.clientHeight;

    if (lastEmptyCellHeight !== emptyCellHeight) {
      photoGallery.style.setProperty('--empty-cell-height', `${ emptyCellHeight }px`);
    }
  }

  /**
   * **************************************************
   * Handlers
   */

  const handleResize = () => {
    clearTimeout(resizeTimeout);
    resizeTimeout = setTimeout(() => {
      photoGalleries.forEach(gallery => updateEmptyCellHeight(gallery));
    }, 16);
  };

  /**
   * **************************************************
   * Listeners
   */

  window.addEventListener('resize', handleResize, { passive: true });

  /**
   * **************************************************
   * Initialize
   */

  photoGalleries.forEach(gallery => {
    updateEmptyCellHeight(gallery);
  });
});
