// debug-toolbar.js - Debug controls for testing and development

// Console logging toggle state (will be loaded from localStorage)
let chartLoggingEnabled = true;
let debugToolbarVisible = false;
let simulationInProgress = false;
let voteHighlightEnabled = false;

// Load debug settings from localStorage
function loadDebugSettings() {
    try {
        const saved = localStorage.getItem('debugToolbarSettings');
        if (saved) {
            const settings = JSON.parse(saved);
            chartLoggingEnabled = settings.loggingEnabled !== false;
            debugToolbarVisible = settings.visible === true;
            voteHighlightEnabled = settings.voteHighlight === true;
            return settings;
        }
    } catch (e) {
        // Ignore localStorage errors
    }
    return null;
}

// Save debug settings to localStorage
function saveDebugSettings() {
    try {
        const settings = {
            visible: debugToolbarVisible,
            loggingEnabled: chartLoggingEnabled,
            simVoteCount: document.getElementById('simVoteCount')?.value || '10',
            simYouTube: document.getElementById('simYouTube')?.checked !== false,
            simTwitch: document.getElementById('simTwitch')?.checked !== false,
            simYapMode: document.getElementById('simYapMode')?.checked === true,
            simMahjongMode: document.getElementById('simMahjongMode')?.checked === true,
            simStrictTest: document.getElementById('simStrictTest')?.checked === true,
            voteHighlight: document.getElementById('voteHighlightToggle')?.checked === true
        };
        localStorage.setItem('debugToolbarSettings', JSON.stringify(settings));
    } catch (e) {
        // Ignore localStorage errors
    }
}

