// Twitch chat connection using Twitch API
let twitchSocket = null;
let channelName = ""; // Your friend's Twitch channel name

let twitchOutputContainer = null;
let isPolling = false;
let voteKeywords = []; // Keywords to track votes for. will be set somewhere else

// Initialize the Twitch chat connection
function initTwitchChat(outputContainerId, channel, keywords = []) {
    twitchOutputContainer = document.getElementById('chatContainerRight');

    // Check if the container exists
    if (!twitchOutputContainer) {
        console.error(`Output container with ID "${outputContainerId}" not found.`);
        return false;
    }

    channelName = channel;
    voteKeywords = keywords;

    // Create a WebSocket connection to Twitch IRC
    twitchSocket = new WebSocket('wss://irc-ws.chat.twitch.tv:443');

    twitchSocket.onopen = function() {
        //hardcoded - consider moving this to a secure configuration
        const TwitchKey = 'j718e92l8pw6k8vqt0za54u63yzdfo';
        twitchSocket.send(`PASS oauth:${TwitchKey}`);
        twitchSocket.send('NICK wjiy6wqp5gebr33wdizdfwpq1zbq1i'); // Anonymous user
        twitchSocket.send(`JOIN #${channelName}`);

        logToPage(twitchOutputContainer, `Connected to Twitch chat for channel: ${channelName}`);
    };

    twitchSocket.onmessage = function(event) {
        handleTwitchMessage(event.data);
    };

    twitchSocket.onerror = function(error) {
        logToPage(twitchOutputContainer, `Error connecting to Twitch chat: ${error.message}`);
        console.error(`Error connecting to Twitch chat: ${error.message}`);
    };

    twitchSocket.onclose = function() {
        logToPage(twitchOutputContainer, 'Disconnected from Twitch chat');
    };
}
// Handle incoming Twitch messages
function handleTwitchMessage(message) {
    // Keep connection alive by responding to PING
    if (message.startsWith('PING')) {
        twitchSocket.send('PONG :tmi.twitch.tv');
        return;
    }

    // Parse Twitch IRC message
    if (message.includes('PRIVMSG')) {
        const parsedMessage = parseTwitchMessage(message);
        if (parsedMessage) {
            const { time, username, text } = parsedMessage;
            const formattedMessage = `[${time}] | ${username} : ${text}`;

            logToPage(twitchOutputContainer, formattedMessage);

            // Check for vote keywords if polling is active
            if (isPolling) {
                checkForVotes(username, text);
            }
        }
    }
}
// Parse the Twitch IRC message format
function parseTwitchMessage(message) {
    try {
        const regex = /:([^!]+)!.*PRIVMSG #[^ ]+ :(.*)/;
        const match = message.match(regex);

        if (match && match.length >= 3) {
            const username = match[1];
            const text = match[2];
            const time = new Date().toLocaleTimeString();

            return { time, username, text };
        }
    } catch (error) {
        console.error('Error parsing Twitch message:', error);
    }

    return null;
}
// Start/stop vote polling
function toggleTwitchVotePolling(enabled) {
    isPolling = enabled;
    const status = enabled ? 'started' : 'stopped';
    logToPage(twitchOutputContainer, `Vote polling ${status}`);
}
// Check message for vote keywords
function checkForVotes(username, message) {
    for (const keyword of voteKeywords) {
        if (message.toLowerCase().includes(keyword.toLowerCase())) {
            // Record vote (you can implement your vote counting system here)
            console.log(`Vote from ${username} for ${keyword}`);
            // You might want to trigger an event or update a counter here
            break; // Count only one vote per message
        }
    }
}
// Disconnect from Twitch chat
function disconnectTwitchChat() {
    if (twitchSocket && twitchSocket.readyState === WebSocket.OPEN) {
        twitchSocket.close();
    }
}
// Log messages to the specified container with error handling
function logToPage(outputContainer, message) {
    if (!outputContainer) {
        console.error("Output container is not defined. Cannot log message:", message);
        return;
    }

    try {
        var logEntry = document.createElement('p');
        logEntry.textContent = message;
        outputContainer.appendChild(logEntry);

        // Check if user is already at the bottom before adding the new message
        // We give a small threshold (200px) to account for minor differences
        const isAtBottom = outputContainer.scrollHeight - outputContainer.clientHeight - outputContainer.scrollTop <= 200;

        // Only auto-scroll if the user was already at the bottom
        if (isAtBottom) {
            outputContainer.scrollTop = outputContainer.scrollHeight;
        }
    } catch (error) {
        console.error("Error logging to page:", error);
    }
}
