// document.body.addEventListener('contextmenu', function (e) {
//    e.preventDefault();
// });



// Top Message
let expDiv = document.createElement('div');
let expDivP = document.createElement('p');
expDivP.textContent = zoom_message || "Zoom message"; // Ensure zoom_message is defined
expDiv.appendChild(expDivP);
//document.body.appendChild(expDiv);

let itemDiv = document.createElement('div');
let paragraph = document.createElement('p');
paragraph.textContent = double_zero_message || "Double zero message"; // Ensure double_zero_message is defined
itemDiv.appendChild(paragraph);
//document.body.appendChild(itemDiv);

//**************************************************************************************************** */
//************************************************************************************************* */


// Create the main container
let betHistory = document.createElement('div');
betHistory.style.display = "flex";
betHistory.style.flexDirection = "row";
betHistory.style.alignItems = "center"; // Aligns items vertically
betHistory.style.gap = "20px"; // Adds space between sections
betHistory.style.position = "fixed"; // Ensure it stays fixed in place, on top
betHistory.style.zIndex = '999999'; // Very high zIndex to ensure it stays on top
betHistory.style.top = "20px"; // Adjust top positioning
betHistory.style.left = "20px"; // Adjust left positioning
betHistory.style.paddingRight = "15px";
betHistory.style.paddingBottom = "15px";
betHistory.style.backgroundColor = "lightblue"; // Set background color
betHistory.style.borderRadius = "10px"; // border raduis
betHistory.classList.add('hidden'); 

// Create a container for betList and its buttons, with background color
let betListContainer = document.createElement('div');
betListContainer.style.display = "flex";
betListContainer.style.flexDirection = "column";
betListContainer.style.gap = "10px"; // Space between elements

betListContainer.style.padding = "10px"; // Add padding for visual space

// Title for betList
let sessionBetsTitle = document.createElement('h3');
sessionBetsTitle.textContent = "Session Bets";
betListContainer.appendChild(sessionBetsTitle);

// Add button below the title
let helloButton = document.createElement('button');
helloButton.textContent = "Save Bet Now";
helloButton.addEventListener('click', () => {
  setOldBet();
});
betListContainer.appendChild(helloButton);

// betList
let betList = document.createElement('select');
betList.id = "betList";
betList.size = 10; // Show 10 items
betList.style.overflowY = "scroll"; // Allow vertical scrolling if needed
betList.style.width = "200px"; // Adjust width if needed
//betList.addEventListener('change', selectOldBet);
betList.addEventListener('click', selectOldBet);
betListContainer.appendChild(betList);



let renameBtn = document.createElement('button');
renameBtn.textContent = "Rename Item";
renameBtn.addEventListener('click', renameSelectedBet);
betListContainer.appendChild(renameBtn);

let removeBetBtn = document.createElement('button');
removeBetBtn.textContent = "Remove Item";
removeBetBtn.addEventListener('click', removeSelectedBet);
betListContainer.appendChild(removeBetBtn);

// Buttons under betList
let clearListBtn = document.createElement('button');
clearListBtn.textContent = "Clear List";
clearListBtn.addEventListener('click', clearList);
betListContainer.appendChild(clearListBtn);





betHistory.appendChild(betListContainer);

// Create a container for the buttons between betList and betCache
let middleButtonsContainer = document.createElement('div');
middleButtonsContainer.style.display = "flex";
middleButtonsContainer.style.flexDirection = "column";
middleButtonsContainer.style.gap = "10px"; // Space between buttons vertically

let button = document.createElement('button');
button.className = 'button-55';
button.setAttribute('role', 'button');
button.setAttribute('id', 'cach-bet-spin-button');
button.innerText = 'Quick Spin';
middleButtonsContainer.appendChild(button);

// "Close Popup" button
let closePopupBtn = document.createElement('button');
closePopupBtn.textContent = "Close Popup";
closePopupBtn.style.backgroundColor = "#e62c1e"; // Set background color
closePopupBtn.addEventListener('click', function() {
    betHistory.classList.add('hidden'); // Hide the betListContainer
});
middleButtonsContainer.appendChild(closePopupBtn);

