const textarea_limit = 250;

const declare_textarea_listener = () => {
  $(".lang-content textarea").off();
  $(".lang-content textarea").on("input", function () {
    if ($(this).val().length > textarea_limit) {
      $(this).val($(this).val().substring(0, textarea_limit));
    }
    var text = $(this).val();
    var count = text.length;
    $(this).next("div.textarea-count").children("span").text(`${count} / ${textarea_limit}`);
  });
};

const extract_heading_from_string = (str) => {
  let heading = str.match(/\{\{(.*?)\}\}/);
  if(heading != null) {
    heading = heading[0].replace(/\{\{/g, '').replace(/\}\}/g, '');
    str = str.replace(/\{\{.*?\}\}/, '').trim();
  }else{
    heading = "";
  }
  return {heading, str};
}

const populate_lang_content = (page) => {
  var curr_page_strings = KIRB_GLOBALS.user_defined_localization[page];
  var curr_map_strings = KIRB_GLOBALS.user_defined_localization_map[page];

  $(".tab-page-lang .lang-content").html("");
  for (let str_id in curr_page_strings) {
    let strings = curr_page_strings[str_id];
    let {heading, def_str} = extract_heading_from_string(curr_map_strings[str_id]);
    
    for (let lang in strings) {
      let heading_code = heading ? `<div class="text-left w-100" style="padding: 5px 20px;font-weight:400;">${heading}</div>` : '';
      let textarea = `
        <div class="textarea-div">
            ${heading_code}
            <textarea data-string="${str_id}" data-lang="${lang}">${strings[lang]}</textarea>
            <div class="textarea-count">
                <span>${strings[lang].length} / ${textarea_limit}</span>
                <div class="language-pera-div">
                    <svg class="lang-img" width="15" height="15" viewBox="0 0 15 15" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M7.44183 13.3337L10.096 6.33366H11.321L13.9752 13.3337H12.7502L12.1231 11.5545H9.29391L8.66683 13.3337H7.44183ZM2.8335 11.5837L2.01683 10.767L4.96266 7.82116C4.62239 7.48088 4.3137 7.09199 4.03662 6.65449C3.75954 6.21699 3.50433 5.72116 3.271 5.16699H4.496C4.69044 5.54616 4.88489 5.87671 5.07933 6.15866C5.27377 6.4406 5.50711 6.72255 5.77933 7.00449C6.10016 6.68366 6.43315 6.23401 6.77829 5.65553C7.12343 5.07706 7.3835 4.52533 7.5585 4.00033H1.0835V2.83366H5.16683V1.66699H6.3335V2.83366H10.4168V4.00033H8.72516C8.521 4.70033 8.21475 5.41977 7.80641 6.15866C7.39808 6.89755 6.99461 7.46144 6.596 7.85033L7.996 9.27949L7.5585 10.4753L5.77933 8.65241L2.8335 11.5837ZM9.6585 10.5337H11.7585L10.7085 7.55866L9.6585 10.5337Z" fill="#838383"/></svg>
                    <p>Comming Soon!</p>
                </div>
            </div>
        </div>`;
      $(`.tab-page-lang .lang-content[data-lang="${lang}"]`).append(textarea);
    }
  }

  // populate default lang content separately
  for (let str_id in curr_map_strings) {
    let {heading, str} = extract_heading_from_string(curr_map_strings[str_id]);
    let heading_code = heading ? `<div class="text-left w-100" style="padding: 5px 20px;font-weight:400;">${heading}</div>` : '';
    var textarea = `
            <div class="textarea-div">
                ${heading_code}
                <textarea disabled>${str}</textarea>
                <div class="textarea-count">
                    <span>${str.length} / ${textarea_limit}</span>
                </div>
            </div>`;
    $(`.tab-page-lang .kirb-default-lang-content`).append(textarea);
  }
  declare_textarea_listener();
};


