    function createLogo() {
      // inject Google Font if not already
      if (!document.getElementById("logo-font")) {
        const link = document.createElement("link");
        link.id = "logo-font";
        link.rel = "stylesheet";
        link.href = "https://fonts.googleapis.com/css2?family=Amaranth:wght@700&display=swap";
        document.head.appendChild(link);
      }

      // inject styles if not already
      if (!document.getElementById("logo-style")) {
        const style = document.createElement("style");
        style.id = "logo-style";
        style.textContent = `
          .dice_top {
            font-size: 1.5rem;
            animation: roll 3s infinite;
            display: inline-block;
          }

          @keyframes roll {
            0% { transform: rotate(0deg); }
            25% { transform: rotate(90deg); }
            50% { transform: rotate(180deg); }
            75% { transform: rotate(270deg); }
            100% { transform: rotate(360deg); }
          }

          .logo_top {
            font-family: 'Amaranth', sans-serif;
            font-weight: 700;
            font-size: 30px;
            color: black;
            position: relative;
            margin-left: 150px;
          }

          .highlight_top {
            background: linear-gradient(to left, yellow, black);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
          }
        `;
        document.head.appendChild(style);
      }

      // build logo DOM
      const logoDiv = document.createElement("div");
      logoDiv.className = "logo_top";

      const dice = document.createElement("span");
      dice.className = "dice_top";
      dice.textContent = "🎲";

      const highlight = document.createElement("span");
      highlight.className = "highlight_top";
      highlight.textContent = "sV10";

      logoDiv.appendChild(dice);
      logoDiv.append(" Trigger");
      logoDiv.appendChild(highlight);


      return logoDiv;
    }

function ensureInputValue(textBoxValue, defaultValue, lessThan=0, greaterThan = 1000000) {
   
    let num = Number(textBoxValue);

    if (isNaN(num) || num >= greaterThan || num <= lessThan) {
	
        return defaultValue;
    }

    return num;
}

function createAndClearBlankDiv(id)
{
    let container = document.getElementById(id);

	if(container){
		container.remove();
		container = document.createElement('div');
		container.id = id;
	}
	else{
		container = document.createElement('div');
		container.id = id;
	}

	return container;
}

function setTriggerCode()
{
	
	let data = document.getElementById('trigger-code');
	data.value = '';
	for(var x=0; x<triggerListLoss.length; x++)
	{
		data.value += triggerListName[x]+":"+triggerListWinLoss[x]+":"+triggerListLoss[x]+":"+triggerListItem[x]+":"+triggerListText[x]+"\n";
	}

	
}

function processValue(input) {
 
    var groups = input.split('-');

    var result = groups.map(group => {

        var cleanedGroup = group.replace(/\s+/g, "").replace(/\./g, ",").replace(/[^0-9,]/g, "");
        
        var numbers = [...new Set(cleanedGroup.split(',')
                       .map(number => parseInt(number, 10))
                       .filter(number => !isNaN(number) && number >= 0 && number <= 36))];

        return numbers;
    }).filter(group => group.length > 0); 

    return result;
}

function isInRed(num) {
	return numRed.includes(num) ? 'R' : num==0? '-': 'B';
}
function mapToRB(subArray) {
	return subArray.map(num => isInRed(num));
}
function isEO(num) {
	return num % 2 === 1 ? 'O' : num==0? '-': 'E';
}

function mapToEO(subArray) {
	return subArray.map(num => isEO(num));
}
function isHL(num) {
	return num >18 ? 'H' : num==0? '-': 'L';
}

function mapToHL(subArray) {
	return subArray.map(num => isHL(num));
}
function isD1(num) {
	var item = "-";
	if(num>=1 && num<=12)
	{
		item = "D1";
	}
	if(num>=13 && num<=24)
	{
		item = "D2";
	}
	if(num>=25 && num<=36)
	{
		item = "D3";
	}
	return item;
}

