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

document.addEventListener('DOMContentLoaded', () => {
  const PHOTO_GALLERY = document.querySelector('.photo-gallery');
  if (!PHOTO_GALLERY) return;

  let resizeTimeout;
  let lastEmptyCellHeight = null;

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

    let emptyCellHeight = EMPTY_CELL.clientHeight;

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

      lastEmptyCellHeight = emptyCellHeight;
    }
  }

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

  const handleResize = () => {
    clearTimeout(resizeTimeout);
    resizeTimeout = setTimeout(updateEmptyCellHeight, 16);
  };

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

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

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

  updateEmptyCellHeight();
});
