// Global variable to track which numbers are highlighted by which buttons
const highlightMap = {};

spinLimit_all = JSON.parse(localStorage.getItem('spinLimit_all')) || spinLimit_all;
groupLengthToggle = JSON.parse(localStorage.getItem('groupLengthToggle')) || groupLengthToggle;
percentLimit_all = JSON.parse(localStorage.getItem('percentLimit_all')) || percentLimit_all;


let edgeDisplay = false;
let groupSizeDisplay = false;
var edgeAlertTable = document.createElement('table');

let useSpins = false;
let usePercent = true;
let useGroupLength = false;


var masterStickyEdgeChart;
var minGroupLength = 4; 
var maxGroupLength = 8;  
var minPercentValue = 90;

let toggleCheck = true;


let helpEdge = false;
let helpSettings = false;
let helpGroupLength = false;
let maxLimit = [0, 569, 260, 185, 112, 87, 87, 69, 65, 56, 50, 37, 33, 33, 28, 28, 25, 23, 22, 22, 21, 18, 16, 15, 15, 12, 12, 12, 11, 10, 8, 8, 7, 7, 6, 5, 4, 1]

let sortOrder = {
    length: 'asc',
    missed: 'asc',
    spinMax: 'asc'
};
let currentSortKey = null;
let currentFilterValue = '';


// Global variable
let previousSpin = 0;
let spins = 0;
let arrayA = Array.from({ length: 37 }, (_, i) => i);

let maxSpins = [1,9,10,12,14,16,18,21,25,26,29,33,35,39,41,45,51,54,56,63,66,74,81,85,93,98,108,123,134,146,161,187,216,265,358,454,810];
let percent90 = [0,85,42,28,21,16,14,11,10,9,8,7,6,6,5,5,5,4,4,4,3,3,3,3,3,3,2,2,2,2,2,2,2,2,1,1,1,1,1];
maxSpins.reverse();

let table = null;
let tableSticky = null;
let sortOrderSticky = 'desc';
let sortOrderNormal = 'desc';

let userSorted = true; // Indicates that the user has sorted the table
let currentSortColumn = 0; // Start with sorting by the first column
let currentSortOrder = 'desc'; // Start with descending order

let userSortedSticky = true; // Indicates that the sticky table is sorted
let currentSortColumnSticky = 0; // Start with sorting by the first column
let currentSortOrderSticky = 'desc'; // Start with descending order for the sticky table

let stickyAlertTable = null;

let filteredMasterChart = null;

function edgeUpdate() {
    getEdgeDataEverySpin();
    let containerCheck = document.getElementById('button-bar-div-14');
    
    // Clear highlight map
    for (const key in highlightMap) {
        delete highlightMap[key];
    }

    if (containerCheck) {
        previousSpin = 0;
        spins = 0;
        arrayA = Array.from({ length: 37 }, (_, i) => i);
        containerCheck.innerHTML = '';
        unhighlightEdge();
        
        let content = theEdge();
        containerCheck.appendChild(content);

        // Reapply the previous sorting for both tables
        if (userSorted && currentSortColumn !== null && currentSortOrder !== null) {
            sortTable(currentSortColumn, currentSortOrder);
        }


    }
}

function getEdgeDataEverySpin()
{
    let edgeData = getEdgeData();


    edgeData.forEach(item=>{

        let data_length = item.length;
        let data_spin = item.spin;
        let data_max = getFrequencies(data_length, data_spin);
        let data_numbers = item.num;

        //const row = createTableRow(button_text, data_length, data_min, data_max, data_spin, data_numbers, data_percent);
        createTableChart(data_length, data_max, data_spin, data_numbers);

    

    });
}

function getColumnIndexBySortKey(sortKey) {
    switch (sortKey) {
        case 'length':
            return 1;
        case 'missed':
            return 2;
        case 'spinMax':
            return 3;
        default:
            return null;
    }
}


