document.addEventListener('DOMContentLoaded', function() {
    const searchForms = document.querySelectorAll('form[action*="/search"]');
    
    searchForms.forEach(form => {
        const input = form.querySelector('input[name="q"]');
        if (!input) return;
        
        // Create results container and append to body to avoid overflow issues
        const resultsContainer = document.createElement('div');
        resultsContainer.className = 'live-search-results';
        resultsContainer.style.display = 'none';
        
        // Additional inline styles for body appended element
        resultsContainer.style.position = 'absolute';
        resultsContainer.style.zIndex = '999999';
        
        document.body.appendChild(resultsContainer);
        
        // Function to update position
        function updatePosition() {
            const rect = input.getBoundingClientRect();
            resultsContainer.style.top = (rect.bottom + window.scrollY + 8) + 'px';
            resultsContainer.style.left = (rect.left + window.scrollX) + 'px';
            resultsContainer.style.width = rect.width + 'px';
        }
        
        let debounceTimer;
        
        input.addEventListener('input', function() {
            clearTimeout(debounceTimer);
            const query = this.value.trim();
            
            if (query.length < 2) {
                resultsContainer.style.display = 'none';
                return;
            }
            
            debounceTimer = setTimeout(() => {
                const baseUrl = form.action.replace('/search', '');
                
                fetch(`${baseUrl}/api/search?q=${encodeURIComponent(query)}`)
                    .then(response => response.json())
                    .then(data => {
                        resultsContainer.innerHTML = '';
                        
                        if (data.length === 0) {
                            resultsContainer.innerHTML = '<div class="live-search-empty">Sonuç bulunamadı</div>';
                        } else {
                            data.forEach(item => {
                                const link = document.createElement('a');
                                link.href = `${baseUrl}/${item.slug}`;
                                link.className = 'live-search-item';
                                
                                const icon = item.type === 'Uyumluluk Tablosu' ? 'fa-table' : 'fa-file-text-o';
                                
                                link.innerHTML = `
                                    <i class="fa ${icon}"></i>
                                    <div class="live-search-item-content">
                                        <div class="live-search-title">${escapeHtml(item.title)}</div>
                                        <div class="live-search-type">${escapeHtml(item.type)}</div>
                                    </div>
                                `;
                                resultsContainer.appendChild(link);
                            });
                        }
                        
                        updatePosition();
                        resultsContainer.style.display = 'block';
                    })
                    .catch(err => console.error('Live search error:', err));
            }, 250);
        });
        
        // Hide results on outside click
        document.addEventListener('click', function(e) {
            if (!form.contains(e.target) && !resultsContainer.contains(e.target)) {
                resultsContainer.style.display = 'none';
            }
        });
        
        // Show results when focusing input if it has value
        input.addEventListener('focus', function() {
            if (this.value.trim().length >= 2 && resultsContainer.innerHTML !== '') {
                updatePosition();
                resultsContainer.style.display = 'block';
            }
        });

        // Update position on window resize
        window.addEventListener('resize', () => {
            if (resultsContainer.style.display === 'block') {
                updatePosition();
            }
        });
    });
    
    function escapeHtml(unsafe) {
        return unsafe
             .replace(/&/g, "&amp;")
             .replace(/</g, "&lt;")
             .replace(/>/g, "&gt;")
             .replace(/"/g, "&quot;")
             .replace(/'/g, "&#039;");
    }
});
