function biasChart() {
    var container = document.createElement('div');
    
    
    // Create buttons for help
    var thresholdHelpButton = document.createElement('button');
    thresholdHelpButton.textContent = 'Threshold Help';
    thresholdHelpButton.style.margin = '10px';
    
    var chiSquareHelpButton = document.createElement('button');
    chiSquareHelpButton.textContent = 'Chi-Square Help';
    chiSquareHelpButton.style.margin = '10px';
    
    // Add buttons to the container
    container.appendChild(thresholdHelpButton);
    container.appendChild(chiSquareHelpButton);
    
    var thresholdHelpContent = document.createElement('div');

    // Your content, split into paragraphs or sections
    var paragraphs = [
        "When analyzing roulette spins with thresholds of 12% and 50%, we're examining how much the actual results deviate from what's expected in a fair scenario. In a fair roulette, each number should come up with equal frequency over many spins.",
        "Understanding the Threshold:\n- The threshold acts like a sensitivity setting. It determines the acceptable deviation from the expected frequency before deciding a number is 'biased'. A lower threshold (12%) means you're sensitive to smaller deviations, flagging numbers as biased for slight differences. A higher threshold (50%) means only significant deviations are considered biased.",
        "Why Different Thresholds Highlight Different Numbers:\n- 12% Threshold: This lower threshold suggests a number is biased if its frequency is just 12% more or less than expected. Given the natural variance, especially over a small sample size like 30 spins, many numbers will naturally fall outside this narrow margin due to chance, leading to many highlighted rows.\n\n- 50% Threshold: This higher threshold indicates concern only for deviations of 50% or more. Such dramatic deviations are less common over 30 spins, so fewer numbers meet this criterion, resulting in fewer highlighted rows.",
        "What This Means:\nIn roulette, over a small number of spins like 30, randomness causes significant variation. The chosen threshold for 'bias' affects how many numbers seem unusual. A lower threshold makes the analysis sensitive to normal fluctuations, while a higher threshold filters for only large deviations, less likely by chance alone. This explains why more numbers are highlighted with a 12% threshold compared to a 50% threshold."
    ];
    
    // Create a <p> for each paragraph
    paragraphs.forEach(function(paragraph, index) {
        var p = document.createElement('p');
        p.textContent = paragraph;
        p.className = "line"; // Apply general styling to each paragraph
    
        // Add extra bottom margin to specific paragraphs if needed
        if (index === 1 || index === 2) { // Example: Apply to the second and third paragraphs
            p.style.marginBottom = "20px";
        }
    
        thresholdHelpContent.appendChild(p);
    });
    thresholdHelpContent.style.backgroundColor = '#ffffe6';
    thresholdHelpContent.style.display = 'none';
    
    var chiSquareHelpContent = document.createElement('div');

    // Split the content into lines
    var lines = `
    The Chi-Square statistic is a number that tells us how much the observed data differs from what was expected. In simpler terms, it helps us understand if the patterns we see in our data (like the results from roulette spins) are just random chance or if there's something more going on.
    
    What is the Chi-Square Statistic?
    - It's a Measure: The Chi-Square statistic measures the discrepancies between the observed frequencies (what actually happened) and the expected frequencies (what we would predict to happen if everything was perfectly balanced or fair).
    
    - It's a Sum: Specifically, it sums up the squared differences between each observed frequency and its expected frequency, divided by the expected frequency. This way, it accounts for how far off each observation is from what was expected, not just overall but for each category or outcome.
    
    How to Read It:
    - Low Chi-Square Value: A low Chi-Square value suggests that the differences between what you observed and what you expected are small. In many cases, this means that any differences could likely be due to chance. In the context of a roulette wheel, a low value might indicate that the wheel is fair.
    
    - High Chi-Square Value: A high Chi-Square value indicates larger discrepancies between the observed and expected frequencies. This suggests that the observed outcomes are not just random variations from what was expected. In roulette, a high value might point towards a bias in the wheel.
    
    Making a Decision:
    - Compare to a Critical Value: To decide if the differences are significant (not just due to chance), you compare your Chi-Square statistic to a critical value from a Chi-Square distribution table. This critical value depends on your chosen level of significance (often 5% or 1%) and the degrees of freedom in your test (usually the number of categories minus one).
    
    - If Chi-Square is Less Than the Critical Value: You conclude there's no significant difference between observed and expected frequencies. Your observation is likely due to chance.
    
    - If Chi-Square is Greater Than the Critical Value: You conclude there is a significant difference. The observed frequencies did not occur by chance alone. In the case of a roulette wheel, this might indicate a bias.
    
    Remember:
    The Chi-Square statistic by itself doesn't tell you why there's a difference or where the bias lies. It only indicates that the observed data significantly deviate from what was expected. Further analysis might be needed to pinpoint the specific biases or patterns.
    `.trim().split('\n');
    
    // Create a <p> or <div> for each line and add it to the chiSquareHelpContent container
    lines.forEach(function(line) {
        var p = document.createElement('p');
        p.className = "line"; // Assuming you have CSS for .line class
        p.textContent = line.trim();
        chiSquareHelpContent.appendChild(p);
    });
    chiSquareHelpContent.style.backgroundColor = '#ffe6cc';
    chiSquareHelpContent.style.display = 'none';
    
    function showPopup(content) {
        var popup = document.createElement('div');
        popup.innerHTML = content.innerHTML;
        // Initial styles
        popup.style.position = 'fixed';
        popup.style.top = '50%';
        popup.style.left = '30%';
        popup.style.transform = 'translate(-50%, -50%)';
        popup.style.backgroundColor = '#ffffe6';
        popup.style.padding = '20px';
        popup.style.border = '1px solid black';
        popup.style.zIndex = '1000';
        popup.style.width = '700px';
        popup.style.maxHeight = '80%';
        popup.style.overflow = 'auto';
        popup.style.resize = 'both';
        popup.style.boxSizing = 'border-box';
        popup.style.fontSize = '14pt';
        popup.style.cursor = 'move';
    
        var closeButton = document.createElement('button');
        closeButton.textContent = 'Close';
        closeButton.style.position = 'absolute';
        closeButton.style.top = '5px';
        closeButton.style.right = '5px';
        closeButton.onclick = function() {
            document.body.removeChild(popup);
        };
        popup.appendChild(closeButton);
    
        var isDragging = false;
        var dragOffsetX, dragOffsetY;
        var disableDragNearBorders = false; // New flag to disable dragging near borders
    
        popup.onmousedown = function(e) {
            var rect = popup.getBoundingClientRect();
            var nearBorder = e.clientX - rect.left > rect.width - 20 || e.clientY - rect.top > rect.height - 20;
            if (nearBorder) {
                // If the mouse is near the bottom or right edge, assume resizing
                disableDragNearBorders = true;
            } else {
                isDragging = true;
                dragOffsetX = e.clientX - popup.offsetLeft;
                dragOffsetY = e.clientY - popup.offsetTop;
            }
        };
    
        document.onmousemove = function(e) {
            if (isDragging && !disableDragNearBorders) {
                popup.style.left = e.clientX - dragOffsetX + 'px';
                popup.style.top = e.clientY - dragOffsetY + 'px';
                popup.style.transform = ''; // Remove the transform to not interfere with positioning
            }
        };
    
        document.onmouseup = function() {
            isDragging = false;
            disableDragNearBorders = false; // Reset the flag
        };
    
        document.body.appendChild(popup);
    }
    
    
    
    // Attach event listeners to buttons
    thresholdHelpButton.addEventListener('click', function() {
        showPopup(thresholdHelpContent);
    });
    
    chiSquareHelpButton.addEventListener('click', function() {
        showPopup(chiSquareHelpContent);
    });
    
    var id = 'bias-table';
    var title = 'Chi-Square Bias Analysis';
    var headerData = ['Number', 'Observed Frequency', 'Expected Frequency'];
    
    var containerWithTable = createStyledTable(id, title, headerData); 
    container.appendChild(containerWithTable);
    
    return container;
}