// "Save to Cache" button
let saveToCacheBtn = document.createElement('button');
saveToCacheBtn.textContent = "Save to Cache";
saveToCacheBtn.addEventListener('click', saveToCache);
middleButtonsContainer.appendChild(saveToCacheBtn);

// Add the text with <br> tags after the button
let infoText = document.createElement('p');
infoText.innerHTML = "<center><b>Place chips on table<br>Press quick spin<br>To save bets here</b></center>";
middleButtonsContainer.appendChild(infoText);

// Add middle buttons container to betHistory
betHistory.appendChild(middleButtonsContainer);

// Create a container for betCache and its buttons
let betCacheContainer = document.createElement('div');
betCacheContainer.style.display = "flex";
betCacheContainer.style.flexDirection = "column";
betCacheContainer.style.gap = "10px"; // Space between elements

// Title for betCache
let cacheBetsTitle = document.createElement('h3');
cacheBetsTitle.textContent = "Cache Bets";
betCacheContainer.appendChild(cacheBetsTitle);





// betCache
let betCache = document.createElement('select');
betCache.id = "betCache";
betCache.size = 10; // Show 10 items
betCache.style.overflowY = "scroll"; // Allow vertical scrolling if needed
betCache.style.width = "200px"; // Adjust width if needed
//betCache.addEventListener('change', selectOldBetCache);
betCache.addEventListener('click', selectOldBetCache);
betCacheContainer.appendChild(betCache);

let renameCacheBtn = document.createElement('button');
renameCacheBtn.textContent = "Rename Item";
renameCacheBtn.addEventListener('click', renameSelectedBetCached);
betCacheContainer.appendChild(renameCacheBtn);

let removeCacheBtn = document.createElement('button');
removeCacheBtn.textContent = "Remove Item";
removeCacheBtn.addEventListener('click', removeSelectedCacheBet);
betCacheContainer.appendChild(removeCacheBtn);

let clearCacheBtn = document.createElement('button');
clearCacheBtn.textContent = "Clear Cache";
clearCacheBtn.addEventListener('click', clearBetCache);
betCacheContainer.appendChild(clearCacheBtn);

// --- Export ONLY the selected cache item ---
const exportOneBtn = document.createElement('button');
exportOneBtn.textContent = "Export Selected";
exportOneBtn.addEventListener('click', () => {
  const sel = document.getElementById('betCache');
  if (!sel || sel.selectedIndex === -1) {
    alert("Select a Cache Bet to export.");
    return;
  }

  const savedCache = JSON.parse(localStorage.getItem('betCache')) || [];
  const idx = sel.selectedIndex;
  const item = savedCache[idx];
  if (!item) {
    alert("Selected cache item not found.");
    return;
  }

  // filename from item.text/name, safe for files
  const base = (item.text || item.name || `Cache ${idx + 1}`).trim();
  const safe = base.replace(/[^\w\- ]+/g, "_"); // basic sanitize
  const blob = new Blob([JSON.stringify(item, null, 2)], { type: "application/json" });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = `${safe}.json`;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
});
betCacheContainer.appendChild(exportOneBtn);