function theEdge() {

    
    let container = document.createElement('div');
    container.style.marginLeft = '25px';
    container.style.marginBottom = '15px';
    container.style.fontSize = '15px';
    container.id = 'theEdge';

    let savedColor = localStorage.getItem(container.id+'-containerIdbackgroundColor');
    if (savedColor) {
        container.style.backgroundColor = savedColor;
    }

    let colorChangerQuickSpin = quickSpin_colorChanger(container.id);
    container.append(colorChangerQuickSpin);

    let titleDiv = document.createElement('div');
    titleDiv.style.display = 'flex';
    titleDiv.style.alignItems = 'center';
    titleDiv.style.marginLeft = '25px';


    // Create the title span
    let titleSpan = document.createElement('span');
    titleSpan.innerHTML = '<h2>The Edge</h2>';
    titleSpan.style.marginRight = '10px';

    // ------------------------------------------------------------
    // HELP BUTTON
    // ------------------------------------------------------------
    // Create the help button
    const button = document.createElement('button');
    button.id = 'how-to-edge';
    button.textContent = "How to";
    button.style.padding = '5px';
    button.style.marginRight = '5px';
    button.onclick = toggleButtonHelpEdge;

    let helpDiv = document.createElement('div');
    helpDiv.id = 'help-edge';
    helpDiv.style.marginLeft = '25px';
    helpDiv.style.marginBottom = '15px';
    helpDiv.style.display = 'none';

        let howToSpan = document.createElement('span');
        howToSpan.innerHTML = '<h2>How To</h2>';
        howToSpan.style.marginLeft = '35px';
        howToSpan.style.display = 'block';
        helpDiv.appendChild(howToSpan);

        let edgeHelp = document.createElement('p');
        edgeHelp.style.fontSize = '18px';
        edgeHelp.style.marginLeft = '25px';
        edgeHelp.innerHTML = `The Edge analyzes the number history to identify groups of numbers that haven't appeared.<br>
        It then predicts when these numbers are likely to hit based on how far back the analysis goes,<br>
        drawing on data from over 100 million spins.<br><br>`;
        
        // Append the paragraph to formToggle
        helpDiv.appendChild(edgeHelp);

    // Create an anchor element
    let helpLink = document.createElement('a');
    helpLink.href = './items/edgeHowTo.pdf'; 
    helpLink.textContent = 'How to use'; 
    helpLink.style.display = 'block';
    helpLink.style.fontSize = '20px';
    helpLink.style.marginLeft = '35px';
    helpLink.target = '_blank';
    helpDiv.appendChild(helpLink);
    
    
        

    // ------------------------------------------------------------
    // END: HELP BUTTON
    // ------------------------------------------------------------


    
    // ------------------------------------------------------------
    // Settings Button
    // ------------------------------------------------------------
    const buttonSettings = document.createElement('button');
    buttonSettings.id = 'settings-edge-button';
    buttonSettings.textContent = "Spin & Percent Filter";
    buttonSettings.style.padding = '5px';
    buttonSettings.style.marginRight = '5px';
    buttonSettings.onclick = toggleButtonSettingsEdge;

    let settingsDiv = document.createElement('div');
    settingsDiv.id = 'settings-edge-div';
    settingsDiv.style.marginLeft = '25px';
    settingsDiv.style.marginBottom = '15px';
    settingsDiv.style.display = 'none';

    const buttonGroupLength = document.createElement('button');
    buttonGroupLength.id = 'groupLength-edge-button';
    buttonGroupLength.textContent = "Group Size Filter";
    buttonGroupLength.style.padding = '5px';
    buttonGroupLength.style.marginRight = '5px';
    buttonGroupLength.onclick = toggleButtonGroupLengthEdge;

    let groupLengthDiv = document.createElement('div');
    groupLengthDiv.id = 'groupLength-edge-div';
    groupLengthDiv.style.marginLeft = '25px';
    groupLengthDiv.style.marginBottom = '15px';
    groupLengthDiv.style.display = 'none';



    // ********************************************************
    // START: Settings
    // *******************************************************
    // Create the form
    let form = document.createElement('form');

    // Create the title
    let title = document.createElement('h2');
    title.textContent = 'Spin & Percent Filters';
    form.appendChild(title);

    // How to
let paragraphTrigger = document.createElement('p');
paragraphTrigger.innerHTML  = 'A row will display with the spin or percent are above the limits set here.';
paragraphTrigger.innerHTML  += '<br/><br/>';
paragraphTrigger.style.fontSize = '18px'; // Optional: Set font size or other styles
form.appendChild(paragraphTrigger);




    
    // Create the textbox for entering values
    let inputBox = document.createElement('input');
    inputBox.type = 'text';
    inputBox.id = 'populateValues';
    inputBox.placeholder = 'Enter values like 1,2,3,4,5';
    inputBox.style.width = '300px'; // Set the width of the textbox
    form.appendChild(inputBox);
    
    // Create a button to trigger auto-populating the input fields
    const populateButton = document.createElement('button');
    populateButton.textContent = 'Populate Spin';
    populateButton.type = 'button'; // Prevent form submission
    const populatePercentButton = document.createElement('button');
    populatePercentButton.textContent = 'Populate Percent';
    populatePercentButton.type = 'button'; // Prevent form submission
    form.appendChild(populateButton);
    form.appendChild(populatePercentButton);
    form.appendChild(document.createElement('br'));
    form.appendChild(document.createElement('br'));
    
    // Create the button to update settings
    const updateButton = document.createElement('button');
    updateButton.textContent = 'Save Settings';
    updateButton.type = 'button'; 
    updateButton.style.fontSize = '24px'; 
    updateButton.style.padding = '10px 20px'; 
    updateButton.style.width = '200px';
    updateButton.style.height = '50px'; 
    form.appendChild(updateButton);

    form.appendChild(document.createElement('br'));
    
    // Loop through indices 1 to 35 to create input fields
    for (let index = 1; index <= 35; index++) {
        let label = document.createElement('label');
        label.htmlFor = `settings_${index}`;
        label.textContent = `Group Size ${index}: `;
    
        let input = document.createElement('input');
        input.type = 'text';
        input.id = `settings_${index}`;

        if (input.value !== spinLimit_all[index]) {
            input.value = spinLimit_all[index];
        }
  
    
        let span = document.createElement('span');
        span.textContent = ' Spin Limit '; // Text to display after the input box

        let inputPercent = document.createElement('input');
        inputPercent.type = 'text';
        inputPercent.id = `settingsPercent_${index}`;

        if (inputPercent.value !== percentLimit_all[index]) {
            inputPercent.value = percentLimit_all[index];
        }

        let spanPercent = document.createElement('span');
        spanPercent.textContent = ' Percent'; // Text to display after the input box
    
        input.classList.add('textbox-container', 'triggerGroups');
        input.style.width = '50px';
        input.style.padding = '3px';

        inputPercent.classList.add('textbox-container', 'triggerGroups');
        inputPercent.style.width = '50px';
        inputPercent.style.padding = '3px';
        inputPercent.style.marginLeft = '20px';
    
    
        label.appendChild(input); // Append input box to label
        label.appendChild(span);
        label.appendChild(inputPercent); // Append input box to label
        label.appendChild(spanPercent);

        form.appendChild(label);
        form.appendChild(input); // Append input box to label
        form.appendChild(span);
        form.appendChild(inputPercent); // Append input box to label
        form.appendChild(spanPercent);

       // form.appendChild(label); // Append label to the form
        form.appendChild(document.createElement('br')); // Line break after each input
    }
    
    // Add the form to the body (or another container)
    settingsDiv.appendChild(form);
    
    // Event listener for the populate button
    populateButton.addEventListener('click', () => {
        let inputValues = document.getElementById('populateValues').value;
        
        // Split the input values by comma and remove any extra spaces
        let valuesArray = inputValues.split(',').map(value => value.trim());
        
        // Populate the input fields
        valuesArray.forEach((value, index) => {
            if (index + 1 <= 35) { // Ensure we don't exceed the available input fields
                let inputField = document.getElementById(`settings_${index + 1}`);
                inputField.value = value; // Set the value in the corresponding input box
            }
        });
    });

        // Event listener for the populate button
        populatePercentButton.addEventListener('click', () => {
            let inputValues = document.getElementById('populateValues').value;
            
            // Split the input values by comma and remove any extra spaces
            let valuesArray = inputValues.split(',').map(value => value.trim());
            
            // Populate the input fields
            valuesArray.forEach((value, index) => {
                if (index + 1 <= 35) { // Ensure we don't exceed the available input fields
                    let inputField = document.getElementById(`settingsPercent_${index + 1}`);
                    inputField.value = value; // Set the value in the corresponding input box
                }
            });
        });
    
    // Event listener for the update button
    updateButton.addEventListener('click', () => {
        // Loop through the input fields to update spinLimit_all array
        for (let index = 1; index <= 35; index++) {
            let inputValue = document.getElementById(`settings_${index}`).value;
            let inputPercentValue = document.getElementById(`settingsPercent_${index}`).value;
            // Parse the input value to a number and update the spinLimit_all array
            spinLimit_all[index] = parseInt(inputValue, 10); // Convert the input value to an integer
            percentLimit_all[index] = parseInt(inputPercentValue, 10);
            
            // Optional: Handle invalid inputs
            if (isNaN(spinLimit_all[index])) {
                spinLimit_all[index] =1; // Default to 0 if input is invalid
            }
            if (isNaN(percentLimit_all[index])) {
                percentLimit_all[index] = 90; // Default to 0 if input is invalid
            }

            if (spinLimit_all[index]<1) {
                spinLimit_all[index] = 1; // Default to 0 if input is invalid
            }
            if (percentLimit_all[index]>100) {
                percentLimit_all[index] = 100; // Default to 0 if input is invalid
            }
            if (percentLimit_all[index]<0) {
                percentLimit_all[index] = 0; // Default to 0 if input is invalid
            }

        }
    
        localStorage.setItem('spinLimit_all', JSON.stringify(spinLimit_all));
        localStorage.setItem('percentLimit_all', JSON.stringify(percentLimit_all));

        
        edgeUpdate();
        addEdgeToBottomSticky();
        
    });


   // ********************************************************
    // END: Settings
    // *******************************************************

    // Append the form to the settings div outside of the event listener
    

// *******************************************************
// START: Group Toggle Settings
// *******************************************************
let formToggle = document.createElement('form');

// Create the title for the form
let titleToggle = document.createElement('h2');
titleToggle.textContent = 'Group Size Filter';
formToggle.appendChild(titleToggle);

// How to
let paragraph = document.createElement('p');
paragraph.innerHTML  = 'Uncheck to remove rows of group size.';
paragraph.innerHTML  += '<br/>Group size is the amount of numbers that a row has.';
paragraph.innerHTML  += '<br/>This number is displayed on the button at the start of the row.';
paragraph.innerHTML  += '<br/><br/>';
paragraph.style.fontSize = '18px'; // Optional: Set font size or other styles
formToggle.appendChild(paragraph);



// Create the button to update settings
const uncheckToggleButton = document.createElement('button');
uncheckToggleButton.textContent = 'Toggle all';
uncheckToggleButton.type = 'button'; // Prevent form submission

// Create the button to update settings
const lengthToggleButton = document.createElement('button');
lengthToggleButton.textContent = 'Save Settings';
lengthToggleButton.type = 'button'; 
lengthToggleButton.style.fontSize = '24px'; 
lengthToggleButton.style.padding = '10px 20px'; 
lengthToggleButton.style.width = '200px';
lengthToggleButton.style.height = '50px'; 







formToggle.appendChild(uncheckToggleButton);
formToggle.appendChild(lengthToggleButton);
formToggle.appendChild(document.createElement('br'));
formToggle.appendChild(document.createElement('br'));


// Loop through indices 0 to 38 to create checkboxes
for (let index = 1; index <= 35; index++) {
    let label = document.createElement('label');
    label.htmlFor = `toggle_${index}`;
    label.textContent = `Group Size ${index}: `;
    label.style.fontSize = '18px';
    label.style.marginTop = '25px;'

    let checkbox = document.createElement('input');
    checkbox.type = 'checkbox';
    checkbox.id = `toggle_${index}`;
    checkbox.style = "transform: scale(2); transform-origin: left top; margin-bottom: 20px; margin-left: 10px;";
    checkbox.checked = groupLengthToggle[index]; // Set initial checkbox state based on the array

    // Add event listener to update groupLengthToggle when the checkbox is clicked
    checkbox.addEventListener('change', function() {
        groupLengthToggle[index] = this.checked; // Set the array value based on checkbox state


    });

    label.appendChild(checkbox); // Append the checkbox to the label
    formToggle.appendChild(label); // Append label and checkbox to the form
    formToggle.appendChild(document.createElement('br')); // Line break after each checkbox
}

lengthToggleButton.addEventListener('click', () => {
    // Loop through the checkboxes to update groupLengthToggle array
    for (let index = 1; index <= 35; index++) {
        let checkbox = document.getElementById(`toggle_${index}`);
        groupLengthToggle[index] = checkbox.checked; // Update the array based on checkbox state
    }
    
    // Ensure the checkbox is checked
    groupSizeDisplay = true;

    localStorage.setItem('groupLengthToggle', JSON.stringify(groupLengthToggle));

    edgeUpdate();
    addEdgeToBottomSticky();
});

// Global variable to manage the toggle state
 // Assume false means unchecked, true means checked

uncheckToggleButton.addEventListener('click', () => {
    // Toggle the value of toggleCheck between true and false
    toggleCheck = !toggleCheck;

    for (let index = 1; index <= 35; index++) {
        let checkbox = document.getElementById(`toggle_${index}`);
        
        // Set each checkbox based on the current value of toggleCheck
        checkbox.checked = toggleCheck;

        // Update the groupLengthToggle array
        groupLengthToggle[index] = checkbox.checked;
    }


});




// *******************************************************
// END: Group Toggle Settings
// *******************************************************
groupLengthDiv.appendChild(formToggle);


    // ------------------------------------------------------------
    // END: Settings Button
    // ------------------------------------------------------------

    var edgeCheckbox = document.createElement('input');
	edgeCheckbox.type = 'checkbox';
	edgeCheckbox.id = "edge-display";
	edgeCheckbox.name = "edgeDisplay";
	edgeCheckbox.placeholder = "";
    edgeCheckbox.checked = edgeDisplay;
    edgeCheckbox.style.transform = 'scale(2)';
    edgeCheckbox.style.transformOrigin = 'top left';
    edgeCheckbox.style.marginBottom = '12px';
    edgeCheckbox.style.marginLeft = '10px';
    edgeCheckbox.addEventListener('change', function() {
        edgeDisplay = this.checked;
        addEdgeToBottomSticky();
                // Reapply sorting for sticky table
                if (userSortedSticky && currentSortColumnSticky !== null && currentSortOrderSticky !== null) {

                   sortTableSticky(currentSortColumnSticky, currentSortOrderSticky);
                }

    });

    var groupSizeCheckox = document.createElement('input');
	groupSizeCheckox.type = 'checkbox';
	groupSizeCheckox.id = "groupSize-display";
	groupSizeCheckox.name = "edgeDisplayGroupSize";
	groupSizeCheckox.placeholder = "";
    groupSizeCheckox.checked = groupSizeDisplay;
    groupSizeCheckox.style.transform = 'scale(2)';
    groupSizeCheckox.style.transformOrigin = 'top left';
    groupSizeCheckox.style.marginBottom = '12px';
    groupSizeCheckox.style.marginLeft = '10px';
    groupSizeCheckox.addEventListener('change', function() {
        groupSizeDisplay = this.checked;
        edgeUpdate();
        addEdgeToBottomSticky();

    });

    let spinCheckbox = document.createElement('input');
    spinCheckbox.type = 'checkbox';
    spinCheckbox.id = 'useSpinLimit';
    spinCheckbox.style.transform = 'scale(2)';
    spinCheckbox.style.transformOrigin = 'top left';
    spinCheckbox.style.marginBottom = '12px';
    spinCheckbox.style.marginLeft = '10px';
    spinCheckbox.checked = useSpins; // Set checkbox based on global variable
    spinCheckbox.addEventListener('change', function() {
        useSpins = spinCheckbox.checked;
        edgeUpdate();
        addEdgeToBottomSticky();
    });

    let percentCheckbox = document.createElement('input');
    percentCheckbox.type = 'checkbox';
    percentCheckbox.id = 'usePercentLimit';
    percentCheckbox.style.transform = 'scale(2)';
    percentCheckbox.style.transformOrigin = 'top left';
    percentCheckbox.style.marginBottom = '12px';
    percentCheckbox.style.marginLeft = '10px';
    percentCheckbox.checked = usePercent;
    percentCheckbox.addEventListener('change', function() {
        usePercent = percentCheckbox.checked;
        edgeUpdate();
        addEdgeToBottomSticky();
    });

    let groupLengthCheckbox = document.createElement('input');
    groupLengthCheckbox.type = 'checkbox';
    groupLengthCheckbox.id = 'useGroupLengthLimit';
    groupLengthCheckbox.style.transform = 'scale(2)';
    groupLengthCheckbox.style.transformOrigin = 'top left';
    groupLengthCheckbox.style.marginBottom = '12px';
    groupLengthCheckbox.style.marginLeft = '10px';
    groupLengthCheckbox.checked = useGroupLength;
    groupLengthCheckbox.addEventListener('change', function() {
        useGroupLength = groupLengthCheckbox.checked;
        edgeUpdate();
        addEdgeToBottomSticky();
    });

    

    table = document.createElement('table');
    const headerRow = document.createElement('tr');
    let sortDirections = {}; 
    const headers = ['Button', 'LookBack', 'Data', 'Percent', 'Max', 'Numbers'];


    headers.forEach((headerText, index) => {
        const headerCell = document.createElement('th');
        headerCell.innerHTML = headerText;
    
        headerCell.style.paddingLeft = '5px';
        headerCell.style.paddingRight = '5px';
    
        // Set default sort direction to ascending for each column
        sortDirections[headerText] = 'desc';
    
        // Add click event to toggle sorting for all except "Numbers"
        if (headerText !== 'Numbers') {
            headerCell.addEventListener('click', function () {
                const sortOrder = sortDirections[headerText];
                // Sort the table based on the current column
               sortTable(index, sortOrder);
                // Toggle the sort direction
                sortDirections[headerText] = sortOrder === 'asc' ? 'desc' : 'asc';
            });
        }
    
        headerRow.appendChild(headerCell);
    });

        table.appendChild(headerRow);

            

                // Body Rows

        if(groupSizeDisplay)
        {
            
            tableChart = masterEdgeChart.filter(row => {
                
                if (spinLimit_all[row.data_length] === undefined) {
                    return false;
                }
                let meetsSpinLimit = useSpins ? row.element_number >= spinLimit_all[row.data_length] : false;
                let meetsPercentLimit = usePercent ? row.percentage >= percentLimit_all[row.data_length] : false;
                let meetsGroupLength = useGroupLength ? groupLengthToggle[row.data_length]==true : true;


                return (meetsSpinLimit || meetsPercentLimit) && meetsGroupLength;

            });
        
        }else
        {
            tableChart = masterEdgeChart.filter(() => true);
        }
               // tableChart.sort((a, b) => b.data_length - a.data_length); // Sorts tableChart in ascending order based on data_length

                tableChart.forEach(rowData => {
        
                        const row = table.insertRow(); // Create a row only if the condition is met
                        appendRow(row, rowData);

                });


               

        titleDiv.appendChild(titleSpan);
        titleDiv.appendChild(button);
        titleDiv.appendChild(buttonSettings);
        titleDiv.appendChild(buttonGroupLength);

        titleDiv.appendChild(edgeCheckbox);
        let spanNode = document.createElement('span'); 
        spanNode.textContent = "Show Alert"; 
        spanNode.style.paddingLeft = '20px';
        titleDiv.appendChild(spanNode); 

        titleDiv.appendChild(groupSizeCheckox);
        let spanNodeGroupSize = document.createElement('span'); 
        spanNodeGroupSize.textContent = "Toggle"; 
        spanNodeGroupSize.style.paddingLeft = '20px';
        titleDiv.appendChild(spanNodeGroupSize); 

        titleDiv.appendChild(spinCheckbox);
        let spanNodespinCheckbox = document.createElement('span'); 
        spanNodespinCheckbox.textContent = "Spin Filter"; 
        spanNodespinCheckbox.style.paddingLeft = '20px';
        titleDiv.appendChild(spanNodespinCheckbox); 

        titleDiv.appendChild(percentCheckbox);
        let spanNodepercentCheckbox = document.createElement('span'); 
        spanNodepercentCheckbox.textContent = "Percent Filter"; 
        spanNodepercentCheckbox.style.paddingLeft = '20px';
        titleDiv.appendChild(spanNodepercentCheckbox); 

        titleDiv.appendChild(groupLengthCheckbox);
        let spanNodeGroupLength = document.createElement('span'); 
        spanNodeGroupLength.textContent = "Group Size Filter"; 
        spanNodeGroupLength.style.paddingLeft = '20px';
        titleDiv.appendChild(spanNodeGroupLength); 

    container.appendChild(titleDiv);
    container.appendChild(helpDiv);
    container.appendChild(settingsDiv);
    container.appendChild(groupLengthDiv);
    
    container.appendChild(table);

    return container;
}

