
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////   AUTO PLAY BUTTON
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

let button_autoButton = null;
let isToggledOn_autoButton = false;
let countdownInterval_autoButton = null;
let countdownTime_autoButton = 15;
let turn_off_overlay_orange_button = 3000;
const turn_off_overlay_random = 0;

// ---- add near your globals
let AUTO_SPIN_DELAY_RANDOM = Number(localStorage.getItem('AUTO_SPIN_DELAY_RANDOM')) || 10;
let AUTO_SPIN_DELAY_CASINO = Number(localStorage.getItem('AUTO_SPIN_DELAY_CASINO')) || 15;
let seenTimestampsByCasino = new Map();
let turn_off_overlay = (typeof window.turn_off_overlay === 'number')
    ? window.turn_off_overlay
    : 3000;



let spinIndex = 0;
let casinoSpins = [];

let lastSpinNumber = null;
let lastSpinSettledAt = null; // track latest timestamp


let selectedCasinoSource = 'spin_auto_roulette.php';
let useRandomNumber = false;
let isWaitingForNewSpin = false;


function q_random_button_sticky_auto_spin() {
  const button = document.createElement('button');
  button.style.minWidth = '220px';
  button.style.height = '100px';
  button.style.margin = '5px 0 5px 10px';
  button.style.fontSize = '60px';
  button.style.padding = '0 30px';
  button.style.textAlign = 'center';
  button.style.lineHeight = '70px';
  button.style.border = '2px solid black';
  button.style.borderRadius = '10px';
  button.style.backgroundColor = '#eee';
  button.style.cursor = 'pointer';
  button.textContent = 'Auto';

  // Make it sticky to bottom right
  button.style.position = 'fixed';
  button.style.bottom = '125px';
  button.style.right = '20px';
  button.style.zIndex = '1000';

  button.id = `countdownBtn`;
	

    button_autoButton = button;


	button.addEventListener('click', () => {
		if (!isToggledOn_autoButton) {
			createCasinoSelectionPopup(() => {

                
				isToggledOn_autoButton = true;
                button.classList.remove('running');
                button.classList.add('auto-active');
                (button_autoButton || button).textContent = 'Waiting'; // shows feedback while polling
                waitForNewSpinAndStartCountdown();

			});
		} else {
			isToggledOn_autoButton = false;
			clearInterval(countdownInterval_autoButton);
			button.textContent = 'Auto';
			button.classList.remove('running');
            button.classList.remove('running', 'auto-active');
		}
	});

	

	return button;

}

async function spinLatestNumber() {
	if (useRandomNumber) {
		const randomNumber = Math.floor(Math.random() * 37);
		pushHistory(randomNumber);
		return;
	}

	try {
		const response = await fetch(selectedCasinoSource);
		const data = await response.json();
		const latestResult = data?.[0];

		if (latestResult) {
			const { number } = latestResult.data.result.outcome;
			const settledAt = latestResult.data.settledAt;

			if (!isNaN(number) && number >= 0 && number <= 36) {
				// Get or create the set for this casino
const normalizedKey = selectedCasinoSource.replace(/spin_/, 'spin_50_');

if (!seenTimestampsByCasino.has(normalizedKey)) {
  seenTimestampsByCasino.set(normalizedKey, new Set());
}
const seenSet = seenTimestampsByCasino.get(normalizedKey);

				if (!seenSet.has(settledAt)) {
					seenSet.add(settledAt);
					console.log("✅ New spin:", number, "from", selectedCasinoSource);
					pushHistory(number);
				} else {
					console.log("⏳ No new spin yet for", selectedCasinoSource);
				}
			} else {
				console.warn("Invalid number from API:", number);
			}
		}
	} catch (error) {
		console.error("Failed to fetch spin:", error);
	}
}



function getAutoBtn() {
  return button_autoButton || document.getElementById('countdownBtn');
}





function startCountdown_random() {
  const btn = getAutoBtn?.() || button_autoButton;
  if (!btn) return;

  clearInterval(countdownInterval_autoButton);

  let timeLeft = Number(AUTO_SPIN_DELAY_RANDOM) || 10;
  btn.textContent = `${timeLeft}s`;
  if (isToggledOn_autoButton) {
    btn.classList.add('auto-active'); // keep green while running
  }

  countdownInterval_autoButton = setInterval(() => {
    if (!document.body.contains(btn)) {
      clearInterval(countdownInterval_autoButton);
      return;
    }

    timeLeft--;
    btn.textContent = `${timeLeft}s`;

    if (timeLeft <= 0) {
      clearInterval(countdownInterval_autoButton);
      btn.classList.add('running');

      const maybePromise = oneRandomNumber?.();

      const restart = () => {
        btn.classList.remove('running');
        if (isToggledOn_autoButton) {
          btn.classList.add('auto-active'); // ✅ keep green on restart
          startCountdown_random();
        } else {
          btn.textContent = 'Auto';
          btn.classList.remove('auto-active'); // back to default
        }
      };

      if (maybePromise && typeof maybePromise.then === 'function') {
        maybePromise.finally(restart);
      } else {
        restart();
      }
    }
  }, 1000);
}


