
let comboLength = 2;
let comboLookBack = 50;
let nCombo = [];
let helpCombo = false;
let comboDisplay = false;
let comboFound = false;


function combo()
{
   
    let container = document.createElement('div');
    container.style.marginLeft = '25px';
    container.style.marginBottom = '15px';
    container.style.fontSize = '30px';



    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>Combo</h2>';
    titleSpan.style.marginRight = '10px'; 
    
    // Create the help button
    const button = document.createElement('button');
    button.id = 'how-to-combo';
    button.textContent = "How to";
    button.style.padding = '5px';
    button.style.marginRight = '5px';
    button.style = 'width: auto; height: 50px; margin: 5px 10px 5px 10px; font-size: 30px;';
    button.onclick = toggleButtonHelpCombo;
    

    var bouncyCheckbox = document.createElement('input');
	bouncyCheckbox.type = 'checkbox';
	bouncyCheckbox.id = "combo-display";
	bouncyCheckbox.name = "comboDisplay";
	bouncyCheckbox.placeholder = "";
    bouncyCheckbox.checked = comboDisplay;
    bouncyCheckbox.style.transform = 'scale(2)';
    bouncyCheckbox.style.transformOrigin = 'top left';
    bouncyCheckbox.style.marginBottom = '12px';
    bouncyCheckbox.style.marginLeft = '10px';
    bouncyCheckbox.addEventListener('change', function() {
        comboDisplay = this.checked;
        displayAlertComboStickyBottom();
    });

    bouncyCheckbox.style.marginTop = '-30px';
    bouncyCheckbox.style.marginLeft = '10px';
    bouncyCheckbox.style.transform = 'scale(4)';
    bouncyCheckbox.style.transformOrigin = 'top left';
    bouncyCheckbox.style.marginRight = '35px';


	// Group Label
	var bouncyCheckboxLabel = document.createElement('label');
	bouncyCheckboxLabel.htmlFor = 'combo-display';
    bouncyCheckboxLabel.style.marginLeft = '15px';
    bouncyCheckboxLabel.style.fontSize = '30px';
	bouncyCheckboxLabel.appendChild(document.createTextNode('Show alert'));


    // Append the title span and button to the title div
    titleDiv.appendChild(titleSpan);
    titleDiv.appendChild(button);
    titleDiv.appendChild(bouncyCheckbox);
    titleDiv.appendChild(bouncyCheckboxLabel);
    

    // Input
    const numberInput = document.createElement('input');
    style_textbox_container(numberInput);
    numberInput.type = 'number';
    numberInput.id = 'number-input-comboLength';
    numberInput.value = comboLength;
    // Label
    const numberInputLabel = document.createElement('label');
    numberInputLabel.textContent = 'Length';
    numberInputLabel.style.fontSize = '20px';
    numberInputLabel.setAttribute('for', 'number-input-comboLookBack');
    numberInputLabel.style.display = 'block'; 
    // Container
    const numberInputContainer = document.createElement('div');
    numberInputContainer.appendChild(numberInputLabel);
    numberInputContainer.appendChild(numberInput);

    // Input Box
    const comboLookbackInput = document.createElement('input');
    style_textbox_container(comboLookbackInput);
    comboLookbackInput.type = 'number';
    comboLookbackInput.id = 'number-input-comboLookBack';
    comboLookbackInput.value = comboLookBack;
    // Label
    const comboLookbackLabel = document.createElement('label');
    comboLookbackLabel.textContent = 'Lookback';
    comboLookbackLabel.style.fontSize = '20px';
    comboLookbackLabel.setAttribute('for', 'number-input-comboLookBack');
    comboLookbackLabel.style.display = 'block'; 
    // Container
    const lookBackContainer = document.createElement('div');
    lookBackContainer.appendChild(comboLookbackLabel);
    lookBackContainer.appendChild(comboLookbackInput);


// Add event listener for the input event
//numberInput.addEventListener('input', bouncyUpdate);
    // Button 1
    let LookBackButton = document.createElement('button');
    LookBackButton.id = 'update-combo-button';
    LookBackButton.textContent = 'Update';
    LookBackButton.style =  'width: auto; height: 50px; margin: 5px 10px 5px 10px; font-size: 30px;';
    LookBackButton.style.marginTop = '25px';
    if (LookBackButton) { LookBackButton.onclick = comboUpdate; }

// Create the alert div
let alert = document.createElement('div');
alert.id = 'combo-alert';
alert.style.border = '5px solid yellow'; 
alert.style.padding = '5px'; 
alert.style.display = 'none';
alert.style.backgroundColor = 'green';

// Create a container to hold both elements
const containerInput = document.createElement('div');
containerInput.id = 'input-alert-container-combo';
containerInput.style.marginLeft = '25px';
containerInput.style.marginBottom = '10px';
containerInput.appendChild(numberInputContainer);
containerInput.appendChild(lookBackContainer);

containerInput.appendChild(LookBackButton);
containerInput.appendChild(alert);

// Apply styles using JavaScript
containerInput.style.display = 'flex';
containerInput.style.alignItems = 'center';
containerInput.style.gap = '10px'; 

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



   // let contentDiv = createComboNumbers();document.getElementById('comboDiv');

    let contentDiv = document.createElement('div');
    contentDiv.id = 'comboDiv';
    contentDiv.style.marginLeft = '25px';
    contentDiv.style.marginBottom = '15px';

    let newLine = document.createElement('br');

    
    container.appendChild(titleDiv);
    container.appendChild(helpDiv);
    container.appendChild(containerInput);
    container.appendChild(newLine);
    container.appendChild(contentDiv);
    container.appendChild(newLine);
    container.appendChild(newLine);
    

    return container;

}




