(function($){
document.addEventListener('DOMContentLoaded', () => {
    const pianoKeys = document.querySelectorAll(".piano-keys .key"),
        volumeSlider = document.querySelector(".volume-slider input"),
        notesCheckbox = document.querySelector("#show-notes-toggle"),
		keysCheckbox = document.querySelector("#show-keys-toggle"),
        
		equalizerCanvas = document.getElementById("equalizer"),
        canvasCtx = equalizerCanvas.getContext("2d");
		const noteDisplay = document.getElementById("played-notes");
		const clearBtn = document.getElementById("clearBtn");
		
		const pianoRecorder = window.pianoRecorder; // Use global instance from piano.recorder.js
		const recordBtn = document.getElementById("recordBtn");
		const playBtn = document.getElementById("playBtn");		
		const playIcon = playBtn.querySelector(".play-icon");
		const playLabel = playBtn.querySelector(".play-label");
		
		const popup = document.getElementById('recordLimitPopup');
		const closeBtn = document.getElementById("closePopupBtn");
		const pianoWrapper = document.querySelector('.ptpiano-wrapper');		
		

    const audioContext = new (window.AudioContext || window.webkitAudioContext)();
    const analyser = audioContext.createAnalyser();
    analyser.fftSize = 128;
    const bufferLength = 20;
    const dataArray = new Uint8Array(64);

    let allKeys = [],
        audioSources = {},
        isDrawing = false;
	
	// Strt audiocontext for midi *************************************************


	// Global flag	

	const enablePianoBtn = document.getElementById('enable-piano-btn');
	const enableMidiDownloadBtn = document.getElementById('mididownloadBtn');

		// Add initial red style
		enablePianoBtn.classList.add('disabled');
		enablePianoBtn.textContent = 'Off'; // Ensure initial state

		function startAudioContext() {
			const currentState = enablePianoBtn.textContent;

			if (currentState === 'Off') {
				// Enable piano
				audioContext.resume().then(() => {
					console.log("AudioContext resumed");

					enablePianoBtn.classList.remove('disabled');
					enablePianoBtn.classList.add('enabled');
					enablePianoBtn.textContent = 'On'; // Toggle to On

					// Optionally connect MIDI here
					 connectMIDIInputs();
				}).catch(err => {
					console.error("Failed to resume AudioContext:", err);
				});
			} else if (currentState === 'On') {
				// Disable piano
				audioContext.suspend().then(() => {
					console.log("AudioContext suspended");

					enablePianoBtn.classList.remove('enabled');
					enablePianoBtn.classList.add('disabled');
					enablePianoBtn.textContent = 'Off'; // Toggle to Off

					// Optionally disconnect MIDI here
					 disconnectMIDIInputs();
				}).catch(err => {
					console.error("Failed to suspend AudioContext:", err);
				});
			}
		}


		// Expose for other files (like MIDI)
		window.startAudioContext = startAudioContext;

		// Hook up button click
		enablePianoBtn.addEventListener('click', () => {	
			
				startAudioContext();			
		});	



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

	// Initialize reverb
	if (window.ptpReverb) {
		ptpReverb.initReverb(audioContext);
		const irSelect = document.getElementById('ptpian_reverb_ir');
		const activeIR = (irSelect && irSelect.value) ? irSelect.value : 'hall';
		ptpReverb.loadReverb(ptpianReverbData?.irs?.[activeIR]);
	}

	// Initialize SoundFont engine and auto-load default instrument
	if (window.ptpSoundFont) {
		ptpSoundFont.init(audioContext);
		// Auto-load Acoustic Grand Piano as default
		ptpSoundFont.loadInstrument(0);
	}

    const playTune = async (key) => {
        try {
            await audioContext.resume();

			// --- SoundFont playback ---
			if (window.ptpSoundFont && window.ptpSoundFont.isActive()) {
				window.ptpSoundFont.playNote(key, volumeSlider.value, analyser);
			}

            const clickedKey = document.querySelector(`[data-key="${key}"]`);
            if (clickedKey) {
                clickedKey.classList.add("active");
                setTimeout(() => clickedKey.classList.remove("active"), 150);
				// ✅THIS IS FOR SONG SELECT PLAY
				jQuery(document).trigger('note:play', [key]);
				
				// Get the note label to display
				const noteLabel = clickedKey.querySelector(".note-label")?.textContent || clickedKey.dataset.note;

				// Create a span or div for the played note
				const noteSpan = document.createElement("span");
				noteSpan.textContent = noteLabel;
				noteSpan.classList.add("played-note"); // optional for styling

				// Append to the note display container
				noteDisplay.appendChild(noteSpan);

				// Optional: Scroll to end if overflow
				noteDisplay.scrollLeft = noteDisplay.scrollWidth;

				// Optional: Limit number of notes displayed (e.g., last 20)
				if (noteDisplay.childNodes.length > 160) {
					noteDisplay.removeChild(noteDisplay.firstChild);
				}
				
				/* Record call ******************************************/
				const note = clickedKey?.dataset.note || key;
				pianoRecorder.recordNote(key, note);

            }

            if (!isDrawing) drawEqualizer();
        } catch (err) {
            console.error("Error playing sound:", err);
        }
    };

    const drawEqualizer = () => {
        isDrawing = true;

        const renderFrame = () => {
            analyser.getByteFrequencyData(dataArray);
            canvasCtx.clearRect(0, 0, equalizerCanvas.width, equalizerCanvas.height);

            const canvasWidth = equalizerCanvas.width;
            const canvasHeight = equalizerCanvas.height;
            const barCount = bufferLength;
            const barGap = 2;
            const totalGapWidth = (barCount - 1) * barGap;
            const barWidth = (canvasWidth - totalGapWidth) / barCount;

            let x = 0;

            for (let i = 0; i < barCount; i++) {
                const barHeight = dataArray[i] / 2;
                canvasCtx.fillStyle = `rgb(${barHeight + 100}, 50, 200)`;
                canvasCtx.fillRect(x, canvasHeight - barHeight, barWidth, barHeight);
                x += barWidth + barGap;
            }

            requestAnimationFrame(renderFrame);
        };

        renderFrame();
    };
	
	// Piano key click events *************************************************
	pianoKeys.forEach(key => {
		allKeys.push(key.dataset.key);

		// Play sound on click (desktop) and touchstart (mobile)
		const handleKeyPress = (e) => {
			// Prevent double-firing on devices that send both touch + click
			if (e.type === 'touchstart') {
				e.preventDefault();
			}

			playTune(key.dataset.key);

			// Add glow instantly
			key.classList.add("glow");

			// Remove glow after 500ms
			setTimeout(() => {
				key.classList.remove("glow");
			}, 500);
		};

		key.addEventListener("click", handleKeyPress);
		key.addEventListener("touchstart", handleKeyPress, { passive: false });
	});


    // Volume slider (volume handled per audio instance in playTune)
    volumeSlider.addEventListener("input", () => {
        // No-op here since it's handled dynamically
    });

	 // Toggle note labels (Do/Re/Mi or सा/रे/गा)
		notesCheckbox.addEventListener("click", () => {
			pianoKeys.forEach(key => {
				const noteLabel = key.querySelector(".note-label");
				if (noteLabel) noteLabel.classList.toggle("hide");
			});
		});

		// Toggle keyboard key labels (A, S, D, etc.)
		keysCheckbox.addEventListener("click", () => {
			pianoKeys.forEach(key => {
				const keyLabel = key.querySelector(".key-label");
				if (keyLabel) keyLabel.classList.toggle("hide");
			});
		});

    // Keyboard keypress
    /*document.addEventListener("keydown", e => {
        if (allKeys.includes(e.key)) playTune(e.key);
    });*/
	document.addEventListener("keydown", e => {
		const pressedKey = e.key.toLowerCase();
		if (allKeys.includes(pressedKey)) {			 
			playTune(pressedKey);

			// Find the piano key element
			const keyElement = document.querySelector(`.key[data-key="${pressedKey}"]`);
			if (keyElement) {
				// Add glow instantly
				keyElement.classList.add("glow");

				// Remove glow after 2 seconds
				setTimeout(() => {
					keyElement.classList.remove("glow");
				}, 500);
			}
		}
	});
			
	/*********Record Keyevent ************************************************/
	
	recordBtn.addEventListener("click", () => {
	  if (!pianoRecorder.isRecording) {		
		noteDisplay.innerHTML = "";
		pianoRecorder.startRecording();
		// Change button text & add class to make icon red
		recordBtn.classList.add('active'); // ✅ Add glow		 
		playBtn.disabled = true;
		clearBtn.disabled = true;
		
		const currentTempo = parseInt(document.getElementById('tempo-display').textContent);
		pianoRecorder.setTempo(currentTempo);
		
		// 🔴 Auto-stop after 30 seconds (30,000 ms)		
		
		const maxDuration = (typeof ptPianSettings !== 'undefined' && ptPianSettings.recordDuration)
		? parseInt(ptPianSettings.recordDuration, 10) * 1000
		: 30000; // fallback to 30s

		setTimeout(() => {
			if (pianoRecorder.isRecording) {
				pianoRecorder.stopRecording();
				recordBtn.classList.remove('active');
				playBtn.disabled = false;
				clearBtn.disabled = false;
				popup.style.display = 'flex';
			}
		}, maxDuration);
				
				if (closeBtn) {
					closeBtn.addEventListener("click", () => {
					  popup.style.display = "none";
					  
					  
					  // Make sure there's something to play
					if (pianoRecorder.recordedNotes.length > 0) {
						isPlaying = true;
						playBtn.classList.add('active');
						if (pianoWrapper) pianoWrapper.classList.add('playing');
						recordBtn.disabled = true;
						clearBtn.disabled = true;
						noteDisplay.innerHTML = "";

						// Start playback
						pianoRecorder.playRecording(playTune, () => {
							// Playback finished
							isPlaying = false;
							playBtn.classList.remove('active');
							if (pianoWrapper) pianoWrapper.classList.remove('playing');
							recordBtn.disabled = false;
							clearBtn.disabled = false;
						});
					}					  
					  
					});
				  }
		
	  } else {
		pianoRecorder.stopRecording();
		// Change back button text & remove red color
		recordBtn.classList.remove('active'); // ✅ Remove glow when done		
		playBtn.disabled = false;
		clearBtn.disabled = false;
	  }
	});
	
	let isPlaying = false; // Track playback state
	noteDisplay.innerHTML = "";
	playBtn.addEventListener("click", () => {	
		if (!isPlaying) {
			if (pianoRecorder.recordedNotes.length > 0) {
				const currentTempo = parseInt(document.getElementById('tempo-display').textContent);
				pianoRecorder.setTempo(currentTempo);
				// Start playing
				isPlaying = true;				
				playBtn.classList.add('active'); // ✅ Add glow
				if (pianoWrapper) pianoWrapper.classList.add('playing');
				recordBtn.disabled = true;
				clearBtn.disabled = true;
			
				noteDisplay.innerHTML = "";
				pianoRecorder.playRecording(playTune, () => {
					// Playback complete
					isPlaying = false;	
					playBtn.classList.remove('active'); // ✅ Remove glow when done
					if (pianoWrapper) pianoWrapper.classList.remove('playing');
					recordBtn.disabled = false;
					clearBtn.disabled = false;
				});
			} else {
				noteDisplay.innerHTML = "Record to play";
				playBtn.classList.remove('active'); // ✅ Remove glow when done
				playBtn.disabled = true;
			}
		} else {
			if (isPlaying) {
				// Stop playback early
				isPlaying = false;
				playBtn.classList.remove('active'); // ✅ Remove glow when done
				if (pianoWrapper) pianoWrapper.classList.remove('playing');

				recordBtn.disabled = false;
				clearBtn.disabled = false;
				
				pianoRecorder.stopPlayback();
			}
		}
	});
	
	// Listen for confirmed clear (from popup confirmation)
	jQuery(document).on("recording:clear", () => {
		if (!isPlaying || !pianoRecorder.isRecording){
		 noteDisplay.innerHTML = "";			
		  for (const key in audioSources) {
			try {
			  audioSources[key].disconnect();
			  delete audioSources[key];
			} catch (e) {
			  console.warn(`Error disconnecting source for key ${key}:`, e);
			}
		  }	
		}		  
	});
	
	document.getElementById("mididownloadBtn").addEventListener("click", () => {
		pianoRecorder.downloadMidi(); // ← assuming your class instance is `pianoRecorder`
	});

	
	
	//MIDI Enable function call ******************************************
	 window.playTune = playTune; // ✅ Make available globally

});
})(jQuery);