function probabilityHitAtLeastOnce(spins, arraySize) {
    const totalOutcomes = 37; 
    const probHitSingleSpin = arraySize / totalOutcomes;
    const probMissSingleSpin = 1 - probHitSingleSpin;
    const probMissAllSpins = Math.pow(probMissSingleSpin, spins);


    return 1 - probMissAllSpins;
}



function createTableRow_good(button_text, data_length, data_min, data_max, data_spin, data_numbers, data_percent) {
    const row = document.createElement('tr');
    row.style.marginBottom = '10px';

    let limit_reached = data_spin > data_max;

    // Highlight the row if the Length is equal to or greater than the 90% value
    if (data_max <=5 && data_length<36)  {
        row.style.backgroundColor = '#FFBF00';
    }

    const buttonCell = document.createElement('td');
    const button = document.createElement('button');
    button.innerText = button_text;
    button.setAttribute('data-numbers', JSON.stringify(data_numbers));
    button.onclick = function () {
        EdgeToggleHighlight(data_numbers, button);
    };
    buttonCell.appendChild(button);

    const lengthCell = document.createElement('td');
    lengthCell.style.textAlign = 'center';
    lengthCell.innerText = data_length;

    const minCell = document.createElement('td');
    minCell.style.textAlign = 'center';
    minCell.innerText = data_min;

    const missedCell = document.createElement('td');
    missedCell.style.textAlign = 'center';
    missedCell.innerText = data_spin;

    const maxCell = document.createElement('td');
    maxCell.style.textAlign = 'center';
    maxCell.innerText = data_max;

    const percentCell = document.createElement('td');
    percentCell.style.textAlign = 'center';
    percentCell.innerHTML = data_percent;

    const numbersCell = document.createElement('td');
    numbersCell.innerText = analyzeRouletteArray(data_numbers).join(' - ') + '\n' + data_numbers.join(', ');
    numbersCell.style.paddingBottom = '10px';

    row.appendChild(buttonCell);
    row.appendChild(lengthCell);
    row.appendChild(minCell);
    row.appendChild(missedCell);
    row.appendChild(maxCell);
    row.appendChild(percentCell);
    row.appendChild(numbersCell);
   
    return row;
}