function mapToD1(subArray) {
	return subArray.map(num => isD1(num));
}
function isR1(num) {
	var r1 = [1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31, 34];
	var r2 = [2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35];
	var r3 = [3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36];
	var item = "-";
	if(r1.includes(num))
	{
		item = "R1";
	}
	if(r2.includes(num))
	{
		item = "R2";
	}
	if(r3.includes(num))
	{
		item = "R3";
	}
	return item;
}

function mapToR1(subArray) {
	return subArray.map(num => isR1(num));
}

function getNumbersForPatterns(text){

	let parts = text.split(" ");
	let patternLength = parseInt(parts[0], 10);
	let patternMultiplier = parseInt(parts[2], 10);
	let patternLookback = patternLength * patternMultiplier;
	
	
	// Get array pattern
	let relevantPortion = numbers.slice(-patternLookback);
	let arrayTotal = [];
	for (let i = 0; i < patternMultiplier; i++) {
	  let start = i * patternLength;
	  let chunk = relevantPortion.slice(start, start + patternLength);
	  arrayTotal.push(chunk);
	}
	return arrayTotal;
}
function getIdForPatternTable(text)
{
	let parts = text.split(" ");
	let patternLength = parseInt(parts[0], 10);
	let patternMultiplier = parseInt(parts[2], 10);
	return ``+patternLength+` x ` + patternMultiplier;

}

function two_box_input_and_button(textboxId, pHolder, button1Id, button2Id,  button1Text, button2Text, spanId, marginLeft){

	/* Attach On click
	
		var updateButtonEvens = document.getElementById('update_button_id_stats_table_evens');
		if (updateButtonEvens) { updateButtonEvens.onclick = calc_Evens; }

	*/

	let container = document.createElement('div');

	const textBox = document.createElement('input');
    textBox.setAttribute('type', 'text');
    textBox.setAttribute('placeholder', pHolder);
    textBox.style.padding = '10px';
    textBox.style.marginLeft = marginLeft;
    textBox.style.borderRadius = '4px';
    textBox.style.border = '1px solid #ccc';
    textBox.style.width = '100px';
    textBox.id = textboxId;
    container.appendChild(textBox);


    var button1 = document.createElement('button');
    button1.textContent = button1Text;
    button1.style.padding = '8px 10px';
    button1.style.fontSize = '14px';
    button1.style.margin = '5px';
    button1.style.width = '100px';
    button1.id = button1Id;
    container.appendChild(button1);

	var button2 = document.createElement('button');
    button2.textContent = button2Text;
    button2.style.padding = '8px 10px';
    button2.style.fontSize = '14px';
    button2.style.margin = '5px';
    button2.style.width = '100px';
    button2.id = button2Id;
    container.appendChild(button2);

    var overSpins = document.createElement('span');
    overSpins.id = spanId;
	overSpins.innerHTML = '';
    container.appendChild(overSpins);
	return  {
        container,
        buttons: {
            button1: button1, 
            button2: button2 
        }
	};
}

function quickSpin_colorChanger(containerId)
{
	    //******************************************************************************** */
    // Start:  Quick Spin and Color Picker
    // ******************************************************************************* */
    // Check if a background color is stored in localStorage
	let mainId = containerId+'-containerId';
    let divContainer = document.createElement('div')
    divContainer.id =mainId;
    let savedColor = localStorage.getItem(mainId+'backgroundColor');

    if (savedColor) {
        divContainer.style.backgroundColor = savedColor;
    }

    let button = document.createElement('button');
	button.className = 'button-55';
	button.setAttribute('role', 'button');
	button.setAttribute('id', mainId+'quick-spin-button');
	button.innerText = 'Quick Spin';
	button.onclick = quickSpin;
    divContainer.appendChild(button);
    
    let colorPicker = document.createElement('input');
    colorPicker.type = 'color';
    colorPicker.id = mainId+'colorPicker';
    colorPicker.value = savedColor || '#990000';  // Use saved color or default
    colorPicker.style.position = 'relative';
    colorPicker.style.top = '4px';
    colorPicker.onchange = function() {
        changeToolColor(this.value);
    };
    divContainer.appendChild(colorPicker);
    
    // Function to change color and save it to localStorage
    function changeToolColor(color) {
        divContainer.style.backgroundColor = color;
        localStorage.setItem(mainId+'backgroundColor', color);
		let mainContainer = document.getElementById(containerId);

		if(mainContainer)
		{
			mainContainer.style.backgroundColor = color;
		}
		
		
    }
    return divContainer;
    //******************************************************************************** */
    // END:  Quick Spin and Color Picker
    // ******************************************************************************* */
}

