//=================================================================================================== 
// START: Global Variables
//=================================================================================================== 
const style = document.createElement('style');
style.innerHTML = `
  /* Hide arrows in input[type=number] */
  input[type=number]::-webkit-inner-spin-button, 
  input[type=number]::-webkit-outer-spin-button { 
    -webkit-appearance: none; 
    margin: 0; 
  }

  input[type=number] {
    -moz-appearance: textfield;  /* Firefox */
  }
`;

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


document.head.appendChild(style);

let edge3_frequency_count = Array.from({ length: 37 }, () => 0);

//=================================================================================================== 
// END: Global Variables
//=================================================================================================== 


// Button Bar Call
function coldBuild_edge_3() {
    let container = document.createElement('div');
    container.style.marginLeft = '25px';
    container.style.marginBottom = '15px';
    container.id = 'edge-3';

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

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

      // Create the "Show Draggable Div" button
      const showButton = document.createElement('button');
      showButton.id = 'showDivButton_edge3alert';
      showButton.textContent = 'Alert Popup';
      container.appendChild(showButton);

      //------------------------------------------------------------------------
      // DRAG ALERT DIV
      // ------------------------------------------------------------------------
      const draggableDiv = document.createElement('div');
      draggableDiv.id = 'draggableDiv_edge3alert';
      draggableDiv.classList.add('hidden_edge3alert');
      draggableDiv.style.width = '300px';
      draggableDiv.style.height = '200px';
      draggableDiv.style.backgroundColor = 'white';
      draggableDiv.style.position = 'absolute';
      draggableDiv.style.border = '1px solid #ccc';
      draggableDiv.style.borderRadius = '5px';
      draggableDiv.style.padding = '0';
      draggableDiv.style.display = 'flex';
      draggableDiv.style.flexDirection = 'column';
      draggableDiv.style.zIndex = '999999';
      draggableDiv.style.resize = 'both';
      draggableDiv.style.overflow = 'hidden'; // Prevents content overflow during resizing
      draggableDiv.style.display = 'none';

      // Create the title bar
      const titleBar = document.createElement('div');
      titleBar.style.backgroundColor = '#0078D7';
      titleBar.style.color = 'white';
      titleBar.style.padding = '5px';
      titleBar.style.fontWeight = 'bold';
      titleBar.style.cursor = 'move';
      titleBar.style.display = 'flex';
      titleBar.style.justifyContent = 'space-between';
      titleBar.style.alignItems = 'center';
      titleBar.style.height = '30px'; // Fixed height for the title bar
      
   
      const titleText = document.createElement('span');
      titleText.textContent = 'Edge Alert Numbers';
      titleBar.appendChild(titleText);
     
      const closeButton = document.createElement('button');
      closeButton.textContent = '✖';
      closeButton.style.backgroundColor = 'transparent';
      closeButton.style.color = 'white';
      closeButton.style.border = 'none';
      closeButton.style.cursor = 'pointer';
      closeButton.style.fontSize = '16px';
      closeButton.addEventListener('click', () => {
          draggableDiv.style.display = 'none';
      });
      titleBar.appendChild(closeButton);
      draggableDiv.appendChild(titleBar);
      
      // Create the content area
      const contentArea = document.createElement('div');
      contentArea.id = 'draggableDiv_edge3alert-content';
      contentArea.style.flex = '1'; // Ensures the content area takes up remaining space
      contentArea.style.padding = '10px';
      contentArea.style.backgroundColor = '#c2edff';
      contentArea.style.overflowY = 'auto'; // Allows scrolling if content overflows
      contentArea.style.fontSize = '18px';
      contentArea.textContent = '';
      
      draggableDiv.appendChild(contentArea);

      // Make the div draggable


      let offsetX, offsetY;

      titleBar.addEventListener('mousedown', (e) => {
          e.preventDefault();
          offsetX = e.clientX - draggableDiv.offsetLeft;
          offsetY = e.clientY - draggableDiv.offsetTop;
      
          function moveAt(event) {
              draggableDiv.style.left = `${event.clientX - offsetX}px`;
              draggableDiv.style.top = `${event.clientY - offsetY}px`;
          }
      
          document.addEventListener('mousemove', moveAt);
      
          document.addEventListener('mouseup', () => {
              document.removeEventListener('mousemove', moveAt);
          }, { once: true });
      });

    // Load the position from localStorage
    function loadPosition_edge3alert() {
        const savedPosition = JSON.parse(localStorage.getItem('draggableDivPosition_edge3alert'));
        if (savedPosition) {
            draggableDiv.style.left = savedPosition.left;
            draggableDiv.style.top = savedPosition.top;
        } else {
            draggableDiv.style.left = '100px';
            draggableDiv.style.top = '100px';
        }
    }

    // Save the position to localStorage
    function savePosition_edge3alert() {
        const rect = draggableDiv.getBoundingClientRect();
        const position = {
            left: `${rect.left}px`,
            top: `${rect.top}px`,
        };
        localStorage.setItem('draggableDivPosition_edge3alert', JSON.stringify(position));
    }

    // Dragging functionality
    let offsetX_edge3alert, offsetY_edge3alert;

    draggableDiv.addEventListener('mousedown', (e) => {
        if (e.target !== titleBar) {
            e.stopPropagation(); // Prevent triggering dragging logic
        }
    });

    // Show the draggable div
    showButton.addEventListener('click', (event) => {
        console.log("ALERT SHOW");
        draggableDiv.style.display = 'block';
        showPopup(event);
    });
    const showPopup = (event) => {
        // Get current position of draggableDiv
        const rect = draggableDiv.getBoundingClientRect();

        // Check if the div is off-screen or more than 1000px from the top
        if (rect.top > 1000 || rect.left < 0 || rect.right > window.innerWidth || rect.bottom > window.innerHeight) {
            // Set the position to where the cursor is
            draggableDiv.style.left = `${event.clientX}px`;
            draggableDiv.style.top = `${event.clientY}px`;
        }

        // Show the div
        draggableDiv.style.display = 'flex';
    };



    

    // Create the "Close" button
    //const closeButton = document.createElement('button');
   // closeButton.id = 'closeDivButton_edge3alert';
   // closeButton.textContent = 'Close';
   // draggableDiv.appendChild(closeButton);
    closeButton.addEventListener('click', () => { draggableDiv.style.display = 'none'; });


    // Add some content to the draggable div
    const content = document.createElement('p');
    content.id = 'edge3-alert-poup';
    content.textContent = '';
    draggableDiv.appendChild(content);
    container.appendChild(draggableDiv);

    // ------------------------------------------------------------
    // 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>The Edge</h2>';
    howToSpan.style.marginLeft = '25px';
    howToSpan.style.display = 'block';
    helpDiv.appendChild(howToSpan);

    let edgeHelp = document.createElement('p');
    edgeHelp.style.fontSize = '18px';
    edgeHelp.style.marginLeft = '25px';
    edgeHelp.innerHTML = `How long does it take a group of numbers to hit? 
        <br>It is not infinity, there is a limit. 
        <br>We tested 100 million spins to find out.
        <br><br>Now you can take advantage of that information and give yourself, The Edge. 
        <br><br>
        <b>Tip</b><br>
        Try playing "B 4" every time it is highlighted in yellow with a trigger range 1-5.
        <br><br>`;

    // Append the paragraph to formToggle
    helpDiv.appendChild(edgeHelp);

    // Create an anchor element
    let helpLink = document.createElement('a');
    helpLink.href = './items/Edge_3_help.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
    // ------------------------------------------------------------

    container.appendChild(button);
    container.appendChild(helpDiv);



    let containerUserInput = document.createElement('div');
    containerUserInput.id = 'container-cold-user-input-edge-3';
    let containerContents = document.createElement('div');
    containerContents.id = 'container-cold-contents-edge-3';

    let titleDiv = document.createElement('div');
    let titleSpan = document.createElement('span');
    titleSpan.innerHTML = '<h2>The Edge</h2>';
    titleDiv.appendChild(titleSpan);
    titleDiv.style.marginBottom = '-20px';
    container.appendChild(titleDiv);





    container.appendChild(containerUserInput);
    container.appendChild(containerContents);

    buildColdTableWithInputsAndButtons('container-cold-contents-edge-3');  // Use the reusable function
    updateEdge3Data();
    let edgeInfoDiv = document.createElement('div');
    edgeInfoDiv.id = 'edgeInfoDiv';

    container.appendChild(edgeInfoDiv);

    	// Initialize the draggable div's position on page load
        loadPosition_edge3alert();
    return container;
}