function createTableChart(data_length, data_max, current_spin, data_numbers) {


    const row = document.createElement('tr');
    row.style.marginBottom = '10px';

    let numberUp = numbers.length === 0 ? 99 : numbers[numbers.length - 1];
    
    // Step 1: Remove rows where current_spin is in data_numbers
    masterEdgeChart = masterEdgeChart.filter(row => !row.data_numbers.includes(numberUp));



    // Helper function to check if data_numbers matches any existing row's data_numbers
    const isUniqueNumbers = (numbers) => {
        return !masterEdgeChart.some(row => 
            row.data_numbers.length === numbers.length 
        );
    };


    
        // Step 2: Add row if data_length <= 10, data_max <= 20, and data_numbers are unique
        if (data_length<36 && isUniqueNumbers(data_numbers)) {

            { data_length, data_max, current_spin, data_numbers }
             
            data_max = getMaxSpin(data_max);
            let element_number = 1;
            let percentage = getPercentageFromLookupTable(data_length, current_spin, element_number);
            percentage = parseFloat(percentage);
            masterEdgeChart.push({ data_length, current_spin, data_max, data_numbers, element_number,percentage});

        }
        
        masterEdgeChart.forEach((item, index) => {
            // Assuming percentage is calculated as (current_spin / data_max) * 100
            let percentage = getPercentageFromLookupTable(item.data_length, item.current_spin, item.element_number);
            percentage = parseFloat(percentage);
            // Update the object with the new percentage
            masterEdgeChart[index] = { 
                ...item,  // keep existing items
                percentage: percentage
            };
        });

       // masterEdgeChart = JSON.parse(JSON.stringify(tableChart));

       

}
function appendRow(row, rowData) {
    const { data_length, data_max, current_spin, data_numbers, element_number,percentage } = rowData;

    
    row.style.backgroundColor = '';

    let meetsSpinLimit = rowData.element_number >= spinLimit_all[rowData.data_length]; 
    let meetsPercentLimit = rowData.percentage >= percentLimit_all[rowData.data_length]; 
    


    if(meetsSpinLimit && meetsPercentLimit){
        row.style.backgroundColor = '#8cff8c';
        
    }
    else
    {
        if(meetsSpinLimit){
            row.style.backgroundColor = '#fff0a6';
        };

        if(meetsPercentLimit){
            row.style.backgroundColor = '#ffcd8c';
          
        };
    }




    // Create button cell
    const buttonCell = row.insertCell();
    const button = document.createElement('button');
    button.innerText = data_length; // Change as needed
    button.setAttribute('data-numbers', JSON.stringify(data_numbers));
    button.onclick = function () {
        EdgeToggleHighlight(data_numbers, button);
    };
    buttonCell.appendChild(button);

    // Lookback
    const LookBack = row.insertCell();
    LookBack.textContent = current_spin;
    LookBack.style.textAlign = 'center';
    LookBack.style.color = 'blue';
    LookBack.style.textDecoration = 'underline';
    LookBack.style.cursor = 'pointer';


   

    LookBack.addEventListener('click', function() {
        // Check if the next sibling is the details row (to avoid adding multiple times)
        if (!row.nextElementSibling || !row.nextElementSibling.classList.contains('details-row')) {



            // Create a new row below the clicked row
            let detailsRow = row.parentNode.insertRow(row.rowIndex + 1);
            detailsRow.classList.add('details-row'); // Add a class for styling if needed
    
            // Create a cell to span across all columns
            let detailsCell = detailsRow.insertCell(0);
            detailsCell.colSpan = row.cells.length; // Span the cell across all table columns
            
            
                                 // Create a close button to hide the details
                                 let closeButton = document.createElement('button');
                                 closeButton.textContent = 'Close';
                                 closeButton.style.marginTop = '10px';
                                 detailsCell.appendChild(closeButton);
            
            let current_item = getFrequencies(data_length, current_spin);


// Calculate the total frequency sum
let totalFrequency = Object.values(current_item).reduce((sum, val) => sum + val, 0);

// Iterate over each key and calculate the percentage
let runningTotal = 0;
let formattedContent = '';
for (let key in current_item) {
    if (current_item.hasOwnProperty(key)) {
        let frequency = current_item[key];
        runningTotal += frequency;
        let percent = ((runningTotal / totalFrequency) * 100).toFixed(2);  // Calculate percentage and format to 2 decimal places
        formattedContent += `${key}: ${frequency}  - ${percent}%\n`;
    }
}


            // Add content to the details cell
            let contentDiv = document.createElement('div');
            contentDiv.innerText = "\n"+formattedContent; 
            detailsCell.appendChild(contentDiv);
    
   
    
            // Close button event listener to remove the row
            closeButton.addEventListener('click', function() {
                detailsRow.remove(); // Remove the details row when close button is clicked
            });
        }
    });

    let current_item = getFrequencies(data_length, current_spin);
    let current_element = getFrequencySpins(current_item, element_number);   
    const groupSpin = row.insertCell();
    groupSpin.appendChild(current_element);
    groupSpin.style.textAlign = 'left';



        // Percent
        const percent = row.insertCell();
        percent.textContent = percentage;
        percent.style.textAlign = 'center';

    const maxCell = row.insertCell();
    maxCell.textContent = data_max;
    maxCell.style.textAlign = 'center';



    const numbersCell = row.insertCell();
    numbersCell.innerHTML = analyzeRouletteArray(data_numbers).join(' - ') + '<br>' + data_numbers.join(', ');
    numbersCell.style.paddingBottom = '10px';

}

