(function(){
'use strict';
document.addEventListener('DOMContentLoaded', function(){
initAutocomplete();
});
function initAutocomplete(){
var inputs=document.querySelectorAll('.cek-autocomplete-product');
if(inputs.length===0) return;
var config=window.cekContactConfig||{
ajaxUrl: '/wp-admin/admin-ajax.php',
productSearchNonce: ''
};
inputs.forEach(function(input){
var dropdown=null;
var debounceTimer=null;
input.addEventListener('input', function(){
var val=sanitizeText(this.value);
if(val.length < 3){
hideDropdown();
return;
}
clearTimeout(debounceTimer);
debounceTimer=setTimeout(function(){
searchProducts(val, input);
}, 300);
});
input.addEventListener('blur', function(){
setTimeout(hideDropdown, 200);
});
function searchProducts(term, inputEl){
var formData=new FormData();
formData.append('action', 'cekonay_search_products');
formData.append('term', term);
formData.append('nonce', config.productSearchNonce||'');
fetch(config.ajaxUrl, {
method: 'POST',
body: formData,
credentials: 'same-origin'
})
.then(function(r){ return r.json(); })
.then(function(r){
if(r.success&&r.data&&r.data.length > 0){
showDropdown(r.data, inputEl);
}else{
hideDropdown();
}})
.catch(function(){
hideDropdown();
});
}
function showDropdown(products, inputEl){
hideDropdown();
dropdown=document.createElement('div');
dropdown.className='cek-autocomplete-dropdown';
products.forEach(function(p){
var item=document.createElement('div');
item.className='cek-autocomplete-item';
item.textContent=sanitizeText(p.name);
item.addEventListener('mousedown', function(e){
e.preventDefault();
inputEl.value=sanitizeText(p.name);
hideDropdown();
});
dropdown.appendChild(item);
});
inputEl.parentNode.style.position='relative';
inputEl.parentNode.appendChild(dropdown);
}
function hideDropdown(){
if(dropdown&&dropdown.parentNode){
dropdown.parentNode.removeChild(dropdown);
}
dropdown=null;
}});
}
function sanitizeText(v){
return (v||'').replace(/<[^>]*>/g, '').trim();
}})();