// Search functionality
(function initSearch(){
  const searchInput = document.getElementById('search-input');
  const ddgButton = document.getElementById('ddg-search-btn');
  
  // DuckDuckGo search function
  function searchDuckDuckGo() {
    const query = searchInput.value.trim();
    if (query) {
      const ddgUrl = `https://duckduckgo.com/?q=${encodeURIComponent(query)}`;
      window.open(ddgUrl, '_blank', 'noopener,noreferrer');
    }
  }
  
  // Add click handler for DDG button
  if (ddgButton) {
    ddgButton.addEventListener('click', (e) => {
      e.preventDefault();
      searchDuckDuckGo();
    });
  }
  
  // Add Enter key handler for DDG search
  searchInput.addEventListener('keydown', (e) => {
    if (e.key === 'Enter') {
      e.preventDefault();
      searchDuckDuckGo();
    }
  });
  
  // Wait for services to load
  const checkServicesLoaded = setInterval(() => {
    if(window.servicesData){
      clearInterval(checkServicesLoaded);
      setupSearch();
    }
  }, 100);
  
  function setupSearch(){
    const { allServices, container } = window.servicesData;
    
    searchInput.addEventListener('input', (e) => {
      const searchTerm = e.target.value.toLowerCase().trim();
      let visibleCount = 0;
      
      // Also hide/show group headers
      const groupSections = container.querySelectorAll('.service-group');
      
      allServices.forEach(card => {
        const serviceName = card.dataset.serviceName;
        if(serviceName.includes(searchTerm)){
          card.style.display = '';
          visibleCount++;
        } else {
          card.style.display = 'none';
        }
      });
      
      // Hide empty groups
      groupSections.forEach(section => {
        const visibleCards = section.querySelectorAll('.service-card:not([style*="display: none"])');
        section.style.display = visibleCards.length > 0 ? '' : 'none';
      });
      
      // Show message if no results
      const existingMsg = container.querySelector('.no-results');
      if(existingMsg) existingMsg.remove();
      if(visibleCount === 0 && searchTerm !== ''){
        const msg = document.createElement('p');
        msg.className = 'notes no-results';
        msg.textContent = `No services found matching "${e.target.value}". Press Enter to search on DuckDuckGo.`;
        container.appendChild(msg);
      }
    });

    // Focus search on '/' key
    document.addEventListener('keydown', (e) => {
      if(e.key === '/' && document.activeElement !== searchInput){
        e.preventDefault();
        searchInput.focus();
      }
    });
  }
})();
