import './site-header.scss';

Drupal.behaviors.siteHeader = {
  attach(context) {
    // Amount to scroll before the site_header gets small.
    const DESKTOP_THRESHOLD = 50;
    const HTML = document.documentElement;
    const SMALL_HEADER_MQ = window.matchMedia(`(max-width: ${ getComputedStyle(HTML).getPropertyValue('--small-header-mq')})`);
    const SITE_HEADER = context.querySelector('[data-js="site-header"]');
    if (!SITE_HEADER) return;

    const SITE_HEADER_CONTENT = SITE_HEADER.querySelector('.site-header__content');
    if (!SITE_HEADER_CONTENT) return;

    let debounceTimeout;
    let scrollTicking = false;
    let isHeaderSmall = false;
    let lastScrollY = window.scrollY || HTML.scrollTop || 0;

    // Get the threshold amount based on the mobile breakpoint.
    const getCurrentThreshold = () => {
      return SMALL_HEADER_MQ.matches ? 0 : DESKTOP_THRESHOLD;
    };

    const shouldHeaderBeSmall = () => {
      return SMALL_HEADER_MQ.matches || lastScrollY >= getCurrentThreshold();
    };

    const updateHeaderHeight = () => {
      // If there's a CSS transition, wait for it to complete.
      const hasTransition = getComputedStyle(SITE_HEADER_CONTENT).transition !== 'none';

      if (hasTransition) {
        const handleTransitionEnd = () => {
          HTML.style.setProperty('--site-header-height', `${SITE_HEADER_CONTENT.clientHeight}px`);
          SITE_HEADER_CONTENT.removeEventListener('transitionend', handleTransitionEnd);
        };

        SITE_HEADER_CONTENT.addEventListener('transitionend', handleTransitionEnd, { once: true });

        // Fallback timeout in case transitionend doesn't fire.
        setTimeout(() => {
          HTML.style.setProperty('--site-header-height', `${SITE_HEADER_CONTENT.clientHeight}px`);
          SITE_HEADER_CONTENT.removeEventListener('transitionend', handleTransitionEnd);
        }, 500);
      }
      else {
        // No transition, update immediately.
        HTML.style.setProperty('--site-header-height', `${SITE_HEADER_CONTENT.clientHeight}px`);
      }
    };

    const handleHeaderStateChange = (event) => {
      const EVENT_TYPE = event.type;

      const executeUpdate = () => {
        // Update scroll position if this is a scroll event
        if (EVENT_TYPE === 'scroll') {
          lastScrollY = window.scrollY || HTML.scrollTop || 0;
          scrollTicking = false;
        }

        HTML.removeAttribute('data-site-header-small');
        isHeaderSmall = false;
        updateHeaderHeight();

        if (shouldHeaderBeSmall() && !isHeaderSmall) {
          HTML.setAttribute('data-site-header-small', true);
          isHeaderSmall = true;
          updateHeaderHeight();
        }
      };

      if (EVENT_TYPE === 'scroll') {
        // Use requestAnimationFrame for scroll events (better performance)
        if (!scrollTicking) {
          window.requestAnimationFrame(executeUpdate);
        }
        scrollTicking = true;
      }
      else {
        // Use debounced timeout for media query changes
        clearTimeout(debounceTimeout);
        debounceTimeout = setTimeout(executeUpdate, 16); // roughly 60fps.
      }
    };

    // Initialize header state
    if (shouldHeaderBeSmall()) {
      HTML.setAttribute('data-site-header-small', true);
      isHeaderSmall = true;
      updateHeaderHeight();
    }

    SMALL_HEADER_MQ.addEventListener('change', handleHeaderStateChange);
    window.addEventListener('resize', handleHeaderStateChange, { passive: true });
    window.addEventListener('scroll', handleHeaderStateChange, { passive: true });

    updateHeaderHeight();
  }
}
