// Eryn Wells <eryn@erynwells.me>

document.addEventListener("DOMContentLoaded", (event) => {
    const furiganaRegex = /(「(.*?)『(.*?)』」)|.*/g;

    let parseFlashcardString = str => {
        let innerHTML = "";

        for (let match of str.matchAll(furiganaRegex)) {
            if (match[2] && match[3]) {
                const mainText = match[2];
                const furiganaText = match[3];
                console.debug(`${mainText} is ${mainText.length} characters long`);
                innerHTML += `<ruby>${mainText}<rp>(</rp><rt>${furiganaText}</rt><rp>)</rp></ruby>`;
            } else {
                innerHTML += match[0];
            }
        }

        return innerHTML;
    };

    let cardsContainer = document.querySelector("section.flashcards > ul");
    if (!cardsContainer) {
        console.error("Can't find flashcards <ul> element");
        return;
    }

    for (let card of flashcards.cards) {
        let frontElement = `<div class="front" lang="${card.front.lang}">${parseFlashcardString(card.front.value)}</div>`;
        let backElement = `<div class="back" lang="${card.back.lang}">${parseFlashcardString(card.back.value)}</div>`;

        let cardElement = document.createElement("div");
        cardElement.classList.add("card")
        cardElement.innerHTML = frontElement + backElement;

        cardElement.addEventListener("click", (event) => {
            let element = event.target;
            console.log("Flipping", element);
            element.classList.toggle("flipped");
        }, true);

        let cardContainerElement = document.createElement("li");
        cardContainerElement.classList.add("card-container");
        cardContainerElement.appendChild(cardElement);

        cardsContainer.appendChild(cardContainerElement);
    }
});
