const SaveAnswersToLocalStorage = () => {
    for (let i = 0; i < questionsArray.length; i++) {
        if (!localStorage.getItem(i)) {
            localStorage.setItem(
                i,
                JSON.stringify(questionsArray[i])
                .slice(1, -1)
                .replace(/"/g, "")
                .replace(",answer", ";answer")
                .replace(/\\/g, "")
                .replace(/“/g, "")
                .replace(/”/g, "")
            );
            break;
        }
    }
};

const cleanAllRubish = (string) => {
    return string.replace(/\s+/g, " ").trim();
};

const questionsArray = [];

for (let i = 0; i < localStorage.length; i++) {
    if (localStorage.getItem(i)) {
        localStorage.removeItem(i);
    }
}

let previousQuestion = "123123";

setInterval(() => {
    const chatMessageElements = document.querySelectorAll(".q-uestion");

    if (
        previousQuestion &&
        previousQuestion != chatMessageElements[0] ? .innerHTML
    ) {
        chatMessageElements.forEach((element) => {
            previousQuestion = chatMessageElements[0] ? .innerHTML;

            const questionText = cleanAllRubish(element.innerText);

            if (
                questionsArray.findIndex(
                    (questionsArrayElement) =>
                    questionsArrayElement.question == questionText
                ) == -1
            ) {
                questionsArray.push({
                    question: questionText,
                    answer: ""
                });
            }
        });
    }

    document.querySelectorAll(".q-answer").forEach((element) => {
        element.addEventListener("click", (event) => {
            if (event.target.closest(".q-answer")) {
                for (let i = 0; i < questionsArray.length; i++) {
                    if (!questionsArray[i].answer) {
                        questionsArray[i].answer = cleanAllRubish(event.target.innerText);
                        SaveAnswersToLocalStorage();
                        break;
                    }
                }
            }
        });
    });
}, 2000);

// setInterval(() => {
//   console.log(questionsArray);
// }, 3000)