function colorChanger(containerId)
{
	    //******************************************************************************** */
    // Start:  Quick Spin and Color Picker
    // ******************************************************************************* */
    // Check if a background color is stored in localStorage
	let mainId = containerId+'-containerId';
    let divContainer = document.createElement('div')
    divContainer.id =mainId;
    let savedColor = localStorage.getItem(mainId+'backgroundColor');

    if (savedColor) {
        divContainer.style.backgroundColor = savedColor;
    }


    let colorPicker = document.createElement('input');
    colorPicker.type = 'color';
    colorPicker.id = mainId+'colorPicker';
    colorPicker.value = savedColor || '#990000';  // Use saved color or default
    colorPicker.style.position = 'relative';
    colorPicker.style.top = '4px';
    colorPicker.onchange = function() {
        changeToolColor(this.value);
    };
    divContainer.appendChild(colorPicker);
    
    // Function to change color and save it to localStorage
    function changeToolColor(color) {
        divContainer.style.backgroundColor = color;
        localStorage.setItem(mainId+'backgroundColor', color);
		let mainContainer = document.getElementById(containerId);

		if(mainContainer)
		{
			mainContainer.style.backgroundColor = color;
		}
		
		
    }
    return divContainer;
    //******************************************************************************** */
    // END:  Quick Spin and Color Picker
    // ******************************************************************************* */
}

//******************************************************************************** */
// START:  Radio button for Bouncy Dozen and Rows
// ******************************************************************************* */

let dozenOrRow = localStorage.getItem('dozenOrRow') || 'dozen'; // Default to 'dozen' if not set

function createRadioButtons() {
    addStyles();
    const container = document.createElement('div');
    container.id = 'radio-container';

    // Create a wrapper div with a specific class to scope the styles
    const wrapper = document.createElement('div');
    wrapper.classList.add('custom-radio-buttons');

    // Create Play Dozens radio button
    const playDozensLabel = document.createElement('label');
    const playDozensRadio = document.createElement('input');
    playDozensRadio.type = 'radio';
    playDozensRadio.name = 'playOptions';
    playDozensRadio.value = 'dozen';
    playDozensRadio.checked = dozenOrRow === 'dozen'; // Set based on the saved value
    playDozensRadio.addEventListener('change', updateOption); // Add change event
    playDozensLabel.appendChild(playDozensRadio);
    playDozensLabel.appendChild(document.createTextNode(' Play Dozens'));

    // Create Play Rows radio button
    const playRowsLabel = document.createElement('label');
    const playRowsRadio = document.createElement('input');
    playRowsRadio.type = 'radio';
    playRowsRadio.name = 'playOptions';
    playRowsRadio.value = 'row';
    playRowsRadio.checked = dozenOrRow === 'row'; // Set based on the saved value
    playRowsRadio.addEventListener('change', updateOption); // Add change event
    playRowsLabel.appendChild(playRowsRadio);
    playRowsLabel.appendChild(document.createTextNode(' Play Rows'));

    // Append both radio buttons to the wrapper
    wrapper.appendChild(playDozensLabel);
    wrapper.appendChild(document.createElement('br')); // line break
    wrapper.appendChild(playRowsLabel);

    // Append the wrapper to the container
    container.appendChild(wrapper);
    return container;
}

