let highLightChecked = false;
let sleeperLookBack = 37;

function navigateFrequencyBuild()
{

    let container = document.getElementById('sub-more-button-bar-div-3');

    if(container)
        {
          
            updateSleeperTable();
        }
        else
        {
        
            return frequencyBuild();
        }
}

function onSpin_frequency()
{
    updateFrequnecyNewNumber();
	updateSleeperTable();
    highlightSleepersEachSpin();
    updateSleeperCount();
    
}

function frequencyBuild() {
    // Main container
    let container = document.createElement('div');
    container.id = 'frequency-container';
    container.style.marginLeft = '25px';
    container.style.marginBottom = '15px';

    container.style.fontSize = '30px';

    var title = document.createElement('h2');
    title.innerText = 'Sleepers';
    container.appendChild(title);

    // User Input Container
    let containerUserInput = document.createElement('div');
    containerUserInput.id = 'container-frequency-user-input';
    containerUserInput.style.display = 'flex';
    containerUserInput.style.alignItems = 'center';
    containerUserInput.style.marginBottom = '20px'; // Space between user input and charts
    

    // Input box
    let inputBox = document.createElement('input');
    inputBox.type = 'text';
    inputBox.style.fontSize = '37px';
    inputBox.style.width = '225px';
    inputBox.setAttribute('type', 'tel');
    inputBox.setAttribute('id', 'freq-inputbox');
    inputBox.setAttribute('pattern', '[0-9]*');
    inputBox.setAttribute('inputmode', 'numeric');
   // inputBox.setAttribute('placeholder', '37');
    inputBox.value = sleeperLookBack; 
    containerUserInput.appendChild(inputBox);

    // Button 1
    let LookBackButton = document.createElement('button');
    LookBackButton.id = 'freq-button';
    LookBackButton.textContent = 'Look Back';
    LookBackButton.style = 'width: auto; height: 50px; margin: 5px 10px 5px 10px; font-size: 30px;';
    containerUserInput.appendChild(LookBackButton);
    if (LookBackButton) { LookBackButton.onclick = frequencyUpdate; }

    // Button 2
    let LookBackButtonAll = document.createElement('button');
    LookBackButtonAll.id = 'freq-button-all';
    LookBackButtonAll.textContent = 'All';
    LookBackButtonAll.style = 'width: 150px; height: 50px; margin: 5px 10px 5px 10px; font-size: 30px;';
    containerUserInput.appendChild(LookBackButtonAll);
    if (LookBackButtonAll) { LookBackButtonAll.onclick = frequencyUpdateAll; }

    // Create the checkbox
    let highLightCheckbox = document.createElement('input');
    highLightCheckbox.id = 'freq-checkbox';
    highLightCheckbox.type = 'checkbox';
    highLightCheckbox.style.transform = 'scale(4)';
    highLightCheckbox.style.marginRight = '20px';
    highLightCheckbox.style.marginLeft = '40px';
   // highLightCheckbox.style.marginTop = '-10px';

    // Check the checkbox if the condition is met
    if (highLightChecked) {
        highLightCheckbox.checked = true;
    }

    // Append the checkbox to the container
    containerUserInput.appendChild(highLightCheckbox);
    if (highLightCheckbox) { highLightCheckbox.onchange = highlightNumbers; }

    // Labels
    let label1 = document.createElement('label');
    label1.textContent = 'Highlight';
    label1.style.fontSize = '35px';
    label1.style.marginLeft = '10px';
    label1.setAttribute('for', 'freq-checkbox');
    containerUserInput.appendChild(label1);


    // Append title and user input container to the main container
    container.appendChild(containerUserInput);



      // Title
      let titleDiv = document.createElement('div');
      let titleSpan = document.createElement('span'); 
      titleDiv.id = 'sleeperCountTitle';
      titleDiv.appendChild(titleSpan);
      titleDiv.style.marginBottom = '20px'; 
      container.appendChild(titleDiv);


      
    // Frequency Chart Container
    let containerContents = document.createElement('div');
    containerContents.id = 'container-frequency-contents';

    // Counting the frequency of each number in lastXNumbers
    let lastXNumbers = getNumberSequence();
    const frequencyCount = lastXNumbers.reduce((acc, num) => {
        acc[num] = (acc[num] || 0) + 1;
        return acc;
    }, {});

    // Array of numbers from 0 to 35
    let allNumbers = Array.from({ length: 37 }, (_, index) => index);

    // Sort these numbers by their frequency in lastXNumbers, then by number if frequencies are equal
    allNumbers.sort((a, b) => {
        const freqA = frequencyCount[a] || 0;
        const freqB = frequencyCount[b] || 0;
        return freqB - freqA || a - b;
    });

    // Frequency table
    const table = document.createElement('div');
    table.style.display = 'flex';

    const numberColumn = document.createElement('div');
    numberColumn.style.display = 'flex';
    numberColumn.style.flexDirection = 'column';
    numberColumn.style.marginRight = '10px'; // Space between columns

    const frequencyColumn = document.createElement('div');
    frequencyColumn.style.display = 'flex';
    frequencyColumn.style.flexDirection = 'column';

    allNumbers.forEach(num => {
        const numberCell = document.createElement('div');
        const frequencyCell = document.createElement('div');

        numberCell.innerText = num;
        frequencyCell.innerText = frequencyCount[num] || 0;

        // Base styles for cells
        [numberCell, frequencyCell].forEach(cell => {
            cell.style.width = '60px';
            cell.style.height = '50px';
            cell.style.fontSize = '35px';
            cell.style.display = 'flex';
            cell.style.justifyContent = 'center';
            cell.style.alignItems = 'center';
            cell.style.border = '1px solid black';
        });

        numberCell.style.color = 'white';
        frequencyCell.style.color = 'blue';

        // Apply background color based on the number
        if (numRed.includes(num)) {
            numberCell.style.backgroundColor = 'rgb(221, 82, 82)'; 
        } else if (numBlack.includes(num)) {
            numberCell.style.backgroundColor = 'rgb(68, 60, 60)'; 
        } else if (num === 0) {
            numberCell.style.backgroundColor = 'rgb(146, 196, 150)'; 
        }

        numberColumn.appendChild(numberCell);
        frequencyColumn.appendChild(frequencyCell);
    });

    table.appendChild(numberColumn);
    table.appendChild(frequencyColumn);

    containerContents.appendChild(table);

    // Sleeper Chart
    let fullArray = Array.from({ length: 37 }, (_, i) => i);
    let finalArray = fullArray.filter(item => !lastXNumbers.includes(item));      
    const frequency = countOutsideNumbersFrequency(finalArray);
    const frequenciesArray = [
        frequency.red, frequency.black, 
        frequency.even, frequency.odd,
        frequency.high, frequency.low, 
        frequency.dozens[0], frequency.dozens[1], frequency.dozens[2], 
        frequency.rows[0], frequency.rows[1], frequency.rows[2]
    ];
    const sleeperChart = createDivContainer(frequenciesArray);

    // Container for both charts side by side
    let chartsContainer = document.createElement('div');
    chartsContainer.style.display = 'flex';
    chartsContainer.style.alignItems = 'flex-start'; // Align at the top
    chartsContainer.appendChild(containerContents); // Frequency chart
    chartsContainer.appendChild(sleeperChart); // Sleeper chart

    // Append charts container to the main container
    container.appendChild(chartsContainer);

    // Final Updates
    titleSpan.innerHTML = '<h2>Frequencies</h2>\n<h2>Sleeper Count:'+finalArray.length+'</h2>';
    return container;
}

