let neighborsHighlights = [];
let allClickedHighlights = [];
let array_highlight = new Array(40).fill(0);
let array_clicked = new Array(40).fill(0);



function neighborBuild() {
  // ===== constants & keys =====
  const LS_LOOKBACK_KEY = 'neighbors_heatmap_lookback';     // heatmap N
  const LS_RECENT_KEY   = 'neighbors_recent_count';         // recency K
  const LS_FLOAT_STATE  = 'neighbors_wheel_docked';         // "docked" | "undocked"
  const LS_FLOAT_LEFT   = 'neighbors_wheel_left_px';
  const LS_FLOAT_TOP    = 'neighbors_wheel_top_px';
  const DEFAULT_LOOKBACK = 35;
  const DEFAULT_RECENT   = 10;  // how many spins to show on the outer rim

  // ===== base container =====
  const container = document.createElement('div');
  container.id = 'neighbors-tool';
  container.style.marginLeft = '25px';
  container.style.marginBottom = '15px';

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

  // (kept) color changer above the card
  const colorChangerQuickSpin = quickSpin_colorChanger(container.id);
  container.append(colorChangerQuickSpin);

  const titleDiv = document.createElement('div');
  titleDiv.style.marginBottom = '-20px';
  titleDiv.innerHTML = '<h2>Neighbors</h2>';
  container.appendChild(titleDiv);

  const flexWrapper = document.createElement('div');
  flexWrapper.style.display = 'flex';
  flexWrapper.style.flexDirection = 'column';
  flexWrapper.style.alignItems = 'flex-start';

  const containerContents = document.createElement('div');
  containerContents.id = 'container-neighbor-contents';
  containerContents.style.marginRight = '0';

  flexWrapper.appendChild(containerContents);
  container.appendChild(flexWrapper);

  // ===== style (one-time) =====
  if (!document.getElementById('neighbors-svg-style')) {
    const style = document.createElement('style');
    style.id = 'neighbors-svg-style';
    style.textContent = `
      :root{
        --border:#e5e7eb; --red:#ef4444; --black:#1f2937; --green:#16a34a; --highlight:#f59e0b;
      }
      .nb-wheel-wrap{ display:flex; flex-direction:column; align-items:stretch; justify-content:flex-start; }
      .nb-card{
        border:1px solid var(--border); border-radius:12px; background:#fff; padding:10px;
        box-shadow:0 4px 18px rgba(15,23,42,.06);
      }
      .nb-card-header{
        display:flex; align-items:center; justify-content:space-between; gap:8px; margin-bottom:6px;
        user-select:none; cursor:default; width:100%;
      }
      .nb-title{ font:700 14px/1 system-ui,-apple-system,Segoe UI,Roboto,Arial; color:#111; }
      .nb-actions{ display:flex; gap:6px; }
      .nb-btn{
        padding:6px 10px; border:none; border-radius:10px; background:#111; color:#fff;
        font:600 12px/1 system-ui,-apple-system,Segoe UI,Roboto,Arial; cursor:pointer;
      }
      .nb-btn:hover{ background:#333; }
      svg.nb-wheel{ width:min(92vw, 460px); height:auto; display:block; background:#fff; border-radius:12px }
      .pocket .wedge{ stroke:#fff; stroke-width:1.2 }
      .pocket.red   .wedge{ fill:var(--red) }
      .pocket.black .wedge{ fill:var(--black) }
      .pocket.green .wedge{ fill:var(--green) }
      .pocket.active .wedge{ fill:var(--highlight) !important }
      .nb-num{ font:700 10px/1 system-ui,-apple-system,Segoe UI,Roboto,Arial; fill:#fff; text-anchor:middle; dominant-baseline:middle }
      .nb-center{ font:700 18px/1 system-ui,-apple-system,Segoe UI,Roboto,Arial; fill:#000; }
      .pocket:focus { outline: none; }

      /* controls inside the card under the wheel */
      .nb-controls{
        display:grid;
        grid-template-columns: repeat(5, auto);
        gap:8px 10px;
        align-items:center;
        justify-content:center;
        margin-top:10px;
      }
      .nb-controls .stack{ display:flex; flex-direction:column; }
      .nb-label{ font:600 12px system-ui,-apple-system,Segoe UI,Roboto,Arial; color:#111; margin-bottom:6px; }
      #neighbor-lookback, #neighbor-text, #neighbor-recent{
        padding:10px; border-radius:10px; border:1px solid #e5e7eb; width:110px;
      }
      #neighbor-clear-btn{
        background:#111; color:#fff; padding:10px 12px; border:none; border-radius:10px; font-weight:700; width:140px; cursor:pointer;
      }
      #neighbor-clear-btn:hover{ background:#333; }
      .nb-legend{ display:flex; align-items:center; gap:6px; font:600 12px system-ui,-apple-system,Segoe UI,Roboto,Arial; color:#111; justify-content:center; }
      .nb-legend-bar{ width:90px; height:10px; background: linear-gradient(90deg, #dbeafe 0%, #93c5fd 50%, #ef4444 100%); border-radius:6px; border:1px solid #e5e7eb; }

      /* recent ring text */
      .nb-recent-text{
        font:700 11px/1 system-ui,-apple-system,Segoe UI,Roboto,Arial;
        fill:#111;
        text-anchor:middle;
        dominant-baseline:middle;
      }

      /* floating popup */
      .nb-float{ position:fixed; z-index:9999; }
      .nb-drag-handle{ cursor:move; }
    `;
    document.head.appendChild(style);
  }

  // ===== controls (inside card) =====
  const lookbackLabel = document.createElement('label');
  lookbackLabel.className = 'nb-label';
  lookbackLabel.textContent = 'Heatmap: Last N spins';

  const lookbackInput = document.createElement('input');
  lookbackInput.id = 'neighbor-lookback';
  lookbackInput.type = 'number';
  lookbackInput.min = '1';
  lookbackInput.step = '1';
  const savedN = parseInt(localStorage.getItem(LS_LOOKBACK_KEY) || '', 10);
  const N0 = Number.isFinite(savedN) && savedN > 0 ? savedN : DEFAULT_LOOKBACK;
  lookbackInput.value = String(N0);

  const neighborsLabel = document.createElement('label');
  neighborsLabel.className = 'nb-label';
  neighborsLabel.textContent = 'Neighbors';

  const textBox = document.createElement('input');
  textBox.type = 'number';
  textBox.placeholder = '2';
  textBox.min = '0';
  textBox.step = '1';
  textBox.id = 'neighbor-text';

  const recentLabel = document.createElement('label');
  recentLabel.className = 'nb-label';
  recentLabel.textContent = 'Recency ring: last K';

  const recentInput = document.createElement('input');
  recentInput.id = 'neighbor-recent';
  recentInput.type = 'number';
  recentInput.min = '1';
  recentInput.step = '1';
  const savedK = parseInt(localStorage.getItem(LS_RECENT_KEY) || '', 10);
  const K0 = Number.isFinite(savedK) && savedK > 0 ? savedK : DEFAULT_RECENT;
  recentInput.value = String(K0);

  const clearBtn = document.createElement('button');
  clearBtn.id = 'neighbor-clear-btn';
  clearBtn.textContent = 'Clear Highlights';

  const legend = document.createElement('div');
  legend.className = 'nb-legend';
  legend.innerHTML = `<span>Cold</span><div class="nb-legend-bar"></div><span>Hot</span>`;

  // ===== data (AC order & colors) =====
  const wheelnumbersAC = [0,26,3,35,12,28,7,29,18,22,9,31,14,20,1,33,16,24,5,10,23,8,30,11,36,13,27,6,34,17,25,2,21,4,19,15,32];
  const numRed   = new Set([1,3,5,7,9,12,14,16,18,19,21,23,25,27,30,32,34,36]);
  const numBlack = new Set([2,4,6,8,10,11,13,15,17,20,22,24,26,28,29,31,33,35]);

  // ===== geometry =====
  const R_OUT = 180, R_IN = 90, LABEL_R = 140;
  const HEAT_R_IN = R_OUT + 6;
  const HEAT_R_OUT = R_OUT + 18;
  const RECENT_R   = R_OUT + 28; // outer ring text radius
  const wedgeDeg = 360 / wheelnumbersAC.length;
  const startDeg = -90;

  const rad = d => d * Math.PI / 180;
  const pol = (r, aDeg) => ({ x: r * Math.cos(rad(aDeg)), y: r * Math.sin(rad(aDeg)) });
  function wedgePath(rOuter, rInner, a0, a1){
    const large = (Math.abs(a1 - a0) > 180) ? 1 : 0;
    const p1 = pol(rOuter, a0), p2 = pol(rOuter, a1);
    const p3 = pol(rInner, a1), p4 = pol(rInner, a0);
    return `M ${p1.x} ${p1.y}
            A ${rOuter} ${rOuter} 0 ${large} 1 ${p2.x} ${p2.y}
            L ${p3.x} ${p3.y}
            A ${rInner} ${rInner} 0 ${large} 0 ${p4.x} ${p4.y}
            Z`;
  }

  // ===== wheel card =====
  const card = document.createElement('div');
  card.className = 'nb-card nb-wheel-wrap';
  card.id = 'nb-wheel-card';

  const header = document.createElement('div');
  header.className = 'nb-card-header nb-drag-handle';
  const title = document.createElement('div');
  title.className = 'nb-title';
  title.textContent = 'Hold to Drag';
  const actions = document.createElement('div');
  actions.className = 'nb-actions';

  const btnPopDock = document.createElement('button');
  btnPopDock.className = 'nb-btn';
  btnPopDock.type = 'button';
  btnPopDock.textContent = 'Pop out';
  actions.appendChild(btnPopDock);

  const btnResetWheel = document.createElement('button');
  btnResetWheel.className = 'nb-btn';
  btnResetWheel.type = 'button';
  btnResetWheel.textContent = 'Reset';
  actions.prepend(btnResetWheel);

  header.append(title, actions);

  const svgNS = 'http://www.w3.org/2000/svg';
  const svg = document.createElementNS(svgNS, 'svg');
  svg.setAttribute('viewBox', '-240 -240 480 480'); // slightly larger to accommodate outer ring text
  svg.setAttribute('class', 'nb-wheel');

  // subtle rims
  svg.insertAdjacentHTML('beforeend',
    `<circle cx="0" cy="0" r="${R_OUT+3}" fill="#e5e7eb" />
     <circle cx="0" cy="0" r="${R_IN-3}" fill="#e5e7eb" />`
  );

  const centerText = document.createElementNS(svgNS, 'text');
  centerText.setAttribute('class', 'nb-center');
  centerText.setAttribute('x', '0');
  centerText.setAttribute('y', '0');
  centerText.setAttribute('text-anchor', 'middle');
  centerText.setAttribute('dominant-baseline', 'middle');

  const heatGroup   = document.createElementNS(svgNS, 'g');
  heatGroup.setAttribute('id', 'nb-heatmap-ring');

  const recentGroup = document.createElementNS(svgNS, 'g');
  recentGroup.setAttribute('id', 'nb-recent-ring');

  const pocketsGroup = document.createElementNS(svgNS, 'g');

  svg.append(centerText, heatGroup, recentGroup, pocketsGroup);

  // controls container inside the card
  const controls = document.createElement('div');
  controls.className = 'nb-controls';

  const stackLookback = document.createElement('div');
  stackLookback.className = 'stack';
  stackLookback.append(lookbackLabel, lookbackInput);

  const stackNeighbors = document.createElement('div');
  stackNeighbors.className = 'stack';
  stackNeighbors.append(neighborsLabel, textBox);

  const stackRecent = document.createElement('div');
  stackRecent.className = 'stack';
  stackRecent.append(recentLabel, recentInput);

  controls.append(stackLookback, stackNeighbors, stackRecent, clearBtn, legend);

  // assemble card
  card.append(header, svg, controls);

  // dock anchor
  const dockAnchor = document.createElement('div');
  dockAnchor.id = 'nb-wheel-dock-anchor';
  containerContents.appendChild(dockAnchor);
  dockAnchor.insertAdjacentElement('afterend', card);

  // ===== behavior helpers (neighbors) =====
  function highlightNeighbors(visualNum, neighborCount, preview) {
    const wheelIndex = wheelnumbersAC.indexOf(visualNum);
    const affected = [];
    for (let i = -neighborCount; i <= neighborCount; i++) {
      const idx = (wheelIndex + i + 37) % 37;
      const v = wheelnumbersAC[idx];
      affected.push(v);

      const g = document.getElementById(`pocket-${v}`) || document.getElementById(`neighbor_${v}`);
      if (!g) continue;

      if (preview) {
        if (array_clicked[v] === 1 || i === 0) {
          g.classList.add('active');
          g.querySelector('.wedge')?.setAttribute('fill', '#71d6fd');
        } else {
          g.classList.add('active');
          g.querySelector('.wedge')?.setAttribute('fill', '#f59e0b');
        }
      } else {
        if (array_highlight[v] <= 0 && array_clicked[v] === 0) {
          g.classList.remove('active');
          const base = (v === 0) ? 'green' : (numRed.has(v) ? 'red' : 'black');
          g.classList.remove('red','black','green'); g.classList.add(base);
        } else if (array_highlight[v] > 0 && array_clicked[v] === 0) {
          g.classList.add('active');
          g.querySelector('.wedge')?.setAttribute('fill', '#f59e0b');
        }
      }
    }
    return affected;
  }

  function handleHighlightedNumbers(n) {
    const mid = (n.length - 1) / 2;
    const clicked = n[mid];
    const existingIdx = neighborsHighlights.indexOf(clicked);

    if (existingIdx !== -1) {
      array_clicked[clicked] = 0;
      n.forEach(x => { array_highlight[x] -= 1; });
      neighborUnhighlight(n);
      neighborsHighlights.splice(existingIdx, 1);
    } else {
      array_clicked[clicked] = 1;
      n.forEach(x => { array_highlight[x] += 1; });
      neighborHighlight(n);
      neighborsHighlights.push(clicked);
    }
  }

  function getActiveWheelNumbers() {
    const result = [];
    for (const v of wheelnumbersAC) {
      if ((typeof array_highlight !== 'undefined' && array_highlight[v] > 0) ||
          (typeof array_clicked   !== 'undefined' && array_clicked[v] === 1)) {
        result.push(v);
      }
    }
    return result;
  }

  // build pockets
  wheelnumbersAC.forEach((num, i) => {
    const a0 = startDeg + i * wedgeDeg;
    const a1 = a0 + wedgeDeg;
    const aMid = (a0 + a1) / 2;

    const g = document.createElementNS(svgNS, 'g');
    g.setAttribute('id', `pocket-${num}`);
    g.setAttribute('data-n', String(num));
    g.setAttribute('class', `pocket ${num===0?'green':(numRed.has(num)?'red':'black')}`);
    g.setAttribute('tabindex', '0');
    g.setAttribute('role', 'button');
    g.setAttribute('aria-label', `Number ${num}`);

    const legacy = document.createElementNS(svgNS, 'g');
    legacy.setAttribute('id', `neighbor_${num}`);
    legacy.setAttribute('visibility', 'hidden');
    g.appendChild(legacy);

    const path = document.createElementNS(svgNS, 'path');
    path.setAttribute('class', 'wedge');
    path.setAttribute('d', wedgePath(R_OUT, R_IN, a0, a1));

    const labelPos = pol(LABEL_R, aMid);
    const text = document.createElementNS(svgNS, 'text');
    text.setAttribute('class', 'nb-num');
    text.setAttribute('x', labelPos.x);
    text.setAttribute('y', labelPos.y);
    text.textContent = String(num);

    g.append(path, text);
    pocketsGroup.appendChild(g);

    // interactions
    g.addEventListener('mouseover', () => {
      const n = parseInt(textBox.value, 10);
      const neighborCount = Number.isFinite(n) ? Math.max(0, n) : 2;
      if (array_clicked[num] === 0) highlightNeighbors(num, neighborCount, true);
      centerText.textContent = String(num);
    });
    g.addEventListener('mouseout', () => {
      const n = parseInt(textBox.value, 10);
      const neighborCount = Number.isFinite(n) ? Math.max(0, n) : 2;
      if (array_clicked[num] === 0) highlightNeighbors(num, neighborCount, false);
      centerText.textContent = '';
    });
    g.addEventListener('click', () => {
      const n = parseInt(textBox.value, 10);
      const neighborCount = Number.isFinite(n) ? Math.max(0, n) : 2;
      const affected = highlightNeighbors(num, neighborCount, true);
      handleHighlightedNumbers(affected);

      if (array_clicked[num] === 1) {
        g.classList.add('active');
        g.querySelector('.wedge')?.setAttribute('fill', '#71d6fd');
      } else {
        const base = (num === 0) ? 'green' : (numRed.has(num) ? 'red' : 'black');
        g.classList.remove('active','red','black','green'); g.classList.add(base);
      }
    });
    g.addEventListener('keydown', (e) => {
      if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); g.dispatchEvent(new MouseEvent('click')); }
    });
  });

  // ===== Heatmap Ring =====
  function drawHeatmapRing(N) {
    while (heatGroup.firstChild) heatGroup.removeChild(heatGroup.firstChild);

    const spins = Array.isArray(numbers) ? numbers : [];
    const look = Math.max(1, Math.min(N, spins.length || N));
    const recent = spins.slice(-look);

    const freq = new Map(wheelnumbersAC.map(n => [n, 0]));
    for (const v of recent) if (freq.has(v)) freq.set(v, freq.get(v) + 1);
    const maxCount = Math.max(1, ...freq.values());

    const cold = [219,234,254];
    const hot  = [239, 68, 68];
    const lerp = (a,b,t)=> Math.round(a + (b-a)*t);

    wheelnumbersAC.forEach((num, i) => {
      const a0 = startDeg + i * wedgeDeg;
      const a1 = a0 + wedgeDeg;

      const t = (freq.get(num) || 0) / maxCount; // 0..1
      const r = lerp(cold[0], hot[0], t);
      const g = lerp(cold[1], hot[1], t);
      const b = lerp(cold[2], hot[2], t);
      const fill = `rgb(${r},${g},${b})`;

      const path = document.createElementNS(svgNS, 'path');
      path.setAttribute('d', wedgePath(HEAT_R_OUT, HEAT_R_IN, a0, a1));
      path.setAttribute('fill', fill);
      path.setAttribute('stroke', '#e5e7eb');
      path.setAttribute('stroke-width', '0.6');
      heatGroup.appendChild(path);
    });
  }

  // ===== Recency Ring (outer labels for last K spins, supports repeats) =====
  function drawRecencyRing(K) {
    // clear old
    while (recentGroup.firstChild) recentGroup.removeChild(recentGroup.firstChild);

    const spins = Array.isArray(numbers) ? numbers : [];
    const k = Math.max(1, Math.min(K, spins.length || K));
    const lastK = spins.slice(-k); // oldest .. most recent

    // Build a map: pocket -> array of labels to show
    // We follow your request: label "10" for most recent when K=10, ... "1" for oldest.
    // So label = (position from end), i.e., idx from 1..k where k=most recent, 1=oldest -> we invert to show most recent as k.
    // Example: lastK = [10,9,8,...,1] (10 oldest ... 1 most recent), labels shown: most recent gets "10".
    const occurrences = new Map(wheelnumbersAC.map(n => [n, []]));
    for (let i = 0; i < lastK.length; i++) {
      const pocket = lastK[i];
      if (!occurrences.has(pocket)) occurrences.set(pocket, []);
      const isOldestIndex = i;           // 0 .. k-1
      const label = isOldestIndex + 1;   // k (most recent) .. 1 (oldest)  <-- matches your description
      occurrences.get(pocket).push(label);
    }

    // For each pocket that has entries, place a text outside the heatmap at arc midpoint
    wheelnumbersAC.forEach((num, i) => {
      const labs = occurrences.get(num);
      if (!labs || labs.length === 0) return;

      const a0 = startDeg + i * wedgeDeg;
      const a1 = a0 + wedgeDeg;
      const aMid = (a0 + a1) / 2;
      const pos = pol(RECENT_R, aMid);

      const t = document.createElementNS(svgNS, 'text');
      t.setAttribute('class', 'nb-recent-text');
      t.setAttribute('x', pos.x);
      t.setAttribute('y', pos.y);
      // If multiple hits, show comma-separated (e.g., "5,8,12")
      t.textContent = labs.sort((a,b)=>a-b).join(',');

      // Slight rotation to face outward (optional for style; comment out if undesired)
      t.setAttribute('transform', `rotate(${aMid}, ${pos.x}, ${pos.y})`);

      recentGroup.appendChild(t);
    });
  }

  // public updater
  window.updateNeighborHeatmap = function(optionalN){
    clearAllHighlights();
    if (typeof removeAll === 'function') { try { removeAll(); } catch(e){} }
    if (typeof placeBetHeatMap === 'function') { try { placeBetHeatMap([]); } catch(e){} }

    let N = optionalN;
    if (!Number.isFinite(N) || N <= 0) {
      const current = parseInt(lookbackInput.value, 10);
      N = Number.isFinite(current) && current > 0 ? current : DEFAULT_LOOKBACK;
    } else {
      lookbackInput.value = String(N);
      localStorage.setItem(LS_LOOKBACK_KEY, String(N));
    }
    drawHeatmapRing(N);

    const K = Math.max(1, parseInt(recentInput.value, 10) || DEFAULT_RECENT);
    localStorage.setItem(LS_RECENT_KEY, String(K));
    drawRecencyRing(K);
  };

  // initial draw
  drawHeatmapRing(N0);
  drawRecencyRing(K0);

  // persist + redraw on changes
  lookbackInput.addEventListener('change', () => {
    const n = parseInt(lookbackInput.value, 10);
    const N = Number.isFinite(n) && n > 0 ? n : DEFAULT_LOOKBACK;
    lookbackInput.value = String(N);
    localStorage.setItem(LS_LOOKBACK_KEY, String(N));
    drawHeatmapRing(N);
  });

  recentInput.addEventListener('change', () => {
    const k = Math.max(1, parseInt(recentInput.value, 10) || DEFAULT_RECENT);
    recentInput.value = String(k);
    localStorage.setItem(LS_RECENT_KEY, String(k));
    drawRecencyRing(k);
  });

  // ===== Clear button: reset wheel UI + your arrays =====
  function clearAllHighlights() {
    if (typeof array_highlight !== 'undefined') for (let i = 0; i < 37; i++) array_highlight[i] = 0;
    if (typeof array_clicked !== 'undefined')   for (let i = 0; i < 37; i++) array_clicked[i] = 0;
    if (typeof neighborsHighlights !== 'undefined' && Array.isArray(neighborsHighlights)) neighborsHighlights.length = 0;

    wheelnumbersAC.forEach((v) => {
      const g = document.getElementById(`pocket-${v}`);
      if (!g) return;
      g.classList.remove('active','red','black','green');
      const base = (v === 0) ? 'green' : (numRed.has(v) ? 'red' : 'black');
      g.classList.add(base);
      g.querySelector('.wedge')?.removeAttribute('fill');
    });
    const ct = svg.querySelector('.nb-center'); if (ct) ct.textContent = '';

    if (typeof removeAllHighlights === 'function') { try { removeAllHighlights(); } catch(e){} }
    if (typeof neighborUnhighlight === 'function') { try { neighborUnhighlight([]); } catch(e){} }
  }

  clearBtn.addEventListener('click', () => {
    clearAllHighlights();
    if (typeof removeAll === 'function') { try { removeAll(); } catch(e){} }
  });

  // ===== Reset button =====
  btnResetWheel.addEventListener('click', () => {
    clearAllHighlights();
    if (typeof removeAll === 'function') { try { removeAll(); } catch(e){} }
    if (typeof placeBetHeatMap === 'function') { try { placeBetHeatMap([]); } catch(e){} }
    if (typeof clearTable === 'function') { try { clearTable(); } catch(e){} }
    const n = parseInt(lookbackInput.value, 10);
    drawHeatmapRing(Number.isFinite(n) && n > 0 ? n : DEFAULT_LOOKBACK);
    const k = Math.max(1, parseInt(recentInput.value, 10) || DEFAULT_RECENT);
    drawRecencyRing(k);
  });

  // ===== Pop out / Dock + Dragging =====
  function undockWheel() {
    if (card.classList.contains('nb-float')) return;
    const rect = card.getBoundingClientRect();
    card.style.width = rect.width + 'px';
    card.classList.add('nb-float');
    document.body.appendChild(card);

    let left = parseFloat(localStorage.getItem(LS_FLOAT_LEFT));
    let top  = parseFloat(localStorage.getItem(LS_FLOAT_TOP));
    if (!Number.isFinite(left) || !Number.isFinite(top)) {
      left = Math.max(12, rect.left);
      top  = Math.max(12, rect.top);
    }
    card.style.left = left + 'px';
    card.style.top  = top  + 'px';

    btnPopDock.textContent = 'Dock';
    localStorage.setItem(LS_FLOAT_STATE, 'undocked');
  }

  function dockWheel(force = false) {
    if (!force && !card.classList.contains('nb-float')) {
      btnPopDock.textContent = 'Pop out';
      if (card.previousElementSibling !== dockAnchor) {
        dockAnchor.insertAdjacentElement('afterend', card);
      }
      return;
    }
    const left = parseFloat(card.style.left || '0');
    const top  = parseFloat(card.style.top  || '0');
    if (Number.isFinite(left)) localStorage.setItem(LS_FLOAT_LEFT, String(left));
    if (Number.isFinite(top))  localStorage.setItem(LS_FLOAT_TOP,  String(top));

    card.classList.remove('nb-float');
    card.style.left = '';
    card.style.top  = '';
    card.style.width = '';
    dockAnchor.insertAdjacentElement('afterend', card);

    btnPopDock.textContent = 'Pop out';
    localStorage.setItem(LS_FLOAT_STATE, 'docked');
  }

  btnPopDock.addEventListener('click', () => {
    if (card.classList.contains('nb-float')) dockWheel(); else undockWheel();
  });

  (function makeDraggable(handleEl, moveEl){
    let dragging = false, startX=0, startY=0, startLeft=0, startTop=0;

    function onDown(e){
      if (!card.classList.contains('nb-float')) return;
      dragging = true;
      const isTouch = e.type.startsWith('touch');
      const p = isTouch ? e.touches[0] : e;
      startX = p.clientX; startY = p.clientY;
      const rect = moveEl.getBoundingClientRect();
      startLeft = rect.left; startTop = rect.top;
      document.addEventListener(isTouch ? 'touchmove' : 'mousemove', onMove, {passive:false});
      document.addEventListener(isTouch ? 'touchend'  : 'mouseup', onUp, {passive:false, once:true});
      e.preventDefault();
    }
    function onMove(e){
      if (!dragging) return;
      const isTouch = e.type.startsWith('touch');
      const p = isTouch ? e.touches[0] : e;
      const dx = p.clientX - startX;
      const dy = p.clientY - startY;
      const newLeft = Math.max(0, startLeft + dx);
      const newTop  = Math.max(0, startTop + dy);
      moveEl.style.left = newLeft + 'px';
      moveEl.style.top  = newTop  + 'px';
      e.preventDefault();
    }
    function onUp(){
      dragging = false;
      const left = parseFloat(moveEl.style.left || '0');
      const top  = parseFloat(moveEl.style.top  || '0');
      if (Number.isFinite(left)) localStorage.setItem(LS_FLOAT_LEFT, String(left));
      if (Number.isFinite(top))  localStorage.setItem(LS_FLOAT_TOP,  String(top));
      document.removeEventListener('mousemove', onMove);
      document.removeEventListener('touchmove', onMove);
    }

    handleEl.addEventListener('mousedown', onDown);
    handleEl.addEventListener('touchstart', onDown, {passive:false});
  })(header, card);

  // ===== FORCE DOCK ON PAGE LOAD =====
  localStorage.setItem(LS_FLOAT_STATE, 'docked');
  dockWheel(true);

  if (typeof placeBetHeatMap === 'function') {
    try { placeBetHeatMap([]); } catch(e) {}
  }

  // ===== mount base container =====
  return container;
}


