(function($){
  const $input = $('.site-header__search-input');
  const $container = $('<ul class="site-header__search-suggestions"></ul>').insertAfter($input);
  let timer;

  $input.on('keyup', function(){
    const term = $(this).val().trim();
    clearTimeout(timer);
    if (term.length < 2) {
      $container.empty().hide();
      return;
    }
    timer = setTimeout(() => {
      $.getJSON(pandaLiveSearch.ajax_url, {
        action: 'live_search',
        term: term
      }).done(function(results){
        $container.empty();
        if (results.length) {
          results.forEach(item => {
            $container.append(
              `<li>
                 <a href="${item.permalink}">
                   <img src="${item.thumb}" alt=""/> 
                   ${item.title}
                 </a>
               </li>`
            );
          });
          $container.show();
        } else {
          $container.hide();
        }
      });
    }, 300);
  });

  $(document).on('click', function(e){
    if (!$(e.target).closest('.site-header__search-input, .site-header__search-suggestions').length) {
      $container.hide();
    }
  });
})(jQuery);