// After Spin Call
function updateColdNewNumber_edge_3() {

    var container = document.getElementById('container-cold-contents-edge-3');
    if (container) {
        unhighlight_outside_edge3();
        updateEdge3Data();
        updateColdTable_edge_3();  // Just call the update function
        remove_edge3_highlights();


    }

}

// Add event listeners to trigger highlight check on change

// Reusable table build function with buttons and input boxes
function buildColdTableWithInputsAndButtons(containerId) {

    // Populate allNumbers array globally
    allNumbers = Array.from({ length: 36 }, (_, index) => index + 1);


    // Create container for the table
    const table = document.createElement('div');

    // Create rows for input boxes, buttons, numbers, and frequencies
    const inputRowUpper = document.createElement('div');
    const inputRowLower = document.createElement('div');



    const buttonRow = document.createElement('div');
    const numberRow = document.createElement('div');
    const frequencyRow = document.createElement('div');

    const infoRow = document.createElement('div');

    inputRowLower.style.display = inputRowUpper.style.display = buttonRow.style.display = numberRow.style.display = frequencyRow.style.display = infoRow.style.display = 'flex';



    //=================================================================================================== 
    // START: Upper and Lower Bounds
    //=================================================================================================== 




    let upperValue = [691, 188, 128, 5, 16, 16, 10, 10, 10, 10, 7, 6, 8, 8, 8, 8, 8, 8, 7, 7, 6, 6, 4, 4, 4, 4, 4, 4, 4, 4, 2, 2, 2, 2, 2, 11];
    let lowerValue = [650, 178, 118, 1, 13, 13, 9, 9, 9, 9, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 5, 5, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 10];


    const edge3_alert_numbers = [];
    for (let i = 1; i <= 36; i++) {
        const inputCellLower = document.createElement('div');
        const inputCellUpper = document.createElement('div');
        const inputBoxLower = document.createElement('input');
        const inputBoxUpper = document.createElement('input');

        inputBoxLower.type = 'number';
        inputBoxLower.id = `lower-trigger-${i}`;
        inputBoxLower.value = localStorage.getItem(`lower-trigger-${i}`) || lowerValue[i-1]; // Default lower to 0

        inputBoxUpper.type = 'number';
        inputBoxUpper.id = `upper-trigger-${i}`;
        inputBoxUpper.value = localStorage.getItem(`upper-trigger-${i}`) || upperValue[i-1]; // Default upper to i

        // Helper function to update styles based on frequency
        const updateStyles = () => {
            const freqValue = allNumbers.map(num => edge3_frequency_count[num])[i - 1];
            const lowerValue = parseInt(inputBoxLower.value, 10);
            const upperValue = parseInt(inputBoxUpper.value, 10);

            if (freqValue >= lowerValue && freqValue <= upperValue) {
                inputBoxLower.style.backgroundColor = 'yellow';
                inputBoxUpper.style.backgroundColor = 'yellow';
            } else {
                inputBoxLower.style.backgroundColor = '';
                inputBoxUpper.style.backgroundColor = '';
            }
        };

        // Event listeners for lower and upper input boxes
        inputBoxLower.addEventListener('change', (event) => {
            localStorage.setItem(`lower-trigger-${i}`, event.target.value);
            updateStyles();
        });

        inputBoxUpper.addEventListener('change', (event) => {
            localStorage.setItem(`upper-trigger-${i}`, event.target.value);
            updateStyles();
        });

            // Function to enlarge the input box on focus
    inputBoxLower.addEventListener('focus', () => {
        inputBoxUpper.style.width = '50px'; // Adjust as needed
        inputBoxUpper.style.height = '35px'; // Adjust as needed
        inputBoxLower.style.width = '50px'; // Adjust as needed
        inputBoxLower.style.height = '35px'; // Adjust as needed
    });

    inputBoxLower.addEventListener('blur', () => {
        inputBoxUpper.style.width = '27px'; // Revert to original size
        inputBoxUpper.style.height = '25px'; // Revert to original size
        inputBoxLower.style.width = '27px'; // Revert to original size
        inputBoxLower.style.height = '25px'; // Revert to original size
    });

    inputBoxUpper.addEventListener('focus', () => {
        inputBoxUpper.style.width = '50px'; // Adjust as needed
        inputBoxUpper.style.height = '35px'; // Adjust as needed
        inputBoxLower.style.width = '50px'; // Adjust as needed
        inputBoxLower.style.height = '35px'; // Adjust as needed
    });

    inputBoxUpper.addEventListener('blur', () => {
        inputBoxUpper.style.width = '27px'; // Revert to original size
        inputBoxUpper.style.height = '25px'; // Revert to original size
        inputBoxLower.style.width = '27px'; // Revert to original size
        inputBoxLower.style.height = '25px'; // Revert to original size
    });

        // Append input boxes to their respective cells
        inputCellLower.appendChild(inputBoxLower);
        inputCellUpper.appendChild(inputBoxUpper);

        // Set input styles to match other cells
        inputBoxLower.style.width = '27px';  // Same width as other cells
        inputBoxLower.style.height = '25px';
        inputBoxLower.style.textAlign = 'center';

        inputBoxUpper.style.width = '27px';  // Same width as other cells
        inputBoxUpper.style.height = '25px';
        inputBoxUpper.style.textAlign = 'center';
        //inputBox.style.boxSizing = 'border-box';  // Ensure consistent width

        inputCellLower.style.display = 'flex';
        inputCellLower.style.justifyContent = 'center';
        inputCellLower.style.alignItems = 'center';
        inputCellLower.style.border = '1px solid black';

        inputCellUpper.style.display = 'flex';
        inputCellUpper.style.justifyContent = 'center';
        inputCellUpper.style.alignItems = 'center';
        inputCellUpper.style.border = '1px solid black';

        inputCellLower.appendChild(inputBoxLower);
        inputCellUpper.appendChild(inputBoxUpper);

        inputRowLower.appendChild(inputCellLower);
        inputRowUpper.appendChild(inputCellUpper);
        updateStyles();


        const freq_value = allNumbers.map(num => edge3_frequency_count[num])[i - 1];
        const low_value = parseInt(inputBoxLower.value, 10);
        const high_value = parseInt(inputBoxUpper.value, 10);
        if (freq_value >= low_value && freq_value <= high_value) { edge3_alert_numbers.push(i);}


    }

  
    let alertBox = document.getElementById('draggableDiv_edge3alert-content');
    if (alertBox) {
        // Clear the contents of the alert box
        alertBox.innerHTML = '';
    
        // Style the alert box to ensure content starts at the top
        alertBox.style.display = 'block'; // Use block layout
        alertBox.style.position = 'relative';
        alertBox.style.overflowY = 'auto'; // Ensure scrollable if content overflows
        alertBox.style.height = '200px'; // Set a fixed height for the alert box
        alertBox.style.padding = '10px';
        alertBox.style.border = '1px solid #ccc';
        
    
        // Create a new div to hold the formatted numbers
        const contentDiv = document.createElement('div');
        contentDiv.style.display = 'flex';
        contentDiv.style.flexWrap = 'wrap';
        contentDiv.style.gap = '10px'; // Add spacing between numbers
        contentDiv.style.alignItems = 'flex-start'; // Ensure content aligns to the top
    
        // Loop through the numbers and create a wrapping layout
        edge3_alert_numbers.forEach((num, index) => {
            const numberSpan = document.createElement('span');
            numberSpan.textContent = num;
            numberSpan.style.margin = '5px'; // Add margin for spacing
            contentDiv.appendChild(numberSpan);
    
            // Add a line break after every 5 numbers
            if ((index + 1) % 5 === 0) {
                const lineBreak = document.createElement('br');
                contentDiv.appendChild(lineBreak);
            }
        });
    
        // Append the content div to the alert box
        alertBox.appendChild(contentDiv);
    }
    

    // Add default Button
    // Create the button
    const setValuesButton = document.createElement('button');
    setValuesButton.textContent = 'Use default values';
    setValuesButton.style.margin = '5px';


    // Add event listener to the button
    setValuesButton.addEventListener('click', () => {
        for (let i = 1; i <= 36; i++) {
            // Set the value of the lower text box
            const lowerInputBox = document.getElementById(`lower-trigger-${i}`);
            if (lowerInputBox) {
                lowerInputBox.value = lowerValue[i-1];
                localStorage.setItem(`lower-trigger-${i}`, event.target.value);
            }

            // Set the value of the upper text box
            const upperInputBox = document.getElementById(`upper-trigger-${i}`);
            if (upperInputBox) {
                upperInputBox.value = upperValue[i-1];
                localStorage.setItem(`upper-trigger-${i}`, event.target.value);
            }

            const freqValue = allNumbers.map(num => edge3_frequency_count[num])[i - 1];


            if (freqValue >= lowerValue[i] && freqValue <= upperValue[i]) {
                lowerInputBox.style.backgroundColor = 'yellow';
                upperInputBox.style.backgroundColor = 'yellow';
            } else {
                lowerInputBox.style.backgroundColor = '';
                upperInputBox.style.backgroundColor = '';
            }
        }



    });




    //=================================================================================================== 
    // END: Upper and Lower Bounds
    //=================================================================================================== 



    // Create buttons from B37 to B1
    for (let i = 1; i <= 36; i++) {
        const buttonCell = document.createElement('div');
        const button = document.createElement('button');


        button.innerText = `B\n${i}`;  // Display B on top and the number below

        button.style.backgroundColor = '#8FBC8F';
        button.style.color = 'black';  // Use !important to test overriding
        //button.style.whiteSpace = 'pre';  // Ensure the newline character is respected

        // Check the frequency against the input value, highlight if condition is met


        button.addEventListener('click', () => toggleEdgeBetButton(button, i));


        buttonCell.style.width = '32px';
        buttonCell.style.height = '50px';  // Adjust height to accommodate two lines
        buttonCell.style.display = 'flex';
        buttonCell.style.justifyContent = 'center';
        buttonCell.style.alignItems = 'center';
        buttonCell.style.border = '1px solid black';



        buttonCell.appendChild(button);
        buttonRow.appendChild(buttonCell);
    }




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

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

        // Base styles for cells
        [numberCell, frequencyCell].forEach(cell => {
            cell.style.width = '32px';  // Keep consistent width
            cell.style.height = '25px';
            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 = '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)';
        }

        numberRow.appendChild(numberCell);
        frequencyRow.appendChild(frequencyCell);
    });



    // InfoButtons
    for (let i = 1; i <= 36; i++) {
        const buttonCell = document.createElement('div');
        const button = document.createElement('button');


        button.innerText = `${i}`;  // Display B on top and the number below
        button.id = `edge-info-${i}`;
        button.style.backgroundColor = 'gray';
        button.style.color = 'white';  // Use !important to test overriding
        //button.style.whiteSpace = 'pre';  // Ensure the newline character is respected

        // Check the frequency against the input value, highlight if condition is met


        // button.addEventListener('click', () => toggleEdgeBetButton_info(button, i));


        buttonCell.style.width = '32px';
        buttonCell.style.height = '50px';  // Adjust height to accommodate two lines
        buttonCell.style.display = 'flex';
        buttonCell.style.justifyContent = 'center';
        buttonCell.style.alignItems = 'center';
        buttonCell.style.border = '1px solid black';



        buttonCell.appendChild(button);
        infoRow.appendChild(buttonCell);
    }





    table.appendChild(setValuesButton);
    table.appendChild(inputRowUpper);
    table.appendChild(inputRowLower); // Append input row first

    table.appendChild(buttonRow);  // Then append button row
    table.appendChild(frequencyRow);  // Then append frequency row
   // table.appendChild(numberRow);  // Finally append number row
    table.appendChild(infoRow);





    const container = document.getElementById(containerId);
    if (container) {
        container.innerHTML = '';  // Clear existing content
        container.appendChild(table);  // Append the new table

        for (let i = 1; i <= 36; i++) {
            const button = document.getElementById(`edge-info-${i}`);

            if (button) {
                button.addEventListener('click', handleEdgeBetButtonClick);    // Then add it
            }

        }
    }
}