// Initialize debug toolbar
function initDebugToolbar() {
    // Wait for chartToolbar to exist
    const chartToolbar = document.getElementById('chartToolbar');
    if (!chartToolbar) {
        // Retry after a short delay if chartToolbar doesn't exist yet
        setTimeout(initDebugToolbar, 100);
        return;
    }

    // Prevent duplicate initialization
    if (document.getElementById('debugToggleBtn')) return;

    // Load saved settings before creating UI
    const savedSettings = loadDebugSettings();

    // Add toggle button to chartToolbar
    const toggleBtn = document.createElement('button');
    toggleBtn.id = 'debugToggleBtn';
    toggleBtn.className = 'btn btn-outline-secondary btn-sm';
    toggleBtn.innerHTML = '<i class="fas fa-bug"></i>';
    toggleBtn.title = 'Toggle Debug Tools';
    toggleBtn.addEventListener('click', toggleDebugToolbar);
    chartToolbar.appendChild(toggleBtn);

    // Create the debug toolbar (hidden by default)
    const toolbar = document.createElement('div');
    toolbar.id = 'debugToolbar';
    toolbar.className = 'd-none flex-column justify-content-center align-items-center gap-2 p-2 mt-2 border rounded bg-warning bg-opacity-10';
    toolbar.innerHTML = `
        <div class="d-flex flex-wrap justify-content-center align-items-center gap-2">
            <span class="text-muted small me-2"><i class="fas fa-bug"></i> Debug</span>

            <div class="form-check form-check-inline mb-0">
                <input class="form-check-input" type="checkbox" id="chartLoggingToggle" checked>
                <label class="form-check-label small" for="chartLoggingToggle">Log votes</label>
            </div>
            <div class="form-check form-check-inline mb-0">
                <input class="form-check-input" type="checkbox" id="voteHighlightToggle">
                <label class="form-check-label small" for="voteHighlightToggle">Highlight</label>
            </div>

            <div class="vr mx-1"></div>

            <div class="d-flex align-items-center gap-1">
                <label class="small mb-0" for="simVoteCount">Sim:</label>
                <input type="number" id="simVoteCount" class="form-control form-control-sm" style="width: 60px;" value="10" min="1" max="1000">
                <div class="form-check form-check-inline mb-0 ms-1">
                    <input class="form-check-input" type="checkbox" id="simYouTube" checked>
                    <label class="form-check-label small" for="simYouTube">YT</label>
                </div>
                <div class="form-check form-check-inline mb-0">
                    <input class="form-check-input" type="checkbox" id="simTwitch" checked>
                    <label class="form-check-label small" for="simTwitch">TW</label>
                </div>
                <button id="simVotesBtn" class="btn btn-outline-warning btn-sm">
                    <i class="fas fa-random"></i> Go
                </button>
            </div>
        </div>

        <div class="d-flex flex-wrap justify-content-center align-items-center gap-2">
            <div class="form-check form-check-inline mb-0" title="Increases chance simulated user will send more than one message, to test 1/user filter">
                <input class="form-check-input" type="checkbox" id="simYapMode">
                <label class="form-check-label small" for="simYapMode">📢 Yap</label>
            </div>
            <div class="form-check form-check-inline mb-0" title="Simulate votes based on a random 14-tile mahjong hand (locked during poll)">
                <input class="form-check-input" type="checkbox" id="simMahjongMode">
                <label class="form-check-label small" for="simMahjongMode">🀄 Mahjong</label>
            </div>
            <div class="form-check form-check-inline mb-0" title="Some messages will be exact alias matches (to test strict voting mode)">
                <input class="form-check-input" type="checkbox" id="simStrictTest">
                <label class="form-check-label small" for="simStrictTest">🎯 Strict</label>
            </div>
        </div>

        <div class="d-flex flex-wrap justify-content-center align-items-center gap-2">
            <div class="form-check form-switch mb-0" title="Send as YouTube or Twitch">
                <input class="form-check-input" type="checkbox" id="manualSourceSwitch">
                <label class="form-check-label small" for="manualSourceSwitch" id="manualSourceLabel">YT</label>
            </div>
            <div class="form-check form-check-inline mb-0" title="Randomize username each send">
                <input class="form-check-input" type="checkbox" id="manualRandomUser">
                <label class="form-check-label small" for="manualRandomUser">🎲</label>
            </div>
            <input type="text" id="manualUsername" class="form-control form-control-sm" style="width: 110px;" placeholder="username">
            <input type="text" id="manualMessage" class="form-control form-control-sm" style="width: 160px;" placeholder="message">
            <button id="manualSendBtn" class="btn btn-outline-info btn-sm" title="Send message">
                <i class="fas fa-paper-plane"></i>
            </button>
        </div>
    `;

    // Insert after chartToolbar
    chartToolbar.parentNode.insertBefore(toolbar, chartToolbar.nextSibling);

    // Inject highlight CSS
    if (!document.getElementById('vote-highlight-styles')) {
        const hlStyle = document.createElement('style');
        hlStyle.id = 'vote-highlight-styles';
        hlStyle.textContent = '.vote-highlight { background-color: rgba(255, 215, 0, 0.4); border-radius: 2px; padding: 0 1px; }';
        document.head.appendChild(hlStyle);
    }

    // Set up event listeners
    setupDebugListeners();

    // Apply saved settings to UI elements
    if (savedSettings) {
        // Restore input values
        const simVoteCount = document.getElementById('simVoteCount');
        if (simVoteCount && savedSettings.simVoteCount) {
            simVoteCount.value = savedSettings.simVoteCount;
        }

        const simYouTube = document.getElementById('simYouTube');
        if (simYouTube) {
            simYouTube.checked = savedSettings.simYouTube !== false;
        }

        const simTwitch = document.getElementById('simTwitch');
        if (simTwitch) {
            simTwitch.checked = savedSettings.simTwitch !== false;
        }

        const simYapMode = document.getElementById('simYapMode');
        if (simYapMode) {
            simYapMode.checked = savedSettings.simYapMode === true;
        }

        const simMahjongMode = document.getElementById('simMahjongMode');
        if (simMahjongMode) {
            simMahjongMode.checked = savedSettings.simMahjongMode === true;
        }

        const simStrictTest = document.getElementById('simStrictTest');
        if (simStrictTest) {
            simStrictTest.checked = savedSettings.simStrictTest === true;
        }

        const loggingToggle = document.getElementById('chartLoggingToggle');
        if (loggingToggle) {
            loggingToggle.checked = chartLoggingEnabled;
        }

        const voteHighlightToggle = document.getElementById('voteHighlightToggle');
        if (voteHighlightToggle) {
            voteHighlightToggle.checked = voteHighlightEnabled;
        }

        // Restore toolbar visibility (directly set UI without toggling state)
        if (debugToolbarVisible) {
            toolbar.classList.remove('d-none');
            toolbar.classList.add('d-flex');
            toggleBtn.classList.remove('btn-outline-secondary');
            toggleBtn.classList.add('btn-warning');
        }
    }
}

