// 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 = []) {
    // The problem might be here - let's use the parameter correctly
    twitchOutputContainer = document.getElementById(outputContainerId);
    channelName = channel;
    //voteKeywords = keywords;

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

    twitchSocket.onopen = function () {
        // Anonymous connection - no need for OAuth
        const anonymousUsername = 'justinfan' + Math.floor(Math.random() * 100000);
        twitchSocket.send(`NICK ${anonymousUsername}`);
        twitchSocket.send(`JOIN #${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);
    };

    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}`;

            var twHighlightRanges = null;
            if (isOpen && window.voteHighlightEnabled && typeof window.findVoteMatchesInText === 'function') {
                var rawRanges = window.findVoteMatchesInText(text);
                if (rawRanges.length > 0) {
                    var prefixLen = formattedMessage.length - text.length;
                    twHighlightRanges = rawRanges.map(function(r) {
                        return { start: r.start + prefixLen, length: r.length };
                    });
                }
            }

            logToPage(twitchOutputContainer, formattedMessage, twHighlightRanges);

            //// Check for vote keywords if polling is active
            //if (isPolling) {
            //    checkForVotes(username, text);
            //}

            if (isOpen) {
                parseMessageForVote(text, 'twitch', username);
                if (typeof VoteChart !== 'undefined') {
                    VoteChart.setData(stats);
                    VoteChart.render();
                }
            }
        }
    }
}

// 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 (i dont use this)
function toggleTwitchVotePolling(enabled) {
    isPolling = enabled;
    const status = enabled ? 'started' : 'stopped';
    logToPage(twitchOutputContainer, `Vote polling ${status}`);
}

// Check message for vote keywords (i dont use this either)
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();
        
    }
}

function logToPage(outputContainer, message, highlightRanges) {
    if (!outputContainer) {
        console.error("Output container is not defined:", message);
        return;
    }

    var logEntry = document.createElement('p');

    if (highlightRanges && highlightRanges.length > 0) {
        var sorted = highlightRanges.slice().sort(function(a, b) { return a.start - b.start; });
        var lastIndex = 0;
        for (var i = 0; i < sorted.length; i++) {
            var range = sorted[i];
            if (range.start > lastIndex) {
                logEntry.appendChild(document.createTextNode(message.substring(lastIndex, range.start)));
            }
            var span = document.createElement('span');
            span.className = 'vote-highlight';
            span.textContent = message.substring(range.start, range.start + range.length);
            logEntry.appendChild(span);
            lastIndex = range.start + range.length;
        }
        if (lastIndex < message.length) {
            logEntry.appendChild(document.createTextNode(message.substring(lastIndex)));
        }
    } else {
        logEntry.textContent = message;
    }

    outputContainer.appendChild(logEntry);

    // Trim old entries to prevent memory leak
    if (typeof window.trimContainer === 'function') {
        window.trimContainer(outputContainer, window.MAX_CHAT_ENTRIES || 300);
    }

    // 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;
    }
}