import './view.content-projects.block-all.scss';

Drupal.behaviors.viewProjectBlockAll = {
  attach(context) {
    const VIEW = context.querySelector('.view--content-projects.view--block-all');
    if (!VIEW) return;

    let resizeTimeout;
    let lastViewRowContentHeight = null;

    /**
     * Update the view's CSS custom property with the row content height.
     */
    const updateViewRowContentHeight = () => {
      const ROW_CONTENT = VIEW.querySelector('.view__row-content');
      if (!ROW_CONTENT) return;

      let viewRowContentHeight = ROW_CONTENT.clientHeight;

      if (lastViewRowContentHeight !== viewRowContentHeight) {
        VIEW.style.setProperty('--view-row-content-height', `${ viewRowContentHeight }px`);

        lastViewRowContentHeight = viewRowContentHeight;
      }
    };

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

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

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

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

    // Initialize
    updateViewRowContentHeight();
  }
}