// Toggle debug toolbar visibility
function toggleDebugToolbar() {
    const toolbar = document.getElementById('debugToolbar');
    const toggleBtn = document.getElementById('debugToggleBtn');
    if (!toolbar) return;

    debugToolbarVisible = !debugToolbarVisible;

    // Use Bootstrap classes instead of inline styles (d-flex has !important)
    if (debugToolbarVisible) {
        toolbar.classList.remove('d-none');
        toolbar.classList.add('d-flex');
    } else {
        toolbar.classList.remove('d-flex');
        toolbar.classList.add('d-none');
    }

    // Update button style
    if (toggleBtn) {
        toggleBtn.classList.toggle('btn-outline-secondary', !debugToolbarVisible);
        toggleBtn.classList.toggle('btn-warning', debugToolbarVisible);
    }

    // Save visibility state
    saveDebugSettings();
}

function setupDebugListeners() {
    // Console logging toggle
    const loggingToggle = document.getElementById('chartLoggingToggle');
    if (loggingToggle) {
        loggingToggle.addEventListener('change', function() {
            chartLoggingEnabled = this.checked;
            saveDebugSettings();
            if (typeof window.logToConsole === 'function') {
                window.logToConsole(`Vote logging ${chartLoggingEnabled ? 'enabled' : 'disabled'}`);
            }
        });
    }

    // Vote highlight toggle
    const voteHighlightToggle = document.getElementById('voteHighlightToggle');
    if (voteHighlightToggle) {
        voteHighlightToggle.addEventListener('change', function() {
            voteHighlightEnabled = this.checked;
            saveDebugSettings();
            if (typeof window.logToConsole === 'function') {
                window.logToConsole(`Vote highlighting ${voteHighlightEnabled ? 'enabled' : 'disabled'}`);
            }
        });
    }

    // Sim button
    const simBtn = document.getElementById('simVotesBtn');
    if (simBtn) {
        simBtn.addEventListener('click', simulateVotes);
    }

    // Save settings when simulation options change
    const simVoteCount = document.getElementById('simVoteCount');
    if (simVoteCount) {
        simVoteCount.addEventListener('change', saveDebugSettings);
    }

    const simYouTube = document.getElementById('simYouTube');
    if (simYouTube) {
        simYouTube.addEventListener('change', saveDebugSettings);
    }

    const simTwitch = document.getElementById('simTwitch');
    if (simTwitch) {
        simTwitch.addEventListener('change', saveDebugSettings);
    }

    const simYapMode = document.getElementById('simYapMode');
    if (simYapMode) {
        simYapMode.addEventListener('change', saveDebugSettings);
    }

    const simMahjongMode = document.getElementById('simMahjongMode');
    if (simMahjongMode) {
        simMahjongMode.addEventListener('click', function(e) {
            // Prevent changing while poll is open
            if (typeof isOpen !== 'undefined' && isOpen) {
                e.preventDefault();
                if (typeof showInputError === 'function') {
                    showInputError(this, 'Cannot change while poll is open');
                }
                return;
            }
        });
        simMahjongMode.addEventListener('change', saveDebugSettings);
    }

    const simStrictTest = document.getElementById('simStrictTest');
    if (simStrictTest) {
        simStrictTest.addEventListener('change', saveDebugSettings);
    }

    // Manual message source switch label
    const manualSourceSwitch = document.getElementById('manualSourceSwitch');
    const manualSourceLabel = document.getElementById('manualSourceLabel');
    if (manualSourceSwitch && manualSourceLabel) {
        manualSourceSwitch.addEventListener('change', function() {
            manualSourceLabel.textContent = this.checked ? 'TW' : 'YT';
        });
    }

    // Manual send button
    const manualSendBtn = document.getElementById('manualSendBtn');
    if (manualSendBtn) {
        manualSendBtn.addEventListener('click', sendManualMessage);
    }

    // Send on Enter in message field
    const manualMessage = document.getElementById('manualMessage');
    if (manualMessage) {
        manualMessage.addEventListener('keydown', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                sendManualMessage();
            }
        });
    }
}