function updateOption(event) {
    dozenOrRow = event.target.value;
    localStorage.setItem('dozenOrRow', dozenOrRow); // Save the selection in localStorage


    let container = document.getElementById('button-bar-div-12');
    if (container) {
        // Clear the container before loading new content
        container.innerHTML = '';
        
        if (dozenOrRow === 'dozen') {
           
            useBouncyDozenBet = false;
            useBouncyDozenBet_bounceRow = false;
            oldUserBets_rows = new Map();

            let itemDozen = document.getElementById('use-bouncy-dozen');
            if(itemDozen) itemDozen.checked = false;

            let itemRow = document.getElementById('use-bouncy-dozen_bounceRow');
            if(itemRow) itemRow.checked = false;

            clearTheBets();
            appendOrRemoveAlert();

            let bb = bounce();
            container.appendChild(bb);

        } else if (dozenOrRow === 'row') {
           
            useBouncyDozenBet = false;
            useBouncyDozenBet_bounceRow = false;

            let itemDozen = document.getElementById('use-bouncy-dozen');
            if(itemDozen) itemDozen.checked = false;

            let itemRow = document.getElementById('use-bouncy-dozen_bounceRow');
            if(itemRow) itemRow.checked = false;


            clearTheBets();
            appendOrRemoveAlert_bounceRow();

            let bb = bounce_bounceRow();
            container.appendChild(bb);
        }
    }
}

function addStyles() {
    const style = document.createElement('style');
    style.innerHTML = `
        /* Apply styles only to the elements inside .custom-radio-buttons */
        .custom-radio-buttons {
            margin: 20px;
            padding: 20px;
            border: 2px solid #ccc;
            border-radius: 8px;
            width: fit-content;
            background-color: #f9f9f9;
        }

        .custom-radio-buttons label {
            font-size: 24px;
            font-weight: bold;
            margin-right: 20px;
        }

        .custom-radio-buttons input[type="radio"] {
            width: 24px;
            height: 24px;
            margin-right: 10px;
        }

        .custom-radio-buttons input[type="radio"]:checked + label {
            color: #007BFF;
        }

        .custom-radio-buttons label:hover {
            color: #007BFF;
        }
    `;
    document.head.appendChild(style);
}

//******************************************************************************** */
// END:  Radio button for Bouncy Dozen and Rows
// ******************************************************************************* */

function clearTheBets()
{
    oldUserBets_dozens = new Map();
    oldUserBets_rows = new Map();

    bouncyProfit = 0;
    bouncyProfit_bounceRow = 0;

    global_bouncy_bet_index = 0;
    global_bouncy_bet_index_bounceRow = 0;

    bouncyDozenBetPlaced = false;
    bouncyDozenBetPlaced_bounceRow = false;

    bankValue = bankValue + currentBet;
				
    currentBet = 0;
    document.getElementById('bankSpan').innerText = '' + bankValue.toLocaleString("en-GB") + '';
    document.getElementById('betSpan').innerText = '' + currentBet.toLocaleString("en-GB") + '';
    clearBet();
    removeChips();

    var bottomStickyBox = document.getElementById('sticky-bottom-alert');
    bottomStickyBox.innerHTML = '';


}