function updateSleeperTable()
{
    let item = document.getElementById('sleeper-chart');

  
            if (item) {
                item.innerHTML = '';
                let lastXNumbers = getNumberSequence();
                let fullArray = Array.from({ length: 37 }, (_, i) => i);
                let finalArray = fullArray.filter(item => !lastXNumbers.includes(item));      
    
                const frequency = countOutsideNumbersFrequency(finalArray);
    
                const frequenciesArray = [
                    frequency.red, frequency.black, 
                    frequency.even, frequency.odd,
                    frequency.high, frequency.low, 
                    frequency.dozens[0], frequency.dozens[1],frequency.dozens[2], 
                    frequency.rows[0], frequency.rows[1], frequency.rows[2]
                ];
                const sleeperChart = createDivContainer(frequenciesArray);
                item.appendChild(sleeperChart);
            }
}

function createDivContainer(frequenciesArray) {
    // Assuming numbers is defined elsewhere in your code
    let currentNumber = numbers.length ? numbers[numbers.length - 1] : null;

    // Create container div
    const container = document.createElement('div');
    container.id = 'sleeper-chart';

    // Create a wrapper for the columns
    const columnWrapper = document.createElement('div');
    columnWrapper.style.display = 'flex';

    // Create number column
    const numberColumn = document.createElement('div');
    numberColumn.style.display = 'flex';
    numberColumn.style.flexDirection = 'column';
    numberColumn.style.marginRight = '10px'; // Space between columns
    numberColumn.style.width = 'auto';
    numberColumn.style.height = '50px';
    numberColumn.style.fontSize = '35px'

    // Create frequency column
    const frequencyColumn = document.createElement('div');
    frequencyColumn.style.display = 'flex';
    frequencyColumn.style.flexDirection = 'column';
    frequencyColumn.style.width = 'auto';
    frequencyColumn.style.height = '50px';
    frequencyColumn.style.fontSize = '35px'

    // Create headers and append to numberColumn
    const columnHeaders = ['Red', 'Black', 'Even', 'Odd', 'High', 'Low', 'Doz 1', 'Doz 2', 'Doz 3', 'Row 1', 'Row 2', 'Row 3'];

    columnHeaders.forEach(columnHeader => {
        const columnHeaderDiv = document.createElement('div');
        columnHeaderDiv.classList.add('label-sleeper-chart');
        columnHeaderDiv.textContent = columnHeader;

        // Highlight the header if it matches currentNumber logic
        if (currentNumber !== null && currentNumber > 0) {
            if (
                (columnHeader === 'Red' && numRed.includes(currentNumber)) ||
                (columnHeader === 'Black' && numBlack.includes(currentNumber)) ||
                (columnHeader === 'Even' && currentNumber % 2 === 0) ||
                (columnHeader === 'Odd' && currentNumber % 2 !== 0) ||
                (columnHeader === 'High' && currentNumber > 18) ||
                (columnHeader === 'Low' && currentNumber <= 18) ||
                (columnHeader === 'Doz 1' && rouletteAttributes.dozens[0].includes(currentNumber)) ||
                (columnHeader === 'Doz 2' && rouletteAttributes.dozens[1].includes(currentNumber)) ||
                (columnHeader === 'Doz 3' && rouletteAttributes.dozens[2].includes(currentNumber)) ||
                (columnHeader === 'Row 1' && rouletteAttributes.columns[0].includes(currentNumber)) ||
                (columnHeader === 'Row 2' && rouletteAttributes.columns[1].includes(currentNumber)) ||
                (columnHeader === 'Row 3' && rouletteAttributes.columns[2].includes(currentNumber))
            ) {
                columnHeaderDiv.style.backgroundColor = 'lightgreen';
            }
        }

        numberColumn.appendChild(columnHeaderDiv);
    });

    // Create data cells and append to frequencyColumn
    frequenciesArray.forEach(data => {
        const dataDiv = document.createElement('div');
        dataDiv.classList.add('data-sleeper-chart'); // Change the class to 'data-sleeper-chart'
        dataDiv.textContent = data;
        frequencyColumn.appendChild(dataDiv);
    });

    // Append columns to the wrapper
    columnWrapper.appendChild(numberColumn);
    columnWrapper.appendChild(frequencyColumn);

    // Append the wrapper to the container
    container.appendChild(columnWrapper);

    // Return the container
    return container;
}
/*----------------------------------------------------------------------------------------------------------
    Update Frequency
//-------------------------------------------------------------------------------------------------------*/

