// AJAX Search - Simple and Clean
document.addEventListener('DOMContentLoaded', function() {
    const searchInputs = document.querySelectorAll('.ajax-search-input');
    
    searchInputs.forEach(function(searchInput) {
        const searchContainer = searchInput.closest('.ajax-search-container');
        if (!searchContainer) {
            return;
        }
        
        const searchResults = searchContainer.querySelector('.ajax-search-results');
        if (!searchResults) {
            return;
        }
        
        let searchTimeout;
        
        searchInput.addEventListener('input', function() {
            const query = this.value.trim();
            
            clearTimeout(searchTimeout);
            
            if (query.length < 2) {
                searchResults.classList.remove('active');
                return;
            }
            
            searchResults.innerHTML = '<div class="search-loading">Searching...</div>';
            searchResults.classList.add('active');
            
            searchTimeout = setTimeout(() => {
                performSearch(query, searchResults);
            }, 300);
        });
        
        // Close on outside click
        document.addEventListener('click', function(e) {
            if (!searchInput.contains(e.target) && !searchResults.contains(e.target)) {
                searchResults.classList.remove('active');
            }
        });
        
        // Close on ESC key
        searchInput.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                searchResults.classList.remove('active');
            }
        });
    });
    
    function performSearch(query, searchResults) {
        // Get site base URL - use current page origin and path
        const pathParts = window.location.pathname.split('/').filter(p => p);
        let basePath = '';
        
        // If we have path parts, the first one is likely the site folder
        if (pathParts.length > 0) {
            basePath = '/' + pathParts[0];
        }
        
        const searchUrl = window.location.origin + basePath + '/ajax_search.php?q=' + encodeURIComponent(query);
        
        fetch(searchUrl)
            .then(response => response.json())
            .then(data => {
                displayResults(data, query, searchResults);
            })
            .catch(error => {
                searchResults.innerHTML = '<div class="search-error">Search failed. Please try again.</div>';
            });
    }
    
    function displayResults(data, query, searchResults) {
        const { stores, categories } = data;
        
        if (stores.length === 0 && categories.length === 0) {
            searchResults.innerHTML = '<div class="search-no-results">No results found</div>';
            return;
        }
        
        let html = '';
        
        // Display stores
        if (stores.length > 0) {
            html += '<div class="search-section">';
            html += '<div class="search-section-title">in Stores</div>';
            
            stores.forEach(store => {
                const couponText = store.coupon_count + ' Coupon' + (store.coupon_count != 1 ? 's' : '') + ' Available';
                html += `
                    <a href="store/${store.store_slug}" class="search-item">
                        <div class="search-item-content">
                            <div class="search-item-title">
                                <span class="search-coupon-count">${couponText}</span>
                                ${highlightText(store.store_title, query)}
                            </div>
                            <div class="search-item-meta">in Stores</div>
                        </div>
                    </a>
                `;
            });
            
            html += '</div>';
        }
        
        // Display categories
        if (categories.length > 0) {
            html += '<div class="search-section">';
            html += '<div class="search-section-title">in Categories</div>';
            
            categories.forEach(category => {
                const storeText = category.store_count + ' Store' + (category.store_count != 1 ? 's' : '');
                html += `
                    <a href="category/${category.category_slug}" class="search-item">
                        <div class="search-item-content">
                            <div class="search-item-title">
                                <span class="search-coupon-count">${storeText}</span>
                                ${highlightText(category.category_title, query)}
                            </div>
                            <div class="search-item-meta">in Categories</div>
                        </div>
                    </a>
                `;
            });
            
            html += '</div>';
        }
        
        searchResults.innerHTML = html;
    }
    
    function highlightText(text, query) {
        const regex = new RegExp('(' + query + ')', 'gi');
        return text.replace(regex, '<span class="highlight">$1</span>');
    }
});