const sync_regional_data = () => {
  
    let m_regional_data = [];
    $(".kirb-lang-btn").each(function () {
      if ($(this).hasClass("active")) {
        let lang = $(this).data("lang");
        let ring_size = $(`.kirb-lang-select-slider[data-lang='${lang}']`).val();
        ring_size = ring_size ? ring_size : '';
        m_regional_data.push({lang,ring_size});
      }
    });
    $("input[name='regional_lang_data']").val(JSON.stringify(m_regional_data));
};

$(document).ready(() => {
  populate_lang_content(KIRB_GLOBALS.initial_page);
  $("#lang_page").on("change", function () {
    var page = $(this).val();
    populate_lang_content(page);
    $("#kirb_language_form input[name='current_page']").val(page);
  });

  $("#save_localization_settings").click(function (e) {
    e.preventDefault();
    var page = $("#lang_page").val();
    var m_strings = {};
    var curr_page_strings = KIRB_GLOBALS.user_defined_localization[page];
    let blank_flg = false;
    for (let str_id in curr_page_strings) {
      let strings = curr_page_strings[str_id];
      let lang_strings = {};
      for (let lang in strings) {
        var text = $(
          `.tab-page-lang .lang-content[data-lang="${lang}"] textarea[data-string="${str_id}"][data-string="${str_id}"]`
        ).val();
        text = text.replace(/"/g, '\\"');
        lang_strings[lang] = text.trim();
        if(lang_strings[lang].length == 0) {
          blank_flg = true;
        }
      }
      m_strings[str_id] = lang_strings;
    }
    KIRB_GLOBALS.user_defined_localization[page] = m_strings;

    if(blank_flg) {
      alert("All fields are required, no field can be left blank.");
      return;
    }

    $("#kirb_language_form input[name='user_defined_localization']").val(
      JSON.stringify(KIRB_GLOBALS.user_defined_localization)
    );

    let other_lang_data = {}
    $(".other_lang_group .other_lang_translations").each(function(){
      other_lang_data[$(this).data("key")] = $(this).val();
    });
    
    $("#kirb_language_form input[name='other_lang_data']").val(
      JSON.stringify(other_lang_data)
    );

    $("#kirb_language_form").submit();
  });

  $(".kirb-lang-btn").click(function () {
    if($(this).data("lang") != 'en_US') {
      $(this).toggleClass("active");
      $(`#lang-${$(this).data("lang")}-btn`).toggle();
      if($(`#lang-${$(this).data("lang")}-btn`).hasClass("active")) {
        $(`#lang-en_US-btn`).click();
      }
      let isChecked = $(this).find("input").prop("checked");
      $(`.kirb-lang-select-slider[data-lang="${$(this).data("lang")}"]`).css("visibility", isChecked ? "" : "hidden");
      sync_regional_data();

      // UI Update To Language Tab
      $(".tab-section-lang button").removeClass("last");
      $('.tab-section-lang button').filter(function() {
        return $(this).css('display') !== 'none';
      }).last().addClass("last");

      if($(this).data("lang") == 'other') {
        $(".kirb-other-lang-section").toggle(isChecked);
      }
    }
  });

  $(".kirb-lang-select-slider").on("change", function () {
    sync_regional_data();
  });

  $("#lang-trans-tab, #lang-basic-tab").click(function () {
    let id = this.id;
    if(id == 'lang-trans-tab') {
      $("#kirb_language_form input[name='current_tab']").val("translations-tab");
    }else if(id == 'lang-basic-tab') {
      $("#kirb_language_form input[name='current_tab']").val("basic-tab");
    }
  });

  $(".kirb-lang-plus").click(() => {
    $("#lang-basic-tab").click();
  });

  // Minor UI Update To Language Tab
  $(".tab-section-lang button").removeClass("last");
  $('.tab-section-lang button').filter(function() {
    return $(this).css('display') !== 'none';
  }).last().addClass("last");
});