// Fake username generators
const fakeNamePrefixes = ['xX', 'Pro', 'Epic', 'Dark', 'Cool', 'The', 'Mr', 'Dr', 'Sir', 'Lord', 'King', 'Queen', ''];
const fakeNameWords = ['Gamer', 'Player', 'Ninja', 'Wolf', 'Dragon', 'Phoenix', 'Shadow', 'Storm', 'Fire', 'Ice', 'Star', 'Moon', 'Sun', 'Tiger', 'Lion', 'Bear', 'Hawk', 'Viper', 'Ghost', 'Demon', 'Angel', 'Knight', 'Wizard', 'Mage'];
const fakeNameSuffixes = ['Xx', '123', '420', '69', '99', '007', '_TTV', '_YT', '', '', '', ''];

// Mahjong tile types for hand generation (uses aliases that match registry)
const mahjongTiles = [
    '1p', '2p', '3p', '4p', '5p', '6p', '7p', '8p', '9p',
    '1m', '2m', '3m', '4m', '5m', '6m', '7m', '8m', '9m',
    '1s', '2s', '3s', '4s', '5s', '6s', '7s', '8s', '9s',
    'east', 'south', 'west', 'north',
    'white', 'green', 'red'
];

// Mahjong actions for combo mode (weighted - riichi and dama appear more often)
const mahjongActions = [
    'riichi', 'riichi', 'riichi', 'riichi',  // 4x weight
    'dama', 'dama', 'dama',                   // 3x weight
    'pon', 'chi', 'kan', 'ron', 'tsumo', 'skip'  // 1x weight each
];

// Current mahjong hand for simulation
let currentMahjongHand = null;

// Generate a random 14-tile mahjong hand
function generateMahjongHand() {
    // Create a wall with 4 of each tile
    const wall = [];
    mahjongTiles.forEach(tile => {
        for (let i = 0; i < 4; i++) {
            wall.push(tile);
        }
    });

    // Shuffle the wall
    for (let i = wall.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [wall[i], wall[j]] = [wall[j], wall[i]];
    }

    // Draw 14 tiles
    const hand = wall.slice(0, 14);

    // Sort hand by suit and number for display
    hand.sort((a, b) => {
        const order = ['man', 'pin', 'sou', 'east', 'south', 'west', 'north', 'white', 'green', 'red'];
        const getSuit = (tile) => {
            for (const suit of order) {
                if (tile.startsWith(suit)) return order.indexOf(suit);
            }
            return 99;
        };
        const getNum = (tile) => {
            const num = tile.match(/\d+/);
            return num ? parseInt(num[0]) : 0;
        };
        const suitDiff = getSuit(a) - getSuit(b);
        return suitDiff !== 0 ? suitDiff : getNum(a) - getNum(b);
    });

    return hand;
}

// Get a display string for the mahjong hand
function formatMahjongHand(hand) {
    return hand.join(' ');
}

// Chat filler phrases to make messages more realistic
const chatFillers = [
    '', '', '', // Empty = just the vote word
    'I vote ',
    'my pick is ',
    'going with ',
    'definitely ',
    'gotta be ',
    'lets go ',
    'im saying ',
    'easy ',
    'obviously ',
    'for sure ',
    'probably ',
];
const chatSuffixes = [
    '', '', '', '', // Empty most of the time
    '!',
    '!!',
    ' lol',
    ' :)',
    ' pog',
    ' for sure',
    ' ez',
];

// Generate a random fake username
function generateFakeUsername() {
    const prefix = fakeNamePrefixes[Math.floor(Math.random() * fakeNamePrefixes.length)];
    const word = fakeNameWords[Math.floor(Math.random() * fakeNameWords.length)];
    const suffix = fakeNameSuffixes[Math.floor(Math.random() * fakeNameSuffixes.length)];
    const num = Math.random() > 0.5 ? Math.floor(Math.random() * 9999) : '';
    return `${prefix}${word}${suffix}${num}`;
}

// Generate a fake chat message containing a vote keyword
function generateFakeMessage(keyword) {
    const filler = chatFillers[Math.floor(Math.random() * chatFillers.length)];
    const suffix = chatSuffixes[Math.floor(Math.random() * chatSuffixes.length)];
    return `${filler}${keyword}${suffix}`;
}

// Get all votable aliases from registry
function getVotableAliases() {
    const aliases = [];

    if (typeof candidateRegistry !== 'undefined' && Array.isArray(candidateRegistry)) {
        candidateRegistry.forEach(entry => {
            if (entry.aliases && Array.isArray(entry.aliases)) {
                entry.aliases.forEach(alias => {
                    aliases.push({ alias, candidate: entry.candidate });
                });
            }
        });
    }

    return aliases;
}

