const chatwin = document.getElementById("chatwin");
const anchor = document.getElementById("anchor");
const specialKeywords = ['sergshemet', 'sergeyshemet', 'sshemet', 'серг', 'серег', 'серёг', 'админ'];
function containsSpecialKeywords(text) {
    const lowerText = text.toLowerCase();
    return specialKeywords.some(keyword => lowerText.includes(keyword.toLowerCase()));
}
function createNewLine(json) {
    json.sort((a, b) => new Date(a.date) - new Date(b.date));
    
    json.forEach(element => {
        let existingMsg = document.getElementById(element["id"]);
        if (existingMsg) {
            existingMsg.innerHTML = element["msg"];
            if (containsSpecialKeywords(element["msg"])) {
                existingMsg.classList.add("highlight-message");
            } else {
                existingMsg.classList.remove("highlight-message");
            }
            return;
        }
        const nameBlock = document.createElement("div");
        nameBlock.className = "nameline " + element["type"];
        if (element["type"] == "donate") {
            nameBlock.innerHTML = element["sendr"] + '<br><p style="color: red">' + element['amount'] + "</p>";
        } else {
            nameBlock.innerHTML = element["sendr"];
        }
        const msgBlock = document.createElement("div");
        msgBlock.className = "msgline";
        msgBlock.innerHTML = element["msg"];
        msgBlock.id = element["id"];
        if (containsSpecialKeywords(element["msg"])) {
            msgBlock.classList.add("highlight-message");
        }
        if (element["type"] == "donate") {
            msgBlock.style.backgroundColor = "#0000FF20";
        }
        const row = document.createElement("div");
        row.className = "chatRow";
        row.setAttribute("name", element["id"]);
        
        row.appendChild(nameBlock);
        row.appendChild(msgBlock);
        chatwin.insertBefore(row, anchor);
        scrollToBottom();
    });
    removeOldMessages(200);
}
function scrollToBottom() {
    setTimeout(() => {
    window.scrollTo({ top: document.body.scrollHeight, behavior: 'smooth' });
    }, 10);
}
function removeOldMessages(maxMessages = 200) {
    const messageRows = document.getElementsByClassName("chatRow");
    const rowsToRemove = messageRows.length - maxMessages;
    
    if (rowsToRemove > 0) {
        for (let i = 0; i < rowsToRemove; i++) {
            if (messageRows[0]) {
                messageRows[0].remove();
            }
        }
    }
}
function requestNewLines() {
    fetch("http://localhost:8008/")
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            createNewLine(data);
        })
        .catch(error => {
            console.error('Error fetching chat messages:', error);
            const errorRow = document.getElementById("error-message");
            if (!errorRow) {
                const errorDiv = document.createElement("div");
                errorDiv.id = "error-message";
                errorDiv.className = "chatRow error";
                errorDiv.innerHTML = '<div class="nameline hello">Maya</div><div class="msgline">Тацуя, демоны отключили сервер чата!</div>';
                chatwin.insertBefore(errorDiv, anchor);
                scrollToBottom();
            }
        });
}
function initChat() {
    scrollToBottom();
    requestNewLines();
    setInterval(requestNewLines, 1000);
}
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initChat);
} else {
    initChat();
}