function handleEdgeBetButtonClick(event) {
    const buttonNumber = parseInt(event.target.id.replace('edge-info-', ''), 10);
    toggleEdgeBetButton_info(event.target, buttonNumber);
}

// Bet Button Click On
function handleButtonClick(buttonNumber) {


    for (var n = buttonNumber; n >= 0; n--) {

        if (oldUserBets_Edge3.has(n.toString())) {
            // If the entry exists, increment the first element (the amount)
            let existingBet = oldUserBets_Edge3.get(n.toString());
            existingBet[0] += 1;  // Increment the amount by 1
            oldUserBets_Edge3.set(n.toString(), existingBet);  // Update the map with the incremented value
        } else {
            // If the entry does not exist, add it with the initial value
            oldUserBets_Edge3.set(n.toString(), [1, "inside_whole", 35]);
        }

    }






    rebetEdge3();

}
// Bet Button Click Off
function handleButtonClickOff(buttonNumber) {



    for (var n = buttonNumber; n >= 0; n--) {
        let key = n.toString();

        if (oldUserBets_Edge3.has(key)) {
            // If the entry exists, decrement the first element (the amount)
            let existingBet = oldUserBets_Edge3.get(key);
            existingBet[0] -= 1;  // Decrement the amount by 1

            if (existingBet[0] <= 0) {
                // If the amount is 0 or less, remove the entry
                oldUserBets_Edge3.delete(key);
            } else {
                // Otherwise, update the map with the decremented value
                oldUserBets_Edge3.set(key, existingBet);
            }
        }
    };


    rebetEdge3();
}