// Get current time formatted like real chat messages
function getFormattedTime() {
    const now = new Date();
    const hours = now.getHours().toString().padStart(2, '0');
    const minutes = now.getMinutes().toString().padStart(2, '0');
    const seconds = now.getSeconds().toString().padStart(2, '0');
    return `${hours}:${minutes}:${seconds}`;
}

// Send a manually typed message through the chat pipeline
function sendManualMessage() {
    const sourceSwitch = document.getElementById('manualSourceSwitch');
    const usernameInput = document.getElementById('manualUsername');
    const messageInput = document.getElementById('manualMessage');
    if (!messageInput) return;

    const text = messageInput.value.trim();
    if (!text) {
        if (typeof showInputError === 'function') {
            showInputError(messageInput, 'Enter a message');
        }
        return;
    }

    const source = (sourceSwitch && sourceSwitch.checked) ? 'twitch' : 'youtube';
    const randomUserCheck = document.getElementById('manualRandomUser');
    const useRandom = randomUserCheck && randomUserCheck.checked;
    const username = useRandom ? generateFakeUsername() : ((usernameInput && usernameInput.value.trim()) || 'DebugUser');

    // Display in the appropriate chat container
    logSimulatedMessage(source, username, text);

    // Route through vote parsing if poll is open
    if (typeof isOpen !== 'undefined' && isOpen && typeof parseMessageForVote === 'function') {
        parseMessageForVote(text, source, username);
        if (typeof VoteChart !== 'undefined' && VoteChart.render) {
            VoteChart.setData(stats);
            VoteChart.render();
        }
    }

    // Clear message field, keep username for convenience
    messageInput.value = '';
    messageInput.focus();
}

// Log a simulated message to the appropriate chat container
function logSimulatedMessage(source, username, text) {
    // Get the appropriate output container based on source
    // Real YouTube chat goes to chatContainerLeft, real Twitch goes to chatContainerRight
    let container = null;

    if (source === 'twitch') {
        // Twitch uses chatContainerRight (or twitchOutputContainer if set)
        container = (typeof twitchOutputContainer !== 'undefined' && twitchOutputContainer)
            ? twitchOutputContainer
            : document.getElementById('chatContainerRight');
    } else {
        // YouTube uses chatContainerLeft (the dark box where real YT chat appears)
        container = document.getElementById('chatContainerLeft');
    }

    if (!container) return;

    // Format message like real chat handlers do
    const time = getFormattedTime();
    const formattedMessage = source === 'twitch'
        ? `[${time}] | ${username} : ${text}`  // Twitch format (space around colon)
        : `[${time}] | ${username}: ${text}`;  // YouTube format (no space before colon)

    // Create and append the log entry
    const logEntry = document.createElement('p');

    // Apply vote highlighting if enabled
    let simHighlighted = false;
    if (typeof isOpen !== 'undefined' && isOpen && voteHighlightEnabled
        && typeof window.findVoteMatchesInText === 'function') {
        const rawRanges = window.findVoteMatchesInText(text);
        if (rawRanges.length > 0) {
            const prefixLength = formattedMessage.length - text.length;
            const ranges = rawRanges
                .map(r => ({ start: r.start + prefixLength, length: r.length }))
                .sort((a, b) => a.start - b.start);

            let lastIndex = 0;
            for (const range of ranges) {
                if (range.start > lastIndex) {
                    logEntry.appendChild(document.createTextNode(formattedMessage.substring(lastIndex, range.start)));
                }
                const span = document.createElement('span');
                span.className = 'vote-highlight';
                span.textContent = formattedMessage.substring(range.start, range.start + range.length);
                logEntry.appendChild(span);
                lastIndex = range.start + range.length;
            }
            if (lastIndex < formattedMessage.length) {
                logEntry.appendChild(document.createTextNode(formattedMessage.substring(lastIndex)));
            }
            simHighlighted = true;
        }
    }

    if (!simHighlighted) {
        logEntry.textContent = formattedMessage;
    }

    // Add a subtle indicator that this is simulated
    logEntry.style.opacity = '0.7';
    logEntry.title = 'Simulated message';

    container.appendChild(logEntry);

    // Trim old entries if trimContainer is available
    if (typeof window.trimContainer === 'function') {
        window.trimContainer(container, window.MAX_CHAT_ENTRIES || 300);
    }

    // Auto-scroll if near bottom
    const isAtBottom = container.scrollHeight - container.clientHeight - container.scrollTop <= 200;
    if (isAtBottom) {
        container.scrollTop = container.scrollHeight;
    }
}

