document.addEventListener('DOMContentLoaded', function() {
var searchInput = document.getElementById('searchInput');
var suggestions = document.getElementById('autocomplete-suggestions');
if (!searchInput || !suggestions) {
console.error('Elements not found!');
return;
}
searchInput.addEventListener('input', function() {
var query = this.value.trim();
if (query.length < 2) {
suggestions.style.display = 'none';
return;
}
// Get site code from URL
var path = window.location.pathname.split('/');
var siteCode = path.length > 1 && path[1] ? path[1] : 'shop';
var url = '/' + siteCode + '/search/autocomplete?q=' + encodeURIComponent(query);
fetch(url)
.then(function(response) { return response.json(); })
.then(function(data) {
if (data.length === 0) {
suggestions.innerHTML = 'No products found
';
suggestions.style.display = 'block';
return;
}
var html = '';
data.forEach(function(item) {
html += '' + item.name + '';
});
html += 'View all results';
suggestions.innerHTML = html;
suggestions.style.display = 'block';
})
.catch(function(err) {
console.error('Fetch error:', err);
suggestions.innerHTML = 'Error loading suggestions
';
suggestions.style.display = 'block';
});
});
// Hide when clicking outside
document.addEventListener('click', function(e) {
var wrapper = document.querySelector('.search-wrapper');
if (wrapper && !wrapper.contains(e.target)) {
suggestions.style.display = 'none';
}
});
});