const messages = document.getElementById('messages')
const chat = document.getElementById('chat')
const checkBox = document.getElementById('check-scroll-checkbox')
const cachedMessages = localStorage.getItem('messages') ? JSON.parse(localStorage.getItem('messages')) : []
const maxMessages = 50

for (const message of cachedMessages) {
    updateMessages(message)
}

function updateMessages({message, stringifiedMessage}) {
    const el = document.createElement('div')
    el.innerHTML = `
    <h1 class="text-xl">
         ${message}
    </h1>
`
    el.className = 'border-2 rounded-xl border-white m-3 p-3 bg-gray-950 transition-all ease-in-out hover:bg-gray-800 hover:cursor-pointer'
    messages.appendChild(el)
    el.onclick = async () => {
        if (navigator.clipboard) {
            await navigator.clipboard.writeText(stringifiedMessage)
        } else {
            const el = document.createElement('textarea')
            el.value = stringifiedMessage
            document.body.appendChild(el)
            el.select()
            document.execCommand('copy')
            document.body.removeChild(el)
        }
    }
    if (checkBox.checked) {
        chat.scrollTop = chat.scrollHeight
    }
    localStorage.setItem('messages', JSON.stringify(cachedMessages))
}

socket.on('message', (data) => {
    if (cachedMessages.length > maxMessages) {
        cachedMessages.shift()
    }
    cachedMessages.push(data)
    updateMessages(data)
})
