let LangLettersUp = [];
let currentLang = "";
let currentLetter = "";
let global_scale = 1;

function customUpper(txt, upper = true) {
    search = "άέήίύόώΰΐϊϋçéáàèùâêîôûëïüìòõñãäöß";
    repla = "αεηιυοωυιιυceaaeuaeioueiuioonaaos";
    for (let b = 0; b < search.length; b++) {
        patt = new RegExp(search[b], "g");
        txt = txt.replace(patt, repla[b]);
    }
    return upper ? txt.toUpperCase() : txt;
}

function setImageMargin() {
    $(".accordion-body img").css({
        margin: 10 * global_scale + "px " + 16 * global_scale + "px",
        marginLeft: "1px",
    });
}

function renderResults(words) {
    let results_html = "";
    let wordsLower = [];

    for (a in words) {
        word = words[a];
        words[a] = customUpper(word.toLowerCase());
        wordsLower[words[a]] = word;
    }

    words = $.unique(words).sort();

    for (a in words) {
        word = words[a];

        results_html += `
                        <div class="accordion-item">

                        <h2 class="accordion-header" id="word-${a}">
                        <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#word-body-${a}" aria-expanded="false" aria-controls="word-body-${a}">
                            ${wordsLower[word]}
                        </button>
                        </h2>

                        <div id="word-body-${a}" class="accordion-collapse collapse" aria-labelledby="word-${a}" data-bs-parent="#accordionResults">
                        <div class="accordion-body" tabindex="0"></div>
                        </div>
                    </div>\n
                    `;
    }

    $("#accordionResults").empty().html(results_html);
    $("#total_results span").text(words.length);
    $("#total_results").hide().fadeIn(800);

    // Lazy Loading accordion body text on accordion item click
    $(".accordion-button").on("click", function () {
        let word = $.trim($(this).text());
        let txt = "";

        for (i in data[currentLang]) {
            if ($.trim(data[currentLang][i][0]) == word) {
                txt = `<b>${word}:</b> \n\n` + $.trim(data[currentLang][i][1]);
                $(this)
                    .closest(".accordion-item")
                    .find(".accordion-body")
                    .html(txt + ' <span class="clearfix"></span>');
                setImageMargin();
            }
        }
        MathJax.typeset();
    });
}

function getWords(search = "") {
    let words = [];
    let word = (wordUp = searchUp = "");

    searchUp = customUpper(search.toLowerCase());

    if (search.length === 1) {
        currentLetter = customUpper(search.charAt(0).toLowerCase());
    }

    for (let a = 0; a < data[currentLang].length; a++) {
        word = $.trim(data[currentLang][a][0]);

        if (search.length < 2) {
            if (customUpper(word.charAt(0).toLowerCase()) == currentLetter) {
                words.push(word);
            }
        } else {
            wordUp = customUpper(word.toLowerCase());
            if (wordUp.indexOf(searchUp) === 0) {
                words.push(word);
            }
        }
    }

    if (search.length > 1 && words.length < 1) {
        for (let a = 0; a < data[currentLang].length; a++) {
            word = $.trim(data[currentLang][a][0]);
            wordUp = customUpper(word.toLowerCase());

            if (wordUp.indexOf(searchUp) != -1) {
                words.push(word);
            }
        }
    }

    if (search.length > 0) {
        if (search.length > 1) {
            currentLetter = "";
        }
        setActiveLetter();
    }
    renderResults(words);
}

function setActiveLetter() {
    let letter = "";
    $("#letters button").removeClass("active");
    $("#letters button").each(function (i) {
        letter = $.trim($(this).text());

        if (letter == currentLetter) {
            $(this).addClass("active");
            return true;
        }
    });
}

function showLetters(lang) {
    lettters_html = "";
    for (let a = 0; a < LangLettersUp[lang].length; a++) {
        letter = LangLettersUp[lang][a];
        lettters_html += '<button type="button" class="btn btn-sm btn-light" aria-label="' + letter + '">' + letter + "</button>\n";
    }

    $("#letters").empty().html(lettters_html);
    $("#letters button:first").addClass("active");

    currentLetter = $.trim($("#letters button:first").text());

    // -- Letter clicked ----
    $("#letters button").on("click", function () {
        $("#letters button").removeClass("active");
        $(this).addClass("active");
        currentLetter = $.trim($(this).text());
        getWords();
    });
    getWords();
}

// ---------- Get letters by Lang --------------------
for (lang in data) {
    LangLettersUp[lang] = [];
    for (let a = 0; a < data[lang].length; a++) {
        LangLettersUp[lang].push(
            customUpper(data[lang][a][0].charAt(0).toLowerCase())
        );
    }
    LangLettersUp[lang] = $.unique(LangLettersUp[lang].sort());
}

// --------- Language select --------------------
let select_html = "";

for (lang in LangLettersUp) {
    select_html += '<option value="' + lang + '">' + lang + "</option>\n";
}

$("#select_lang").change(function () {
    currentLang = $(this).val();
    showLetters(currentLang);
});

$("#select_lang").empty().html(select_html);
$("#select_lang option:first").attr("selected", "selected").change();

// ----------- Search -----------
$("#search_button").on("click", function () {
    let search = $.trim($("#search").val());
    getWords(search);
});

$("#search").on("keyup", function (e) {
    if (e.keyCode == 13) {
        $("#search_button").click();
    }
});

$("body").on("click", ".accordion-body img", function () {
    $("#imageModal .modal-body").empty().html($(this).parent().html());
    $("#imageModal").modal("show");
});