// piano.songs.js

let selectedSong = null;
let learningNotes = [];
let currentStep = 0;
let isLearningMode = false;

(function ($) {

document.addEventListener("DOMContentLoaded", function () {

    const dropdown = document.getElementById("ptpian-song-select");
    const loadBtn = document.getElementById("ptpian-load-song");
    const autoPlayBtn = document.getElementById("ptpian-autoplay-song");

    if (!dropdown || typeof ptpianSongs === "undefined") return;

    // 🎵 Load songs into dropdown
    ptpianSongs.forEach((song, index) => {
        let option = document.createElement("option");
        option.value = index;
        option.textContent = song.name;
        dropdown.appendChild(option);
    });

    // 🎵 On song select
    dropdown.addEventListener("change", function () {
        let index = this.value;

        if (index === "") {
            selectedSong = null;
            return;
        }

        selectedSong = ptpianSongs[index];

        document.getElementById("ptpian-song-name").innerText = selectedSong.name;
        document.getElementById("ptpian-scale-display").innerText = selectedSong.scale;

        loadBtn.disabled = false;
        autoPlayBtn.disabled = false;
    });

    // 🎓 LEARNING MODE
    loadBtn.addEventListener("click", function () {

        if (!selectedSong) return;

        learningNotes = selectedSong.notes.split(",");
        currentStep = 0;
        isLearningMode = true;

        alert("🎹 Learning Mode Started! Follow highlighted keys");

        highlightNextNote();

        // Close popup
        if (window.PTPiano?.SongPopup) {
            window.PTPiano.SongPopup.close();
        }
    });

    // ▶ AUTO PLAY MODE
    autoPlayBtn.addEventListener("click", function () {

        if (!selectedSong) return;

        const notes = selectedSong.notes.split(",");
        let index = 0;
        const tempo = 600;

        function playNext() {

            if (index >= notes.length) return;

            let note = notes[index].trim();

            // Remove octave (C4 → C)
            let baseNote = note.replace(/[0-9]/g, '');

            const keyEl = document.querySelector(`.key[data-note="${baseNote}"]`);

            if (keyEl) {
                const keyChar = keyEl.dataset.key;

                // 🎹 Play sound
                if (window.playTune) {
                    playTune(keyChar);
                }

                // 🌟 Glow
                keyEl.classList.add("glow");
                setTimeout(() => keyEl.classList.remove("glow"), 400);
            }

            index++;
            setTimeout(playNext, tempo);
        }

        playNext();

        // Close popup
        if (window.PTPiano?.SongPopup) {
            window.PTPiano.SongPopup.close();
        }
    });

});


// 🎯 Highlight next note (Learning Mode)
function highlightNextNote() {

    let note = learningNotes[currentStep].trim();
    highlightGuideKey(note);
}


// 🌟 Highlight guide key
function highlightGuideKey(note) {

    let baseNote = note.replace(/[0-9]/g, '');

    // remove old highlight
    document.querySelectorAll('.key').forEach(k => {
        k.classList.remove('guide');
    });

    // pick FIRST matching key
    const keys = document.querySelectorAll(`.key[data-note="${baseNote}"]`);
    const key = keys[0];

    if (key) {
        key.classList.add('guide');
    }
}


// 🎹 Detect correct key press (FIXED with jQuery)
$(document).on("note:play", function (e, playedKey) {

    if (!isLearningMode) return;

    const keyEl = document.querySelector(`.key[data-key="${playedKey}"]`);
    if (!keyEl) return;

    let playedNote = keyEl.dataset.note.trim().toUpperCase();
    let expectedNote = learningNotes[currentStep]
        .replace(/[0-9]/g, '')
        .trim()
        .toUpperCase();

    if (playedNote === expectedNote) {

        currentStep++;

        // 🎉 CHECK COMPLETION HERE (IMPORTANT)
        if (currentStep >= learningNotes.length) {
            setTimeout(() => {
                alert("🎉 Song Completed!");
                isLearningMode = false;

                // remove highlight
                document.querySelectorAll('.key').forEach(k => {
                    k.classList.remove('guide');
                });

            }, 200); // small delay for UX

            return;
        }

        highlightNextNote();
    }
});


// 🎹 Optional helper (safe play function)
function playSongNote(note) {

    let baseNote = note.replace(/[0-9]/g, '');

    const keyEl = document.querySelector(`.key[data-note="${baseNote}"]`);

    if (keyEl) {
        const keyChar = keyEl.dataset.key;

        if (window.playTune) {
            playTune(keyChar);
        }

        keyEl.classList.add("glow");

        setTimeout(() => {
            keyEl.classList.remove("glow");
        }, 400);
    }
}

})(jQuery);