function updateSleeperCount()
{
    let titleSpan = document.getElementById('sleeperCountTitle');
    if(titleSpan)
    {
        let lastXNumbers = getNumberSequence();
        let fullArray = Array.from({ length: 37 }, (_, i) => i);
        let finalArray = fullArray.filter(item => !lastXNumbers.includes(item));   
        titleSpan.innerHTML = '<h2>Frequencies</h2>\n<h2>Sleeper Count:'+finalArray.length+'</h2>';
    }
}
function getNumberSequence()
{

    let lastXNumbers = [...numbers];
    if(numbers.length>sleeperLookBack)
        {
            lastXNumbers = numbers.slice(-sleeperLookBack);
        }
    return lastXNumbers;
}

function countOutsideNumbersFrequency(finalArray) {


    let red = 0, black = 0, even = 0, odd = 0, low = 0, high = 0;
    let dozens = [0, 0, 0];
    let rows = [0, 0, 0];

    finalArray.forEach(number => {
        // Count red and black
        if ((number >0)) {

            if (number % 2 === 0) even++;
            else odd++;
            
            if (number <= 18) low++;
            else high++;
            
            if (numRed.includes(number)) red++;
            if (numBlack.includes(number)) black++;
        }

        // Count dozens
        if (rouletteAttributes.dozens[0].includes(number)) dozens[0]++;
        if (rouletteAttributes.dozens[1].includes(number)) dozens[1]++;
        if (rouletteAttributes.dozens[2].includes(number)) dozens[2]++;

        // Count rows
        if (rouletteAttributes.columns[0].includes(number)) rows[0]++;
        if (rouletteAttributes.columns[1].includes(number)) rows[1]++;
        if (rouletteAttributes.columns[2].includes(number)) rows[2]++;
    });

    return {
        red,
        black,
        even,
        odd,
        low,
        high,
        dozens,
        rows
    };
}