function createComboNumbers() {
    comboFound = false;  

    // Check if numbers is defined and is an array
    if (!Array.isArray(numbers)) {
        const widgetContainer = document.createElement('div');
        widgetContainer.id = 'widget-container-combo';
        widgetContainer.style.marginLeft = '25px';
        widgetContainer.style.marginBottom = '15px';
        return widgetContainer;
    }

    // Create widget container
    const widgetContainer = document.createElement('div');
    widgetContainer.id = 'widget-container-combo';
    widgetContainer.style.marginLeft = '25px';
    widgetContainer.style.marginBottom = '15px';

    // Create number list container
    const numberList = document.createElement('div');
    numberList.id = 'number-list-combo';
    widgetContainer.appendChild(numberList);

    // Get the most recent numbers up to searchLength
    const recentNumbers = numbers.slice(-comboLookBack);

    // Get the initial comboLength most recent numbers for highlighting
    const initialHighlightNumbers = recentNumbers.slice(-comboLength);

    // Create elements in memory and store in an array
    const numberElements = recentNumbers.map(number => {
        const numberElement = document.createElement('div');
        numberElement.className = 'number';
        numberElement.textContent = number;
        return numberElement;
    });

    function addNumberToList(number, numberList) {
        const numberDiv = document.createElement('div');
        numberDiv.classList.add('number');
        if (number === 0) {
            numberDiv.classList.add('green');
        } else if ([32, 19, 21, 25, 34, 27, 36, 30, 23, 5, 16, 1, 14, 9, 18, 7, 12, 3].includes(number)) {
            numberDiv.classList.add('red');
        } else {
            numberDiv.classList.add('black');
        }
        numberDiv.textContent = number;
        numberList.insertBefore(numberDiv, numberList.firstChild);
    }

    // Function to check if two arrays have the same elements regardless of order
    function arraysHaveSameElements(arr1, arr2) {
        if (arr1.length !== arr2.length) return false;
        let sortedArr1 = [...arr1].sort();
        let sortedArr2 = [...arr2].sort();
        return sortedArr1.every((value, index) => value === sortedArr2[index]);
    }
    let comboAmount = 0;
    // Apply highlighting logic in memory
    for (let i = 0; i <= recentNumbers.length - comboLength; ) {
        const sequence = recentNumbers.slice(i, i + comboLength);
        if (arraysHaveSameElements(sequence, initialHighlightNumbers)) {

            for (let j = i; j < i + comboLength; j++) {
                numberElements[j].classList.add('highlight');
            }
            i += comboLength;
            comboAmount++;
             
        } else {
            i++;
        }
    }


    if(comboAmount>1)
    {
        comboFound = true; 
    }
    // Append all elements to the DOM in reverse order
    for (let i = numberElements.length - 1; i >= 0; i--) {
        numberList.appendChild(numberElements[i]);
    }

    // Add styles directly to elements
    const styles = `
        #widget-container {
            width: 1200px;
            height: 300px;
            overflow-x: auto;
            overflow-y: auto;
            border: 1px solid #ccc;
            padding: 10px;
            position: relative;
        }
        #number-list-combo {
            display: flex;
            flex-wrap: wrap;
            justify-content: flex-start;
            align-content: flex-start;
            width: 100%;
        }
        .number {
            display: inline-block;
            width: 30px;
            height: 30px;
            line-height: 30px;
            text-align: center;
            margin: 5px;
            cursor: pointer;
            border: 2px solid #ccc;
            border-radius: 10%;
            padding: 15px;
            fontSize: 50px;
            fontWeight: bold;
            
        }
        .red { color: red; font-weight: bold; }
        .black { color: black; font-weight: bold; }
        .green { color: rgba(71, 255, 26, 0.93); font-weight: bold; }
        .highlight { background-color: rgba(42, 209, 0, 0.4); }
    `;
    const styleSheet = document.createElement('style');
    styleSheet.type = 'text/css';
    styleSheet.innerText = styles;
    document.head.appendChild(styleSheet);


    return widgetContainer;
}