// Simulate random votes - routes through parseMessageForVote like real messages
function simulateVotes() {
    // Prevent rapid clicking / multiple simultaneous simulations
    if (simulationInProgress) {
        return;
    }

    // Check if poll is open
    if (typeof isOpen === 'undefined' || !isOpen) {
        const simBtn = document.getElementById('simVotesBtn');
        if (simBtn && typeof showInputError === 'function') {
            showInputError(simBtn, 'Poll is not open');
        }
        if (typeof window.logToConsole === 'function') {
            window.logToConsole('Cannot simulate: poll is not open');
        }
        return;
    }

    // Check parseMessageForVote exists
    if (typeof parseMessageForVote !== 'function') {
        if (typeof window.logToConsole === 'function') {
            window.logToConsole('Cannot simulate: parseMessageForVote not available');
        }
        return;
    }

    // Get parameters
    const n = parseInt(document.getElementById('simVoteCount').value) || 10;
    const youtube = document.getElementById('simYouTube').checked;
    const twitch = document.getElementById('simTwitch').checked;
    const yapMode = document.getElementById('simYapMode')?.checked || false;
    const mahjongMode = document.getElementById('simMahjongMode')?.checked || false;
    const strictTest = document.getElementById('simStrictTest')?.checked || false;

    // Get votable aliases from registry (only needed for non-mahjong mode)
    const aliases = getVotableAliases();
    if (!mahjongMode && aliases.length === 0) {
        if (typeof window.logToConsole === 'function') {
            window.logToConsole('Cannot simulate: no aliases in registry');
        }
        return;
    }

    // In mahjong mode, check if we have a hand (generated when poll opened)
    if (mahjongMode && !currentMahjongHand) {
        if (typeof window.logToConsole === 'function') {
            window.logToConsole('🀄 No mahjong hand available - reopen poll to generate one');
        }
        return;
    }

    // Lock to prevent re-entry
    simulationInProgress = true;
    const simBtn = document.getElementById('simVotesBtn');
    if (simBtn) simBtn.disabled = true;

    // Determine source distribution
    const effectiveYT = youtube || (!youtube && !twitch);
    const effectiveTW = twitch || (!youtube && !twitch);

    let ytCount = 0;
    let twCount = 0;
    let processedCount = 0;

    // Yap mode: keep a small pool of usernames to reuse (to test one-vote-per-user filter)
    const usernamePool = [];
    const yapPoolSize = Math.max(3, Math.floor(n / 3)); // Pool is 1/3 the size of votes

    try {
        // Process each simulated vote through the real parseMessageForVote function
        // This faithfully recreates what happens with real Twitch/YouTube messages
        for (let i = 0; i < n; i++) {
            let voteText;

            if (mahjongMode && currentMahjongHand) {
                // Pick a random tile from the hand
                const tile = currentMahjongHand[Math.floor(Math.random() * currentMahjongHand.length)];

                // Check if combo mode is enabled - sometimes add an action
                const comboEnabled = typeof window.comboModeEnabled !== 'undefined' && window.comboModeEnabled;
                if (comboEnabled && Math.random() < 0.4) {
                    // 40% chance to include an action with combo mode
                    const action = mahjongActions[Math.floor(Math.random() * mahjongActions.length)];
                    // Randomly put action before or after tile
                    voteText = Math.random() < 0.5 ? `${action} ${tile}` : `${tile} ${action}`;
                } else {
                    voteText = tile;
                }
            } else {
                // Normal mode - pick a random alias from registry
                const aliasEntry = aliases[Math.floor(Math.random() * aliases.length)];
                voteText = aliasEntry.alias;
            }

            // Use voteText as the base for the message
            const alias = voteText;

            // Determine source for this vote
            const source = (effectiveYT && effectiveTW)
                ? (Math.random() < 0.5 ? 'youtube' : 'twitch')
                : (effectiveTW ? 'twitch' : 'youtube');

            // Generate or reuse username based on yap mode
            let fakeUsername;
            if (yapMode && usernamePool.length > 0 && Math.random() < 0.5) {
                // 50% chance to reuse an existing username from the pool
                fakeUsername = usernamePool[Math.floor(Math.random() * usernamePool.length)];
            } else {
                // Generate new username
                fakeUsername = generateFakeUsername();
                // Add to pool if in yap mode and pool not full
                if (yapMode && usernamePool.length < yapPoolSize) {
                    usernamePool.push(fakeUsername);
                }
            }

            // In strict test mode, 50% of messages are exact alias matches (pass strict mode)
            // Other 50% have chat filler (would fail strict mode)
            const fakeMessage = (strictTest && Math.random() < 0.5)
                ? alias  // Exact match - passes strict voting
                : generateFakeMessage(alias);  // With filler - may fail strict voting

            // Log to chat display if logging is enabled (like real messages appearing in chat)
            if (chartLoggingEnabled) {
                logSimulatedMessage(source, fakeUsername, fakeMessage);
            }

            // Route through parseMessageForVote - exactly like real Twitch/YouTube handlers do
            // This tests: strict voting, one-vote-per-user, translate map lookup, username recording
            parseMessageForVote(fakeMessage, source, fakeUsername);

            if (source === 'youtube') ytCount++;
            else twCount++;
            processedCount++;
        }

        // Update chart once at the end (like YouTube batch processing)
        if (typeof VoteChart !== 'undefined' && VoteChart.render) {
            VoteChart.setData(stats);
            VoteChart.render();
        }

        // Log result
        if (typeof window.logToConsole === 'function') {
            let sourceInfo = '';
            if (effectiveYT && effectiveTW) {
                sourceInfo = ` (YT: ${ytCount}, TW: ${twCount})`;
            } else if (effectiveYT) {
                sourceInfo = ' (YT only)';
            } else {
                sourceInfo = ' (TW only)';
            }
            window.logToConsole(`Simulated ${processedCount} votes${sourceInfo}`);
            window.logToConsole('Simulation finished');
        }
    } catch (error) {
        console.error('Simulation error:', error);
        if (typeof window.logToConsole === 'function') {
            window.logToConsole(`Simulation error: ${error.message}`);
        }
    } finally {
        // Always unlock, even if there was an error
        setTimeout(() => {
            simulationInProgress = false;
            const simBtn = document.getElementById('simVotesBtn');
            if (simBtn) simBtn.disabled = false;
        }, 100);
    }
}