function frequencyUpdateAll(){

    sleeperLookBack = numbers.length;
    let inputBox = document.getElementById('freq-inputbox');
    inputBox.value = sleeperLookBack;
    onSpin_frequency();
}
function frequencyUpdate(){
    let spinLength = document.getElementById('freq-inputbox').value;
    sleeperLookBack = ensureInputValue(spinLength,37);
    if(sleeperLookBack>numbers.length) {sleeperLookBack = numbers.length; }

    onSpin_frequency();
}

function updateFrequencyTable() {
    var newSpins = numbers.slice(-sleeperLookBack);
    
    var container = document.getElementById('container-frequency-contents');
    container.innerHTML = '';

    const frequencyCount = newSpins.reduce((acc, num) => {
        acc[num] = (acc[num] || 0) + 1;
        return acc;
    }, {});

    let allNumbers = Array.from({length: 37}, (_, index) => index);

    allNumbers.sort((a, b) => {
        const freqA = frequencyCount[a] || 0;
        const freqB = frequencyCount[b] || 0;
        return freqB - freqA || a - b;
    });

    const table = document.createElement('div');
    table.style.display = 'flex';

    const numberColumn = document.createElement('div');
    numberColumn.style.display = 'flex';
    numberColumn.style.flexDirection = 'column';
    numberColumn.style.marginRight = '10px'; // Space between columns

    const frequencyColumn = document.createElement('div');
    frequencyColumn.style.display = 'flex';
    frequencyColumn.style.flexDirection = 'column';

    allNumbers.forEach(num => {
        const numberCell = document.createElement('div');
        const frequencyAllCell = document.createElement('div');

        numberCell.innerText = num;
        frequencyAllCell.innerText = frequencyCount[num] || 0;

        [numberCell, frequencyAllCell].forEach(cell => {
            cell.style.width = '60px';
            cell.style.height = '50px';
            cell.style.fontSize = '35px'
            cell.style.display = 'flex';
            cell.style.justifyContent = 'center';
            cell.style.alignItems = 'center';
            cell.style.border = '1px solid black';
        });

        numberCell.style.color = 'white';
        frequencyAllCell.style.color = 'black';

        if (numRed.includes(num)) {
            numberCell.style.backgroundColor = 'rgb(221, 82, 82)'; 
        } else if (numBlack.includes(num)) {
            numberCell.style.backgroundColor = 'rgb(68, 60, 60)'; 
        } else if (num === 0) {
            numberCell.style.backgroundColor = 'rgb(146, 196, 150)';
        }

        numberColumn.appendChild(numberCell);
        frequencyColumn.appendChild(frequencyAllCell);
    });

    table.appendChild(numberColumn);
    table.appendChild(frequencyColumn);
    container.appendChild(table);

    
}

