let statLookBack = numbers.length;
let statsLookBackAll = true;


function updateStats()
{

    calc_Evens();
    calc_Dozens();
    calc_Combo();
}

function calc_Evens()
{    var table = document.getElementById('id_stats_table_evens'); 


    // Get Lookback Spins
    var id = 'id_stats_table_evens';
    var overSpinsInput = document.getElementById('look_back_' + id);
    if (overSpinsInput) {

        var overSpinsValue = Number(overSpinsInput.value);

        if (isNaN(overSpinsValue) || overSpinsValue < 1) {
            overSpinsInput.value = 30;
            overSpinsValue = 30;
            
        }

        // Set text display of over spins
        var textDisplay = document.getElementById('over_spins_text_' + id);
        textDisplay.innerHTML = 'Over the last '+overSpinsValue+' spins.';
        
        // Disabled Drag when clicking in text box
        overSpinsInput.addEventListener('mousedown', function(event) {
            isDragging = false;
            event.stopPropagation();
        });

    }
    
    var newData = logic_Evens(overSpinsValue);

    updateTableData("id_stats_table_evens", newData);

}

function calc_Dozens()
{    var table = document.getElementById('id_stats_table_evens'); 


    // Get Lookback Spins
    var id = 'id_stats_table_dozens';
    var overSpinsInput = document.getElementById('look_back_' + id);
    if (overSpinsInput) {

        var overSpinsValue = Number(overSpinsInput.value);

        if (isNaN(overSpinsValue) || overSpinsValue < 1) {
            overSpinsInput.value = 30;
            overSpinsValue = 30;
            
        }

        // Set text display of over spins
        var textDisplay = document.getElementById('over_spins_text_' + id);
        textDisplay.innerHTML = 'Over the last '+overSpinsValue+' spins.';
        
        // Disabled Drag when clicking in text box
        overSpinsInput.addEventListener('mousedown', function(event) {
            isDragging = false;
            event.stopPropagation();
        });

    }
    
    var newData = logic_Dozens(overSpinsValue);

    updateTableData("id_stats_table_dozens", newData);

}

function calc_Combo()
{    var table = document.getElementById('id_stats_table_combo'); 

    // Get Lookback Spins
    var id = 'id_stats_table_combo';
    var overSpinsInput = document.getElementById('look_back_' + id);
    if (overSpinsInput) {

        var overSpinsValue = Number(overSpinsInput.value);

        if (isNaN(overSpinsValue) || overSpinsValue < 1) {
            overSpinsInput.value = 30;
            overSpinsValue = 30;
            
        }

        // Set text display of over spins
        var textDisplay = document.getElementById('over_spins_text_' + id);
        textDisplay.innerHTML = 'Over the last '+overSpinsValue+' spins.';
        
        // Disabled Drag when clicking in text box
        overSpinsInput.addEventListener('mousedown', function(event) {
            isDragging = false;
            event.stopPropagation();
        });

    }
    
    var newData = logic_Combo(overSpinsValue);

    updateTableData("id_stats_table_combo", newData);

}

function logic_Evens(overSpins)
{

    const labels = ['Red', 'Black', 'Even', 'Odd', 'High', 'Low'];
    const functions = [misses_in_a_row, hits_in_a_row, percent_hits, total_hit];
    const conditions = [condition_red, condition_black, condition_even, condition_odd, condition_high, condition_low];

   const allResults = executeAndCollectResults(overSpins, conditions, functions, labels);

   var newData = Object.keys(allResults).map(label => {
        let data = allResults[label];
        let percentageFormatted = `${data[2].toFixed(2)}%`;
        return [label, data[0], data[1], data[3], percentageFormatted];
    });

    return newData;
}

