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=new PianoRecorder();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 audioContext=new(window.AudioContext||window.webkitAudioContext)();const analyser=audioContext.createAnalyser();analyser.fftSize=128;const bufferLength=20;const dataArray=new Uint8Array(64);let allKeys=[],audioCache={},audioSources={},isDrawing=!1;const pluginBaseUrl=ptpianData.pluginsUrl+'/ptpiano/tunes/';const enablePianoBtn=document.getElementById('enable-piano-btn');const enableMidiDownloadBtn=document.getElementById('mididownloadBtn');enablePianoBtn.classList.add('disabled');enablePianoBtn.textContent='Off';function startAudioContext(){const currentState=enablePianoBtn.textContent;if(currentState==='Off'){audioContext.resume().then(()=>{console.log("AudioContext resumed");enablePianoBtn.classList.remove('disabled');enablePianoBtn.classList.add('enabled');enablePianoBtn.textContent='On';connectMIDIInputs()}).catch(err=>{console.error("Failed to resume AudioContext:",err)})}else if(currentState==='On'){audioContext.suspend().then(()=>{console.log("AudioContext suspended");enablePianoBtn.classList.remove('enabled');enablePianoBtn.classList.add('disabled');enablePianoBtn.textContent='Off';disconnectMIDIInputs()}).catch(err=>{console.error("Failed to suspend AudioContext:",err)})}}
window.startAudioContext=startAudioContext;enablePianoBtn.addEventListener('click',()=>{startAudioContext()});if(window.ptpReverb){ptpReverb.initReverb(audioContext);ptpReverb.loadReverb(ptpianReverbData?.irs?.hall)}
pianoKeys.forEach(key=>{const keyData=key.dataset.key;const audio=new Audio(pluginBaseUrl+`${keyData}.wav`);audio.preload='auto';audioCache[keyData]=audio});const playTune=async(key)=>{try{await audioContext.resume();const audio=audioCache[key].cloneNode();const source=audioContext.createMediaElementSource(audio);if(window.ptpReverb){ptpReverb.applyReverb(source,analyser)}else{source.connect(analyser)}
analyser.connect(audioContext.destination);audio.volume=volumeSlider.value;audio.play();audioSources[key]=source;audio.onended=()=>{source.disconnect();delete audioSources[key]};const clickedKey=document.querySelector(`[data-key="${key}"]`);if(clickedKey){clickedKey.classList.add("active");setTimeout(()=>clickedKey.classList.remove("active"),150);const noteLabel=clickedKey.querySelector(".note-label")?.textContent||clickedKey.dataset.note;const noteSpan=document.createElement("span");noteSpan.textContent=noteLabel;noteSpan.classList.add("played-note");noteDisplay.appendChild(noteSpan);noteDisplay.scrollLeft=noteDisplay.scrollWidth;if(noteDisplay.childNodes.length>160){noteDisplay.removeChild(noteDisplay.firstChild)}
const note=clickedKey?.dataset.note||key;pianoRecorder.recordNote(key,note)}
if(!isDrawing)drawEqualizer();}catch(err){console.error("Error playing sound:",err)}};const drawEqualizer=()=>{isDrawing=!0;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()};pianoKeys.forEach(key=>{allKeys.push(key.dataset.key);key.addEventListener("click",()=>{playTune(key.dataset.key);key.classList.add("glow");setTimeout(()=>{key.classList.remove("glow")},500)})});volumeSlider.addEventListener("input",()=>{});notesCheckbox.addEventListener("click",()=>{pianoKeys.forEach(key=>{const noteLabel=key.querySelector(".note-label");if(noteLabel)noteLabel.classList.toggle("hide");})});keysCheckbox.addEventListener("click",()=>{pianoKeys.forEach(key=>{const keyLabel=key.querySelector(".key-label");if(keyLabel)keyLabel.classList.toggle("hide");})});document.addEventListener("keydown",e=>{const pressedKey=e.key.toLowerCase();if(allKeys.includes(pressedKey)){playTune(pressedKey);const keyElement=document.querySelector(`.key[data-key="${pressedKey}"]`);if(keyElement){keyElement.classList.add("glow");setTimeout(()=>{keyElement.classList.remove("glow")},500)}}});recordBtn.addEventListener("click",()=>{if(!pianoRecorder.isRecording){noteDisplay.innerHTML="";pianoRecorder.startRecording();recordBtn.classList.add('active');playBtn.disabled=!0;clearBtn.disabled=!0;const currentTempo=parseInt(document.getElementById('tempo-display').textContent);pianoRecorder.setTempo(currentTempo);const maxDuration=(typeof ptPianSettings!=='undefined'&&ptPianSettings.recordDuration)?parseInt(ptPianSettings.recordDuration,10)*1000:30000;setTimeout(()=>{if(pianoRecorder.isRecording){pianoRecorder.stopRecording();recordBtn.classList.remove('active');playBtn.disabled=!1;clearBtn.disabled=!1;popup.style.display='flex'}},maxDuration);if(closeBtn){closeBtn.addEventListener("click",()=>{popup.style.display="none";if(pianoRecorder.recordedNotes.length>0){isPlaying=!0;playBtn.classList.add('active');recordBtn.disabled=!0;clearBtn.disabled=!0;noteDisplay.innerHTML="";pianoRecorder.playRecording(playTune,()=>{isPlaying=!1;playBtn.classList.remove('active');recordBtn.disabled=!1;clearBtn.disabled=!1})}})}}else{pianoRecorder.stopRecording();recordBtn.classList.remove('active');playBtn.disabled=!1;clearBtn.disabled=!1}});let isPlaying=!1;noteDisplay.innerHTML="";playBtn.addEventListener("click",()=>{if(!isPlaying){if(pianoRecorder.recordedNotes.length>0){const currentTempo=parseInt(document.getElementById('tempo-display').textContent);pianoRecorder.setTempo(currentTempo);isPlaying=!0;playBtn.classList.add('active');recordBtn.disabled=!0;clearBtn.disabled=!0;noteDisplay.innerHTML="";pianoRecorder.playRecording(playTune,()=>{isPlaying=!1;playBtn.classList.remove('active');recordBtn.disabled=!1;clearBtn.disabled=!1})}else{noteDisplay.innerHTML="Record to play";playBtn.classList.remove('active');playBtn.disabled=!0}}else{if(isPlaying){isPlaying=!1;playBtn.classList.remove('active');recordBtn.disabled=!1;clearBtn.disabled=!1;pianoRecorder.stopPlayback()}}});clearBtn.addEventListener("click",()=>{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()});window.playTune=playTune})