function updateFrequnecyNewNumber()
{

    var container = document.getElementById('container-frequency-contents');
    if(container)
    {
        updateFrequencyTable();
    }
}

/*----------------------------------------------------------------------------------------------------------
    Highlight Checkbox
//-------------------------------------------------------------------------------------------------------*/

function highlightSleepersEachSpin()
{
    if(highLightChecked)
    {
        let fullArray = Array.from({ length: 37 }, (_, i) => i);
        sliderUnhighlight();

        let lastXNumbers = getNumberSequence();

        let finalArray = fullArray.filter(item => !lastXNumbers.includes(item));

        sliderHighlight(finalArray);
    }
    else{
        sliderUnhighlight();
    }
}
function highlightNumbers() {
    

    if (this.checked) {
        highLightChecked = true;


        clickFirstButton();

    } else {
        highLightChecked = false;

    }
}


function sliderHighlight(arr)
{
   
    arr.forEach(item => {
     
        const selector = `cellSleeper_${item}`;
		const element = document.getElementById(selector);
        
       
        if (element) {
            element.classList.add('sleeper-highlights');
        }
    });

}
function sliderUnhighlight()
{
  
    let arr = Array.from({ length: 37 }, (_, i) => i);
    arr.forEach(item => {
        const selector = `cellSleeper_${item}`;
		const element = document.getElementById(selector);
        if (element) {
            element.classList.remove('sleeper-highlights');
        }
    });
}

/*----------------------------------------------------------------------------------------------------------
    Show Chart under roulette board
//-------------------------------------------------------------------------------------------------------*/