// Info Button Click On
function handleButtonClick_info(buttonNumber) {


    // Since the numbers are sorted from least missed to most missed,
    // we take the last `buttonNumber` numbers from the list
    let startIndex = 37 - buttonNumber;  // Calculate the start index for the last N numbers
    let mostMissedNumbers = allNumbers.slice(0, buttonNumber);

    mostMissedNumbers.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);
        }
    });

}

// Info Button Click Off
function handleButtonClickOff_info(buttonNumber) {



    let startIndex = 37 - buttonNumber;  // Calculate the start index for the last N numbers
    let mostMissedNumbers = allNumbers.slice(0, buttonNumber);

    mostMissedNumbers.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);
        }
    });
}


function toggleEdgeBetButton(button, buttonNumber) {

    // Check if the button is already toggled on by checking a custom data attribute
    const isToggledOn = button.getAttribute('data-toggled') === 'true';

    if (isToggledOn) {
        // Toggle off
        handleButtonClickOff(buttonNumber);
        button.removeAttribute('data-toggled'); // Set toggle state to off
        button.style.backgroundColor = '#8FBC8F';
        button.style.color = 'black';
    } else {
        // Toggle on
        handleButtonClick(buttonNumber);
        button.setAttribute('data-toggled', 'true'); // Set toggle state to on
        button.style.backgroundColor = 'blue'; // Change color to green
        button.style.color = 'white';
    }
}

