// Chatbox controls for the Daily Tarot Game
let socket;
let isCardNameSent = false;
let chatWrapper, gameType, tokenUrl, webSocketUrl, startChatButton, overlay, formClone;

function initializeChat() {

    chatWrapper = document.querySelector('.tah_chat-wrapper');
    gameType = chatWrapper ? chatWrapper.getAttribute('data-game-type') : null;
    tokenUrl = chatWrapper ? chatWrapper.getAttribute('data-token-url') : null;
    webSocketUrl = chatWrapper ? chatWrapper.getAttribute('data-ws-url') : null;
    startChatButton = document.getElementById('startChatButton');
    overlay = document.getElementById('overlay');
    formClone = document.querySelector('.tah_form') ? document.querySelector('.tah_form').cloneNode(true) : null;

    if (startChatButton) {
        startChatButton.replaceWith(startChatButton.cloneNode(true));
        startChatButton = document.getElementById('startChatButton');

        startChatButton.addEventListener('click', () => {
            if (overlay) overlay.style.display = 'none';
            const bodyData = { security: chatboxSettings.token_nonce };
            fetch(tokenUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(bodyData)
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Token request failed with status: ' + response.status);
                    }
                    return response.json();
                })
                .then(data => {
                    const token = data.token;
                    if (!token) {
                        throw new Error('No token in response');
                    }
                    socket = new WebSocket(`${webSocketUrl}?token=${token}&message_count=${chatboxSettings.messageCap}`);
                    socket.addEventListener('close', handleConnectionClosed);
                    socket.addEventListener('open', sendCardName);
                    socket.addEventListener('message', event => {
                        const message = JSON.parse(event.data);
                        displayMessage(message.message);
                    });
                })
                .catch(error => {
                    displayMessage('Failed to connect to chat server');
                });
        });
    }

    const form = document.querySelector('.tah_form');
    if (form) form.addEventListener('submit', handleSubmit);
}

function sendCardName() {
    if (!isCardNameSent) {
        const cardName1 = document.getElementById('dailyTarotCardName').textContent;
        const message = { cardName1: cardName1 };
        socket.send(JSON.stringify(message));
        isCardNameSent = true;
        const welcomeMessage = chatboxSettings.tahChatWelcomeMessage || 'Hello, please ask me your question.';
        displayMessage(welcomeMessage);
    }
}

function handleSubmit(event) {
    event.preventDefault();
    const inputField = document.querySelector('input[name="message"]');
    const message = inputField.value;

    if (message.trim() !== '') {
        const messagesContainer = document.querySelector('.tah_messages');
        const messageContainer = document.createElement('div');
        messageContainer.classList.add('tah_user-message');

        messageContainer.style.backgroundColor = chatboxSettings.userMessageBgColor;
        messageContainer.style.color = chatboxSettings.userMessageFontColor;
        messageContainer.style.fontSize = chatboxSettings.userMessageFontSize;
        messageContainer.style.fontFamily = chatboxSettings.userMessageFontFamily;

        const pElement = document.createElement('p');
        pElement.textContent = message;
        messageContainer.appendChild(pElement);
        messagesContainer.appendChild(messageContainer);
        if (messagesContainer) messagesContainer.scrollTop = messagesContainer.scrollHeight;
    }

    if (socket && socket.readyState === WebSocket.OPEN) {
        sendMessage({ message: message });
    } else {
        displayMessage('Unable to send message: Chat connection is closed.');
    }
    inputField.value = '';
}

function sendMessage(message) {
    if (socket && socket.readyState === WebSocket.OPEN) {
        socket.send(JSON.stringify({ message: message.message }));
    } else {
        displayMessage('Unable to send message: Chat connection is closed.');
    }
}

function displayMessage(message) {
    const messagesContainer = document.querySelector('.tah_messages');
    const messageElement = document.createElement('div');
    messageElement.classList.add('tah_response-message');

    messageElement.style.backgroundColor = chatboxSettings.responseMessageBgColor;
    messageElement.style.color = chatboxSettings.responseMessageFontColor;
    messageElement.style.fontSize = chatboxSettings.responseMessageFontSize;
    messageElement.style.fontFamily = chatboxSettings.responseMessageFontFamily;

    const pElement = document.createElement('p');
    pElement.textContent = message;
    messageElement.appendChild(pElement);
    messagesContainer.appendChild(messageElement);
    messagesContainer.scrollTop = messagesContainer.scrollHeight;
}

function handleConnectionClosed() {
    const form = document.querySelector('.tah_form');
    if (form) {
        form.innerHTML = '<p style="color: red;">Connection Closed</p>';
    }
}

function resetChat() {
    const chatMessages = document.querySelector('.tah_messages');
    const chatFormContainer = document.querySelector('.tah_form').parentNode;

    chatMessages.innerHTML = '';

    if (formClone) {
        chatFormContainer.replaceChild(formClone.cloneNode(true), document.querySelector('.tah_form'));
        document.querySelector('.tah_form').addEventListener('submit', handleSubmit);
    }

    overlay.style.display = 'flex';
    isCardNameSent = false;

    if (socket && socket.readyState === WebSocket.OPEN) {
        socket.close();
    }
}

initializeChat();

window.initializeChat = initializeChat;
window.resetChat = resetChat;