function toggleButtonSettingsEdgeHelp()
{
    const button = document.getElementById(`settings-edge-button-help`);
    if (button) {
        helpSettings = !helpSettings;
        button.style.backgroundColor = helpSettings ? 'lightgreen' : '';

        let helpDiv = document.getElementById('settings-edge-div-help');
        

        if (helpSettings) {
            helpDiv.style.display = 'block';
        }
        else
        {
            helpDiv.style.display = 'none'; 
        }
    } 
}

function toggleButtonSettingsEdge()
{
    const button = document.getElementById(`settings-edge-button`);
    if (button) {
        helpSettings = !helpSettings;
        button.style.backgroundColor = helpSettings ? 'lightgreen' : '';

        let helpDiv = document.getElementById('settings-edge-div');
        

        if (helpSettings) {
            helpDiv.style.display = 'block';
        }
        else
        {
            helpDiv.style.display = 'none'; 
        }
    } 
}

function toggleButtonGroupLengthEdge()
{
    const button = document.getElementById(`groupLength-edge-button`);
    if (button) {
        helpGroupLength = !helpGroupLength;
        button.style.backgroundColor = helpGroupLength ? 'lightgreen' : '';

        let helpDiv = document.getElementById('groupLength-edge-div');
        

        if (helpGroupLength) {
            helpDiv.style.display = 'block';
        }
        else
        {
            helpDiv.style.display = 'none'; 
        }
    } 
}
function toggleButtonHelpEdge() {
    const button = document.getElementById(`how-to-edge`);
    if (button) {
        helpEdge = !helpEdge;
        button.style.backgroundColor = helpEdge ? 'lightgreen' : '';

        let helpDiv = document.getElementById('help-edge');
        

        if (helpEdge) {
            helpDiv.style.display = 'block';
        }
        else
        {
            helpDiv.style.display = 'none'; 
        }
    }
}

function unhighlightEdge()
{
    let arr = Array.from({ length: 37 }, (_, i) => i);
    arr.forEach(item => {
        let div;
        if (item === 0) {
            div = document.querySelector(`div[data-values="zero_${item}"]`);
        } else {
            div = document.querySelector(`div[data-values="${item}"]`);
        }
        div.classList.remove('slider-highlights');
    });
}



function EdgeToggleHighlight(arr, button) {
    
    arr.forEach(item => {
        let div;
        if (item === 0) {
            div = document.querySelector(`div[data-values="zero_${item}"]`);
        } else {
            div = document.querySelector(`div[data-values="${item}"]`);
        }

        if (div) {
            if (!highlightMap[item]) {
                highlightMap[item] = new Set();
                
            }

            if (highlightMap[item].has(button)) {
                highlightMap[item].delete(button);
                
                if (highlightMap[item].size === 0) {
                    div.classList.remove('slider-highlights');
                }
            } else {
                highlightMap[item].add(button);
                
                div.classList.add('slider-highlights');
            }
        } else {
            console.error('Failed to find div for item:', item);
        }
    });

    const isHighlighted = arr.some(item => highlightMap[item] && highlightMap[item].has(button));
    button.style.backgroundColor = isHighlighted ? 'darkblue' : '';
}