function toggleEdgeBetButton_info(button, buttonNumber) {



    let startIndex = 37 - buttonNumber;  // Calculate the start index for the last N numbers
    let mostMissedNumbers = allNumbers.slice(0, buttonNumber);


   // highlight_outside_edge3(mostMissedNumbers);
    for (let item = 1; item <= 36; item++) {

 

        let button = document.getElementById(`edge-info-${item}`);

        if (button) {
            button.style.backgroundColor = 'gray';
        }
    }


    mostMissedNumbers.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');
                    button.style.backgroundColor = 'gray';
                    unhighlight_outside_edge3();
                    let infoDiv = document.getElementById('edgeInfoDiv');
                    if (infoDiv) {
                        infoDiv.innerHTML = '';
                    }

                }
            } else {
                highlightMap[item].add(button);

                //div.classList.add('slider-highlights');
                button.style.backgroundColor = 'blue';

                let infoDiv = document.getElementById('edgeInfoDiv');
                const functionName = `edge_info_${buttonNumber}`;




                // Check if the function exists before calling it
                if (typeof window[functionName] === 'function') {
                    const newContent = window[functionName]();
                    if (infoDiv) {
                        infoDiv.innerHTML = newContent;
                    }
                }


            }
        } else {
            console.error('Failed to find div for item:', item);
        }
    });

}