async function startCountdown() {
  const btn = getAutoBtn();
  if (!btn) { console.warn('Auto button not found; aborting countdown'); return; }

  clearInterval(countdownInterval_autoButton);

  let timeLeft = Number(AUTO_SPIN_DELAY_CASINO) || 15;
  btn.textContent = `${timeLeft}s`;

  countdownInterval_autoButton = setInterval(async () => {
    // if element got removed/replaced, stop cleanly
    if (!document.body.contains(getAutoBtn())) {
      clearInterval(countdownInterval_autoButton);
      return;
    }

    timeLeft--;
    getAutoBtn().textContent = `${timeLeft}s`;




    if (timeLeft <= 0) {
  clearInterval(countdownInterval_autoButton);
  getAutoBtn().classList.add('running');

  if (savedSpinNumber !== null) {
    if (useRandomNumber) {
      await spin();
    } else {
      await numberPadSpinAsync(savedSpinNumber); // <-- this already waits overlay ms
    }
    savedSpinNumber = null;
  }

  // 🔧 No second overlay wait here
  const b = getAutoBtn();
  if (!b) return;

  b.classList.remove('running');

  if (isToggledOn_autoButton) {
    b.textContent = 'Wait';
    b.classList.add('auto-active');   // keep green while active
    waitForNewSpinAndStartCountdown();
  } else {
    b.textContent = 'Auto';
    b.classList.remove('auto-active');
  }
}






  }, 1000);
}

function numberPadSpinAsync(n) {
	return new Promise(resolve => {
		pushHistory(n);
        resolve();
		
	});
}

let savedSpinNumber = null;

async function waitForNewSpinAndStartCountdown() {
	isWaitingForNewSpin = true;

	if (button_autoButton) {
		button_autoButton.textContent = 'Wait';

	}

	if (useRandomNumber) {
		const randomNumber = Math.floor(Math.random() * 37);
		savedSpinNumber = randomNumber;
		isWaitingForNewSpin = false;
		startCountdown_random();
		return;
	}

	while (isWaitingForNewSpin) {
		try {
			const response = await fetch(selectedCasinoSource);
			const data = await response.json();
			console.log("Parsed API Data:", data);

			if (Array.isArray(data) && data.length > 0) {
				const latestResult = data[0];
				const { number } = latestResult.data.result.outcome;
				const settledAt = latestResult.data.settledAt;

				if (!isNaN(number) && number >= 0 && number <= 36) {
					// Get or initialize Set for this casino
const normalizedKey = selectedCasinoSource.replace(/spin_/, 'spin_50_');

if (!seenTimestampsByCasino.has(normalizedKey)) {
  seenTimestampsByCasino.set(normalizedKey, new Set());
}
const seenSet = seenTimestampsByCasino.get(normalizedKey);

					if (!seenSet.has(settledAt)) {
						seenSet.add(settledAt);
						savedSpinNumber = number;
						console.log("✅ Detected new spin:", number);
						isWaitingForNewSpin = false;
						turn_off_overlay = 3000;
						startCountdown();
						return;
					}
				}
			} else {
				console.warn("⚠️ API returned no usable spin data.");
			}
		} catch (error) {
			console.error("Error checking for new spin:", error);
		}

		await new Promise(resolve => setTimeout(resolve, 1000));
	}
}