function resetEdgeToggle() {
    // Iterate over all items in highlightMap
    for (const item in highlightMap) {
        const div = item === '0' ? document.querySelector(`div[data-values="zero_${item}"]`) : document.querySelector(`div[data-values="${item}"]`);

        if (div) {
            div.classList.remove('slider-highlights');
        }
    }

    // Clear the highlightMap
    Object.keys(highlightMap).forEach(item => {
        highlightMap[item].clear(); // Clear the set of buttons for each item
    });

    // Reset all button background colors (if needed)
    const buttons = document.querySelectorAll('button');
    buttons.forEach(button => {
        button.style.backgroundColor = ''; // Remove the highlight color
    });
}

function analyzeRouletteArray(arr) {
    // Red numbers in a standard roulette wheel
    const redNumbers = new Set([1, 3, 5, 7, 9, 12, 14, 16, 18, 19, 21, 23, 25, 27, 30, 32, 34, 36]);
    
    // Initialize counts
    let evenCount = 0, oddCount = 0;
    let redCount = 0, blackCount = 0;
    let highCount = 0, lowCount = 0;
    let dozen1Count = 0, dozen2Count = 0, dozen3Count = 0;
    let row1Count = 0, row2Count = 0, row3Count = 0;
    
    arr.forEach(num => {
        if (num !== 0) {  // 0 is neither red/black, high/low, etc.
            // Even/Odd
            if (num % 2 === 0) {
                evenCount++;
            } else {
                oddCount++;
            }
            
            // Red/Black
            if (redNumbers.has(num)) {
                redCount++;
            } else {
                blackCount++;
            }
            
            // High/Low
            if (num >= 1 && num <= 18) {
                lowCount++;
            } else {
                highCount++;
            }
            
            // Dozens
            if (num >= 1 && num <= 12) {
                dozen1Count++;
            } else if (num >= 13 && num <= 24) {
                dozen2Count++;
            } else {
                dozen3Count++;
            }
            
            // Rows
            if ((num - 1) % 3 === 0) {
                row1Count++;
            } else if ((num - 1) % 3 === 1) {
                row2Count++;
            } else {
                row3Count++;
            }
        }
    });
    
    // Determine the most frequent in each category
    const evenOdd = evenCount >= oddCount ? 'E' : 'O';
    const redBlack = redCount >= blackCount ? 'R' : 'B';
    const highLow = highCount >= lowCount ? 'H' : 'L';
    const dozen = dozen1Count >= dozen2Count && dozen1Count >= dozen3Count ? 'D1' : (dozen2Count >= dozen3Count ? 'D2' : 'D3');
    const row = row1Count >= row2Count && row1Count >= row3Count ? 'R1' : (row2Count >= row3Count ? 'R2' : 'R3');
    
    return [evenOdd, redBlack, highLow, dozen, row];
}

function parseFilterInput(input) {
    const filters = input.split(',').map(range => {
        const [start, end] = range.split('-').map(Number);
        if (end !== undefined) {
            return Array.from({ length: end - start + 1 }, (_, i) => start + i);
        } else {
            return [start];
        }
    });

    return filters.flat(); // Flatten the array of arrays into a single array
}


function sortTable(columnIndex, sortOrder) {
    userSorted = true;
    currentSortColumn = columnIndex;
    currentSortOrder = sortOrder;

    
    // Sort tableChart based on the selected column index

    tableChart.sort((a, b) => {
        const aValue = getColumnValue(a, columnIndex);
        const bValue = getColumnValue(b, columnIndex);

        // Sort based on whether the value is numeric or string
        if (typeof aValue === 'number' && typeof bValue === 'number') {
            return sortOrder === 'asc' ? aValue - bValue : bValue - aValue;
        } else {
            return sortOrder === 'asc' ? aValue.localeCompare(bValue) : bValue.localeCompare(aValue);
        }
    });

    // Rebuild the table rows with the sorted data
    rebuildTableRows();
}
function sortTableSticky(columnIndex, sortOrderSticky) {
    userSortedSticky = true;
    currentSortColumnSticky = columnIndex;
    currentSortOrderSticky = sortOrderSticky;

    // Sort filteredMasterChart based on the selected column index
    filteredMasterChart.sort((a, b) => {
        const aValue = getColumnValue(a, columnIndex);
        const bValue = getColumnValue(b, columnIndex);

        // Sort based on whether the value is numeric or string
        if (typeof aValue === 'number' && typeof bValue === 'number') {
            return sortOrderSticky === 'asc' ? aValue - bValue : bValue - aValue;
        } else {
            return sortOrderSticky === 'asc' ? aValue.localeCompare(bValue) : bValue.localeCompare(aValue);
        }
    });

    // Rebuild the sticky table rows with the sorted data
    rebuildTableRowsSticky();
}

function getColumnValue(rowData, columnIndex) {
    switch (columnIndex) {
        case 0: // Button header (sort by the length of data-numbers array)
            return rowData.data_length;
        case 1: // LookBack header (sort by current_spin)
            return rowData.current_spin;
        case 2: // Data header (sort by the value in the first <td>)
            return getFirstTDValue(rowData);
        case 3: // Percent header (sort by percentage)
            return calculateSpinPercentage(getFrequencies(rowData.data_length, rowData.current_spin), rowData.element_number);
        case 4: // Max header (sort by data_max)
            return rowData.data_max;
        default:
            return '';
    }
}
function getFirstTDValue(rowData) {
    // Assuming the first <td> contains numeric data
    const firstTD = rowData.data_length; // Change this if needed to retrieve the first td value
    return firstTD;
}

function rebuildTableRows() {
    // Remove existing rows (except the header)
    while (table.rows.length > 1) {
        table.deleteRow(1);
    }

    // Rebuild the table with sorted data
    tableChart.forEach(rowData => {
        const row = table.insertRow();
        appendRow(row, rowData);
    });
}
function rebuildTableRowsSticky() {
    // Remove existing rows (except the header)
    while (tableSticky.rows.length > 1) {
        tableSticky.deleteRow(1);
    }

    // Rebuild the table with sorted filteredMasterChart data
    filteredMasterChart.forEach(rowData => {
        const row = tableSticky.insertRow();
        appendStickyRow(row, rowData);
    });
}



function filterTableByLength(input) {
    const table = document.querySelector('#theEdge table');
    const rows = Array.from(table.rows).slice(1); // Skip the header row

    const filters = parseFilterInput(input);

    rows.forEach(row => {
        const lengthCell = row.cells[1].innerText;
        const length = parseInt(lengthCell, 10);

        // Check if the length is included in the filters array
        if (filters.includes(length)) {
            row.style.display = '';
        } else {
            row.style.display = 'none';
        }
    });

    // Store the current filter value
    currentFilterValue = input;
}
function filterStickTable(input) {
    const table = document.querySelector('#edge-alert-sticky table');
    const rows = Array.from(table.rows).slice(1); // Skip the header row

    const filters = parseFilterInput(input);

    rows.forEach(row => {
        const lengthCell = row.cells[1].innerText;
        const length = parseInt(lengthCell, 10);

        // Check if the length is included in the filters array
        if (filters.includes(length)) {
            row.style.display = '';
        } else {
            row.style.display = 'none';
        }
    });

    // Store the current filter value
    currentFilterValue = input;
}



