$(function(){
 
  let data = [];
  let randerCodeData = [];
  $.getJSON('https://f.cliproxy.com/json/country_code.json', function(jsonData) {
    data = jsonData;
  });


  function fuzzySearch(query, array) {
    const result = [];
    query = query.toLowerCase();
    for (let i = 0; i < array.length; i++) {
        const item = array[i];
        const nameMatch = item.name && item.name.toLowerCase().includes(query);
        const codeMatch = item.code && item.code.toString().includes(query);
        if (nameMatch || codeMatch) {
            result.push(item);
        }
    }
    return result;
  }

  $('.search_input').on('click',function(){
    var search_contant = $('.serach_code').val();
    randerCodeData = fuzzySearch(search_contant, data);
    $('ul>li' ).removeClass('active');
    randerCode();
  })

  $('.load_more').on('click',function(){
    $('.country_cont .more_code:hidden').first().show();
    if ($('.country_cont .more_code:hidden').length === 0) {
      $('.load_more').hide();
    } else {
        $('.load_more').show();
    }
  })

  $('ul>li').on('click',function(){
    $(this).addClass('active').siblings().removeClass('active');
    searchChar($(this).text())
  })

  

  $('.serach_code').on('keydown', function (event) {
    if (event.key === "Enter") {
      var search_contant = $('.serach_code').val();
      randerCodeData = fuzzySearch(search_contant, data);
      $('ul>li' ).removeClass('active');
      randerCode();
        
    }
  });

  
  function randerCode(){
    
    let countryHtml = '';
    randerCodeData.forEach(function(item) {
      countryHtml += `<p><img src="/static/images/country/icon/${item.code.toLowerCase()}.png" alt="" /><span>${item.code}</span><span>${item.name}</span></p>`;
    });
    $('.render_code,.more_code').hide();
    $('.load_more').hide();
    $('.search_counry_conntent').html(countryHtml);
    
  }

  function searchChar(chat){
    $('.serach_code').val('');  
    randerCodeData = data.filter(function(item) {
      return item.char == chat;
    });

    randerCode();
    
  }
})