(function(){
  "use strict";

  function ready(fn){
    if(document.readyState === "loading"){
      document.addEventListener("DOMContentLoaded", fn, { passive: true });
    } else {
      fn();
    }
  }

  function slugify(text){
    return (text || "")
      .toString()
      .normalize("NFD").replace(/[\u0300-\u036f]/g, "") // remove diacritics
      .toLowerCase()
      .replace(/[^a-z0-9\s-]/g, "")
      .trim()
      .replace(/\s+/g, "-")
      .replace(/-+/g, "-");
  }

  function smoothScrollTo(target){
    try {
      // Prefer CSS scroll-margin-top on sections; fallback to JS offset
      target.scrollIntoView({ behavior: "smooth", block: "start" });
    } catch(_e){
      // mark as used to satisfy eslint no-unused-vars
      void _e;
      const y = target.getBoundingClientRect().top + window.scrollY - 80;
      window.scrollTo({ top: y, behavior: "smooth" });
    }
  }


  function buildNav(){
    const nav = document.querySelector('.foodord-scroll-nav');
    if(!nav) return;

    // Server-side places nav after header hook, independent of banner visibility.

    const list = nav.querySelector('.foodord-scroll-nav__list');
    if(!list) return;
    
    const innerEl = nav.querySelector('.foodord-scroll-nav__inner');

    function createMobileSheet(config){
      const button = config.button;
      const onSelect = config.onSelect;
      const getTitle = config.getTitle;
      const getCloseLabel = config.getCloseLabel;

      const backdrop = document.createElement('div');
      backdrop.className = 'foodord-sheet-backdrop';
      backdrop.hidden = true;

      const sheet = document.createElement('div');
      sheet.className = 'foodord-sheet';
      sheet.setAttribute('role', 'dialog');
      sheet.setAttribute('aria-modal', 'true');
      sheet.setAttribute('tabindex', '-1');

      const titleId = 'foodord-sheet-title-' + Math.random().toString(16).slice(2);
      sheet.setAttribute('aria-labelledby', titleId);

      const handle = document.createElement('span');
      handle.className = 'foodord-sheet__handle';
      sheet.appendChild(handle);

      const header = document.createElement('div');
      header.className = 'foodord-sheet__header';

      const titleEl = document.createElement('p');
      titleEl.className = 'foodord-sheet__title';
      titleEl.id = titleId;
      header.appendChild(titleEl);

      const closeBtn = document.createElement('button');
      closeBtn.type = 'button';
      closeBtn.className = 'foodord-sheet__close';
      // optionally set accessible labels from config
      try {
        const closeLabel = (typeof getCloseLabel === 'function') ? getCloseLabel() : '';
        if (closeLabel) {
          closeBtn.setAttribute('aria-label', closeLabel);
          closeBtn.setAttribute('title', closeLabel);
        }
      } catch (_e) { void _e; }
      header.appendChild(closeBtn);

      sheet.appendChild(header);

      const body = document.createElement('div');
      body.className = 'foodord-sheet__body';
      const listEl = document.createElement('ul');
      listEl.className = 'foodord-sheet__list';
      body.appendChild(listEl);
      sheet.appendChild(body);

      backdrop.appendChild(sheet);
      document.body.appendChild(backdrop);

      let items = [];
      let openState = false;

      function renderItems(){
        listEl.innerHTML = '';
        items.forEach(function(item){
          const li = document.createElement('li');
          li.className = 'foodord-sheet__item';

          const link = document.createElement('button');
          link.type = 'button';
          link.className = 'foodord-sheet__link';
          link.textContent = item.title;
          link.setAttribute('data-category-id', item.id);
          link.addEventListener('click', function(){
            onSelect(item.id);
            close();
          }, { passive: false });

          li.appendChild(link);
          listEl.appendChild(li);
        });
      }

      function setItems(nextItems){
        items = Array.isArray(nextItems) ? nextItems.slice() : [];
        renderItems();
      }

      function setActive(id){
        const links = listEl.querySelectorAll('.foodord-sheet__link');
        links.forEach(function(link){
          if(link.getAttribute('data-category-id') === id){
            link.classList.add('is-active');
          } else {
            link.classList.remove('is-active');
          }
        });
      }

      function focusActive(){
        const activeLink = listEl.querySelector('.foodord-sheet__link.is-active');
        const target = activeLink || listEl.querySelector('.foodord-sheet__link') || closeBtn;
        if(target && typeof target.focus === 'function'){
          requestAnimationFrame(function(){
            target.focus({ preventScroll: true });
          });
        }
      }

      function onKeydown(event){
        if(event.key === 'Escape'){
          event.preventDefault();
          close();
        }
      }

      function open(){
        if(openState){
          return;
        }
        openState = true;
        backdrop.hidden = false;
        titleEl.textContent = typeof getTitle === 'function' ? getTitle() : '';
        document.body.classList.add('foodord-sheet-open');
        requestAnimationFrame(function(){
          backdrop.classList.add('is-visible');
          focusActive();
        });
        button.classList.add('is-active');
        button.setAttribute('aria-expanded', 'true');
        document.addEventListener('keydown', onKeydown);
      }

      function close(){
        if(!openState){
          return;
        }
        openState = false;
        button.classList.remove('is-active');
        button.setAttribute('aria-expanded', 'false');
        backdrop.classList.remove('is-visible');
        document.body.classList.remove('foodord-sheet-open');
        document.removeEventListener('keydown', onKeydown);
        const hide = function(){
          backdrop.hidden = true;
          if(typeof button.focus === 'function'){
            button.focus({ preventScroll: true });
          }
        };
        backdrop.addEventListener('transitionend', hide, { once: true });
        setTimeout(function(){
          if(!backdrop.hidden){
            hide();
          }
        }, 320);
      }

      backdrop.addEventListener('click', function(event){
        if(event.target === backdrop){
          close();
        }
      });

      closeBtn.addEventListener('click', function(){
        close();
      });

      return {
        open: open,
        close: close,
        setItems: setItems,
        setActive: setActive,
        getElement: function(){
          return sheet;
        },
        isOpen: function(){
          return openState;
        }
      };
    }
    
    // Create navigation arrows
    const leftArrow = document.createElement('button');
    leftArrow.className = 'foodord-scroll-nav__arrow foodord-scroll-nav__arrow--left';
    leftArrow.innerHTML = '<svg width="26" height="26" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 18L8.5 12L14.5 6" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>';
    leftArrow.type = 'button';
    leftArrow.setAttribute('aria-label', 'Previous categories');
    leftArrow.style.display = 'none';
    
    const rightArrow = document.createElement('button');
    rightArrow.className = 'foodord-scroll-nav__arrow foodord-scroll-nav__arrow--right';
    rightArrow.innerHTML = '<svg width="26" height="26" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M9.5 6L15.5 12L9.5 18" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>';
    rightArrow.type = 'button';
    rightArrow.setAttribute('aria-label', 'Next categories');
    rightArrow.style.display = 'none';
    
    // Insert arrows before and after the list
    if(innerEl) {
      innerEl.insertBefore(leftArrow, list);
      innerEl.insertBefore(rightArrow, list.nextSibling);
    }

    // Dynamic position for the right arrow: align to the end of category list
    function positionRightArrow(){
      if(!rightArrow || !innerEl || !list) return;
      if(window.innerWidth <= 768){ return; }
      const innerRect = innerEl.getBoundingClientRect();
      const listRect = list.getBoundingClientRect();
      const arrowW = rightArrow.offsetWidth || 36;

      // Find the rightmost edge of the last (partially) visible category item
      const items = list.querySelectorAll('.foodord-scroll-nav__item');
      let lastEdge = listRect.left; // default to list left
      for(let i=0;i<items.length;i++){
        const r = items[i].getBoundingClientRect();
        // Consider items that intersect the viewport of the list
        if(r.left < listRect.right && r.right > listRect.left){
          // Take the furthest right visible point but not beyond list viewport
          lastEdge = Math.max(lastEdge, Math.min(r.right, listRect.right));
        }
      }

      // Base left: a small gap after the last visible item
      let left = (lastEdge - innerRect.left) + 6;

      // Prevent overlap with search box (detect side dynamically)
      const searchBox = innerEl.querySelector('.foodord-scroll-nav__search');
      if(searchBox){
        const srect = searchBox.getBoundingClientRect();
        const searchOnLeft = (srect.left - innerRect.left) < (innerRect.width / 2);
        if(searchOnLeft){
          // Ensure arrow stays to the right of the search box if it sits on the left
          const minLeftFromSearch = (srect.right - innerRect.left) + 6;
          left = Math.max(left, minLeftFromSearch);
        } else {
          // Cap arrow before the search box if it sits on the right
          const maxLeft = (srect.left - innerRect.left) - arrowW - 6;
          left = Math.min(left, maxLeft);
        }
      }

      // Keep inside container and after the left safe area
      const minLeft = 72; // after menu area
      const hardMaxLeft = innerRect.width - arrowW - 6;
      left = Math.max(minLeft, Math.min(left, hardMaxLeft));

      rightArrow.style.right = 'auto';
      rightArrow.style.left = Math.round(left) + 'px';
    }

    // Dynamic position for the left arrow: align just before the category list
    function positionLeftArrow(){
      if(!leftArrow || !innerEl || !list) return;
      if(window.innerWidth <= 768){ return; }
      const innerRect = innerEl.getBoundingClientRect();
      const listRect = list.getBoundingClientRect();
      const arrowW = leftArrow.offsetWidth || 36;
      // Place the arrow just before the start of the list
      let left = (listRect.left - innerRect.left) - arrowW - 6; // 6px gap before list
      // Ensure it does not overlap the search box when search is on the left
      const searchBox = innerEl.querySelector('.foodord-scroll-nav__search');
      if(searchBox){
        const srect = searchBox.getBoundingClientRect();
        const searchOnLeft = (srect.left - innerRect.left) < (innerRect.width / 2);
        if(searchOnLeft){
          const minLeftFromSearch = (srect.right - innerRect.left) + 6;
          left = Math.max(left, minLeftFromSearch);
        }
      }
      // Keep it after the safe area
      const minLeft = 56; // safe after edge elements
      left = Math.max(minLeft, left);
      leftArrow.style.right = 'auto';
      leftArrow.style.left = Math.round(left) + 'px';
    }
    
    // Arrow click handlers
    leftArrow.addEventListener('click', function() {
      // Scroll by 2 items at a time
      const items = list.querySelectorAll('.foodord-scroll-nav__item');
      if(items.length > 0) {
        const itemWidth = items[0].offsetWidth;
        const gap = 8; // gap between items from CSS
        const scrollAmount = (itemWidth + gap) * 2; // Scroll 2 items
        list.scrollBy({ left: -scrollAmount, behavior: 'smooth' });
      }
    });
    
    rightArrow.addEventListener('click', function() {
      // Scroll by 2 items at a time
      const items = list.querySelectorAll('.foodord-scroll-nav__item');
      if(items.length > 0) {
        const itemWidth = items[0].offsetWidth;
        const gap = 8; // gap between items from CSS
        const scrollAmount = (itemWidth + gap) * 2; // Scroll 2 items
        list.scrollBy({ left: scrollAmount, behavior: 'smooth' });
      }
    });
    
    // Function to check and update arrow visibility
    function updateArrows() {
      const scrollLeft = list.scrollLeft;
      const scrollWidth = list.scrollWidth;
      const clientWidth = list.clientWidth;
      
      // Hide arrows on small screens (768px and below)
      if(window.innerWidth <= 768) {
        leftArrow.style.display = 'none';
        rightArrow.style.display = 'none';
        return;
      }
      
      // Check if scrolling is possible
      if(scrollWidth <= clientWidth) {
        leftArrow.style.display = 'none';
        rightArrow.style.display = 'none';
        return;
      }
      
      // Show/hide left arrow
      leftArrow.style.display = scrollLeft > 5 ? 'flex' : 'none';
      
      // Show/hide right arrow
      rightArrow.style.display = (scrollLeft + clientWidth < scrollWidth - 5) ? 'flex' : 'none';

      // Update arrow positions to align with list edges
      positionLeftArrow();
      positionRightArrow();
    }
    
    // Update arrows on scroll
    list.addEventListener('scroll', updateArrows, { passive: true });
    
    // Menu button functionality
    const menuBtn = nav.querySelector('.foodord-scroll-nav__menu-btn');
    let dropdownMenu = null;
    let mobileSheet = null;
    
    if(menuBtn) {
      // Create dropdown menu
      dropdownMenu = document.createElement('div');
      dropdownMenu.className = 'foodord-scroll-nav__dropdown';
      dropdownMenu.style.display = 'none';
      
      const dropdownList = document.createElement('ul');
      dropdownList.className = 'foodord-scroll-nav__dropdown-list';
      dropdownMenu.appendChild(dropdownList);
      
      // Add dropdown after menu button
      menuBtn.parentElement.insertBefore(dropdownMenu, menuBtn.nextSibling);
      
      // Toggle dropdown on button click
      menuBtn.addEventListener('click', function(e) {
        e.stopPropagation();
        if(window.innerWidth <= 768){
          if(!mobileSheet){
            mobileSheet = createMobileSheet({
              button: menuBtn,
              onSelect: function(id){
                const target = document.getElementById(id);
                if(target){ smoothScrollTo(target); }
                if(activeId && linkMap.get(activeId)){
                  const prevLink = linkMap.get(activeId);
                  prevLink.classList.remove('is-active');
                  prevLink.removeAttribute('aria-current');
                }
                const nextLink = linkMap.get(id);
                if(nextLink){
                  nextLink.classList.add('is-active');
                  nextLink.setAttribute('aria-current','true');
                }
                activeId = id;
                updateDropdownActiveState(id);
                if(nextLink){
                  scrollLinkIntoView(nextLink);
                }
                syncMobileSheetItems();
              },
              getTitle: function(){
                return menuBtn.getAttribute('data-sheet-title') || '';
              },
              getCloseLabel: function(){
                return menuBtn.getAttribute('data-sheet-close') || '';
              }
            });
            syncMobileSheetItems();
          }
          if(mobileSheet.isOpen()){
            mobileSheet.close();
          } else {
            syncMobileSheetItems();
            mobileSheet.open();
          }
          return;
        }

        const isOpen = dropdownMenu.style.display !== 'none';
        
        if(isOpen) {
          dropdownMenu.style.display = 'none';
          menuBtn.classList.remove('is-active');
          menuBtn.setAttribute('aria-expanded', 'false');
        } else {
          dropdownMenu.style.display = 'block';
          menuBtn.classList.add('is-active');
          menuBtn.setAttribute('aria-expanded', 'true');
        }
      });
      
      // Close dropdown when clicking outside
      document.addEventListener('click', function(e) {
        if(window.innerWidth <= 768){
          if(mobileSheet && mobileSheet.isOpen()){
            const sheetEl = mobileSheet.getElement();
            if(sheetEl && !sheetEl.contains(e.target) && !menuBtn.contains(e.target)){
              mobileSheet.close();
            }
          }
          return;
        }
        if(!menuBtn.contains(e.target) && !dropdownMenu.contains(e.target)) {
          dropdownMenu.style.display = 'none';
          menuBtn.classList.remove('is-active');
          menuBtn.setAttribute('aria-expanded', 'false');
        }
      });
      
      // Close dropdown on ESC key
      document.addEventListener('keydown', function(e) {
        if(window.innerWidth <= 768){
        if(mobileSheet && mobileSheet.isOpen()){
          mobileSheet.close();
        }
          return;
        }
        if(e.key === 'Escape' && dropdownMenu.style.display !== 'none') {
          dropdownMenu.style.display = 'none';
          menuBtn.classList.remove('is-active');
          menuBtn.setAttribute('aria-expanded', 'false');
          menuBtn.focus();
        }
      });
    }

    // Find category sections from foodord products renderer
    const sections = Array.prototype.slice.call(document.querySelectorAll('.foodord-category-section'));
    if(sections.length === 0){
      // Nothing to build yet; keep nav visible and exit gracefully
      list.innerHTML = '';
      list.removeAttribute('aria-busy');
      return;
    }

    // Clear previous items (idempotent)
    list.innerHTML = '';
    list.setAttribute('aria-busy','true');

    const linkMap = new Map();
    let activeId = null;

    function collectSheetItems(){
      return Array.from(linkMap.entries()).map(function(entry){
        const buttonEl = entry[1];
        const mainText = buttonEl ? buttonEl.querySelector('.foodord-scroll-nav__text') : null;
        const fallback = buttonEl ? buttonEl.textContent : '';
        const titleText = mainText ? mainText.textContent.trim() : fallback.trim();
        return { id: entry[0], title: titleText };
      });
    }

    function syncMobileSheetItems(){
      if(!mobileSheet){
        return;
      }
      mobileSheet.setItems(collectSheetItems());
      const candidateId = activeId || (sections[0] ? sections[0].id : '');
      if(candidateId){
        mobileSheet.setActive(candidateId);
      }
    }

    sections.forEach(function(section){
      const titleEl = section.querySelector('.foodord-product-category');
      const title = titleEl ? (titleEl.textContent || titleEl.innerText || '').trim() : '';
      if(!title){ return; }

      let id = section.id;
      if(!id){
        id = 'category-' + slugify(title);
        // Ensure uniqueness
        const base = id; let i = 2;
        while(document.getElementById(id)){
          id = base + '-' + (i++);
        }
        section.id = id;
      }

      const li = document.createElement('li');
      li.className = 'foodord-scroll-nav__item';

      const a = document.createElement('button');
      a.className = 'foodord-scroll-nav__link';
      a.type = 'button';
      const normalSpan = document.createElement('span');
      normalSpan.className = 'foodord-scroll-nav__text';
      normalSpan.textContent = title;
      const boldSpan = document.createElement('span');
      boldSpan.className = 'foodord-scroll-nav__text--bold';
      boldSpan.setAttribute('aria-hidden', 'true');
      boldSpan.textContent = title;
      const label = document.createElement('span');
      label.className = 'foodord-scroll-nav__label';
      label.appendChild(normalSpan);
      label.appendChild(boldSpan);
      a.appendChild(label);

      a.addEventListener('click', function(ev){
        ev.preventDefault();
        const target = document.getElementById(id);
        if(target){ smoothScrollTo(target); }
        if(activeId && linkMap.get(activeId)){
          const prev = linkMap.get(activeId);
          prev.classList.remove('is-active');
          prev.removeAttribute('aria-current');
        }
        a.classList.add('is-active');
        a.setAttribute('aria-current','true');
        activeId = id;
        updateDropdownActiveState(id);
        // Ensure the newly active link is visible
        scrollLinkIntoView(a);
        if(mobileSheet && mobileSheet.isOpen()){
          mobileSheet.close();
        }
      }, { passive: false });

      li.appendChild(a);
      list.appendChild(li);
      linkMap.set(id, a);
      
      // Add item to dropdown menu if exists
      if(dropdownMenu){
        const dropdownList = dropdownMenu.querySelector('.foodord-scroll-nav__dropdown-list');
        if(dropdownList) {
          const dropdownItem = document.createElement('li');
          dropdownItem.className = 'foodord-scroll-nav__dropdown-item';
          dropdownItem.setAttribute('data-category-id', id);

          const dropdownLink = document.createElement('button');
          dropdownLink.className = 'foodord-scroll-nav__dropdown-link';
          dropdownLink.type = 'button';
          dropdownLink.textContent = title;
          dropdownLink.setAttribute('data-category-id', id);
          dropdownLink.setAttribute('data-text', title);

          dropdownLink.addEventListener('click', function(e) {
            e.preventDefault();
            const target = document.getElementById(id);
            if(target) { smoothScrollTo(target); }

            // Close dropdown
            dropdownMenu.style.display = 'none';
            menuBtn.classList.remove('is-active');
            menuBtn.setAttribute('aria-expanded', 'false');

            // Update active state
            if(activeId && linkMap.get(activeId)){
              const prev = linkMap.get(activeId);
              prev.classList.remove('is-active');
              prev.removeAttribute('aria-current');
            }
            a.classList.add('is-active');
            a.setAttribute('aria-current','true');
            activeId = id;

            // Update dropdown active state
            updateDropdownActiveState(id);

            // Ensure the corresponding top nav link is visible
            scrollLinkIntoView(a);
          });

      dropdownItem.appendChild(dropdownLink);
      dropdownList.appendChild(dropdownItem);
        }
      }
      // Set first item active by default in mobile sheet
      syncMobileSheetItems();
    });

    // Hover behavior via delegation to avoid flicker between siblings
    list.addEventListener('pointerover', function(e){
      const link = e.target && e.target.closest('.foodord-scroll-nav__link');
      if(!link || !list.contains(link)) return;
      if(hoveredLink === link) return;
      hoveredLink = link;
      updateActiveBgTo(link);
      // Recompute after CSS hover (bold) applies to avoid width mismatch
      requestAnimationFrame(function(){
        if(hoveredLink === link){ updateActiveBgTo(link); }
      });
    }, { passive: true });

    list.addEventListener('pointerleave', function(){
      hoveredLink = null;
      const cur = activeId ? linkMap.get(activeId) : null;
      if(cur){ updateActiveBgTo(cur); }
    }, { passive: true });

    list.removeAttribute('aria-busy');

    // On very small screens (<=520px), cap list width to four categories so search fits
    function updateListForSmallScreens(){
      if(!list) return;
      const isSmall = (window.innerWidth || 0) <= 520;
      if(!isSmall){
        list.style.maxWidth = '';
        return;
      }
      const items = list.querySelectorAll('.foodord-scroll-nav__item');
      let width = 0; let shown = 0; const gap = 8;
      for(let i=0;i<items.length && shown<4;i++){
        const w = items[i].offsetWidth;
        if(w > 0){ width += w; if(shown>0) width += gap; shown++; }
      }
      if(width > 0){ list.style.maxWidth = width + 'px'; }
    }

    // Initial compute and arrow visibility
    setTimeout(function(){ updateListForSmallScreens(); updateArrows(); positionLeftArrow(); positionRightArrow(); }, 120);
    
    // Update on window resize
    window.addEventListener('resize', function(){
      updateListForSmallScreens();
      updateArrows();
      positionLeftArrow();
      positionRightArrow();
      syncMobileSheetItems();
      if(mobileSheet && window.innerWidth > 768 && mobileSheet.isOpen()){
        mobileSheet.close();
      }
    }, { passive: true });

    // Active state on scroll
    // Function to update dropdown active state
    function updateDropdownActiveState(currentActiveId) {
      if(dropdownMenu) {
        const dropdownLinks = dropdownMenu.querySelectorAll('.foodord-scroll-nav__dropdown-link');
        dropdownLinks.forEach(function(link) {
          const linkId = link.getAttribute('data-category-id');
          if(linkId === currentActiveId) {
            link.classList.add('is-active');
          } else {
            link.classList.remove('is-active');
          }
        });
      }
      if(mobileSheet){
        mobileSheet.setActive(currentActiveId);
      }
    }

    // Centralized state setter to avoid conflicting updates
    function setActiveById(id){
      if(!id || id === activeId) return;
      const link = linkMap.get(id);
      if(!link) return;
      // Clear previous
      if(activeId && linkMap.get(activeId)){
        const prev = linkMap.get(activeId);
        prev.classList.remove('is-active');
        prev.removeAttribute('aria-current');
      }
      // Set new
      link.classList.add('is-active');
      link.setAttribute('aria-current','true');
      activeId = id;
      updateIndicatorTo(link);
      updateActiveBgTo(link);
      updateDropdownActiveState(id);
      scrollLinkIntoView(link);
    }

    // Indicator & background elements
    const indicator = nav.querySelector('.foodord-scroll-nav__indicator');
    const activeBg = nav.querySelector('.foodord-scroll-nav__active-bg');
    // innerEl already defined above
    let hoveredLink = null;

    function updateIndicatorTo(link){
      if(!indicator || !link || !innerEl) return;
      const linkRect = link.getBoundingClientRect();
      const innerRect = innerEl.getBoundingClientRect();
      const listRect = list.getBoundingClientRect();
      // Clamp indicator within the visible viewport of the categories list
      const leftEdge = Math.max(linkRect.left, listRect.left);
      const rightEdge = Math.min(linkRect.right, listRect.right);
      const clampedWidth = Math.max(0, rightEdge - leftEdge);
      const left = leftEdge - innerRect.left;
      if(clampedWidth > 0){
        indicator.style.width = clampedWidth + 'px';
        indicator.style.transform = 'translateX(' + Math.round(left) + 'px)';
      } else {
        indicator.style.width = '0px';
      }
    }

    function updateActiveBgTo(link){
      if(!activeBg || !link || !innerEl) return;
      const linkRect = link.getBoundingClientRect();
      const innerRect = innerEl.getBoundingClientRect();
      const listRect = list.getBoundingClientRect();
      // Clamp hover background within the visible viewport of the categories list
      const leftEdge = Math.max(linkRect.left, listRect.left);
      const rightEdge = Math.min(linkRect.right, listRect.right);
      const clampedWidth = Math.max(0, rightEdge - leftEdge);
      const left = leftEdge - innerRect.left;
      if(clampedWidth > 0){
        activeBg.style.width = clampedWidth + 'px';
        activeBg.style.transform = 'translateX(' + Math.round(left) + 'px)';
      } else {
        activeBg.style.width = '0px';
      }
    }

    // Ensure active link is visible within the horizontal list viewport
    function scrollLinkIntoView(link){
      if(!list || !link) return;
      const listRect = list.getBoundingClientRect();
      const linkRect = link.getBoundingClientRect();
      const padding = 8; // keep a small side gap
      const needsLeft = linkRect.left < (listRect.left + padding);
      const needsRight = linkRect.right > (listRect.right - padding);
      if(needsLeft || needsRight){
        const current = list.scrollLeft;
        // Compute link center relative to list scroll origin
        const linkCenter = (linkRect.left - listRect.left) + current + (linkRect.width / 2);
        let target = Math.round(linkCenter - (list.clientWidth / 2));
        // Clamp within scrollable bounds
        const maxScroll = Math.max(0, list.scrollWidth - list.clientWidth);
        target = Math.max(0, Math.min(target, maxScroll));
        list.scrollTo({ left: target, behavior: 'smooth' });
      }
    }

    // Initial active: prefer hash, else first category
    (function setInitialActive(){
      const hash = (window.location.hash || '').replace('#','');
      const initialId = (hash && linkMap.has(hash)) ? hash : (sections[0] ? sections[0].id : null);
      if(initialId){ setActiveById(initialId); }
    })();

    if('IntersectionObserver' in window){
      const observer = new IntersectionObserver(function(entries){
        // Prefer the entry closest to the top by boundingClientRect.top
        let candidate = null;
        let bestTop = Infinity;
        entries.forEach(function(entry){
          if(!entry.isIntersecting) return;
          const top = entry.target.getBoundingClientRect().top;
          if(top < bestTop){ bestTop = top; candidate = entry.target; }
        });
        if(candidate){ setActiveById(candidate.id); }
      }, { root: null, rootMargin: '0px 0px -70% 0px', threshold: 0.1 });

      sections.forEach(function(s){ observer.observe(s); });
    }

    // Precise active detection using a reference line just below the nav (works with sticky)
    let scrollScheduled = false;
    function computeActiveByRef(){
      scrollScheduled = false;
      if(!sections.length) return;
      // Reference line: a bit below the navigation so the highlighted
      // category reflects what is visually in view, not just the section
      // whose heading touches the sticky bar.
      const navRect = nav.getBoundingClientRect();
      const navBottom = navRect.bottom || 0;
      const viewportHeight = window.innerHeight || document.documentElement.clientHeight || 0;
      const navHeight = navRect.height || nav.offsetHeight || 0;
      const dynamicOffset = Math.min(
        Math.max(navHeight + 40, viewportHeight * 0.35),
        Math.max(180, viewportHeight * 0.6)
      );
      const refY = navBottom + dynamicOffset;
      let best = null;
      let bestTop = -Infinity;
      for(let i=0;i<sections.length;i++){
        const sec = sections[i];
        const top = sec.getBoundingClientRect().top;
        if(top <= refY && top > bestTop){ bestTop = top; best = sec; }
      }
      if(!best){ best = sections[0]; }
      if(best){ setActiveById(best.id); }
    }

    window.addEventListener('scroll', function(){
      if(!scrollScheduled){ scrollScheduled = true; requestAnimationFrame(computeActiveByRef); }
    }, { passive: true });
    window.addEventListener('resize', function(){
      if(!scrollScheduled){ scrollScheduled = true; requestAnimationFrame(computeActiveByRef); }
    }, { passive: true });
    // Initial compute
    computeActiveByRef();

    // Sticky behavior
    let originalTop = null;
    let spacer = null;
    const siteMain = document.querySelector('.site-main');
    const siteMainBasePaddingTop = siteMain ? (parseFloat(window.getComputedStyle(siteMain).paddingTop || '0') || 0) : 0;
    const isPluginOnlyNav = nav.classList.contains('foodord-scroll-nav--plugin-only');

    function getAdminBarOffset(){
      const bar = document.getElementById('wpadminbar');
      if (!bar) return 0;
      const barStyle = window.getComputedStyle(bar);
      // Only count admin bar height if it's fixed positioned
      if (barStyle.position === 'fixed') {
        return bar.offsetHeight;
      }
      return 0;
    }

    function getStickyTopOffset(){
      return getAdminBarOffset();
    }

    function getStickyFrame(){
      const rect = nav.getBoundingClientRect();
      const left = Math.max(0, Math.round(rect.left));
      const availableWidth = Math.max(0, window.innerWidth - left);
      const width = Math.min(Math.ceil(rect.width), availableWidth);

      return {
        left: left,
        width: width > 0 ? width : availableWidth,
      };
    }

    function setScrollNavTop(offset, includeFrame) {
      let styleEl = document.getElementById('foodord-scroll-nav-top');
      if (!styleEl) {
        styleEl = document.createElement('style');
        styleEl.id = 'foodord-scroll-nav-top';
        styleEl.type = 'text/css';
        document.head.appendChild(styleEl);
      }
      let css = `:root{--foodord-scroll-nav-top:${offset}px;}`;
      if(includeFrame){
        const frame = getStickyFrame();
        css = `:root{--foodord-scroll-nav-top:${offset}px;--foodord-scroll-nav-left:${frame.left}px;--foodord-scroll-nav-width:${frame.width}px;}`;
      }
      if (styleEl.textContent !== css) {
        styleEl.textContent = css;
      }
    }

    function refreshCurrentVisuals(){
      const cur = activeId ? linkMap.get(activeId) : null;
      const bgTarget = hoveredLink || cur;

      requestAnimationFrame(function(){
        if(cur){ updateIndicatorTo(cur); }
        if(bgTarget){ updateActiveBgTo(bgTarget); }
        updateArrows();
      });
    }

    function ensureSpacer(){
      if(spacer && spacer.parentNode){
        return spacer;
      }

      spacer = document.createElement('div');
      spacer.className = 'foodord-scroll-nav-spacer';
      spacer.style.height = '0px';
      nav.parentNode.insertBefore(spacer, nav.nextSibling);

      return spacer;
    }

    function clearSpacer(){
      if(spacer && spacer.parentNode){
        spacer.style.height = '0px';
      }
    }

    function getSpacerHeight(){
      const navStyles = window.getComputedStyle(nav);
      const marginBottom = parseFloat(navStyles.marginBottom || '0') || 0;

      return Math.ceil(nav.offsetHeight + marginBottom);
    }

    function getStickyReserveHeight(){
      if(siteMain){
        const reserveHeight = Math.round(siteMain.getBoundingClientRect().top - nav.getBoundingClientRect().top);
        if(reserveHeight > 0){
          return reserveHeight;
        }
      }

      return getSpacerHeight();
    }

    function applySiteMainOffset(height){
      if(!siteMain){
        return;
      }

      siteMain.style.paddingTop = height > 0 ? (siteMainBasePaddingTop + height) + 'px' : '';
    }

    function computeOriginalTop(){
      // Only compute when not sticky to avoid layout shifts
      if(!nav.classList.contains('is-sticky')){
        originalTop = nav.getBoundingClientRect().top + window.scrollY;
      }
    }

    function updateSticky(){
      if(originalTop === null){ computeOriginalTop(); }
      const threshold = (originalTop || 0);
      const topOffset = getStickyTopOffset();
      const scrollLine = Math.round(window.scrollY + topOffset);

      if(isPluginOnlyNav){
        if(nav.classList.contains('is-sticky')){
          nav.classList.remove('is-sticky');
        }
        clearSpacer();
        applySiteMainOffset(0);
        setScrollNavTop(topOffset, false);
        refreshCurrentVisuals();
        return;
      }

      setScrollNavTop(topOffset, true);

      if(scrollLine >= threshold){
        if(!nav.classList.contains('is-sticky')){
          const reserveHeight = getStickyReserveHeight();
          nav.classList.add('is-sticky');
          const sp = ensureSpacer();
          sp.style.height = '0px';
          applySiteMainOffset(reserveHeight);
          refreshCurrentVisuals();
        }
      } else {
        if(nav.classList.contains('is-sticky')){
          nav.classList.remove('is-sticky');
          clearSpacer();
          applySiteMainOffset(0);
          // Recompute threshold since layout restored
          computeOriginalTop();
          refreshCurrentVisuals();
        }
      }
    }

    // Initial compute and listeners
    computeOriginalTop();
    updateSticky();
    updateArrows();
    window.addEventListener('scroll', updateSticky, { passive: true });
    window.addEventListener('resize', function(){
      // On resize, drop sticky to recompute baseline accurately
      if(nav.classList.contains('is-sticky')){
        nav.classList.remove('is-sticky');
        clearSpacer();
        applySiteMainOffset(0);
      }
      originalTop = null;
      computeOriginalTop();
      updateSticky();
      // Reposition indicator to current active link
      const cur = activeId ? linkMap.get(activeId) : null;
      if(cur){ updateIndicatorTo(cur); updateActiveBgTo(cur); scrollLinkIntoView(cur); }
      updateArrows();
    }, { passive: true });

    // Reposition indicator on horizontal scroll of the list
    list.addEventListener('scroll', function(){
      const cur = activeId ? linkMap.get(activeId) : null;
      const bgTarget = hoveredLink || cur;
      if(cur){ updateIndicatorTo(cur); }
      if(bgTarget){ updateActiveBgTo(bgTarget); }
    }, { passive: true });
  }

  ready(buildNav);
})();