function logic_Dozens(overSpins)
{

    const labels = ['Dozen 1', 'Dozen 2', 'Dozen 3', 'Row 1', 'Row 2', 'Row 3'];
    const functions = [misses_in_a_row, hits_in_a_row, percent_hits, total_hit];
    const conditions = [condition_dozen1, condition_dozen2, condition_dozen3, condition_row1, condition_row2, condition_row3];

   const allResults = executeAndCollectResults(overSpins, conditions, functions, labels);

   var newData = Object.keys(allResults).map(label => {
        let data = allResults[label];
        let percentageFormatted = `${data[2].toFixed(2)}%`;
        return [label, data[0], data[1], data[3], percentageFormatted];
    });

    return newData;
}

function logic_Combo(overSpins){
    const labels =[       
        'Red Odd  High', 
        'Red Odd  Low', 
        'Red Even High',
        'Red Even Low',
        'Black Odd High',
        'Black Odd Low',
        'Black Even High',
        'Black Even Low'
    ];

    const functions = [misses_in_a_row, hits_in_a_row, percent_hits, total_hit];

    const conditions = [
          condition_red_odd_high
        , condition_red_odd_low
        , condition_red_even_high
        , condition_red_even_low
        , condition_black_odd_high
        , condition_black_odd_low
        , condition_black_even_high
        , condition_black_even_low
    ];

   const allResults = executeAndCollectResults(overSpins, conditions, functions, labels);

   var newData = Object.keys(allResults).map(label => {
        let data = allResults[label];
        let percentageFormatted = `${data[2].toFixed(2)}%`;
        return [label, data[0], data[1], data[3], percentageFormatted];
    });

    return newData;

}

function calculateRouletteStats(arr) {
    const redNumbers = [1, 3, 5, 7, 9, 12, 14, 16, 18, 19, 21, 23, 25, 27, 30, 32, 34, 36];
    const blackNumbers = [2, 4, 6, 8, 10, 11, 13, 15, 17, 20, 22, 24, 26, 28, 29, 31, 33, 35];
    
    let stats = {
        high: 0,
        low: 0,
        even: 0,
        odd: 0,
        black: 0,
        red: 0,
        dozen1: 0,
        dozen2: 0,
        dozen3: 0,
        row1: 0,
        row2: 0,
        row3: 0
    };
    
    arr.forEach(num => {
        if (num === 0) return;
        if (num >= 1 && num <= 18) stats.low++;
        if (num >= 19 && num <= 36) stats.high++;
        if (num % 2 === 0) stats.even++;
        else stats.odd++;
        if (redNumbers.includes(num)) stats.red++;
        if (blackNumbers.includes(num)) stats.black++;
        if (num >= 1 && num <= 12) stats.dozen1++;
        if (num >= 13 && num <= 24) stats.dozen2++;
        if (num >= 25 && num <= 36) stats.dozen3++;
        if ([1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31, 34].includes(num)) stats.row1++;
        if ([2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35].includes(num)) stats.row2++;
        if ([3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36].includes(num)) stats.row3++;
    });

    return stats;
}

