const midiToVirtualKey={60:'a',61:'w',62:'s',63:'e',64:'d',65:'f',66:'t',67:'g',68:'y',69:'h',70:'u',71:'j',72:'k',73:'o',74:'l',75:'p',76:'z',77:'x',78:'4',79:'c',80:'5',81:'v',82:'6',83:'b'};let midiAccess=null;function handleMIDIMessage(event){const[command,note,velocity]=event.data;const isNoteOn=(command&0xf0)===0x90&&velocity>0;const virtualKey=midiToVirtualKey[note];if(isNoteOn&&virtualKey){playTune(virtualKey)}}
function onMIDISuccess(midi){midiAccess=midi;connectMIDIInputs()}
function connectMIDIInputs(){if(!midiAccess)return;let connectedInputs=[];for(let input of midiAccess.inputs.values()){input.onmidimessage=handleMIDIMessage;connectedInputs.push(input.name);console.log("Connected MIDI input:",input.name)}
const statusEl=document.getElementById("midi-status");if(statusEl){if(connectedInputs.length>0){statusEl.innerHTML=`🎹 <span style="color: green;font-size:11px">${connectedInputs.join(', ')}</span>`}else{statusEl.innerHTML=`🎹 <span style="color: orange;">No device</span>`}}}
function disconnectMIDIInputs(){if(!midiAccess)return;for(let input of midiAccess.inputs.values()){input.onmidimessage=null;console.log("Disconnected MIDI input:",input.name)}
const statusEl=document.getElementById("midi-status");if(statusEl){statusEl.innerHTML=`🎹 <span style="color: red;">Disconnected</span>`}}
function onMIDIFailure(){console.error("MIDI connection failed. Try a supported browser like Chrome.");const statusEl=document.getElementById("midi-status");if(statusEl){statusEl.innerHTML=`🎹 <span style="color: red;">No Connection</span>`}}
if(navigator.requestMIDIAccess){navigator.requestMIDIAccess().then(onMIDISuccess,onMIDIFailure)}else{alert("Web MIDI API not supported in this browser.")}