// Update function for when the table needs refreshing
function updateColdTable_edge_3() {
    var newSpins = [...numbers];
    newSpins.reduce((acc, num, index) => {
        acc[num] = newSpins.length - 1 - index;
        return acc;
    }, Array.from({ length: 37 }, () => newSpins.length));

    buildColdTableWithInputsAndButtons('container-cold-contents-edge-3');  // Use the reusable function
}
function updateEdge3Data() {
    let last37 = [...numbers];


    edge3_frequency_count = Array.from({ length: 37 }, () => 0);


    // Iterate over the array to set the frequencies based on the described rules.
    last37.forEach((num, index) => {
      
        if(num == 0)
        {
           
  
                for (let i = 0; i < edge3_frequency_count.length; i++){
                edge3_frequency_count[i] += 1;
            }
       
        }
        else
        {
                // Set the indexes from 0 up to the number to 0.
                for (let i = 0; i < num; i++) {
                    edge3_frequency_count[i] += 1;
                }

                // Increase the frequencies for indexes greater than the number by 1.
                for (let i = num; i < edge3_frequency_count.length; i++) {
                    edge3_frequency_count[i] = 0;


                }
        }
 
    });



}



//=================================================================================================== 
// START: Highlight Functions
//=================================================================================================== 

function remove_edge3_highlights() {
    for (let item = 1; item <= 37; item++) {
        let div;
        if (item === 0) {
            div = document.querySelector(`div[data-values="zero_${item}"]`);
        } else {
            div = document.querySelector(`div[data-values="${item}"]`);
        }
        if (div) {
            div.classList.remove('slider-highlights');

        }

        let button = document.getElementById(`edge-info-${item}`);

        if (button) {
            button.style.backgroundColor = 'gray';
        }
    }
}