function displayRouletteStats_old() {
    var newArray = numbers.slice(-statLookBack);

    const stats = calculateRouletteStats(newArray);
    const totalNumbers = newArray.length;
    const statsDiv = document.getElementById('stats');
    statsDiv.innerHTML = '';

    const statsKeys = [
        { key: 'low', className: 'low_stat', label: 'L' },
        { key: 'even', className: 'even_stat', label: 'E' },
        { key: 'red', className: 'red_stat', label: 'R' },
        { key: 'dozen1', className: 'dozen1_stat', label: 'D 1' },
        { key: 'dozen2', className: 'dozen2_stat', label: 'D 2' },
        { key: 'dozen3', className: 'dozen3_stat', label: 'D 3' },
        { key: 'high', className: 'high_stat', label: 'H' },
        { key: 'odd', className: 'odd_stat', label: 'O' },
        { key: 'black', className: 'black_stat', label: 'B' },
        { key: 'row1', className: 'row1_stat', label: 'R 1' },
        { key: 'row2', className: 'row2_stat', label: 'R 2' },
        { key: 'row3', className: 'row3_stat', label: 'R 3' }
    ];
    

    statsKeys.forEach(stat => {
        let percentage = (stats[stat.key] / totalNumbers) * 100;
        percentage = isNaN(percentage) ? '0.00' : percentage.toFixed(2);
        const statItem = document.createElement('div');
        statItem.className = `stat-item ${stat.className}`;
        statItem.innerHTML = `<strong>${stat.label}</strong>: ${stats[stat.key]} (${percentage}%)`;
        statsDiv.appendChild(statItem);
    });

    let userInput = two_box_input_and_button('statOutside-inputbox', '77', 'statOutside-button', 'statOutside-button-all', 'Lookback', 'All', 'freq-span', '0px');
    let userInputContainer = userInput.container;
    let inputElement = userInputContainer.querySelector('#statOutside-inputbox')
    inputElement.value = statLookBack;

    var freqButton = userInput.buttons.button1;
    var freqButtonAll = userInput.buttons.button2;

    if (freqButton) { freqButton.onclick = outsideStatsUpdate; }
    if (freqButtonAll) { freqButtonAll.onclick = outsideStatsUpdateAll; }
    statButtons_panel.innerHTML = '';
    statButtons_panel.appendChild(userInputContainer);
}
function displayRouletteStats_old2() {
    var newArray = numbers.slice(-statLookBack);

    const stats = calculateRouletteStats(newArray);
    const totalNumbers = newArray.length;
    const statsDiv = document.getElementById('stats');
    statsDiv.innerHTML = '';

    const statsKeys = [
        { key: 'red', className: 'red_stat', label: 'R' },
        { key: 'black', className: 'black_stat', label: 'B' },
        { key: 'even', className: 'even_stat', label: 'E' },
        { key: 'odd', className: 'odd_stat', label: 'O' },
        { key: 'high', className: 'high_stat', label: 'H' },
        { key: 'low', className: 'low_stat', label: 'L' },
        { key: 'dozen1', className: 'dozen1_stat', label: 'D 1' },
        { key: 'dozen2', className: 'dozen2_stat', label: 'D 2' },
        { key: 'dozen3', className: 'dozen3_stat', label: 'D 3' },
        { key: 'row1', className: 'row1_stat', label: 'R 1' },
        { key: 'row2', className: 'row2_stat', label: 'R 2' },
        { key: 'row3', className: 'row3_stat', label: 'R 3' }
    ];

    statsKeys.forEach(stat => {
        // Label row
        const statLabel = document.createElement('div');
        statLabel.className = `stat-item ${stat.className}_label`;
        statLabel.innerHTML = `<strong>${stat.label}</strong>`;
        statsDiv.appendChild(statLabel);
    
        // Count row
        const statCount = document.createElement('div');
        statCount.className = `stat-item ${stat.className}_count`;
        statCount.innerHTML = `${stats[stat.key]}`;
        statsDiv.appendChild(statCount);
    
        // Percentage row
        let percentage = (stats[stat.key] / totalNumbers) * 100;
        percentage = isNaN(percentage) ? '0.00' : percentage.toFixed(2);
        const statPercentage = document.createElement('div');
        statPercentage.className = `stat-item ${stat.className}_percentage`;
        statPercentage.innerHTML = `${percentage}%`;
        statsDiv.appendChild(statPercentage);
    });

    let userInput = two_box_input_and_button('statOutside-inputbox', '77', 'statOutside-button', 'statOutside-button-all', 'Lookback', 'All', 'freq-span', '0px');
    let userInputContainer = userInput.container;
    let inputElement = userInputContainer.querySelector('#statOutside-inputbox')
    inputElement.value = statLookBack;

    var freqButton = userInput.buttons.button1;
    var freqButtonAll = userInput.buttons.button2;

    if (freqButton) { freqButton.onclick = outsideStatsUpdate; }
    if (freqButtonAll) { freqButtonAll.onclick = outsideStatsUpdateAll; }
    statButtons_panel.innerHTML = '';
    statButtons_panel.appendChild(userInputContainer);
}