function createPopup(content) {
    // Create the overlay (background) for the popup
    const overlay = document.createElement('div');
    overlay.style.position = 'fixed';
    overlay.style.top = '0';
    overlay.style.left = '0';
    overlay.style.width = '100%';
    overlay.style.height = '100%';
    overlay.style.backgroundColor = 'rgba(0, 0, 0, 0.5)'; // Semi-transparent background
    overlay.style.zIndex = '999'; // Ensure it appears on top
  
    // Create the popup container
    const popup = document.createElement('div');
    popup.style.position = 'fixed';
    popup.style.top = '50%';
    popup.style.left = '50%';
    popup.style.transform = 'translate(-50%, -50%)'; // Center the popup
    popup.style.backgroundColor = '#fff';
    popup.style.padding = '20px';
    popup.style.borderRadius = '8px';
    popup.style.boxShadow = '0 4px 8px rgba(0, 0, 0, 0.2)';
    popup.style.zIndex = '1000';
    popup.style.minWidth = '300px'; // Adjust size as needed
  
    // Add the content to the popup
    popup.appendChild(content);
  
    // Create the close button
    const closeButton = document.createElement('button');
    closeButton.textContent = '✖'; // Close icon
    closeButton.style.position = 'absolute';
    closeButton.style.top = '10px';
    closeButton.style.right = '10px';
    closeButton.style.background = 'transparent';
    closeButton.style.border = 'none';
    closeButton.style.color = '#333';
    closeButton.style.fontSize = '20px';
    closeButton.style.cursor = 'pointer';
  
    // Close the popup when the button is clicked
    closeButton.addEventListener('click', () => {
      document.body.removeChild(overlay);
    });
  
    // Add the close button to the popup
    popup.appendChild(closeButton);
  
    // Add the popup to the overlay
    overlay.appendChild(popup);
  
    // Add the overlay to the body
    document.body.appendChild(overlay);
  }
  


//******************************************************************************** */
// START: Roulette Heatmap 
// ******************************************************************************* */



