(function () {
  "use strict";

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

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

  function debounce(fn, wait) {
    let t; return function () { const self = this, args = arguments; clearTimeout(t); t = setTimeout(function () { fn.apply(self, args); }, wait); };
  }

  function ensureEmptyState(root, onBack) {
    let empty = root.querySelector('.foodord-search-empty');
    if (!empty) {
      empty = document.createElement('div');
      empty.className = 'foodord-search-empty';
      empty.innerHTML = (
        '<div class="foodord-search-empty__card">' +
        '<div class="foodord-search-empty__icon" aria-hidden="true">' +
        '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">' +
        '<circle cx="11" cy="11" r="8"></circle>' +
        '<line x1="21" y1="21" x2="16.65" y2="16.65"></line>' +
        '<line x1="8" y1="11" x2="14" y2="11"></line>' +
        '</svg>' +
        '</div>' +
        '<div class="foodord-search-empty__title"></div>' +
        '<div class="foodord-search-empty__desc"></div>' +
        '<button type="button" class="foodord-search-empty__btn"></button>' +
        '</div>'
      );
      root.appendChild(empty);
    }
    const title = empty.querySelector('.foodord-search-empty__title');
    const desc = empty.querySelector('.foodord-search-empty__desc');
    const btn = empty.querySelector('.foodord-search-empty__btn');
    title.textContent = (window.FoodordScrollNavSearch && FoodordScrollNavSearch.noTitle) || "That's not on the menu";
    desc.textContent = (window.FoodordScrollNavSearch && FoodordScrollNavSearch.noDesc) || "Try something else?";
    btn.textContent = (window.FoodordScrollNavSearch && FoodordScrollNavSearch.backLabel) || "Back to menu";
    btn.addEventListener('click', function () { onBack && onBack(); }, { passive: true });
    empty.style.display = 'flex';
    return empty;
  }

  function hideEmptyState(root) {
    const el = root.querySelector('.foodord-search-empty');
    if (el) { el.style.display = 'none'; }
  }

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

    const input = nav.querySelector('#foodord-scroll-nav-search');
    const clearBtn = nav.querySelector('.foodord-scroll-nav__clear-btn');
    const runBtn = nav.querySelector('.foodord-scroll-nav__search-btn');
    const productsRoot = document.querySelector('.foodord-products-shortcode') || document.body;
    const contentRoot = document.querySelector('.foodord-layout__content');

    // Ensure clear button is hidden initially and only appears when there is text
    if (clearBtn) {
      clearBtn.hidden = !(input && input.value && input.value.length > 0);
    }

    // Mobile search overlay functionality
    function isMobile() {
      return window.innerWidth <= 768;
    }

    const searchOverlayCloseMs = 320;
    const searchOverlayFocusMs = 260;

    function keepEmptyStateNearStickyNav() {
      if (!isMobile()) {
        return;
      }

      const navRect = nav.getBoundingClientRect();
      const navBottomY = navRect.bottom + window.scrollY;
      const targetY = Math.max(0, Math.round(navBottomY + 8));
      const maxY = Math.max(0, document.documentElement.scrollHeight - window.innerHeight);
      const finalY = Math.min(targetY, maxY);

      if (window.scrollY > finalY) {
        window.scrollTo(0, finalY);
      }
    }

    const getSearchString = (key, fallback) => (
      window.FoodordScrollNavSearch && typeof FoodordScrollNavSearch[key] === 'string'
    ) ? FoodordScrollNavSearch[key] : fallback;

    function normalizeOrderMode(mode) {
      return mode === 'pickup' ? 'pickup' : 'delivery';
    }

    function getActiveOrderMode() {
      const mobileToggle = document.querySelector('.foodord-mode-toggle-mobile[data-active-mode]');
      if (mobileToggle) {
        const mobileMode = mobileToggle.getAttribute('data-active-mode');
        if (mobileMode === 'pickup' || mobileMode === 'delivery') {
          return mobileMode;
        }
      }

      if (window.FoodordDeliveryPickup && (window.FoodordDeliveryPickup.currentMode === 'pickup' || window.FoodordDeliveryPickup.currentMode === 'delivery')) {
        return window.FoodordDeliveryPickup.currentMode;
      }

      if (window.foodord_location_vars && (window.foodord_location_vars.mode === 'pickup' || window.foodord_location_vars.mode === 'delivery')) {
        return window.foodord_location_vars.mode;
      }

      if (document.querySelector('.wr-card.is-pickup')) {
        return 'pickup';
      }

      return 'delivery';
    }

    function isStoreModeOpen(mode) {
      const status = window.FoodordStoreStatus || null;
      const normalized = normalizeOrderMode(mode);

      if (status && status.modes && typeof status.modes === 'object' && Object.prototype.hasOwnProperty.call(status.modes, normalized)) {
        const data = status.modes[normalized];
        if (data && Object.prototype.hasOwnProperty.call(data, 'is_open')) {
          if (data.manual_locked || data.locked || data.custom_closed) {
            return false;
          }
          if (data.is_open) {
            return true;
          }
          if (data.preorder_enabled && data.preorder_open) {
            return true;
          }
          return false;
        }
      }

      if (status && typeof status.isOpen === 'boolean') {
        return status.isOpen;
      }

      return true;
    }

    function blockClosedStoreOverlayResult() {
      const mode = getActiveOrderMode();
      if (isStoreModeOpen(mode)) {
        return false;
      }

      if (window.FoodordStoreStatusToast && typeof window.FoodordStoreStatusToast.show === 'function') {
        window.FoodordStoreStatusToast.show(mode);
      }

      return true;
    }

    function blockMissingLocationOverlayResult() {
      const mode = getActiveOrderMode();
      if (mode === 'pickup') {
        return false;
      }

      if (typeof window.foodordHasLocation !== 'function' || window.foodordHasLocation()) {
        return false;
      }

      if (typeof window.foodordOpenLocationModal === 'function') {
        window.foodordOpenLocationModal();
        return true;
      }

      const addressTrigger = document.querySelector('[data-foodord-location-trigger], .wr-card__address-bar, .wr-card__address-change');
      if (addressTrigger) {
        addressTrigger.click();
        return true;
      }

      return false;
    }

    function getCardField(card, selector) {
      const element = card.querySelector(selector);
      return element ? element.textContent.trim() : '';
    }

    function matchesNormalizedQuery(haystack, normalizedQuery) {
      if (!normalizedQuery) {
        return false;
      }

      if (haystack.indexOf(normalizedQuery) !== -1) {
        return true;
      }

      const terms = normalizedQuery.split(' ').filter(Boolean);
      if (terms.length < 2) {
        return false;
      }

      return terms.every(function (term) {
        return haystack.indexOf(term) !== -1;
      });
    }

    function removeClonedIds(root) {
      if (!root) {
        return;
      }

      root.removeAttribute('id');
      root.querySelectorAll('[id]').forEach(function (element) {
        element.removeAttribute('id');
      });
    }

    function getMatchingCards(queryRaw) {
      const query = norm(queryRaw);
      if (!query) {
        return [];
      }

      const matches = [];
      collectSections().forEach(function (section) {
        collectCardsWithin(section).forEach(function (card) {
          if (matchesNormalizedQuery(cardText(card), query)) {
            matches.push(card);
          }
        });
      });
      return matches;
    }

    function isUnavailableCard(card) {
      const availabilityFlag = card ? String(card.getAttribute('data-foodord-available') || '').toLowerCase() : '';
      return !!(
        card &&
        (
          card.classList.contains('foodord-product-card--unavailable') ||
          availabilityFlag === '0' ||
          availabilityFlag === 'false' ||
          availabilityFlag === 'no'
        )
      );
    }

    function openOverlayResult(card, trigger) {
      if (blockClosedStoreOverlayResult()) {
        return;
      }

      if (blockMissingLocationOverlayResult()) {
        return;
      }

      if (!card || isUnavailableCard(card)) {
        return;
      }

      const productId = parseInt(card.getAttribute('data-product-id'), 10) || 0;
      if (productId && window.foodordModal && typeof window.foodordModal.openModal === 'function') {
        window.foodordModal.openModal(productId, { trigger: trigger || card });
        return;
      }

      card.dispatchEvent(new MouseEvent('click', {
        bubbles: true,
        cancelable: true,
        view: window
      }));
    }

    function renderOverlayEmptyState(overlay, titleText, descText, showReset) {
      const results = overlay ? overlay.querySelector('.foodord-scroll-nav__search-overlay-results') : null;
      if (!results) {
        return;
      }

      const empty = document.createElement('div');
      empty.className = 'foodord-scroll-nav__search-overlay-empty foodord-search-empty';
      empty.style.display = 'flex';

      const card = document.createElement('div');
      card.className = 'foodord-search-empty__card';

      const icon = document.createElement('div');
      icon.className = 'foodord-search-empty__icon';
      icon.setAttribute('aria-hidden', 'true');
      icon.innerHTML = (
        '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">' +
        '<circle cx="11" cy="11" r="8"></circle>' +
        '<line x1="21" y1="21" x2="16.65" y2="16.65"></line>' +
        '<line x1="8" y1="11" x2="14" y2="11"></line>' +
        '</svg>'
      );

      const title = document.createElement('div');
      title.className = 'foodord-search-empty__title';
      title.textContent = titleText;

      const desc = document.createElement('div');
      desc.className = 'foodord-search-empty__desc';
      desc.textContent = descText;

      const btn = document.createElement('button');
      btn.type = 'button';
      btn.className = 'foodord-search-empty__btn';
      btn.textContent = getSearchString('backLabel', 'Back to menu');

      if (showReset) {
        btn.addEventListener('click', function () {
          closeSearchOverlay(overlay, true);
        }, { passive: true });
      } else {
        btn.hidden = true;
      }

      card.appendChild(icon);
      card.appendChild(title);
      card.appendChild(desc);
      card.appendChild(btn);
      empty.appendChild(card);
      results.appendChild(empty);
    }

    function renderOverlayResults(overlay, queryRaw) {
      const results = overlay ? overlay.querySelector('.foodord-scroll-nav__search-overlay-results') : null;
      if (!results) {
        return;
      }

      const query = norm(queryRaw);
      results.textContent = '';

      if (!query) {
        renderOverlayEmptyState(
          overlay,
          getSearchString('placeholder', 'Search the menu…'),
          getSearchString('startTypingDesc', 'Start typing to find products.'),
          false
        );
        return;
      }

      const cards = getMatchingCards(queryRaw);
      if (!cards.length) {
        renderOverlayEmptyState(
          overlay,
          getSearchString('noTitle', "That's not on the menu"),
          getSearchString('noDesc', 'Try something else?'),
          true
        );
        return;
      }

      cards.slice(0, 30).forEach(function (card) {
        const result = document.createElement('article');
        const image = card.querySelector('img');
        const title = getCardField(card, '.product-title') || getCardField(card, '.woocommerce-loop-product__title');
        const description = getCardField(card, '.product-description-text');
        const priceSource = card.querySelector('.product-price-container') || card.querySelector('.price');
        const imageSrc = image ? (image.currentSrc || image.src || '') : '';

        result.className = 'foodord-scroll-nav__search-overlay-result';
        result.setAttribute('role', 'listitem');
        result.tabIndex = 0;

        if (imageSrc) {
          const thumb = document.createElement('img');
          thumb.className = 'foodord-scroll-nav__search-overlay-result-image';
          thumb.src = imageSrc;
          thumb.alt = image.alt || '';
          thumb.loading = 'lazy';
          result.appendChild(thumb);
        } else {
          result.classList.add('foodord-scroll-nav__search-overlay-result--no-image');
        }

        const copy = document.createElement('span');
        copy.className = 'foodord-scroll-nav__search-overlay-result-copy';

        const titleEl = document.createElement('span');
        titleEl.className = 'foodord-scroll-nav__search-overlay-result-title';
        titleEl.textContent = title || getSearchString('productLabel', 'Product');
        copy.appendChild(titleEl);

        if (description) {
          const descEl = document.createElement('span');
          descEl.className = 'foodord-scroll-nav__search-overlay-result-desc';
          descEl.textContent = description;
          copy.appendChild(descEl);
        }

        if (priceSource) {
          const priceEl = priceSource.cloneNode(true);
          removeClonedIds(priceEl);
          priceEl.classList.add('foodord-scroll-nav__search-overlay-result-price');
          copy.appendChild(priceEl);
        }

        result.appendChild(copy);

        const openResultCard = function () {
          openOverlayResult(card, result);
        };

        result.addEventListener('click', function (event) {
          if (event.target.closest('button, a, input, select, textarea')) {
            return;
          }
          openResultCard();
        });

        result.addEventListener('keydown', function (event) {
          if (event.key !== 'Enter' && event.key !== ' ') {
            return;
          }
          event.preventDefault();
          openResultCard();
        });

        results.appendChild(result);
      });
    }

    function createSearchOverlay() {
      if (nav.querySelector('.foodord-scroll-nav__search-overlay')) {
        return nav.querySelector('.foodord-scroll-nav__search-overlay');
      }

      const overlay = document.createElement('div');
      overlay.className = 'foodord-scroll-nav__search-overlay';
      overlay.innerHTML = `
        <div class=\"foodord-scroll-nav__search-overlay-content\">
          <span class=\"foodord-swipe-dismiss__handle\" aria-hidden=\"true\"></span>
          <div class=\"foodord-scroll-nav__search-overlay-header\">
            <input type="text" inputmode="search" class="foodord-scroll-nav__search-overlay-input" placeholder="${getSearchString('placeholder', 'Search the menu…')}" autocomplete="off" />
            <button type="button" class="foodord-scroll-nav__search-overlay-clear" hidden>${getSearchString('clearLabel', 'Clear search')}</button>
            <button type="button" class="foodord-scroll-nav__search-overlay-close" aria-label="${getSearchString('closeLabel', 'Close search')}">
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none" aria-hidden="true" focusable="false">
                <path d="M6 6L18 18" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" />
                <path d="M18 6L6 18" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" />
              </svg>
            </button>
          </div>
          <div class=\"foodord-scroll-nav__search-overlay-results\" role="list"></div>
        </div>
      `;

      // Append to navigation container, not body
      nav.appendChild(overlay);

      const overlayInput = overlay.querySelector('.foodord-scroll-nav__search-overlay-input');
      const overlayClearBtn = overlay.querySelector('.foodord-scroll-nav__search-overlay-clear');
      const overlayCloseBtn = overlay.querySelector('.foodord-scroll-nav__search-overlay-close');

      if (overlayCloseBtn && !overlayCloseBtn._foodordBound) {
        overlayCloseBtn.addEventListener('click', () => {
          closeSearchOverlay(overlay, true);
        }, { passive: true });
        overlayCloseBtn._foodordBound = true;
      }

      if (overlayClearBtn && !overlayClearBtn._foodordBound) {
        overlayClearBtn.addEventListener('click', () => {
          if (overlayInput) {
            overlayInput.value = '';
          }
          input.value = '';
          applyFilter('');
          renderOverlayResults(overlay, '');
          overlayClearBtn.hidden = true;
          if (overlayInput) {
            try {
              overlayInput.focus({ preventScroll: true });
            } catch {
              overlayInput.focus();
            }
          }
        }, { passive: true });
        overlayClearBtn._foodordBound = true;
      }

      return overlay;
    }

    // Close overlay safely and remove listeners
    function closeSearchOverlay(overlay, focusTrigger) {
      if (!overlay) {
        return;
      }

      const overlayInput = overlay.querySelector('.foodord-scroll-nav__search-overlay-input');
      const overlayClearBtn = overlay.querySelector('.foodord-scroll-nav__search-overlay-clear');

      if (overlay._openFocusTimer) {
        clearTimeout(overlay._openFocusTimer);
        overlay._openFocusTimer = null;
      }
      if (overlay._closeTimer) {
        clearTimeout(overlay._closeTimer);
      }

      overlay.classList.remove('is-opening', 'is-open');
      overlay.classList.add('is-closing');
      overlay._closeTimer = setTimeout(() => {
        overlay.classList.remove('is-closing');
        document.body.classList.remove('foodord-search-overlay-open');
        overlay._closeTimer = null;
      }, searchOverlayCloseMs);

      if (overlay._pendingListenerTimer) {
        clearTimeout(overlay._pendingListenerTimer);
        overlay._pendingListenerTimer = null;
      }
      if (overlay._handleOverlayInput && overlayInput) {
        overlayInput.removeEventListener('input', overlay._handleOverlayInput);
      }
      if (overlay._handleOverlayKeydown && overlayInput) {
        overlayInput.removeEventListener('keydown', overlay._handleOverlayKeydown);
      }
      if (overlay._handleOutsideClick) {
        document.removeEventListener('click', overlay._handleOutsideClick);
      }
      if (overlay._handleEscapeKey) {
        document.removeEventListener('keydown', overlay._handleEscapeKey);
      }
      overlay._handleOverlayInput = null;
      overlay._handleOverlayKeydown = null;
      overlay._handleOutsideClick = null;
      overlay._handleEscapeKey = null;

      if (overlayInput) {
        overlayInput.value = '';
      }
      renderOverlayResults(overlay, '');
      if (overlayClearBtn) {
        overlayClearBtn.hidden = true;
      }
      if (input) {
        input.value = '';
        applyFilter('');
      }
      if (clearBtn) {
        clearBtn.hidden = true;
      }

      if (focusTrigger !== false && !isMobile()) {
        const triggerBtn = nav.querySelector('.foodord-scroll-nav__search-btn');
        if (triggerBtn) {
          try {
            triggerBtn.focus({ preventScroll: true });
          } catch {
            triggerBtn.focus();
          }
        }
      }
    }

    function openSearchOverlay() {
      if (!isMobile()) return;

      const overlay = createSearchOverlay();
      const overlayInput = overlay.querySelector('.foodord-scroll-nav__search-overlay-input');
      const overlayClearBtn = overlay.querySelector('.foodord-scroll-nav__search-overlay-clear');

      if (overlay._closeTimer) {
        clearTimeout(overlay._closeTimer);
        overlay._closeTimer = null;
      }
      if (overlay._openFocusTimer) {
        clearTimeout(overlay._openFocusTimer);
        overlay._openFocusTimer = null;
      }

      overlay.classList.remove('is-open', 'is-closing');
      overlay.classList.add('is-opening');
      overlayInput.value = input.value;

      if (overlayClearBtn) {
        overlayClearBtn.hidden = !(overlayInput.value && overlayInput.value.length > 0);
      }

      document.body.classList.add('foodord-search-overlay-open');
      renderOverlayResults(overlay, overlayInput.value);

      requestAnimationFrame(() => {
        overlay.classList.remove('is-opening');
        overlay.classList.add('is-open');
      });

      const focusOverlayInput = function () {
        if (!overlayInput) {
          return;
        }
        try {
          overlayInput.focus({ preventScroll: true });
        } catch {
          overlayInput.focus();
        }
        if (overlayInput.setSelectionRange) {
          const end = overlayInput.value.length;
          try { overlayInput.setSelectionRange(end, end); } catch { /* noop */ }
        }
      };

      overlay._openFocusTimer = setTimeout(() => {
        focusOverlayInput();
        overlay._openFocusTimer = null;
      }, searchOverlayFocusMs);

      // Handle overlay input
      const handleOverlayInput = debounce(function () {
        input.value = overlayInput.value;
        applyFilter(overlayInput.value);
        renderOverlayResults(overlay, overlayInput.value);
        if (overlayClearBtn) {
          overlayClearBtn.hidden = !(overlayInput.value && overlayInput.value.length > 0);
        }
      }, 180);

      const handleOverlayKeydown = function (e) {
        if (e.key === 'Enter') {
          e.preventDefault();
          input.value = overlayInput.value;
          applyFilter(overlayInput.value);
          renderOverlayResults(overlay, overlayInput.value);
          overlayInput.blur();
        }
      };

      if (overlay._handleOverlayInput) {
        overlayInput.removeEventListener('input', overlay._handleOverlayInput);
      }
      if (overlay._handleOverlayKeydown) {
        overlayInput.removeEventListener('keydown', overlay._handleOverlayKeydown);
      }

      overlayInput.addEventListener('input', handleOverlayInput);
      overlayInput.addEventListener('keydown', handleOverlayKeydown);

      // Handle outside clicks to close overlay
      const handleOutsideClick = function (e) {
        if (!overlay.contains(e.target) && !nav.querySelector('.foodord-scroll-nav__search').contains(e.target)) {
          const card = e.target.closest('.foodord-product-card');
          const inModal = e.target.closest('.foodord-modal') || e.target.closest('.foodord-modal-overlay') || document.body.classList.contains('foodord-modal-open');

          if (inModal) {
            return;
          }

          closeSearchOverlay(overlay, !(card || inModal));

          if (card) {
            const section = card.closest('.foodord-category-section');
            if (section) {
              setTimeout(() => {
                const hadModalOpen = document.body.classList.contains('foodord-modal-open');
                if (hadModalOpen) document.body.classList.remove('foodord-modal-open');
                const y = section.getBoundingClientRect().top + window.scrollY - 90;
                window.scrollTo(0, y);
                if (hadModalOpen) document.body.classList.add('foodord-modal-open');
              }, 10);
            }
          }
        }
      };

      // Handle escape key
      const handleEscapeKey = function (e) {
        if (e.key === 'Escape') {
          closeSearchOverlay(overlay, true);
        }
      };

      if (overlay._pendingListenerTimer) {
        clearTimeout(overlay._pendingListenerTimer);
      }
      if (overlay._handleOutsideClick) {
        document.removeEventListener('click', overlay._handleOutsideClick);
      }
      if (overlay._handleEscapeKey) {
        document.removeEventListener('keydown', overlay._handleEscapeKey);
      }

      // Store handlers on overlay so we can remove them later
      overlay._handleOutsideClick = handleOutsideClick;
      overlay._handleEscapeKey = handleEscapeKey;
      overlay._handleOverlayInput = handleOverlayInput;
      overlay._handleOverlayKeydown = handleOverlayKeydown;

      // Add listeners with slight delay to prevent immediate closing
      overlay._pendingListenerTimer = setTimeout(() => {
        document.addEventListener('click', handleOutsideClick);
        document.addEventListener('keydown', handleEscapeKey);
        overlay._pendingListenerTimer = null;
      }, 100);
    }

    // Reflect placeholder from localized strings if available
    if (input && window.FoodordScrollNavSearch && FoodordScrollNavSearch.placeholder) {
      input.setAttribute('placeholder', FoodordScrollNavSearch.placeholder);
    }

    function updateSearchWidthClass() {
      const searchBox = nav.querySelector('.foodord-scroll-nav__search');
      if (searchBox) {
        const w = Math.max(searchBox.offsetWidth || 0, 200);
        // Remove existing width classes
        nav.classList.remove('search-width-small', 'search-width-medium', 'search-width-large');
        // Add appropriate width class
        if (w <= 250) {
          nav.classList.add('search-width-small');
        } else if (w <= 320) {
          nav.classList.add('search-width-medium');
        } else {
          nav.classList.add('search-width-large');
        }
      }
    }
    updateSearchWidthClass();
    window.addEventListener('resize', debounce(updateSearchWidthClass, 150), { passive: true });

    // Auto-close overlay when resizing above mobile breakpoint
    window.addEventListener('resize', debounce(function () {
      if (window.innerWidth > 768) {
        const overlay = nav.querySelector('.foodord-scroll-nav__search-overlay');
        if (overlay) { closeSearchOverlay(overlay, false); }
      }
    }, 150), { passive: true });

    // Build an index of products
    function collectSections() {
      return Array.prototype.slice.call(document.querySelectorAll('.foodord-category-section'));
    }
    function collectCardsWithin(section) {
      return Array.prototype.slice.call(section.querySelectorAll('.foodord-product-card')).filter(function (card) {
        return !card.hidden && !card.classList.contains('foodord-product-card--listing-hidden');
      });
    }

    const cache = new WeakMap();
    function cardText(card) {
      if (cache.has(card)) return cache.get(card);
      const title = card.querySelector('.product-title');
      const desc = card.querySelector('.product-description-text');
      const t = norm((title ? title.textContent : '') + ' ' + (desc ? desc.textContent : ''));
      cache.set(card, t);
      return t;
    }

    function setHidden(el, hidden) { el.style.display = hidden ? 'none' : ''; }

    function setCampaignsHidden(hidden) {
      if (!contentRoot) {
        return;
      }

      const campaigns = contentRoot.querySelectorAll('.foodord-products-campaigns');
      campaigns.forEach(function (campaign) {
        setHidden(campaign, hidden);
      });
    }

    function applyFilter(queryRaw) {
      const q = norm(queryRaw);
      const sections = collectSections();
      if (q === '') {
        sections.forEach(function (sec) {
          setHidden(sec, false);
          collectCardsWithin(sec).forEach(function (card) { setHidden(card, false); });
        });
        hideEmptyState(productsRoot);
        setCampaignsHidden(false);
        if (clearBtn) clearBtn.hidden = true;
        return;
      }

      let totalMatches = 0;
      sections.forEach(function (sec) {
        let matchesInSection = 0;
        collectCardsWithin(sec).forEach(function (card) {
          const match = matchesNormalizedQuery(cardText(card), q);
          setHidden(card, !match);
          if (match) matchesInSection++;
        });
        setHidden(sec, matchesInSection === 0);
        totalMatches += matchesInSection;
      });

      if (clearBtn) clearBtn.hidden = (q.length === 0);

      if (totalMatches === 0) {
        const empty = ensureEmptyState(productsRoot, function () { if (input) { input.value = ''; applyFilter(''); input.focus(); } });
        // Hide all sections while empty state is visible
        sections.forEach(function (sec) { setHidden(sec, true); });
        setCampaignsHidden(true);
        empty.style.display = 'flex';
        requestAnimationFrame(keepEmptyStateNearStickyNav);
      } else {
        hideEmptyState(productsRoot);
        setCampaignsHidden(false);
      }
    }

    if (!input) return;

    const debounced = debounce(function () { applyFilter(input.value); }, 180);

    input.addEventListener('input', debounced);
    input.addEventListener('keydown', function (e) { if (e.key === 'Enter') { e.preventDefault(); applyFilter(input.value); } });

    // Handle search button click - mobile overlay or normal search
    if (runBtn) {
      runBtn.addEventListener('click', function () {
        if (isMobile()) {
          openSearchOverlay();
        } else {
          applyFilter(input.value);
        }
      }, { passive: true });
    }

    // Handle search container click on mobile for opening overlay
    const searchContainer = nav.querySelector('.foodord-scroll-nav__search');
    if (searchContainer) {
      searchContainer.addEventListener('click', function (e) {
        if (isMobile() && !e.target.closest('input')) {
          openSearchOverlay();
        }
      }, { passive: true });
    }

    document.addEventListener('click', function (e) {
      if (!input || !input.value) {
        return;
      }
      if (!nav.contains(e.target)) {
        const card = e.target.closest('.foodord-product-card');
        const inModal = e.target.closest('.foodord-modal') || e.target.closest('.foodord-modal-overlay') || document.body.classList.contains('foodord-modal-open');

        if (inModal) {
          return;
        }

        input.value = '';
        const overlay = nav.querySelector('.foodord-scroll-nav__search-overlay');
        if (overlay && overlay.querySelector('.foodord-scroll-nav__search-overlay-input')) {
          overlay.querySelector('.foodord-scroll-nav__search-overlay-input').value = '';
        }
        applyFilter('');
        if (clearBtn) {
          clearBtn.hidden = true;
        }

        if (card) {
          const section = card.closest('.foodord-category-section');
          if (section) {
            setTimeout(() => {
              const hadModalOpen = document.body.classList.contains('foodord-modal-open');
              if (hadModalOpen) document.body.classList.remove('foodord-modal-open');
              const y = section.getBoundingClientRect().top + window.scrollY - 90;
              window.scrollTo(0, y);
              if (hadModalOpen) document.body.classList.add('foodord-modal-open');
            }, 10);
          }
        }
      }
    }, { passive: true });

    input.addEventListener('blur', function () {
      setTimeout(() => {
        if (!input.value) {
          return;
        }
        const overlay = nav.querySelector('.foodord-scroll-nav__search-overlay');
        const overlayOpen = overlay && overlay.classList.contains('is-open');
        const active = document.activeElement;

        if (overlayOpen || (active && nav.contains(active))) {
          return;
        }

        if (document.body.classList.contains('foodord-modal-open') || (active && active.closest('.foodord-product-card'))) {
          return;
        }

        input.value = '';
        if (overlay && overlay.querySelector('.foodord-scroll-nav__search-overlay-input')) {
          overlay.querySelector('.foodord-scroll-nav__search-overlay-input').value = '';
        }
        applyFilter('');
        if (clearBtn) {
          clearBtn.hidden = true;
        }
      }, 120);
    });

    if (clearBtn) { clearBtn.addEventListener('click', function () { input.value = ''; applyFilter(''); input.focus(); }); }
  });
})();