function biasChartUpdate() {
    
    
    var id = 'bias-table';
    var table = document.getElementById(id); // Make sure to get the table reference correctly
    var threshold = 0.05; // Default threshold
    var overSpinsInput = document.getElementById('look_back_' + id);

    if (overSpinsInput) {
        
        overSpinsInput.addEventListener('mousedown', (e) => {
                e.stopPropagation(); // Prevent drag behavior when interacting with the input box
            });
        
        threshold = Number(overSpinsInput.value) / 100;
        if (isNaN(threshold) || threshold < 0.01) { // Ensure threshold is at least 1%
            overSpinsInput.value = 5; // Reset to a default value if the input is not valid
            threshold = 0.05; // 5%
        }
    }
    
    var spanContainer = document.getElementById('over_spins_text_'+id);
    if(!spanContainer)
    {
        return;
    }
    spanContainer.innerHTML = ` Using a threshold of `+threshold+'%';

    

    const validNumbers = numbers.filter(spin => typeof spin === 'number' && spin >= 0 && spin <= 36);
    const totalSpins = validNumbers.length;
    const expectedFrequency = totalSpins / 37;
    let observedFrequencies = new Array(37).fill(0);
    let chiSquareStatistic = 0;

    // Count observed frequencies
    validNumbers.forEach(spin => {
        observedFrequencies[spin]++;
    });

    // Calculate Chi-Square Statistic
    observedFrequencies.forEach(observed => {
        chiSquareStatistic += Math.pow(observed - expectedFrequency, 2) / expectedFrequency;
    });

    // Prepare the data for the table
    let tableData = observedFrequencies.map((observed, number) => {
        let deviation = Math.abs(observed - expectedFrequency) / expectedFrequency;
        let isBiased = deviation > threshold;
        return { data: [number, observed, expectedFrequency.toFixed(2)], isBiased };
    });

    // Append Chi-Square statistic at the end
    tableData.push({ data: ['Chi-Square Statistic', chiSquareStatistic.toFixed(2), ''], isBiased: false });

    // Update the table with new data
    if (!table) {
        console.log('Table not found!', id);
        return;
    }

    // Delete existing table rows, except for the header
    while (table.rows.length > 1) {
        table.deleteRow(1);
    }

    // Append new data
    tableData.forEach(function(item) {
        var row = table.insertRow(-1);
        item.data.forEach(function(cellData) {
            var cell = row.insertCell(-1);
            cell.textContent = cellData;
        });
        if (item.isBiased) {
            row.style.backgroundColor = 'yellow'; // Highlight biased rows
        }
    });
}
//------------------------------------------------------------------------------
// Hidden Div
// ------------------------------------------------------------------------------
const hiddenContainer = document.createElement('div');
hiddenContainer.id = 'hidden-draggable-div';
hiddenContainer.style.position = 'fixed';
hiddenContainer.style.top = '50%';
hiddenContainer.style.left = '50%';
hiddenContainer.style.transform = 'translate(-50%, -50%)';
hiddenContainer.style.backgroundColor = '#fff';
hiddenContainer.style.padding = '20px';
hiddenContainer.style.borderRadius = '8px';
hiddenContainer.style.boxShadow = '0 4px 8px rgba(0, 0, 0, 0.2)';
hiddenContainer.style.zIndex = '1000';
hiddenContainer.style.minWidth = '300px';
hiddenContainer.style.display = 'none'; // Initially hidden
hiddenContainer.style.cursor = 'move';