function getRouletteHeatmapWidget(initialN) {
  const LS_KEY = 'roulette_heatmap_lastN';
  const saved = parseInt(localStorage.getItem(LS_KEY) || '', 10);
  const N0 = Number.isFinite(initialN) ? Math.max(1, initialN)
           : (Number.isFinite(saved) ? Math.max(1, saved) : 35);

  // One-time style injection
  if (!document.getElementById('roulette-heatmap-style')) {
    const style = document.createElement('style');
    style.id = 'roulette-heatmap-style';
    style.textContent = `
:root{
  --cell-h: clamp(28px, 6vw, 42px);
  --cell-w: 84px;
}

.rh-wrap{ font-family: system-ui,-apple-system,Segoe UI,Roboto,Arial,sans-serif; color:#0f172a }
.rh-card{ border:1px solid #e5e7eb; border-radius:12px; background:#fff; padding:10px }
.rh-head{ display:flex; align-items:center; justify-content:space-between; gap:10px; margin-bottom:8px; flex-wrap:wrap }
.rh-left{ font-weight:700 }
.rh-controls{ display:flex; align-items:center; gap:8px; font-size:.9rem; color:#334155 }
.rh-controls input{ width:80px; padding:6px 8px; border-radius:8px; border:1px solid #cbd5e1; font:inherit }
.rh-controls label{ display:flex; align-items:center; gap:6px }
.rh-legend{ display:flex; align-items:center; gap:8px; font-size:.9rem; color:#475569 }
.rh-bar{ height:10px; width:220px; border-radius:6px; background:linear-gradient(90deg,#e0f2fe,#ef4444); border:1px solid #e5e7eb }

.rh-gridwrap{ display:grid; grid-template-columns:auto 1fr; gap:6px }
.rh-zeros{ display:flex; flex-direction:column; gap:6px }

/* Zero boxes */
.rh-zero, .rh-dzero{
  width: calc(var(--cell-w) * 1.35);
  height: calc(var(--cell-h) * 2 + 6px);
  display:flex; align-items:center; justify-content:center;
  border:1px solid #e5e7eb; border-radius:10px; background:#dcfce7;
  position:relative; overflow:hidden; font-weight:800
}

/* Grid */
.rh-grid{
  display:grid;
  grid-template-columns: repeat(12, var(--cell-w));
  grid-auto-rows: var(--cell-h);
  gap:6px
}
.rh-cell{
  position:relative; display:flex; align-items:center; justify-content:center;
  width: var(--cell-w); height: var(--cell-h);
  border:1px solid #e5e7eb; border-radius:10px;
  overflow:hidden; user-select:none; font-weight:800
}
.rh-num{ position:relative; z-index:1; color:#111 }
.rh-count{
  position:absolute; bottom:4px; right:4px; z-index:1;
  font:700 11px/1 ui-monospace,Menlo,Consolas,monospace;
  color:#0b1020; background:#ffffffd9; padding:1px 5px; border-radius:999px; border:1px solid #e5e7eb
}
.rh-heat{ position:absolute; inset:0; border-radius:10px; background:#f8fafc; z-index:0 }

/* === One-line KPIs + Action button === */
.rh-stats{ margin-top:10px }
.rh-kpis{
  display:flex; gap:10px; align-items:stretch; flex-wrap:nowrap;
  overflow-x:auto; padding-bottom:2px;
}
.rh-kpi{
  flex:0 0 auto; display:flex; align-items:center; gap:8px;
  border:1px solid #e5e7eb; border-radius:999px; padding:6px 10px;
  white-space:nowrap; background:#fff;
}
.rh-kpi .kpi-label{ color:#475569; font-size:.85rem }
.rh-kpi .kpi-value{ font-weight:800; font-size:1rem }

/* Button styled to match chips */
.rh-action{
  cursor:pointer; user-select:none;
  background:#0ea5e9; color:#fff; border-color:#0ea5e9;
}
.rh-action:hover{ filter:brightness(0.95) }
.rh-action:active{ filter:brightness(0.9) }
.rh-action:disabled{
  opacity:.5; cursor:not-allowed; filter:none; background:#94a3b8; border-color:#94a3b8;
}

.rh-foot{ text-align:center; color:#475569; font-size:.9rem; margin-top:6px }

@media (prefers-color-scheme:dark){
  .rh-wrap{ color:#e5e7eb }
  .rh-card{ background:#0f172a; border-color:#273244 }
  .rh-zero, .rh-dzero{ background:#064e3b; border-color:#273244 }
  .rh-grid .rh-cell{ border-color:#273244 }
  .rh-num{ color:#e5e7eb }
  .rh-count{ color:#0b1020; background:#e5e7ebd9; border-color:#273244 }
  .rh-kpi{ border-color:#273244; background:#0b1320 }
  .rh-action{ background:#0ea5e9; border-color:#0ea5e9; color:#0b1320 }
}

/* your positioning tweaks */
.rh-wrap {
  position: relative;
  margin-left: 25px;
  display: inline-block;
  max-width: 50%;
}
  .rh-card { width: fit-content; }
    `;
    document.head.appendChild(style);
  }

  // Build container
  const root = document.createElement('div');
  root.className = 'rh-wrap';

  root.innerHTML = `
    <div class="rh-card">
      <div class="rh-head">
        <div class="rh-left">Roulette Heatmap</div>
        <div class="rh-controls">
          <label title="How many most-recent spins to include">
            Last N:
            <input type="number" min="1" step="1" value="${N0}" />
          </label>
        </div>
        <div class="rh-legend"><span>Cold</span><span class="rh-bar"></span><span>Hot</span></div>
      </div>

      <div class="rh-gridwrap">
        <div class="rh-zeros">
          <div id="rh-cell-0"  class="rh-zero"  data-num="0"><span class="rh-num">0</span><span class="rh-count">0</span><div class="rh-heat"></div></div>
          <div id="rh-cell-00" class="rh-dzero" data-num="00" style="display:none"><span class="rh-num">00</span><span class="rh-count">0</span><div class="rh-heat"></div></div>
        </div>
        <div id="rh-grid" class="rh-grid" aria-live="polite"></div>
      </div>

      <div class="rh-stats">
        <div class="rh-kpis">
          <div class="rh-kpi">
            <span class="kpi-label">Unhit in last <span class="kpi-n">${N0}</span>:</span>
            <span class="kpi-value" id="kpi-m">—</span>
          </div>
          <div class="rh-kpi">
            <span class="kpi-label">Probability to hit in the next 5 spins:</span>
            <span class="kpi-value" id="kpi-p5">—</span>
          </div>
          <div class="rh-kpi">
            <span class="kpi-label">Expected wait to any unhit:</span>
            <span class="kpi-value" id="kpi-wait">—</span>
          </div>
          <!-- Action button on same line -->
          <button type="button" class="rh-kpi rh-action" id="rh-bet-btn" title="Bet all numbers currently unhit in last N">Bet Unhit (0)</button>
        </div>
      </div>

    </div>
  `;

  const grid    = root.querySelector('#rh-grid');
  const inputN  = root.querySelector('input[type="number"]');
  const kpiM    = root.querySelector('#kpi-m');
  const kpiP5   = root.querySelector('#kpi-p5');
  const kpiW    = root.querySelector('#kpi-wait');
  const betBtn  = root.querySelector('#rh-bet-btn');

  // Base board colors
  const REDS = new Set([32,19,21,25,34,27,36,30,23,5,16,1,14,9,18,7,12,3]);
  const redBg   = '#fee2e2';
  const blackBg = '#e5e7eb';

  // Helpers
  const POCKETS = 37;
  const fmtPct  = (x) => (x*100).toFixed(2) + '%';
  const fmtWait = (x) => (x === Infinity ? '—' : x.toFixed(1) + ' spin' + (x>=1.5?'s':''));
  const uniqKeys = ["0", ...Array.from({length:36}, (_,i)=>String(i+1))];

  // Safely access global spins
  function getSpins() {
    if (Array.isArray(numbers)) return numbers;
    if (Array.isArray(Numbers)) return Numbers;
    return [];
  }

  // Build the 12x3 grid (3..36 / 2..35 / 1..34)
  function buildCellsOnce() {
    if (grid.childElementCount) return;
    const addRow = (first) => {
      for (let col = 0; col < 12; col++) {
        const n = first + 3 * col;
        const cell = document.createElement('div');
        cell.className = 'rh-cell';
        cell.id = `rh-cell-${n}`;
        cell.dataset.num = String(n);
        cell.style.background = REDS.has(n) ? redBg : blackBg;
        cell.innerHTML = `<span class="rh-num">${n}</span><span class="rh-count">0</span><div class="rh-heat"></div>`;
        grid.appendChild(cell);
      }
    };
    addRow(3); addRow(2); addRow(1);
  }

  // Color scale cold→hot
  function blendColdHot(t) {
    const c0 = [0xE0, 0xF2, 0xFE], c1 = [0xEF, 0x44, 0x44];
    const ch = (a,b)=>Math.round(a + (b-a)*t);
    const [r,g,b] = [ch(c0[0],c1[0]), ch(c0[1],c1[1]), ch(c0[2],c1[2])];
    return `#${r.toString(16).padStart(2,'0')}${g.toString(16).padStart(2,'0')}${b.toString(16).padStart(2,'0')}`;
  }

  let lastBetArray = []; // updated each render

  // Paint from global spins + N and update stats
  function render(N) {
    const n = Math.max(1, Math.floor(N || 35));
    inputN.value = String(n);
    localStorage.setItem(LS_KEY, String(n));
    root.querySelectorAll('.kpi-n').forEach(el => el.textContent = String(n));

    const spins = getSpins();

    // Recent window for heatmap
    const recent = (n > 0 ? spins.slice(-n) : spins).map(v => {
      if (v === '00') return '00';
      const k = Number(v);
      return Number.isFinite(k) ? String(k) : null;
    }).filter(Boolean);

    // Initialize counts (0..36) and include 00 if present
    const counts = Object.fromEntries(uniqKeys.map(k => [k, 0]));
    let hasDoubleZero = false;
    for (const s of recent) {
      if (s === '00') hasDoubleZero = true;
      if (!(s in counts)) counts[s] = 0;
      counts[s]++;
    }
    const el00 = root.querySelector('#rh-cell-00');
    el00.style.display = hasDoubleZero ? '' : 'none';

    // Min/max for normalization
    const vals = Object.values(counts);
    const max = Math.max(...vals);
    const min = Math.min(...vals);
    const span = Math.max(1, max - min);

    function paintCell(id, key) {
      const el = root.querySelector(id);
      if (!el) return;
      const c = counts[key] || 0;
      const t = (c - min) / span;
      el.querySelector('.rh-count').textContent = String(c);
      el.querySelector('.rh-heat').style.background = blendColdHot(t);
      el.title = `${key} — ${c} hit(s) in last ${n}`;
    }

    for (let i = 1; i <= 36; i++) paintCell(`#rh-cell-${i}`, String(i));
    paintCell('#rh-cell-0', '0');
    if (hasDoubleZero) paintCell('#rh-cell-00', '00');

    // ===== KPIs + Bet button =====
    const unhitInN = uniqKeys.filter(k => (counts[k] || 0) === 0);
    const m = unhitInN.length;
    const p5 = m > 0 ? (1 - Math.pow(1 - m / POCKETS, 5)) : 0;
    const wait = m > 0 ? (POCKETS / m) : Infinity;

    kpiM.textContent  = String(m);
    kpiP5.textContent = fmtPct(p5);
    kpiW.textContent  = fmtWait(wait);

    // Prepare bet array (numbers where possible)
    lastBetArray = unhitInN.map(k => (k === '00' ? '00' : Number(k)));

    // Button state & label
    betBtn.textContent = `Bet Unhit (${m})`;
    betBtn.disabled = m === 0;
  }

  // Build once, then render
  buildCellsOnce();
  render(N0);

  // Wire controls
  inputN.addEventListener('change', () => {
    const v = parseInt(inputN.value || '35', 10);
    render(Number.isFinite(v) ? v : 35);
  });

  betBtn.addEventListener('click', () => {
    if (!lastBetArray.length) return;
    if (typeof placeBetHeatMap === 'function') {
      try { placeBetHeatMap(lastBetArray.slice()); }
      catch (e) { console.error('placeBet(betArray) threw an error:', e); }
    } else {
      // Fallback: emit an event your app can listen for
      root.dispatchEvent(new CustomEvent('heatmapPlaceBet', { detail: { bets: lastBetArray.slice() } }));
      console.warn('placeBet(betArray) is not defined; dispatched "heatmapPlaceBet" event instead.', lastBetArray);
    }
  });

  return root;
}

function placeBetHeatMap(betArray) {


   
  const chip = document.querySelector('.cdChipActive');
  if (chip) chip.click();
  console.log(betArray);
   betArray.forEach(num => {
            const component = document.querySelector(`[data-values="${num}"]`);
            if (component) component.click();
        });

}

// Reusable clear routine
function clearTable() {
  // Refund current bet
  bankValue += currentBet;
  session_user_amount += currentBet;

  // Reset current bet
  currentBet = 0;

  // Update UI
  const bankEl = document.getElementById('bankSpan');
  const betEl  = document.getElementById('betSpan');
  if (bankEl) bankEl.innerText = bankValue.toLocaleString("en-GB");
  if (betEl)  betEl.innerText  = currentBet.toLocaleString("en-GB");

  // Preserve whatever tracking you're doing (kept as in your original)
  if (betEl) {
    global_chip_id.push(betEl.id);
    // 'wager' may be undefined if no chip is selected; guard it if needed:
    if (typeof wager !== "undefined") global_chip_amt.push(wager);
  }

  // Your existing helpers
  clearBet();
  removeChips();
}