// Helper function to add numbers to the list
function addNumberToListCombo(number, numberList) {
    const numberElement = document.createElement('div');
    numberElement.className = 'number';
    numberElement.textContent = number;
    numberList.appendChild(numberElement);
}




function updateHoverAfterNumberChange() {
    let numberList = document.getElementById('number-list-combo');
    if (numberList) {
        numberList.innerHTML = '';
        numbers.forEach(x => addNumberToList(x, numberList));
    } 
}

function toggleButtonHelpCombo() {
    const button = document.getElementById(`how-to-combo`);
    if(button)
    {
        helpBouncy = !helpBouncy; 
        button.style.backgroundColor = helpBouncy ? 'lightgreen' : ''; 
        
        let helpDiv = document.getElementById('help-combo');
        helpDiv.innerHTML = ''; 
        
        if (helpBouncy) {
            const img = document.createElement('img');
            img.src = 'items/comboHelp.png';
            img.alt = 'Help Image'; 

            img.onerror = function() {
                console.error('Failed to load image: ' + img.src);
                // Additional diagnostic information
                console.log('Current directory: ' + window.location.href);
            };
            helpDiv.appendChild(img); 
        }
    }

}



function comboUpdate(event) {
    let test = createComboNumbers();
    handleInputChangeCombo(event);
    displayAlertCombo(event);
    displayAlertComboStickyBottom();

}

