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


function button_update_evens()
{
    even_button_all = false;
    calc_Evens();
}
function calc_Evens() {

    var id = 'id_stats_table_evens';
    var overSpinsInput = document.getElementById(`look_back_` + id);
    if (overSpinsInput) {

        global_stats_even_spins_value = Number(overSpinsInput.value);

        if (isNaN(global_stats_even_spins_value) || global_stats_even_spins_value < 1) {

            global_stats_even_spins_value = numbers.length;


        }
        if (global_stats_even_spins_value > numbers.length) {
            global_stats_even_spins_value = numbers.length;

        }
        overSpinsInput.value = global_stats_even_spins_value;


        // Set text display of over spins
        var textDisplay = document.getElementById('over_spins_text_' + id);
        textDisplay.innerHTML = 'Over the last ' + global_stats_even_spins_value + ' spins.';




        var newData = logic_Evens(global_stats_even_spins_value);

        updateTableData("id_stats_table_evens", 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 button_update_dozens()
{
    dozen_button_all = false;
    calc_Dozens() ;
}
function calc_Dozens() {
    


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

        global_stats_dozens_spins_value = Number(overSpinsInput.value);

        if (isNaN(global_stats_dozens_spins_value) || global_stats_dozens_spins_value < 1) {
            global_stats_dozens_spins_value = numbers.length;

        }

        if (global_stats_dozens_spins_value > numbers.length) {
            global_stats_dozens_spins_value = numbers.length;

        }
        overSpinsInput.value = global_stats_dozens_spins_value;

        // Set text display of over spins
        var textDisplay = document.getElementById('over_spins_text_' + id);
        textDisplay.innerHTML = 'Over the last ' + global_stats_dozens_spins_value + ' spins.';

    }

    var newData = logic_Dozens(global_stats_dozens_spins_value);

    updateTableData("id_stats_table_dozens", 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 button_update_combo()
{
    combo_button_all = false;
    calc_Combo() ;
}
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) {

        global_stats_combo_spins_value = Number(overSpinsInput.value);

        if (isNaN(global_stats_combo_spins_value) || global_stats_combo_spins_value < 1) {
            global_stats_combo_spins_value = numbers.length;

        }

        if (global_stats_combo_spins_value > numbers.length) {
            global_stats_combo_spins_value = numbers.length;

        }
        overSpinsInput.value = global_stats_combo_spins_value;

        // Set text display of over spins
        var textDisplay = document.getElementById('over_spins_text_' + id);
        textDisplay.innerHTML = 'Over the last ' + global_stats_combo_spins_value + ' spins.';


    }

    var newData = logic_Combo(global_stats_combo_spins_value);

    updateTableData("id_stats_table_combo", 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 button_update_street()
{
    street_button_all = false;
    calc_Street() ;
}
function calc_Street() {
    


    var table = document.getElementById('id_stats_table_street');

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

        global_stats_street_spins_value = Number(overSpinsInput.value);

        if (isNaN(global_stats_street_spins_value) || global_stats_street_spins_value < 1) {
            global_stats_street_spins_value = numbers.length;

        }

        if (global_stats_street_spins_value > numbers.length) {
            global_stats_street_spins_value = numbers.length;

        }
        overSpinsInput.value = global_stats_street_spins_value;

        // Set text display of over spins
        var textDisplay = document.getElementById('over_spins_text_' + id);
        textDisplay.innerHTML = 'Over the last ' + global_stats_street_spins_value + ' spins.';


    }

    var newData = logic_Street(global_stats_street_spins_value);

    updateTableData("id_stats_table_street", newData);

}
function logic_Street(overSpins) {

    const labels = [
        'Street 1,2,3',
        'Street 4,5,6',
        'Street 7,8,9',
        'Street 10,11,12',
        'Street 13,14,15',
        'Street 16,17,18',
        'Street 19,20,21',
        'Street 22,23,24',
        'Street 25,26,27',
        'Street 28,29,30',
        'Street 31,32,33',
        'Street 34,35,36'
    ];

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

    const conditions = [
        condition_street_1_2_3,
        condition_street_4_5_6,
        condition_street_7_8_9,
        condition_street_10_11_12,
        condition_street_13_14_15,
        condition_street_16_17_18,
        condition_street_19_20_21,
        condition_street_22_23_24,
        condition_street_25_26_27,
        condition_street_28_29_30,
        condition_street_31_32_33,
        condition_street_34_35_36
    ];

    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 button_update_line()
{
    line_button_all = false;
    calc_Line() ;
}
function calc_Line() {
    


    var table = document.getElementById('id_stats_table_line');

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

        global_stats_line_spins_value = Number(overSpinsInput.value);

        if (isNaN(global_stats_line_spins_value) || global_stats_line_spins_value < 1) {
            global_stats_line_spins_value = numbers.length;

        }

        if (global_stats_line_spins_value > numbers.length) {
            global_stats_line_spins_value = numbers.length;

        }
        overSpinsInput.value = global_stats_line_spins_value;

        // Set text display of over spins
        var textDisplay = document.getElementById('over_spins_text_' + id);
        textDisplay.innerHTML = 'Over the last ' + global_stats_line_spins_value + ' spins.';


    }

    var newData = logic_Line(global_stats_line_spins_value);

    updateTableData("id_stats_table_line", newData);

}
function logic_Line(overSpins) {

    const labels = [
        'Line 1,2,3,4,5,6',
        'Line 4,5,6,7,8,9',
        'Line 7,8,9,10,11,12',
        'Line 10,11,12,13,14,15',
        'Line 13,14,15,16,17,18',
        'Line 16,17,18,19,20,21',
        'Line 19,20,21,22,23,24',
        'Line 22,23,24,25,26,27',
        'Line 25,26,27,28,29,30',
        'Line 28,29,30,31,32,33',
        'Line 31,32,33,34,35,36'
    ];

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

    const conditions = [
        condition_line_1_2_3_4_5_6,
        condition_line_4_5_6_7_8_9,
        condition_line_7_8_9_10_11_12,
        condition_line_10_11_12_13_14_15,
        condition_line_13_14_15_16_17_18,
        condition_line_16_17_18_19_20_21,
        condition_line_19_20_21_22_23_24,
        condition_line_22_23_24_25_26_27,
        condition_line_25_26_27_28_29_30,
        condition_line_28_29_30_31_32_33,
        condition_line_31_32_33_34_35_36
    ];

    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: 'Low' },
        { key: 'even', className: 'even_stat', label: 'Even' },
        { key: 'red', className: 'red_stat', label: 'Red' },
        { key: 'dozen1', className: 'dozen1_stat', label: 'Dozen 1' },
        { key: 'dozen2', className: 'dozen2_stat', label: 'Dozen 2' },
        { key: 'dozen3', className: 'dozen3_stat', label: 'Dozen 3' },
        { key: 'high', className: 'high_stat', label: 'High' },
        { key: 'odd', className: 'odd_stat', label: 'Odd' },
        { key: 'black', className: 'black_stat', label: 'Black' },
        { key: 'row1', className: 'row1_stat', label: 'Row 1' },
        { key: 'row2', className: 'row2_stat', label: 'Row 2' },
        { key: 'row3', className: 'row3_stat', label: 'Row 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.style.fontSize = '1.7em';
    inputElement.value = statLookBack;

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

    freqButton.style = 'width: 190px; height: 70px; margin-bottom: 5px; margin-top: 5px; margin-left: 10px; font-size: 30px;';
    freqButtonAll.style = 'width: 190px; height: 70px; margin-bottom: 5px; margin-top: 5px; margin-left: 10px; font-size: 30px;';

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

    
}

function displayRouletteStats() {
    const container = document.createElement('div');
    container.id = 'roulette-stats-container';
     container.style.paddingTop = '40px';

    const newArray = numbers.slice(-statLookBack);
    const stats = calculateRouletteStats(newArray);
    const totalNumbers = newArray.length;

    const statsKeys = [
        { key: 'low', className: 'low_stat', label: 'Low', group: 'even' },
        { key: 'even', className: 'even_stat', label: 'Even', group: 'even' },
        { key: 'red', className: 'red_stat', label: 'Red', group: 'even' },
        { key: 'high', className: 'high_stat', label: 'High', group: 'even' },
        { key: 'odd', className: 'odd_stat', label: 'Odd', group: 'even' },
        { key: 'black', className: 'black_stat', label: 'Black', group: 'even' },

        { key: 'dozen1', className: 'dozen1_stat', label: 'Dozen 1', group: 'dozen' },
        { key: 'dozen2', className: 'dozen2_stat', label: 'Dozen 2', group: 'dozen' },
        { key: 'dozen3', className: 'dozen3_stat', label: 'Dozen 3', group: 'dozen' },

        { key: 'row1', className: 'row1_stat', label: 'Row 1', group: 'other' },
        { key: 'row2', className: 'row2_stat', label: 'Row 2', group: 'other' },
        { key: 'row3', className: 'row3_stat', label: 'Row 3', group: 'other' }
    ];

    // Build stat entries with percentages
    const statEntries = statsKeys.map(stat => {
        const value = stats[stat.key];
        const percentage = totalNumbers > 0 ? ((value / totalNumbers) * 100).toFixed(2) : '0.00';
        return {
            ...stat,
            value,
            percentage: parseFloat(percentage)
        };
    });

    // Group and sort
    const groupOrder = ['even', 'dozen'];
    groupOrder.forEach(groupName => {
        const groupDiv = document.createElement('div');
        groupDiv.style.marginBottom = '20px'; // spacing between groups

        const groupStats = statEntries
            .filter(entry => entry.group === groupName)
            .sort((a, b) => b.percentage - a.percentage);

        groupStats.forEach(stat => {
            const statItem = document.createElement('div');
            statItem.className = `stat-item ${stat.className}`;
            statItem.innerHTML = `<strong>${stat.label}</strong>: ${stat.value} (${stat.percentage.toFixed(2)}%)`;
            groupDiv.appendChild(statItem);
        });

        container.appendChild(groupDiv);
    });

    // Optionally show other group last
    const otherStats = statEntries
        .filter(entry => entry.group === 'other')
        .sort((a, b) => b.percentage - a.percentage);

    otherStats.forEach(stat => {
        const statItem = document.createElement('div');
        statItem.className = `stat-item ${stat.className}`;
        statItem.innerHTML = `<strong>${stat.label}</strong>: ${stat.value} (${stat.percentage.toFixed(2)}%)`;
        container.appendChild(statItem);
    });

    // User Input and Buttons
    const userInput = two_box_input_and_button('statOutside-inputbox', '77', 'statOutside-button', 'statOutside-button-all', 'Lookback', 'All', 'freq-span', '0px');
    const userInputContainer = userInput.container;
     userInputContainer.style.marginTop = '30px';
    const inputElement = userInputContainer.querySelector('#statOutside-inputbox');
    inputElement.style.fontSize = '1.7em';
    inputElement.value = statLookBack;

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

    freqButton.style = 'width: 190px; height: 70px; margin-bottom: 5px; margin-top: 5px; margin-left: 10px; font-size: 30px;';
    freqButtonAll.style = 'width: 190px; height: 70px; margin-bottom: 5px; margin-top: 5px; margin-left: 10px; font-size: 30px;';

    if (freqButton) freqButton.onclick = outsideStatsUpdate;
    if (freqButtonAll) freqButtonAll.onclick = outsideStatsUpdateAll;

    container.appendChild(userInputContainer);

    return container;
}


function update_displayRouletteStats()
{
    const existingStatsPanel = document.getElementById('roulette-stats-container');

if (existingStatsPanel) {
    // It's in the DOM — update it!
    const updatedStats = displayRouletteStats();

    existingStatsPanel.replaceWith(updatedStats);
}
}
function statsAfterSpin()
{
    if(statsLookBackAll)
    {
        statLookBack = numbers.length;
       
        
    }
    update_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;

    update_displayRouletteStats();
}

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