function displayRouletteStats() {
    var newArray = numbers.slice(-statLookBack);

    const stats = calculateRouletteStats(newArray);
    const totalNumbers = newArray.length;
    const statsDiv = document.getElementById('stats');
    statsDiv.innerHTML = '';

    const statsKeys = [
        { key: 'red', label: 'R' },
        { key: 'black', label: 'B' },
        { key: 'even', label: 'E' },
        { key: 'odd', label: 'O' },
        { key: 'high', label: 'H' },
        { key: 'low', label: 'L' },
        { key: 'dozen1', label: 'D 1' },
        { key: 'dozen2', label: 'D 2' },
        { key: 'dozen3', label: 'D 3' },
        { key: 'row1', label: 'R 1' },
        { key: 'row2', label: 'R 2' },
        { key: 'row3', label: 'R 3' }
    ];

    // Create the table
    const table = document.createElement('table');
    table.style.borderCollapse = 'collapse';
    table.style.width = '100%';
    table.style.margin = '10px 0';

    // Create the header row for labels
    const labelRow = document.createElement('tr');
    statsKeys.forEach(stat => {
        const th = document.createElement('th');
        th.style.border = '1px solid #ccc';
        th.style.padding = '5px';
        th.innerHTML = `<strong>${stat.label}</strong>`;
        labelRow.appendChild(th);
    });
    table.appendChild(labelRow);

    // Create the row for counts
    const countRow = document.createElement('tr');
    statsKeys.forEach(stat => {
        const td = document.createElement('td');
        td.style.border = '1px solid #ccc';
        td.style.padding = '5px';
        td.innerHTML = `${stats[stat.key]}`;
        countRow.appendChild(td);
    });
    table.appendChild(countRow);

    // Create the row for percentages
    const percentageRow = document.createElement('tr');
    statsKeys.forEach(stat => {
        const td = document.createElement('td');
        td.style.border = '1px solid #ccc';
        td.style.padding = '5px';
        let percentage = (stats[stat.key] / totalNumbers) * 100;
        percentage = isNaN(percentage) ? '0.00' : percentage.toFixed(2);
        td.innerHTML = `${percentage} %`;
        percentageRow.appendChild(td);
    });
    table.appendChild(percentageRow);

    // Append the table to the statsDiv
    statsDiv.appendChild(table);

    let userInput = two_box_input_and_button('statOutside-inputbox', '77', 'statOutside-button', 'statOutside-button-all', 'Lookback', 'All', 'freq-span', '0px');
    let userInputContainer = userInput.container;
    let inputElement = userInputContainer.querySelector('#statOutside-inputbox')
    inputElement.value = statLookBack;

    var freqButton = userInput.buttons.button1;
    var freqButtonAll = userInput.buttons.button2;

    if (freqButton) { freqButton.onclick = outsideStatsUpdate; }
    if (freqButtonAll) { freqButtonAll.onclick = outsideStatsUpdateAll; }
    statButtons_panel.innerHTML = '';
    statButtons_panel.appendChild(userInputContainer);
}

function statsAfterSpin()
{
    if(statsLookBackAll)
    {
        statLookBack = numbers.length;
       
        
    }
    displayRouletteStats();



}
function outsideStatsUpdate(){
    let spinBox = document.getElementById('statOutside-inputbox');
    spinLength = ensureInputValue(spinBox.value,37);
    if(spinLength>numbers.length) {spinLength = numbers.length; }
    statLookBack = spinLength;
    statsLookBackAll = false;

    displayRouletteStats();
}

function outsideStatsUpdateAll(){
    statLookBack = numbers.length;
    statsLookBackAll = true;
    displayRouletteStats();
}