function createCasinoSelectionPopup(callback) {
    const popup = document.createElement('div');
    popup.id = 'casino-popup';
    popup.style.position = 'fixed';
    popup.style.top = '50%';
    popup.style.left = '50%';
    popup.style.transform = 'translate(-50%, -50%)';
    popup.style.background = 'white';
    popup.style.padding = '50px 70px'; // large padding
    popup.style.border = '3px solid black';
    popup.style.zIndex = '9999';
    popup.style.width = '750px';   // extra wide
    popup.style.maxWidth = '95%';
    popup.style.minHeight = '600px'; // tall popup
    popup.style.boxShadow = '0 0 50px rgba(0,0,0,0.5)';
    popup.style.fontSize = '22px'; // bigger base font
    popup.style.borderRadius = '12px';
    popup.style.color = 'black';

    const title = document.createElement('h2');
    title.textContent = 'Select Casino or Random';
    title.style.marginBottom = '30px';
    title.style.textAlign = 'center';
    title.style.fontSize = '28px'; // larger title
    popup.appendChild(title);

    list.forEach(item => {
        const btn = document.createElement('button');
        btn.textContent = item.name;
        btn.style.display = 'block';
        btn.style.margin = '20px 0';
        btn.style.padding = '20px 30px'; // big buttons
        btn.style.fontSize = '20px'; // big text
        btn.style.width = '100%';
        btn.style.cursor = 'pointer';
        btn.style.background = '#007bff';
        btn.style.color = '#fff';
        btn.style.border = 'none';
        btn.style.borderRadius = '8px';
        btn.style.transition = 'background 0.2s ease';

        btn.addEventListener('mouseover', () => {
            btn.style.background = '#0056b3';
        });
        btn.addEventListener('mouseout', () => {
            btn.style.background = '#007bff';
        });

        btn.addEventListener('click', () => {
            if (item.file) {
                selectedCasinoSource = item.file;
                useRandomNumber = false;
            } else {
                useRandomNumber = true;
            }
            document.body.removeChild(popup);

            if (typeof callback === 'function') {
                callback();
            }
        });

        popup.appendChild(btn);
    });

    // Make input fields bigger if they exist inside the popup
    popup.querySelectorAll('input, select, textarea').forEach(input => {
        input.style.fontSize = '20px';
        input.style.padding = '12px 15px';
    });

    const link = document.createElement('a');
    link.href = 'spins.php';
    link.target = '_blank';
    link.textContent = 'View Raw Spins';
    link.style.display = 'block';
    link.style.marginTop = '50px';
    link.style.fontSize = '35px';
    link.style.color = '#007bff';
    link.style.textDecoration = 'underline';
    link.style.textAlign = 'center';

    popup.appendChild(link);

    document.body.appendChild(popup);




















// --- Delay Configuration Inputs ---
const delayLabel = document.createElement('h4');
delayLabel.textContent = 'Configure Auto Spin Delay (in seconds)';
delayLabel.style.marginTop = '30px';
delayLabel.style.fontSize = '26px'; // much bigger font
delayLabel.style.fontWeight = 'bold';
delayLabel.style.textAlign = 'center';
delayLabel.style.color = '#000'; // clear, dark text
popup.appendChild(delayLabel);

// Random delay input
const randomDelayWrapper = document.createElement('div');
randomDelayWrapper.style.marginBottom = '20px';
randomDelayWrapper.style.fontSize = '22px';  // bigger text
randomDelayWrapper.style.fontWeight = 'bold';
randomDelayWrapper.style.textAlign = 'center'; // center it in popup

const randomDelayLabel = document.createElement('label');
randomDelayLabel.textContent = 'Random Number Delay: ';
randomDelayLabel.style.marginRight = '10px';

const randomDelayInput = document.createElement('input');
randomDelayInput.type = 'number';
randomDelayInput.min = 1;
randomDelayInput.max = 60;
randomDelayInput.value = AUTO_SPIN_DELAY_RANDOM;
randomDelayInput.style.marginLeft = '5px';
randomDelayInput.style.fontSize = '22px'; // big input text
randomDelayInput.style.padding = '12px 15px'; // big click area
randomDelayInput.style.width = '120px'; // wider box
randomDelayInput.style.border = '2px solid #ccc';
randomDelayInput.style.borderRadius = '6px';
randomDelayInput.style.textAlign = 'center';

randomDelayWrapper.appendChild(randomDelayLabel);
randomDelayWrapper.appendChild(randomDelayInput);
popup.appendChild(randomDelayWrapper);


randomDelayInput.addEventListener('change', () => {
	AUTO_SPIN_DELAY_RANDOM = parseInt(randomDelayInput.value) || 10;
	localStorage.setItem('AUTO_SPIN_DELAY_RANDOM', AUTO_SPIN_DELAY_RANDOM);
});
randomDelayWrapper.appendChild(randomDelayLabel);
randomDelayWrapper.appendChild(randomDelayInput);
popup.appendChild(randomDelayWrapper);

// Casino delay input
const casinoDelayWrapper = document.createElement('div');
casinoDelayWrapper.style.marginBottom = '20px';
casinoDelayWrapper.style.fontSize = '22px';  // bigger label text
casinoDelayWrapper.style.fontWeight = 'bold';
casinoDelayWrapper.style.textAlign = 'center'; // center in popup

const casinoDelayLabel = document.createElement('label');
casinoDelayLabel.textContent = 'Casino Delay: ';
casinoDelayLabel.style.marginRight = '10px';

const casinoDelayInput = document.createElement('input');
casinoDelayInput.type = 'number';
casinoDelayInput.min = 1;
casinoDelayInput.max = 60;
casinoDelayInput.value = AUTO_SPIN_DELAY_CASINO;
casinoDelayInput.style.marginLeft = '5px';
casinoDelayInput.style.fontSize = '22px'; // big input text
casinoDelayInput.style.padding = '12px 15px'; // big click area
casinoDelayInput.style.width = '120px'; // wider input box
casinoDelayInput.style.border = '2px solid #ccc';
casinoDelayInput.style.borderRadius = '6px';
casinoDelayInput.style.textAlign = 'center';

casinoDelayWrapper.appendChild(casinoDelayLabel);
casinoDelayWrapper.appendChild(casinoDelayInput);
popup.appendChild(casinoDelayWrapper);


casinoDelayInput.addEventListener('change', () => {
	AUTO_SPIN_DELAY_CASINO = parseInt(casinoDelayInput.value) || 15;
	localStorage.setItem('AUTO_SPIN_DELAY_CASINO', AUTO_SPIN_DELAY_CASINO);
});
casinoDelayWrapper.appendChild(casinoDelayLabel);
casinoDelayWrapper.appendChild(casinoDelayInput);
popup.appendChild(casinoDelayWrapper);

const closeButton = document.createElement('button');
closeButton.textContent = 'Close';
closeButton.style.marginTop = '30px';
closeButton.style.display = 'block';
closeButton.style.width = '100%';
closeButton.style.padding = '18px'; // bigger click area
closeButton.style.fontSize = '22px'; // large readable text
closeButton.style.fontWeight = 'bold';
closeButton.style.backgroundColor = '#ff4d4d'; // bright red for visibility
closeButton.style.color = '#fff'; // white text for contrast
closeButton.style.border = 'none';
closeButton.style.borderRadius = '8px';
closeButton.style.cursor = 'pointer';
closeButton.style.transition = 'background-color 0.2s ease';

// Hover effect
closeButton.addEventListener('mouseover', () => {
    closeButton.style.backgroundColor = '#cc0000';
});
closeButton.addEventListener('mouseout', () => {
    closeButton.style.backgroundColor = '#ff4d4d';
});


closeButton.addEventListener('click', () => {
	document.body.removeChild(popup);
});

popup.appendChild(closeButton);

	document.body.appendChild(popup);
}