function addEdgeToBottomSticky() {
    var stickyDiv = document.getElementById('sticky-bottom-alert');

    // Remove existing alert container if present
    var existingEdgeAlert = document.getElementById('edge-alert-sticky');
    if (existingEdgeAlert) {
        stickyDiv.removeChild(existingEdgeAlert);
    }

    // Do not proceed if display is not enabled
    if (!edgeDisplay) {
        return;
    }

    // Create a new container for the alert
    var edgeAlertContainer = document.createElement('div');
    edgeAlertContainer.id = 'edge-alert-sticky';
    const viewportHeight = window.innerHeight;
    const maxHeight = viewportHeight * 0.20;
    edgeAlertContainer.style.maxHeight = maxHeight + 'px';
    edgeAlertContainer.style.overflowY = 'auto';
    edgeAlertContainer.style.paddingRight = '25px';
    
    // Build the sticky table and reapply sorting if needed
    stickyAlertTable = stickyTableData();
    
    // Append the filtered table to the container
    edgeAlertContainer.appendChild(stickyAlertTable);

    // Append the container to the sticky div before calculating its height
    stickyDiv.appendChild(edgeAlertContainer);
}


function filterForSticky() {

    return masterEdgeChart.filter(row => {

        if (spinLimit_all[row.data_length] === undefined) {
            return false;
        }
        let meetsSpinLimit = useSpins ? row.element_number >= spinLimit_all[row.data_length] : false;
        let meetsPercentLimit = usePercent ? row.percentage >= percentLimit_all[row.data_length] : false;
        let meetsGroupLength = useGroupLength ? groupLengthToggle[row.data_length]==true : true;


        return (meetsSpinLimit || meetsPercentLimit) && meetsGroupLength;
    });
}
function stickyTableData() {
    // Filter and prepare the table data
    filteredMasterChart = filterForSticky();

    // Create the sticky table
    tableSticky = document.createElement('table');
    const headerRow = document.createElement('tr');
    let sortDirectionsSticky = {};

    const headers = ['Button', 'LookBack', 'Data', 'Percent', 'Max', 'Numbers'];

    headers.forEach((headerText, index) => {
        const headerCell = document.createElement('th');
        headerCell.innerHTML = headerText;

        headerCell.style.paddingLeft = '5px';
        headerCell.style.paddingRight = '5px';
        // Set default sort direction to ascending for each column
        sortDirectionsSticky[headerText] = 'desc';
        // Add click event to toggle sorting for all except "Numbers"
        if (headerText !== 'Numbers') {
            headerCell.addEventListener('click', function () {
                const sortOrderSticky = sortDirectionsSticky[headerText];
                sortTableSticky(index, sortOrderSticky);
                sortDirectionsSticky[headerText] = sortOrderSticky === 'asc' ? 'desc' : 'asc';
            });
        }

        headerRow.appendChild(headerCell);
    });

    tableSticky.appendChild(headerRow);

    // Add rows to the table based on the sorted data
    filteredMasterChart.forEach(rowData => {
        const row = tableSticky.insertRow();
        appendStickyRow(row, rowData);
    });
    
    return tableSticky;
}

function appendStickyRow(row, rowData) {
    const { data_length, data_max, current_spin, data_numbers, element_number, percentage } = rowData;

    row.style.backgroundColor = '';

    let meetsSpinLimit = rowData.element_number >= spinLimit_all[rowData.data_length]; 
    let meetsPercentLimit = rowData.percentage >= percentLimit_all[rowData.data_length]; 
    


    if(meetsSpinLimit && meetsPercentLimit){
        row.style.backgroundColor = '#8cff8c';
        
    }
    else
    {
        if(meetsSpinLimit){
            row.style.backgroundColor = '#fff0a6';
        };

        if(meetsPercentLimit){
            row.style.backgroundColor = '#ffcd8c';
          
        };
    }

    // Create button cell
    const buttonCell = row.insertCell();
    const button = document.createElement('button');
    button.innerText = data_length; // Change as needed
    button.setAttribute('data-numbers', JSON.stringify(data_numbers));
    button.onclick = function () {
        EdgeToggleHighlight(data_numbers, button);
    };
    buttonCell.appendChild(button);

    // Lookback
    const LookBack = row.insertCell();
    LookBack.textContent = current_spin;
    LookBack.style.textAlign = 'left';
    LookBack.style.color = 'blue';
    LookBack.style.textDecoration = 'underline';
    LookBack.style.cursor = 'pointer';

    LookBack.addEventListener('click', function() {
        // Check if the next sibling is the details row (to avoid adding multiple times)
        if (!row.nextElementSibling || !row.nextElementSibling.classList.contains('details-row')) {
    
            // Create a new row below the clicked row
            let detailsRow = row.parentNode.insertRow(row.rowIndex + 1);
            detailsRow.classList.add('details-row'); // Add a class for styling if needed
    
            // Create a cell to span across all columns
            let detailsCell = detailsRow.insertCell(0);
            detailsCell.colSpan = row.cells.length; // Span the cell across all table columns
            detailsCell.style.textAlign = 'left'; // Make sure the content is left-aligned
    
            // Create a close button to hide the details
            let closeButton = document.createElement('button');
            closeButton.textContent = 'Close';
            closeButton.style.marginTop = '10px';
            detailsCell.appendChild(closeButton);
    
            let current_item = getFrequencies(data_length, current_spin);
    
            // Calculate the total frequency sum
            let totalFrequency = Object.values(current_item).reduce((sum, val) => sum + val, 0);
    
            // Iterate over each key and calculate the percentage
            let runningTotal = 0;
            let formattedContent = '';
            for (let key in current_item) {
                if (current_item.hasOwnProperty(key)) {
                    let frequency = current_item[key];
                    runningTotal += frequency;
                    let percent = ((runningTotal / totalFrequency) * 100).toFixed(2);  // Calculate percentage and format to 2 decimal places
                    formattedContent += `${key}: ${frequency}  - ${percent}%\n`;
                }
            }
    
            // Add content to the details cell
            let contentDiv = document.createElement('div');
            contentDiv.innerText = "\n" + formattedContent; 
            contentDiv.style.textAlign = 'left'; // Ensure the content is left-aligned
            detailsCell.appendChild(contentDiv);
    
            // Close button event listener to remove the row
            closeButton.addEventListener('click', function() {
                detailsRow.remove(); // Remove the details row when close button is clicked
            });
        }
    });
    
   


    let current_item = getFrequencies(data_length, current_spin);
    let current_element = getFrequencySpins(current_item, element_number);   
    const groupSpin = row.insertCell();
    groupSpin.appendChild(current_element);
    groupSpin.style.textAlign = 'left';

        // Percent
        const percent = row.insertCell();
        percent.textContent = percentage;
        percent.style.textAlign = 'center';

    const maxCell = row.insertCell();
    maxCell.textContent = data_max;
    maxCell.style.textAlign = 'center';



    const numbersCell = row.insertCell();
    numbersCell.innerHTML = analyzeRouletteArray(data_numbers).join(' - ');
    numbersCell.style.paddingBottom = '10px';

}
// ------------------------------------------------------------------
// NEW
//---------------------------------------------------------------------