// --- Import ONE item from file; auto-rename on duplicates ---
const importOneBtn = document.createElement('button');
importOneBtn.textContent = "Import Item";
importOneBtn.addEventListener('click', () => {
  const input = document.createElement("input");
  input.type = "file";
  input.accept = ".json,application/json";

  input.addEventListener("change", e => {
    const file = e.target.files && e.target.files[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onload = ev => {
      try {
        let parsed = JSON.parse(ev.target.result);

        // Accept either a single object or an array with one object
        let item = Array.isArray(parsed) ? parsed[0] : parsed;

        // Validate minimal shape
        if (!item || typeof item !== "object" || !Array.isArray(item.bets)) {
          throw new Error("Invalid item format (expected an object with a 'bets' array).");
        }

        // Load current cache
        const savedCache = JSON.parse(localStorage.getItem('betCache')) || [];

        // Build set of names to avoid duplicates
        const existingNames = new Set(savedCache.map(x => (x && (x.text || x.name)) || "").filter(Boolean));

        // Base name from incoming item
        const baseNameRaw = (item.text || item.name || "Cache").trim();

        // Helper: strip existing trailing number " ... 2" and then add an increment
        const stripTrailingNumber = (s) => s.replace(/\s+\d+$/, "");
        const baseName = stripTrailingNumber(baseNameRaw) || "Cache";

        let finalName = baseName;
        let n = 2;
        while (existingNames.has(finalName)) {
          finalName = `${baseName} ${n++}`;
        }

        // Set the resolved name on both text and name to keep your code paths consistent
        item.text = finalName;
        item.name = finalName;

        // Push and save
        savedCache.push(item);
        localStorage.setItem("betCache", JSON.stringify(savedCache));

        // Refresh UI safely
        const repaint = () => {
          const sel = document.getElementById('betCache');
          if (!sel) return;
          sel.innerHTML = "";
          savedCache.forEach((it, i) => {
            const opt = document.createElement('option');
            opt.value = i;
            opt.text = it?.text || it?.name || `Cache ${i + 1}`;
            sel.add(opt);
          });
        };

        if (typeof window.loadCacheFromLocalStorage === 'function') {
          // Your existing helper in rebets.js
          window.loadCacheFromLocalStorage(); // repopulates #betCache
        } else {
          repaint();
        }

        alert(`✅ Imported "${finalName}"`);
      } catch (err) {
        console.error(err);
        alert("❌ Import failed: " + err.message);
      }
    };

    reader.readAsText(file);
  });

  input.click();
});
betCacheContainer.appendChild(importOneBtn);






betHistory.appendChild(betCacheContainer);

// Make the betHistory draggable and add it to the document
makeElementDraggableNoToggle(betHistory);
document.body.appendChild(betHistory);



//******************************************************************************************************* */
//******************************************************************************************************* */

// Create the statPanelDiv container
let statPanelDiv = document.createElement('div');
statPanelDiv.id = 'stat-panel-top';

// Buttons For Stats
let statButtons_panel = document.createElement('div');
statButtons_panel.className = 'statistics-buttons';
statPanelDiv.appendChild(statButtons_panel);

// Outside Stats
let outsideStats_Panel = document.createElement('div');
outsideStats_Panel.id = 'stats';
outsideStats_Panel.className = 'statistics';
statPanelDiv.appendChild(outsideStats_Panel);

// Append statPanelDiv to the body
document.body.appendChild(statPanelDiv);




let casinoNumbersButton_panel = document.createElement('div');
casinoNumbersButton_panel.style.paddingBottom = "0px";
casinoNumbersButton_panel.style.marginLeft = "25px";
casinoNumbersButton_panel.style.overflowX = "hidden"; // Hide horizontal scrollbar
casinoNumbersButton_panel.style.overflowY = "auto"; // Enable vertical scrolling
casinoNumbersButton_panel.style.whiteSpace = "normal"; // Allow wrapping to the next line
casinoNumbersButton_panel.style.width = "989px"; // Adjust the width as needed
casinoNumbersButton_panel.style.border = "1px solid #ccc"; // Optional: for visibility
casinoNumbersButton_panel.style.height = `100px`; // Set initial height
casinoNumbersButton_panel.setAttribute('id', 'casinoNumbersButton-panel');



document.body.appendChild(casinoNumbersButton_panel);


// Numbers up Panel
let numbersUp_Panel = document.createElement('div');
numbersUp_Panel.style.paddingTop = "5px";
numbersUp_Panel.style.paddingBottom = "5px";
numbersUp_Panel.setAttribute('id', 'numbersUp-panel');

document.body.appendChild(numbersUp_Panel);


// Numbers up Panel
let spinProfit_Panel = document.createElement('div');
spinProfit_Panel.style.paddingTop = "5px";
spinProfit_Panel.style.paddingBottom = "5px";
spinProfit_Panel.setAttribute('id', 'spinProfit-panel');
document.body.appendChild(spinProfit_Panel);

// Heat Map
let heatMap_Panel = document.createElement('div');
heatMap_Panel.style.paddingTop = "5px";
heatMap_Panel.style.paddingBottom = "5px";
heatMap_Panel.setAttribute('id', 'heatMap-panel');
document.body.appendChild(heatMap_Panel);

// Create the button bar
let buttonBar_top = document.createElement('div');
buttonBar_top.className = 'button-bar-top';
buttonBar_top.style.marginLeft ="25px";
document.body.appendChild(buttonBar_top); // Place the button bar before the statPanelDiv



// Create buttons for showing/hiding the panels
let casinoNumbersButton = document.createElement('button');
casinoNumbersButton.textContent = 'Casino Numbers';
buttonBar_top.appendChild(casinoNumbersButton);

let toggleNumbersUpPanelButton = document.createElement('button');
toggleNumbersUpPanelButton.textContent = 'Recent Panel';
buttonBar_top.appendChild(toggleNumbersUpPanelButton);

// Create buttons for showing/hiding the panels
let toggleStatPanelDivButton = document.createElement('button');
toggleStatPanelDivButton.textContent = 'Stats Panel';
buttonBar_top.appendChild(toggleStatPanelDivButton);


// Create buttons for showing/hiding the panels
let toggleProfitPanelDivButton = document.createElement('button');
toggleProfitPanelDivButton.textContent = 'Spin Profit';
buttonBar_top.appendChild(toggleProfitPanelDivButton);

// Create buttons for showing/hiding the panels
let toggleHeatMapPanelDivButton = document.createElement('button');
toggleHeatMapPanelDivButton.textContent = 'Heat Map';
buttonBar_top.appendChild(toggleHeatMapPanelDivButton);


// Create "Session Profit" inline container
const sessionProfitContainer = document.createElement('div');
sessionProfitContainer.style.display = 'flex';
sessionProfitContainer.style.alignItems = 'center';
sessionProfitContainer.style.gap = '5px';
sessionProfitContainer.style.marginLeft = '20px';

// Title
const sessionProfitLabel = document.createElement('span');
sessionProfitLabel.textContent = 'Session Profit:';
sessionProfitContainer.appendChild(sessionProfitLabel);

// Profit display (non-editable)
const sessionProfitBox = document.createElement('input');
sessionProfitBox.type = 'text';
sessionProfitBox.id = 'session-profit-box';
sessionProfitBox.value = '0';
sessionProfitBox.readOnly = true;
sessionProfitBox.style.width = '80px';
sessionProfitBox.style.textAlign = 'right';
sessionProfitBox.style.backgroundColor = '#eee';
sessionProfitBox.style.border = '1px solid #ccc';
sessionProfitBox.style.padding = '2px 5px';
sessionProfitContainer.appendChild(sessionProfitBox);

// Reset button
const resetProfitBtn = document.createElement('button');
resetProfitBtn.textContent = 'Reset';
resetProfitBtn.addEventListener('click', () => {
    sessionProfitBox.value = '0';
    session_user_amount_array.push(session_user_amount);
    session_user_amount = 0;
    localStorage.setItem("sessionProfit", JSON.stringify(session_user_amount_array));
    localStorage.setItem("sessionProfitBoxValue", JSON.stringify(session_user_amount));
});
sessionProfitContainer.appendChild(resetProfitBtn);





// Append to the existing top button bar
buttonBar_top.appendChild(sessionProfitContainer);




let logo = createLogo();
console.log(logo);
buttonBar_top.appendChild(logo);








// Function to toggle visibility of a div
function toggleVisibility(panel) {
    if (panel.style.display === 'none' || panel.style.display === '') {
        panel.style.display = 'block';
    } else {
        panel.style.display = 'none';
    }
}



// Add event listeners to the buttons
toggleStatPanelDivButton.addEventListener('click', () => {
    toggleVisibility(statPanelDiv);
});

toggleNumbersUpPanelButton.addEventListener('click', () => {
    toggleVisibility(numbersUp_Panel);
});

toggleProfitPanelDivButton.addEventListener('click', () => {
    toggleVisibility(spinProfit_Panel);
    show_bets();
});

toggleHeatMapPanelDivButton.addEventListener('click', () => {
    toggleVisibility(heatMap_Panel);
    show_bets();
});


// Optionally, hide the panels initially

casinoNumbersButton_panel.style.display ='none';
statPanelDiv.style.display = 'none';
numbersUp_Panel.style.display = 'none';
spinProfit_Panel.style.display ='none';
heatMap_Panel.style.display = 'none';

// Alerts Box
let alertsbox = document.createElement('div');
alertsbox.style.display = 'flex';
alertsbox.style.gap = '5px';
alertsbox.style.marginLeft = '25px';
alertsbox.style.padding = '3px';

document.body.appendChild(alertsbox);



// Roulette Board
let rouletteBoard = document.createElement('div');
rouletteBoard.setAttribute('id', 'roulette-board');
document.body.appendChild(rouletteBoard);

// Button Bar
let buttonBar = document.createElement('div');
buttonBar.id = 'button-bar';
buttonBar.style.display = 'flex';
buttonBar.style.justifyContent = 'flex-start';
buttonBar.style.padding = '3px';
buttonBar.style.backgroundColor = 'lightgrey';
buttonBar.style.marginLeft = '25px';
document.body.appendChild(buttonBar);

// Button Bar Click Content
let buttonBarContent = document.createElement('div');
buttonBarContent.style.backgroundColor = '#e8faf3';
buttonBarContent.id = 'button-bar-content';
buttonBarContent.style.marginLeft = '25px';
document.body.appendChild(buttonBarContent);

// Bottom Container
let bottomContainer = document.createElement('div');
bottomContainer.id = 'bottom-container';
bottomContainer.style.display = 'flex';
bottomContainer.style.justifyContent = 'flex-start';
document.body.appendChild(bottomContainer);

// Bottom Container 1
let bottomContainer1 = document.createElement('div');
bottomContainer1.id = 'bottom-container-1';
bottomContainer1.style.marginLeft = '25px';
bottomContainer1.style.marginRight = '10px';
bottomContainer.appendChild(bottomContainer1);

// Bottom Container 2
let bottomContainer2 = document.createElement('div');
bottomContainer2.id = 'bottom-container-2';
bottomContainer.appendChild(bottomContainer2);

// Bottom Container 3
let bottomContainer3 = document.createElement('div');
bottomContainer3.id = 'bottom-container-3';

let dragButtonContainer = document.createElement('div');
dragButtonContainer.id = 'drag-button-container';
dragButtonContainer.style.display = 'flex';
dragButtonContainer.style.flexDirection = 'row'; 
dragButtonContainer.style.alignItems = 'flex-start';
dragButtonContainer.style.justifyContent = 'flex-start';
bottomContainer3.appendChild(dragButtonContainer);

let panelAlertContainer = document.createElement('div');
panelAlertContainer.id = 'panel-alert-container-display';
bottomContainer3.appendChild(panelAlertContainer);

let panelWatchContainer = document.createElement('div');
panelWatchContainer.id = 'panel-watch-container-display';
bottomContainer3.appendChild(panelWatchContainer);

bottomContainer.appendChild(bottomContainer3);

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

footerContainer.style.paddingLeft = '100px';      // Indent from the left


document.body.appendChild(footerContainer);



function updateBorderVisibility() {
    if (outsideStats_Panel.textContent.trim() === '') {
        outsideStats_Panel.classList.add('hidden-border');
    } else {
        outsideStats_Panel.classList.remove('hidden-border');
    }
}







function updateBetProfitPopup() {
    const popup = document.getElementById('button-bar-div-22');
    if (!popup) return; // Do nothing if popup doesn't exist
    popup.innerHTML = '';
    // Remove the old content (everything after the header)
    const children = Array.from(popup.children);
    children.slice(1).forEach(child => child.remove());

    // Generate fresh content
    const newContent = getAllBets();

    // Append the new content
    popup.appendChild(newContent);

      if(spin_profit_uniques_array.length>0)
        {
                    console.log("UNIQUES: ",spin_profit_uniques_array);
        console.log("UNIQUES: ",spin_profit_uniques_array.length);
            
               spin_profit_display_outside();

        }
        else
        {
            spin_profit_display_outside_clear();
        }
}
