<div class="fullsearch-container relative w-full max-w-xl mx-auto">
    <input 
        type="text" 
        class="fullsearch-input w-full rounded-none border p-2 border-primary focus:border-primary focus:ring-primary focus:ring-1 focus:outline-none" 
        placeholder="Cerca..."
        autocomplete="off">
    
    <div class="fullsearch-results absolute top-full mt-2 left-0 w-full bg-white border border-gray-300 shadow-lg z-50 hidden">
        <!-- Results will be populated here -->
    </div>
</div>
 
<style>
.price-badge {
    display: inline-flex;
    align-items: center;
    background: linear-gradient(90deg, #e67e22 0%, #f39c12 100%);
    border-radius: 4px;
    padding: 0;
    text-decoration: none;
    color: white;
    font-weight: 600;
    font-size: 16px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    transition: transform 0.2s ease, box-shadow 0.2s ease;
    overflow: hidden;
    position: relative;
}

.price-symbol {
    background: #d35400;
    padding: 4px 8px;
    border-radius: 4px 0 0 4px;
    position: relative;
    text-shadow: 0 1px 2px rgba(0,0,0,0.3);
}
 
.price-symbol::after {
    content: '';
    position: absolute;
    right: -8px;
    top: 50%;
    transform: translateY(-50%);
    width: 0;
    height: 0;
    border-top: 8px solid transparent;
    border-bottom: 8px solid transparent;
    border-left: 8px solid #d35400;
}
 
.price-value {
    padding: 4px 10px;
    background: #f39c12;
    min-width: 60px;
    text-align: center;
    border-radius: 0 4px 4px 0;
    text-shadow: 0 1px 2px rgba(0,0,0,0.3);
}
</style>

<script>
(function() {
    // Inizializza una singola istanza del pannello di ricerca
    function initSearchInstance(container) {
        const searchInput = container.querySelector('.fullsearch-input');
        const searchResults = container.querySelector('.fullsearch-results');
        
        if (!searchInput || !searchResults) {
            return false;
        }
        
        // Evita doppia inizializzazione
        if (container.hasAttribute('data-initialized')) {
            return true;
        }
        
        container.setAttribute('data-initialized', 'true');

        let searchTimeout;
        
        searchInput.addEventListener('input', function() {
            const searchTerm = this.value.trim();
            
            // Clear previous timeout
            clearTimeout(searchTimeout);
        
            // Hide results if search is empty
            if (searchTerm.length === 0) {
                searchResults.classList.add('hidden');
                return;
            }

            // Debounce the search request
            searchTimeout = setTimeout(() => {
                performSearch(searchTerm);
            }, 300);
        });

        // Gestione submit su Enter
        searchInput.addEventListener('keydown', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                const searchTerm = this.value.trim();
                if (searchTerm.length > 0) {
                    window.location.href = `/?sName=${encodeURIComponent(searchTerm)}`;
                }
            }
        });

        // Hide results when clicking outside
        document.addEventListener('click', function(e) {
            if (!container.contains(e.target)) {
                searchResults.classList.add('hidden');
            }
        });

        function performSearch(searchTerm) {
            const url = `/new_files/ajax/fullsearch.php?search_str=${encodeURIComponent(searchTerm)}&ltype=json`;
            
            fetch(url)
                .then(response => response.json())
                .then(data => {
                    displayResults(data);
                })
                .catch(error => {
                    console.error('Search error:', error);
                    searchResults.innerHTML = '<div class="p-3 text-gray-500">Errore durante la ricerca</div>';
                    searchResults.classList.remove('hidden');
                });
        }

        function displayResults(data) {
            if (!data || !Array.isArray(data) || data.length < 2 || !Array.isArray(data[1])) {
                searchResults.innerHTML = '<div class="p-3 text-gray-500">Nessun risultato trovato</div>';
                searchResults.classList.remove('hidden');
                return;
            }

            const items = data[1];
            let resultsHTML = '';

            items.forEach(item => {
                if (item.model) {
                    const hasVideoReview = item.reviewid && item.reviewid !== 0;
                    const hasPrice = item.price && item.price !== 0;
                    resultsHTML += `
                    <div class="flex items-center h-20 justify-between gap-0 border-b border-gray-200 last:border-b-0 select-none">
                        <div class="p-0 lg:p-2 w-2/12 lg:w-1/12 flex items-center justify-center">
                            <a href="${item.link || '/new_files/redirs/model.php?id=' + item.id}">
                                <img style="height:40px" class="object-contain" src="${item.image_url}">
                            </a>
                        </div>
                        <div class="p-2 w-6/12 lg:w-4/12 flex items-center">
                            <a href="${item.link || '/new_files/redirs/model.php?id=' + item.id}" class="text-sm hover:underline hover:text-red-600 hover:decoration-black">
                                ${item.producer_name} ${item.model}
                            </a>
                        </div>
                        <div class="p-2 w-2/12 hidden lg:flex items-center justify-center">
                            ${(!item.product_type || item.product_type === 'smartphone') ? `<a href="/compara/${item.id}.html" data-type="0" data-id="${item.id}" data-model="${item.model}" data-maker="${item.maker_name}" data-imageid="${item.imageid}" class="flex items-center gap-2">` : '<div class="flex items-center gap-2 opacity-0">'}
                                <span class="flex items-center justify-center border border-gray-200 rounded-full p-1">
                                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="size-3">
                                        <path stroke-linecap="round" stroke-linejoin="round" d="M12 4.5v15m7.5-7.5h-15" />
                                    </svg>
                                </span>
                                <span class="text-xs hover:underline">
                                    Compara
                                </span>
                            ${(!item.product_type || item.product_type === 'smartphone') ? '</a>' : '</div>'}
                        </div>
                        <div class="p-2 w-3/12 hidden lg:flex items-center justify-center">
                            ${hasVideoReview ? `
                            <a href="/new_files/redirs/videoreview.php?id=${item.id}" class="video_review flex items-center gap-2">
                                <div class="color_video relative text-white">
                                    <img src="${item.rimage_url}?w=63&amp;h=42" width="63" height="42">
                                    <div class="absolute top-0 left-0 w-full h-full bg-black/30"></div>
                                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="size-6 absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2">
                                        <path fill-rule="evenodd" d="M2.25 12c0-5.385 4.365-9.75 9.75-9.75s9.75 4.365 9.75 9.75-4.365 9.75-9.75 9.75S2.25 17.385 2.25 12Zm14.024-.983a1.125 1.125 0 0 1 0 1.966l-5.603 3.113A1.125 1.125 0 0 1 9 15.113V8.887c0-.857.921-1.4 1.671-.983l5.603 3.113Z" clip-rule="evenodd" />
                                    </svg>
                                </div>
                                <span class="text-xs text-slate-500 leading-3">Video Review</span>
                            </a>
                            ` : ''}
                        </div>
                        <div class="p-2 w-4/12 lg:w-2/12 flex items-center justify-center">
                             ${hasPrice ? `
                             <a href="${(item.link || '').replace("schede-tecniche","prezzi") || '/new_files/redirs/price.php?id=' + item.id}" class="price-badge" target="_blank">
                                 <span class="price-symbol">&euro;</span>
                                 <span class="price-value">${item.price}</span>
                             </a>
                             ` : ''}
                         </div>
                    </div>`;
                }
            });

            if (resultsHTML === '') {
                resultsHTML = '<div class="p-3 text-gray-500">Nessun risultato trovato</div>';
            }

            searchResults.innerHTML = resultsHTML;
            searchResults.classList.remove('hidden');
        }
        
        return true;
    }
    
    // Inizializza tutte le istanze del pannello di ricerca
    function initAllSearchPanels() {
        const containers = document.querySelectorAll('.fullsearch-container:not([data-initialized])');
        containers.forEach(container => {
            initSearchInstance(container);
        });
    }
    
    // Prova ad inizializzare quando il DOM è pronto
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', function() {
            setTimeout(initAllSearchPanels, 100);
        });
    } else {
        setTimeout(initAllSearchPanels, 100);
    }
    
    // Inizializza anche quando il pannello diventa visibile (Alpine.js)
    // Usa un observer per rilevare quando search-menu diventa visibile
    const observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            if (mutation.type === 'attributes' && mutation.attributeName === 'style') {
                const searchMenu = document.getElementById('search-menu');
                if (searchMenu && searchMenu.style.display !== 'none') {
                    setTimeout(initAllSearchPanels, 50);
                }
            }
        });
    });
    
    // Avvia l'observer quando il DOM è pronto
    function startObserver() {
        const searchMenu = document.getElementById('search-menu');
        if (searchMenu) {
            observer.observe(searchMenu, { attributes: true, attributeFilter: ['style'] });
        } else {
            setTimeout(startObserver, 100);
        }
    }
    
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', startObserver);
    } else {
        startObserver();
    }
})();
</script>