// Add a close button to the hidden container
const hiddenCloseButton = document.createElement('button');
hiddenCloseButton.textContent = 'Close';
hiddenCloseButton.style.position = 'absolute';
hiddenCloseButton.style.top = '10px';
hiddenCloseButton.style.right = '10px';
hiddenCloseButton.style.background = 'transparent';
hiddenCloseButton.style.border = 'none';
hiddenCloseButton.style.color = '#333';
hiddenCloseButton.style.fontSize = '20px';
hiddenCloseButton.style.cursor = 'pointer';

// Close the hidden container when the button is clicked
hiddenCloseButton.addEventListener('click', () => {
    hiddenContainer.style.display = 'none';
});

// Add the close button to the hidden container
hiddenContainer.appendChild(hiddenCloseButton);

// Add the hidden container to the body
document.body.appendChild(hiddenContainer);

// Function to update and show the draggable hidden div
function showDraggablePopup_bias(content) {
    // Clear previous content
    hiddenContainer.innerHTML = '';

    // Re-add the close button
    hiddenContainer.appendChild(hiddenCloseButton);

    // Add the new content
    hiddenContainer.appendChild(content);

    // Unhide the container
    hiddenContainer.style.display = 'block';

    // Make the container draggable
    makeDraggable_bias(hiddenContainer);
}

// Add a helper function to make an element draggable
function makeDraggable_bias(element) {
    let isDragging = false;
    let offsetX, offsetY;

    element.onmousedown = (e) => {
        isDragging = true;
        offsetX = e.clientX - element.offsetLeft;
        offsetY = e.clientY - element.offsetTop;
        element.style.cursor = 'grabbing';
    };

    document.onmousemove = (e) => {
        if (isDragging) {
            element.style.left = `${e.clientX - offsetX}px`;
            element.style.top = `${e.clientY - offsetY}px`;
        }
    };

    document.onmouseup = () => {
        isDragging = false;
        element.style.cursor = 'move';
    };
}