function trackspins2UntilAllGone() {
    let numbersAll = Array.from(Array(37).keys()); // Initialize array with numbers 0-36
    let spins2 = []; // To track what spin each length hit on
    let totalspins2 = 0; // To count total spins2
    // Create a copy of the global randNumbers array and reverse it for backward iteration
    let randNumbersCopy = [...numbers];

    while (numbersAll.length > 0 && randNumbersCopy.length > 0) {
        totalspins2 += 1;
        // Get a number from the end of the randNumbers copy
        let randNumber = randNumbersCopy.pop();

        if (numbersAll.includes(randNumber)) {
            spins2.push({ length: numbersAll.length, spin: totalspins2, num: numbersAll }); // Record the current length and the spin it hit on
            numbersAll = numbersAll.filter(num => num !== randNumber); // Remove the hit number from the array
        }
    }

    return spins2;
}

function getEdgeData() {
    let trialData = trackspins2UntilAllGone();
    let enhancedData = trialData.map(data => {
        let stats = getFrequencyPercentage(data.length, data.spin - 1);
        return {
            ...data,
            percentage: stats.percentage,
            minSpin: stats.minSpin,
            maxSpin: stats.maxSpin
        }; // Append percentage, minSpin, and maxSpin to each data entry
    });
    return enhancedData;
    
}


   
function getFrequencyPercentage(arrayLength, spinNumber) {

    let frequencyObject = frequencyData.find(item => item.arrayLength === arrayLength);
    if (!frequencyObject) {
        return {
            percentage: "Array length not found.",
            minSpin: null,
            maxSpin: null
        };
    }

    let frequencies = frequencyObject.frequencies;
    let minSpin = Math.min(...Object.keys(frequencies).map(key => parseInt(key)));
    let maxSpin = Math.max(...Object.keys(frequencies).map(key => parseInt(key)));
    let totalFrequency = Object.values(frequencies).reduce((sum, current) => sum + current, 0);
    let cumulativeFrequency = 0;

    // Sum frequencies up to and including the spin number
    for (let spin in frequencies) {
        if (parseInt(spin) <= spinNumber) {
            cumulativeFrequency += frequencies[spin];
        }
    }

    let percentage = 0;
    if (cumulativeFrequency === 0) {
        if (spinNumber < minSpin) {
            percentage = 0;
        } else if (spinNumber > maxSpin) {
            percentage = 100;
        }
    } else {
        percentage = (cumulativeFrequency / totalFrequency) * 100;
    }

    return {
        percentage: percentage.toFixed(2),
        minSpin: minSpin,
        maxSpin: maxSpin
    };
}

// ******************************************************************************
 // START: Function to get the frequencies based on Length and LookBack
 // ******************************************************************************

 function getPercentageFromLookupTable(groupLength, lookBack, spin) {
    // Ensure the groupLength, lookBack, and spin exist in the lookup table
    if (!lookupTable[groupLength] || !lookupTable[groupLength][lookBack] || !lookupTable[groupLength][lookBack][spin]) {
        return null; // Return null if any key is not found
    }

    // Get the spin data for the specified groupLength and lookBack
    const spinData = lookupTable[groupLength][lookBack];
    
    // Calculate the total of all spins in the LookBack
    const total = Object.values(spinData).reduce((acc, freq) => acc + freq, 0);

    // Calculate the cumulative frequency from spin 1 to the given spin
    let cumulativeFrequency = 0;
    for (let i = 1; i <= spin; i++) {
        if (spinData[i]) {
            cumulativeFrequency += spinData[i];
        }
    }

    // Calculate the percentage and round to two decimals
    const percentage = (cumulativeFrequency / total) * 100;

    return percentage.toFixed(2);
}


 function getFrequencies(length, lookBack) {
    const lengthStr = length.toString();
    const lookBackStr = lookBack.toString();
    if (lookupTable[lengthStr] && lookupTable[lengthStr][lookBackStr]) {
        return lookupTable[lengthStr][lookBackStr];
    } else {
        return `No data found for Length ${length} and LookBack ${lookBack}`;
    }
}

// Function to handle the button click and display the result
function lookupFrequencies() {
    const length = document.getElementById('lengthInput').value;
    const lookBack = document.getElementById('lookbackInput').value;
    
    if (length === "" || lookBack === "") {
        document.getElementById('result').innerHTML = "Please enter both Length and LookBack.";
        return;
    }

    const result = getFrequencies(length, lookBack);
    document.getElementById('result').innerHTML = 
        typeof result === 'string' ? result : JSON.stringify(result);
}

function getFrequencySpins(data, spinNumber) {
    // Create a table element
    let table = document.createElement('table');
    table.style.borderCollapse = 'collapse'; // Optional styling for table

    // Iterate over the object and create rows
    Object.keys(data).forEach(key => {
        let row = document.createElement('tr');
        let keyCell = document.createElement('td');
        let valueCell = document.createElement('td');

        // Set the text content for the key and value cells
        keyCell.textContent = key;
        valueCell.textContent = data[key];

        // Apply some basic styling
        keyCell.style.border = '1px solid black';
        valueCell.style.border = '1px solid black';
        keyCell.style.padding = '5px';
        valueCell.style.padding = '5px';

        // Highlight the row if it matches the spin number
        if (parseInt(key, 10) === spinNumber) {
            //row.style.backgroundColor = 'yellow'; // You can change this color as desired
            row.appendChild(keyCell);
            row.appendChild(valueCell);
        }

        // Append cells to the row
    //    row.appendChild(keyCell);
     //   row.appendChild(valueCell);

        // Append row to the table
        table.appendChild(row);
    });

   return table;
}
function getMaxSpin(data) {
    // Get the keys of the object and find the maximum key
    const maxSpin = Math.max(...Object.keys(data).map(Number)); // Convert keys to numbers and find the max
    return maxSpin;
}

function calculateSpinPercentage(spinData, spinNumber) {

    // Step 1: Get the total frequency by summing all values in the object
    const totalFrequency = Object.values(spinData).reduce((acc, val) => acc + val, 0);
    

    // Step 2: Check if the spin number exists in the object
    if (spinData[spinNumber] === undefined) {
        // Step 3: Find the closest lower spin number
        const availableSpins = Object.keys(spinData).map(Number); // Convert keys to numbers
        const closestLowerSpin = Math.max(...availableSpins.filter(spin => spin <= spinNumber));
        
        if (closestLowerSpin === -Infinity) {
            return 0;
        }
        
        // Use the closest lower spin number
        spinNumber = closestLowerSpin;
    }
    
    // Step 4: Get the frequency of the (potentially adjusted) spin number
    let cumulativeFrequency = 0;
    for (let spin in spinData) {
        if (parseInt(spin, 10) <= spinNumber) {
            cumulativeFrequency += spinData[spin];
        }
    }

    // Step 4: Calculate the percentage
    const percentage = (cumulativeFrequency / totalFrequency) * 100;

    return percentage.toFixed(2);
}



// ******************************************************************************
 // END: Function to get the frequencies based on Length and LookBack
 // ******************************************************************************