function hoverOverSessionProfit()
{
	// Dummy array for testing (replace with your actual data)
let session_user_amount_array = [0, 5, 10, 6, 14, 8];

// Create the button
const profitChartButton = document.createElement('button');
profitChartButton.textContent = "Show Profit Chart";
profitChartButton.style.marginLeft = '10px';
sessionProfitContainer.appendChild(profitChartButton);

// Create the popup container (but DO NOT add <canvas> yet)
const chartPopup = document.createElement('div');
chartPopup.id = 'chart-popup';
chartPopup.style.position = 'absolute';
chartPopup.style.display = 'none';
chartPopup.style.backgroundColor = '#fff';
chartPopup.style.border = '1px solid #ccc';
chartPopup.style.padding = '10px';
chartPopup.style.boxShadow = '0 2px 10px rgba(0,0,0,0.2)';
chartPopup.style.zIndex = 1000;
document.body.appendChild(chartPopup);

// Toggle state
let chartVisible = false;

// Click to toggle chart
profitChartButton.addEventListener('click', () => {
    if (chartVisible) {
        chartPopup.style.display = 'none';
        chartPopup.innerHTML = ''; // Clear canvas content
        chartVisible = false;
        return;
    }

    // Position chart popup above the button
    const rect = profitChartButton.getBoundingClientRect();
    chartPopup.style.left = `${rect.left + window.scrollX}px`;
    chartPopup.style.top = `${rect.top + window.scrollY - 170}px`;
    chartPopup.style.display = 'block';
    chartVisible = true;

    // Inject fresh canvas into popup
    chartPopup.innerHTML = '<canvas id="sessionChart" width="300" height="150"></canvas>';
    const ctx = document.getElementById('sessionChart').getContext('2d');

    // Destroy previous chart if exists
    if (window.sessionChart) {
        window.sessionChart.destroy();
    }

    // Only draw chart if there is data
    if (session_user_amount_array.length > 0) {
        window.sessionChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: session_user_amount_array.map((_, i) => i + 1),
                datasets: [{
                    label: 'Session Profit',
                    data: session_user_amount_array,
                    borderColor: 'green',
                    backgroundColor: 'rgba(0, 128, 0, 0.1)',
                    borderWidth: 2,
                    fill: true,
                    tension: 0.2
                }]
            },
            options: {
                responsive: false,
                animation: false,
                plugins: {
                    legend: { display: false }
                },
                scales: {
                    x: { display: false },
                    y: { display: true }
                }
            }
        });
    } else {
        chartPopup.innerHTML = '<p>No data to show</p>';
    }
});

// Optional: clicking the chart also closes it
chartPopup.addEventListener('click', () => {
    chartPopup.style.display = 'none';
    chartPopup.innerHTML = '';
    chartVisible = false;
});

}