function getSleeperCount() {
        // Title

        let titleDiv = document.createElement('div');
        titleDiv.id = 'sleeperCountTitleBoard';
        titleDiv.style.marginBottom = '20px'; 

        let titleSpan = document.createElement('span'); 
       
        titleDiv.appendChild(titleSpan);
       
        let lastXNumbers = getNumberSequence();
        let fullArray = Array.from({ length: 37 }, (_, i) => i);
        let finalArray = fullArray.filter(item => !lastXNumbers.includes(item));   
        titleSpan.innerHTML = 'Sleeper Count:'+finalArray.length+'';
        return titleDiv;

}
function showSleeperChart() {
    // Main container
    let container = document.createElement('div');
    container.id = 'frequency-container';
    container.style.marginLeft = '25px';
    container.style.marginBottom = '15px';

    container.style.fontSize = '30px';

    // Title
    let titleDiv = document.createElement('div');
    let titleSpan = document.createElement('span'); 
    titleDiv.id = 'sleeperCountTitle';
    titleDiv.appendChild(titleSpan);
    titleDiv.style.marginBottom = '20px'; 
    container.appendChild(titleDiv);

  

    // Frequency Chart Container
    let containerContents = document.createElement('div');
    containerContents.id = 'container-frequency-contents';

    // Counting the frequency of each number in lastXNumbers
    let lastXNumbers = getNumberSequence();
    const frequencyCount = lastXNumbers.reduce((acc, num) => {
        acc[num] = (acc[num] || 0) + 1;
        return acc;
    }, {});

    // Array of numbers from 0 to 35
    let allNumbers = Array.from({ length: 37 }, (_, index) => index);

    // Sort these numbers by their frequency in lastXNumbers, then by number if frequencies are equal
    allNumbers.sort((a, b) => {
        const freqA = frequencyCount[a] || 0;
        const freqB = frequencyCount[b] || 0;
        return freqB - freqA || a - b;
    });

    // Frequency table
    const table = document.createElement('div');
    table.style.display = 'flex';

    const numberColumn = document.createElement('div');
    numberColumn.style.display = 'flex';
    numberColumn.style.flexDirection = 'column';
    numberColumn.style.marginRight = '10px'; // Space between columns

    const frequencyColumn = document.createElement('div');
    frequencyColumn.style.display = 'flex';
    frequencyColumn.style.flexDirection = 'column';

    allNumbers.forEach(num => {
        const numberCell = document.createElement('div');
        const frequencyCell = document.createElement('div');

        numberCell.innerText = num;
        frequencyCell.innerText = frequencyCount[num] || 0;

        // Base styles for cells
        [numberCell, frequencyCell].forEach(cell => {
            cell.style.width = '60px';
            cell.style.height = '50px';
            cell.style.fontSize = '35px';
            cell.style.display = 'flex';
            cell.style.justifyContent = 'center';
            cell.style.alignItems = 'center';
            cell.style.border = '1px solid black';
        });

        numberCell.style.color = 'white';
        frequencyCell.style.color = 'blue';

        // Apply background color based on the number
        if (numRed.includes(num)) {
            numberCell.style.backgroundColor = 'rgb(221, 82, 82)'; 
        } else if (numBlack.includes(num)) {
            numberCell.style.backgroundColor = 'rgb(68, 60, 60)'; 
        } else if (num === 0) {
            numberCell.style.backgroundColor = 'rgb(146, 196, 150)'; 
        }

        numberColumn.appendChild(numberCell);
        frequencyColumn.appendChild(frequencyCell);
    });

    table.appendChild(numberColumn);
    table.appendChild(frequencyColumn);

    containerContents.appendChild(table);

    // Sleeper Chart
    let fullArray = Array.from({ length: 37 }, (_, i) => i);
    let finalArray = fullArray.filter(item => !lastXNumbers.includes(item));      
    const frequency = countOutsideNumbersFrequency(finalArray);
    const frequenciesArray = [
        frequency.red, frequency.black, 
        frequency.even, frequency.odd,
        frequency.high, frequency.low, 
        frequency.dozens[0], frequency.dozens[1], frequency.dozens[2], 
        frequency.rows[0], frequency.rows[1], frequency.rows[2]
    ];
    const sleeperChart = createDivContainer(frequenciesArray);



    // Container for both charts side by side
    let chartsContainer = document.createElement('div');
    chartsContainer.style.display = 'flex';
    chartsContainer.style.alignItems = 'flex-start'; // Align at the top
    chartsContainer.appendChild(containerContents); // Frequency chart
    chartsContainer.appendChild(sleeperChart); // Sleeper chart

    // Append charts container to the main container
    container.appendChild(chartsContainer);

    // Final Updaes
    titleSpan.innerHTML = '<h2>Frequencies</h2>\n<h2>Sleeper Count:'+finalArray.length+'</h2>';

    return container;
}


