document.addEventListener('DOMContentLoaded', function () {
  const volumeSlider = document.getElementById('volumeControl');
  const volumeRValue = document.getElementById('volumeRValue');
  
  const tempoDisplay = document.getElementById('tempo-display');
  const tempoIncreaseBtn = document.getElementById('tempo-increase');
  const tempoDecreaseBtn = document.getElementById('tempo-decrease');

  function updateVolumeDisplay(value) {
    volumeRValue.textContent = Math.round(parseFloat(value) * 100);
  }

  // On input
  volumeSlider.addEventListener('input', (e) => {
    updateVolumeDisplay(e.target.value);
  });

  // On double click - reset to 50%
  volumeSlider.addEventListener('dblclick', (e) => {
    volumeSlider.value = 0.5;
    updateVolumeDisplay(0.5);
  });

  // Init display
  updateVolumeDisplay(volumeSlider.value);
  

	
	
	/* =========================
	   TEMPO CONTROL
	   Ranges: Slow 60-90 | Medium 90-120 | Dance 120-140 | Fast 140-180
	   Steps in 10 BPM increments
	========================== */
	const MIN_TEMPO = 60;
	const MAX_TEMPO = 180;
	const defaultTempo = 120;
    tempoDisplay.textContent = defaultTempo;
	let tempoInterval;
	let tempoHoldStart = 0;
	
	
	// Helper to update the display and recorder
	function updateTempo(newTempo) {
		tempoDisplay.textContent = newTempo;
		pianoRecorder.setTempo(newTempo);
	}

	// Step size: 10 BPM per click, accelerates on long hold
	function getTempoStep() {
		var holdDuration = Date.now() - tempoHoldStart;
		if (holdDuration > 1500) return 30;  // fast jump after 1.5s
		if (holdDuration > 700) return 20;   // medium jump after 0.7s
		return 10;                            // normal 10 BPM step
	}

	// Start increasing or decreasing on hold
	function startChangingTempo(changeFn) {
		tempoHoldStart = Date.now();
		changeFn();
		tempoInterval = setInterval(changeFn, 200);
	}

	// Stop changing tempo
	function stopChangingTempo() {
		clearInterval(tempoInterval);
	}

	// Increase logic (snap to nearest 10)
	function increaseTempo() {
		let currentTempo = parseInt(tempoDisplay.textContent);
		var step = getTempoStep();
		currentTempo = Math.min(currentTempo + step, MAX_TEMPO);
		// Snap to nearest 10
		currentTempo = Math.round(currentTempo / 10) * 10;
		updateTempo(currentTempo);
	}

	// Decrease logic (snap to nearest 10)
	function decreaseTempo() {
		let currentTempo = parseInt(tempoDisplay.textContent);
		var step = getTempoStep();
		currentTempo = Math.max(currentTempo - step, MIN_TEMPO);
		// Snap to nearest 10
		currentTempo = Math.round(currentTempo / 10) * 10;
		updateTempo(currentTempo);
	}

	// Mouse events
	tempoIncreaseBtn.addEventListener('mousedown', () => startChangingTempo(increaseTempo));
	tempoIncreaseBtn.addEventListener('mouseup', stopChangingTempo);
	tempoIncreaseBtn.addEventListener('mouseleave', stopChangingTempo);

	tempoDecreaseBtn.addEventListener('mousedown', () => startChangingTempo(decreaseTempo));
	tempoDecreaseBtn.addEventListener('mouseup', stopChangingTempo);
	tempoDecreaseBtn.addEventListener('mouseleave', stopChangingTempo);

	// Touch support for mobile
	tempoIncreaseBtn.addEventListener('touchstart', (e) => { e.preventDefault(); startChangingTempo(increaseTempo); }, { passive: false });
	tempoIncreaseBtn.addEventListener('touchend', stopChangingTempo);
	tempoIncreaseBtn.addEventListener('touchcancel', stopChangingTempo);

	tempoDecreaseBtn.addEventListener('touchstart', (e) => { e.preventDefault(); startChangingTempo(decreaseTempo); }, { passive: false });
	tempoDecreaseBtn.addEventListener('touchend', stopChangingTempo);
	tempoDecreaseBtn.addEventListener('touchcancel', stopChangingTempo);
	
	//  Play all highlighted keys 
	
	// After your existing selectMajorElement.addEventListener(...)
		const paddleplayButton = document.getElementById('paddleBtn');

		if (paddleplayButton) {
			paddleplayButton.addEventListener('click', async () => {
				// Find all keys that have been highlighted (.mark)
				const markedKeys = document.querySelectorAll('.piano-keys .key.mark');
				
				console.log(`Selected keys: ${markedKeys.length}`);

				if (markedKeys.length === 0) return;

				// Limit to play at most 6 keys to avoid audio overload
				const keysToPlay = Array.from(markedKeys).slice(0, 6);

				// Optionally play all together or sequentially
				const playTogether = true; // set false if you want them arpeggiated

				if (playTogether) {
					// Play marked keys at once (up to 6)
					keysToPlay.forEach(key => {
						const note = key.dataset.key || key.dataset.note;
						if (note && window.playTune) window.playTune(note);
					});
				} else {
					// Play them one after another (arpeggiated)
					for (let i = 0; i < keysToPlay.length; i++) {
						const key = keysToPlay[i];
						const note = key.dataset.key || key.dataset.note;
						if (note && window.playTune) {
							window.playTune(note);
							await new Promise(res => setTimeout(res, 200)); // 200ms delay
						}
					}
				}
			});
		}
});