function unhighlight_outside_edge3() {
    let d1 = document.getElementById('dozen1');
    let d2 = document.getElementById('dozen2');
    let d3 = document.getElementById('dozen3');
    let r1 = document.getElementById('row1');
    let r2 = document.getElementById('row2');
    let r3 = document.getElementById('row3');
    let even = document.getElementById('outsideEven');
    let odd = document.getElementById('outsideOdd');
    let high = document.getElementById('19to36');
    let low = document.getElementById('1to18');
    let red = document.getElementById('outsideRed');
    let black = document.getElementById('outsideBlack');

    d1.classList.remove('slider-highlights');
    d2.classList.remove('slider-highlights');
    d3.classList.remove('slider-highlights');
    r1.classList.remove('slider-highlights');
    r2.classList.remove('slider-highlights');
    r3.classList.remove('slider-highlights');
    even.classList.remove('slider-highlights');
    odd.classList.remove('slider-highlights');
    high.classList.remove('slider-highlights');
    low.classList.remove('slider-highlights');
    red.classList.remove('slider-highlights');
    black.classList.remove('slider-highlights');
}
function highlight_outside_edge3(mostMissedNumbers) {

    unhighlight_outside_edge3();

    let d1 = document.getElementById('dozen1');
    let d2 = document.getElementById('dozen2');
    let d3 = document.getElementById('dozen3');
    let r1 = document.getElementById('row1');
    let r2 = document.getElementById('row2');
    let r3 = document.getElementById('row3');
    let even = document.getElementById('outsideEven');
    let odd = document.getElementById('outsideOdd');
    let high = document.getElementById('19to36');
    let low = document.getElementById('1to18');
    let red = document.getElementById('outsideRed');
    let black = document.getElementById('outsideBlack');

    let outside_highlight = outside_highlights_edge3(mostMissedNumbers);

    outside_highlight.forEach(item => {
        if (item == "D1") { d1.classList.add('slider-highlights'); }
        if (item == "D2") { d2.classList.add('slider-highlights'); }
        if (item == "D3") { d3.classList.add('slider-highlights'); }
        if (item == "R1") { r1.classList.add('slider-highlights'); }
        if (item == "R2") { r2.classList.add('slider-highlights'); }
        if (item == "R3") { r3.classList.add('slider-highlights'); }
        if (item == "E") { even.classList.add('slider-highlights'); }
        if (item == "O") { odd.classList.add('slider-highlights'); }
        if (item == "H") { high.classList.add('slider-highlights'); }
        if (item == "L") { low.classList.add('slider-highlights'); }
        if (item == "R") { red.classList.add('slider-highlights'); }
        if (item == "B") { black.classList.add('slider-highlights'); }

    });


}

function outside_highlights_edge3(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];
}

//===================================================================================================
// END: Highlight Functions
//=================================================================================================== 
