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 = KRFS_GLOBALS.user_defined_localization[page];
  var curr_map_strings = KRFS_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">
            <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 .krfs-default-lang-content`).append(textarea);
  }
  declare_textarea_listener();
};

// let sync_regional_data_timer = null;
const sync_regional_data = () => {

  let m_regional_data = [];
  $(".krfs-lang-btn").each(function () {
    if ($(this).hasClass("active")) {
      let lang = $(this).data("lang");
      let ring_size = $(`.krfs-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(() => {
  if (typeof KRFS_GLOBALS !== "undefined") {
    populate_lang_content(KRFS_GLOBALS.initial_page);
  }

  $("#lang_page").on("change", function () {
    var page = $(this).val();
    populate_lang_content(page);
    $("#krfs_language_form input[name='current_page']").val(page);
  });

  $("#save_localization_settings").click(function (e) {
    var page = $("#lang_page").val();
    var m_strings = {};
    var curr_page_strings = KRFS_GLOBALS.user_defined_localization[page];
    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();
      }
      m_strings[str_id] = lang_strings;
    }
    KRFS_GLOBALS.user_defined_localization[page] = m_strings;

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

    $("#krfs_language_form").submit();

  });

  $(".krfs-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");
      $(`.krfs-lang-select-slider[data-lang="${$(this).data("lang")}"]`).css("visibility", isChecked ? "" : "hidden");
      sync_regional_data();

      // 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");
    }
  });

  $(".krfs-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') {
      $("#krfs_language_form input[name='current_tab']").val("translations-tab");
    }else if(id == 'lang-basic-tab') {
      $("#krfs_language_form input[name='current_tab']").val("basic-tab");
    }
  });

  $(".krfs-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");
});
