import './view.content-awards.embed-by-project.scss';

Drupal.behaviors.viewAwardsEmbedByProject = {
  attach(context) {
    const HTML = document.documentElement;
    const AWARDS = context.querySelectorAll('.view--content-awards.view--embed-by-project .view__award');
    if (!AWARDS.length) return;

    let resizeTimeout;

    // Function to check and adjust positioning for award info tooltips
    const updateTooltipPosition = (award) => {
      const awardInfo = award.querySelector('.view__award-info');
      if (!awardInfo) return;

      // Reset positioning to get natural dimensions
      awardInfo.style.left = '0';
      awardInfo.style.right = 'auto';

      // Get the bounding rectangles
      const awardRect = award.getBoundingClientRect();
      const awardInfoRect = awardInfo.getBoundingClientRect();
      const viewportWidth = HTML.getBoundingClientRect().width;

      // Check if the tooltip would overflow the right edge of the viewport
      const wouldOverflow = awardRect.left + awardInfoRect.width > viewportWidth;

      if (wouldOverflow) {
        awardInfo.style.left = 'auto';
        awardInfo.style.right = '0';
      }
      else {
        awardInfo.style.left = '0';
        awardInfo.style.right = 'auto';
      }
    };

    const processAllAwardTooltips = () => {
      AWARDS.forEach(award => {
        updateTooltipPosition(award);
      });
    };

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

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

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

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

    // Initialize
    processAllAwardTooltips();
  }
};