function handleInputChangeCombo() {

    let comboLengthInput = document.getElementById('number-input-comboLength');

    let comboLookbackInput = document.getElementById('number-input-comboLookBack');

    if (comboLengthInput) {
        if (comboLengthInput.value === '' || isNaN(comboLengthInput.value) || comboLengthInput.value < 2) {
            comboLengthInput.value = 2;
        }
        if (comboLengthInput.value) {
            comboLength = parseInt(comboLengthInput.value);

        } else {
            comboLength = 2;
        }

        if (comboLookbackInput.value === '' || isNaN(comboLookbackInput.value) || comboLookbackInput.value < 2) {
            comboLookbackInput.value = 2;
        }
        if (comboLookbackInput.value) {
            comboLookBack = parseInt(comboLookbackInput.value);

        } else {
            comboLookBack = 2;
        }
        

        let content = createComboNumbers();

        let contentFromButtonClick = document.getElementById('comboDiv');
        if (contentFromButtonClick) {
            contentFromButtonClick.innerHTML = '';
            contentFromButtonClick.appendChild(content);
        }

    }


}
function displayAlertCombo() {
    let alertBox = document.getElementById('combo-alert');
    if(alertBox)
    {
        alertBox.style.display = 'none';
        alertBox.innerHTML = '';
    }

    if (alertBox && comboFound) {


        // Create a single div element to hold the numbers in a line
        let combinedNumbersDiv = document.createElement('div');


        // Loop through the numbers and build the combined text string
        for (var x = 0; x < comboLength; x++) {
            // Create a span for each number
            let numberSpan = document.createElement('span');
            var colourClass = (numRed.includes(numbers[numbers.length - (1 + x)])) ? ' historyRed' : ' historyBlack';
            if (numbers[numbers.length - (1 + x)] == 0) colourClass = ' historyGreen';

            // Assign the class and text to the span
            numberSpan.className = colourClass;
            numberSpan.innerText = numbers[numbers.length - (1 + x)];

            // Append a comma and space before each span except the first one
            if (x > 0) {
                combinedNumbersDiv.appendChild(document.createTextNode(', '));
            }

            // Append the span to the combinedNumbersDiv
            combinedNumbersDiv.appendChild(numberSpan);
        }
        let titleDiv = document.createElement('div');
        let message = document.createElement('span');
        message.textContent = 'Combo Found';
      
        
        titleDiv.appendChild(message);

        // Append the combinedNumbersDiv to the alertBox\
        alertBox.appendChild(titleDiv);
        alertBox.appendChild(combinedNumbersDiv);

        if (!(alertBox.innerHTML === '')) {
            alertBox.style.display = 'block';
        }
    }

    return;
}

function displayAlertComboStickyBottom() {
    console.log(`Inside App Display: `,comboDisplay);

    let stickyAlert = document.getElementById('sticky-bottom-alert');
    let comboAlertSticky = document.getElementById('combo-alert-sticky');
    if (comboAlertSticky) {
        stickyAlert.removeChild(comboAlertSticky);
    }


    if(comboDisplay)
    {
        let alertBox = document.createElement('div');
        alertBox.id = 'combo-alert-sticky';
        alertBox.style.border = '5px solid yellow';
        alertBox.style.padding = '10px';
        alertBox.style.width = 'auto';
        //alertBox.style.whiteSpace = 'nowrap';
        alertBox.style.display = 'inline-flex'; // Use inline-flex to shrink to fit content
        alertBox.style.flex = '1'; // Ensure it doesn't stretch
        alertBox.style.marginRight = '10px';
        alertBox.style.marginLeft = '10px';
        alertBox.style.fontSize = '50px';
        alertBox.style.fontWeight = 'bold';
        alertBox.style.textAlign = 'left';
         alertBox.style.color = 'black'; 

        console.log(`Combo Found: `,comboFound);
        if (comboFound) {

     
            // Create a single div element to hold the numbers in a line
            let combinedNumbersDiv = document.createElement('div');
            combinedNumbersDiv.style.display = 'inline-block';
            
    
    
            // Loop through the numbers and build the combined text string
            for (var x = 0; x < comboLength; x++) {
                // Create a span for each number
                let numberSpan = document.createElement('span');
                var colourClass = (numRed.includes(numbers[numbers.length - (1 + x)])) ? ' historyRed' : ' historyBlack';
                if (numbers[numbers.length - (1 + x)] == 0) colourClass = ' historyGreen';
    
                // Assign the class and text to the span
                numberSpan.className = colourClass;
                numberSpan.innerText = numbers[numbers.length - (1 + x)];
    
                // Append a comma and space before each span except the first one
                if (x > 0) {
                    combinedNumbersDiv.appendChild(document.createTextNode(', '));
                }
    
                // Append the span to the combinedNumbersDiv
                combinedNumbersDiv.appendChild(numberSpan);
            }

            
            let titleDiv = document.createElement('div');
            titleDiv.style.display = 'inline-block';
            let message = document.createElement('span');
            message.innerHTML = 'Combo Found: &nbsp;&nbsp;';
            titleDiv.appendChild(message);
    
            // Append the combinedNumbersDiv to the alertBox\
            alertBox.appendChild(titleDiv);
            alertBox.appendChild(combinedNumbersDiv);
            stickyAlert.appendChild(alertBox);
            if (!(alertBox.innerHTML === '')) {
                alertBox.style.display = 'block';
            }
        }
    }
    

   

    return;
   
}