// Cancel any running simulation (called when poll closes)
function cancelSimulation() {
    if (simulationInProgress) {
        simulationInProgress = false;
        const simBtn = document.getElementById('simVotesBtn');
        if (simBtn) {
            simBtn.disabled = false;
            simBtn.innerHTML = '<i class="fas fa-random"></i> Go';
        }
        if (typeof window.logToConsole === 'function') {
            window.logToConsole('Simulation cancelled (poll closed)');
        }
    }
}

// Check if mahjong mode is enabled
function isMahjongModeEnabled() {
    return document.getElementById('simMahjongMode')?.checked || false;
}

// Generate mahjong hand (called when poll opens)
function initMahjongHand() {
    if (isMahjongModeEnabled()) {
        currentMahjongHand = generateMahjongHand();
        if (typeof window.logToConsole === 'function') {
            window.logToConsole(`🀄 Mahjong hand: ${formatMahjongHand(currentMahjongHand)}`);
        }
    }
}

// Clear mahjong hand (called when poll closes)
function clearMahjongHand() {
    currentMahjongHand = null;
}

// Expose highlight state globally for chat handlers
Object.defineProperty(window, 'voteHighlightEnabled', {
    get: function() { return voteHighlightEnabled; },
    set: function(v) { voteHighlightEnabled = v; },
    configurable: true
});

// Export logging state checker and toggle
window.debugToolbar = {
    isLoggingEnabled: function() {
        return chartLoggingEnabled;
    },
    setLoggingEnabled: function(enabled) {
        chartLoggingEnabled = enabled;
        const toggle = document.getElementById('chartLoggingToggle');
        if (toggle) toggle.checked = enabled;
    },
    toggle: toggleDebugToolbar,
    isVisible: function() {
        return debugToolbarVisible;
    },
    cancelSimulation: cancelSimulation,
    isMahjongModeEnabled: isMahjongModeEnabled,
    initMahjongHand: initMahjongHand,
    clearMahjongHand: clearMahjongHand
};

// Initialize when DOM is ready
document.addEventListener('DOMContentLoaded', function() {
    // Small delay to ensure other elements are loaded
    setTimeout(initDebugToolbar, 150);
});
