// MIDI Note → Key ID mapping (adjust based on your layout)
// MIDI Note Number → Corresponding Virtual Key (from your PHP layout)
const midiToVirtualKey = {
    60: 'a',  // C4
    61: 'w',  // C#4
    62: 's',  // D4
    63: 'e',  // D#4
    64: 'd',  // E4
    65: 'f',  // F4
    66: 't',  // F#4
    67: 'g',  // G4
    68: 'y',  // G#4
    69: 'h',  // A4
    70: 'u',  // A#4
    71: 'j',  // B4
    72: 'k',  // C5
    73: 'o',  // C#5
    74: 'l',  // D5
    75: 'p',  // D#5
    76: 'z',  // E5
    77: 'x',  // F5
    78: '4',  // F#5
    79: 'c',  // G5
    80: '5',  // G#5
    81: 'v',  // A5
    82: '6',  // A#5
    83: 'b',  // B5
    84: 'n',  // C6
    85: '9',  // C#6
    86: 'm',  // D6
    87: '0',  // D#6
    88: ',',  // E6
    89: '.',  // F6
    90: '-',  // F#6
    91: '/',  // G6
    92: '=',  // G#6
    93: ';',  // A6
    94: '[',  // A#6
    95: '\'', // B6
    96: ']',  // C7
    97: '1',  // C#7
    98: '2',  // D7
    99: '3',  // D#7
    100: '8'  // E7
};

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) {
       // startAudioContext();
        playTune(virtualKey);
    }
}


function onMIDISuccess(midi) {
    midiAccess = midi;
    connectMIDIInputs(); // ✅ Initial connection
}


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>`;
    }
}


// Only request MIDI access if the piano is present on this page
if (document.querySelector('.ptpiano-wrapper')) {
    if (navigator.requestMIDIAccess) {
        navigator.requestMIDIAccess().then(onMIDISuccess, onMIDIFailure);
    } else {
        console.warn("Web MIDI API not supported in this browser.");
    }
}