function clearNeighbors()
{
    let spinLength = document.getElementById('cold-inputbox').value;
    
    spinLength = ensureInputValue(spinLength,37);
}
function neighborHighlight(arr)
{

    arr.forEach(item => {
        let div;
        if (item === 0) {
            div = document.querySelector(`div[data-values="zero_${item}"]`);
            div.click();
      
        } else {
            div = document.querySelector(`div[data-values="${item}"]`);
            div.click();
        }
console.log(div);
        if (div) {
            div.classList.add('neighbors-highlights');
            
        }
    });
/*
         // Remove 0 amounts
                for (let i = bet.length - 1; i >= 0; i--) {
                if (bet[i].amt === 0) {
                    bet.splice(i, 1);
                }
            }
            for (let i = 0; i < bet.length; i++) {
    bet[i].amt = 1;
}
    */
            console.log("NEW BET HI lighlight: ",bet);

}
function neighborUnhighlight(arr) {
    arr.forEach(item => {
       
                

        let div;
            if (item === 0) {
                div = document.querySelector(`div[data-values="zero_${item}"]`);
                if(div)
                {

                    if (array_highlight[item] <=0) {  // Check if the highlight count is not greater than 0
           
            removeAllNeighborHighlightsFromElement(div);
        }

                    removeBet(div, item, 'zero', 35);
                    
if (!div.classList.contains('neighbors-highlights')) {
    let loopCount = 0;
    const maxLoops = 100;

    let betEntry = bet.find(b => b.numbers === item.toString() && b.type === 'zero');

    while (betEntry && betEntry.amt > 0 && loopCount < maxLoops) {
        removeBet(div, item, 'zero', 35);
        betEntry = bet.find(b => b.numbers === item.toString() && b.type === 'zero');
        loopCount++;
    }

    if (loopCount >= maxLoops) {
        console.warn(`Stopped removing zero bet for ${item} after ${maxLoops} attempts (no neighbors-highlights).`);
    }
}


                }
            } else {
                div = document.querySelector(`div[data-values="${item}"]`);
                if(div)
                {
                    if (array_highlight[item] <=0) {  // Check if the highlight count is not greater than 0
           
            removeAllNeighborHighlightsFromElement(div);
        }
        
                    removeBet(div, item, 'inside_whole', 35);
console.log("CLCIKEC REMOVED BET");

                   if (!div.classList.contains('neighbors-highlights')) {
    let loopCount = 0;
    const maxLoops = 100;

    let betEntry = bet.find(b => b.numbers === item.toString() && b.type === 'inside_whole');
console.log("BET ENTRY:L ",betEntry);
    while (betEntry && betEntry.amt > 0 && loopCount < maxLoops) {
        removeBet(div, item, 'inside_whole', 35);
        betEntry = bet.find(b => b.numbers === item.toString() && b.type === 'inside_whole');
        loopCount++;
    }

    if (loopCount >= maxLoops) {
        console.warn(`Stopped removing bet for ${item} after ${maxLoops} attempts (no neighbors-highlights).`);
    }
}
                }
            }


    });

    

            
    
            console.log("NEW BET UN-highlight: ",bet);

}
function removeAllNeighborHighlightsFromElement(element) {
    while (element.classList.contains('neighbors-highlights')) {
        element.classList.remove('neighbors-highlights');
    }
}

function removeAll()
{
    let arr = Array.from({ length: 37 }, (_, i) => i);
    arr.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) {
            div.classList.remove('neighbors-highlights');
            
        }
    });
    removeAllHighlights();
    neighborsHighlights = [];
    allClickedHighlights = [];
    array_highlight = new Array(40).fill(0);
    array_clicked = new Array(40).fill(0);
}

function removeAllHighlights() {
    let allNumbers = Array.from({length: 37}, (_, index) => index);
    allNumbers.forEach(num => {
        let cell = document.getElementById(`neighbor_`+num);
       
        
        if(cell)
        {
           
        
            cell.style.backgroundColor = numRed.includes(num) ? 'rgb(221, 82, 82)' : numBlack.includes(num) ? 'rgb(68, 60, 60)' : 'rgb(146, 196, 150)';
            cell.style.color = 'white';
        }

    });
}