/**
 * PT Piano - Unified Chords & Scales Engine
 * Consolidates major/minor scales and major/minor/diminished/augmented chord highlighting.
 */
document.addEventListener('DOMContentLoaded', () => {
    // DOM Elements
    const selectMajorScale = document.getElementById('majorscale');
    const selectMinorScale = document.getElementById('minorscale');
    const selectMajorChord = document.getElementById('majorchord');
    const selectMinorChord = document.getElementById('minorchord');
    const selectDimChord = document.getElementById('diminishedchord');
    const selectAugChord = document.getElementById('augmentedchord');
    const showChordInput = document.getElementById('showchord');
    const progressionEl = document.getElementById('common-progression');
    const pianoKeys = document.querySelectorAll('.piano-keys .key');

    if (!showChordInput || !pianoKeys.length) return;

    // Chromatic Notes & Mappings
    const chromaticNotes = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'];
    const solfegeMap = {
        'C': 'Do', 'C#': 'Do#', 'D': 'Re', 'D#': 'Re#', 'E': 'Mi',
        'F': 'Fa', 'F#': 'Fa#', 'G': 'So', 'G#': 'So#', 'A': 'La',
        'A#': 'La#', 'B': 'Ti'
    };
    const indianMap = {
        'C': 'सा', 'C#': 'रे♭', 'D': 'रे', 'D#': 'गा♭', 'E': 'गा',
        'F': 'मा', 'F#': 'मा#', 'G': 'प', 'G#': 'धा♭', 'A': 'धा',
        'A#': 'नि♭', 'B': 'नि'
    };

    // Chord Formulas / Collections
    const majorChords = {
        'C':  ['C', 'E', 'G'], 'C#': ['C#', 'F', 'G#'], 'D':  ['D', 'F#', 'A'],
        'D#': ['D#', 'G', 'A#'], 'E':  ['E', 'G#', 'B'], 'F':  ['F', 'A', 'C'],
        'F#': ['F#', 'A#', 'C#'], 'G':  ['G', 'B', 'D'], 'G#': ['G#', 'C', 'D#'],
        'A':  ['A', 'C#', 'E'], 'A#': ['A#', 'D', 'F'], 'B':  ['B', 'D#', 'F#']
    };

    const minorChords = {
        'C':  ['C', 'D#', 'G'], 'C#': ['C#', 'E', 'G#'], 'D':  ['D', 'F', 'A'],
        'D#': ['D#', 'F#', 'A#'], 'E':  ['E', 'G', 'B'], 'F':  ['F', 'G#', 'C'],
        'F#': ['F#', 'A', 'C#'], 'G':  ['G', 'A#', 'D'], 'G#': ['G#', 'B', 'D#'],
        'A':  ['A', 'C', 'E'], 'A#': ['A#', 'C#', 'F'], 'B':  ['B', 'D', 'F#']
    };

    const commonMajorProgressions = {
        'C':  ['C', 'G', 'Am', 'F'], 'C#': ['C#', 'G#', 'A#m', 'F#'], 'D':  ['D', 'A', 'Bm', 'G'],
        'D#': ['D#', 'A#', 'Cm', 'G#'], 'E':  ['E', 'B', 'C#m', 'A'], 'F':  ['F', 'C', 'Dm', 'Bb'],
        'F#': ['F#', 'C#', 'D#m', 'B'], 'G':  ['G', 'D', 'Em', 'C'], 'G#': ['G#', 'D#', 'Fm', 'C#'],
        'A':  ['A', 'E', 'F#m', 'D'], 'A#': ['A#', 'F', 'Gm', 'D#'], 'B':  ['B', 'F#', 'G#m', 'E']
    };

    const commonMinorProgressions = {
        'A':  ['Am', 'F', 'C', 'G'], 'A#': ['A#m', 'G#', 'D#', 'A#'], 'B':  ['Bm', 'G', 'D', 'A'],
        'C':  ['Cm', 'Ab', 'Eb', 'Bb'], 'C#': ['C#m', 'A', 'E', 'B'], 'D':  ['Dm', 'Bb', 'F', 'C'],
        'D#': ['D#m', 'B', 'F#', 'C#'], 'E':  ['Em', 'C', 'G', 'D'], 'F':  ['Fm', 'Db', 'Ab', 'Eb'],
        'F#': ['F#m', 'D', 'A', 'E'], 'G':  ['Gm', 'Eb', 'Bb', 'F'], 'G#': ['G#m', 'E', 'B', 'F#']
    };

    // Helper functions
    function matchNote(keyElement, noteLetter) {
        const keyNote = keyElement.dataset.note;
        if (keyNote === noteLetter) return true;

        const noteLabelSpan = keyElement.querySelector('.note-label');
        if (!noteLabelSpan) return false;

        const label = noteLabelSpan.textContent;
        return (label === solfegeMap[noteLetter] || label === indianMap[noteLetter]);
    }

    function getScaleNotes(rootNote, intervals) {
        const scale = [];
        let startIndex = chromaticNotes.indexOf(rootNote);
        if (startIndex === -1) return scale;

        scale.push(chromaticNotes[startIndex]);
        let currentIndex = startIndex;
        for (let i = 0; i < intervals.length; i++) {
            currentIndex = (currentIndex + intervals[i]) % chromaticNotes.length;
            scale.push(chromaticNotes[currentIndex]);
        }
        return scale;
    }

    function getDiminishedChord(rootNote) {
        const rootIndex = chromaticNotes.indexOf(rootNote);
        if (rootIndex === -1) return [];
        return [
            rootNote,
            chromaticNotes[(rootIndex + 3) % 12],
            chromaticNotes[(rootIndex + 6) % 12]
        ];
    }

    function getAugmentedChord(rootNote) {
        const rootIndex = chromaticNotes.indexOf(rootNote);
        if (rootIndex === -1) return [];
        return [
            rootNote,
            chromaticNotes[(rootIndex + 4) % 12],
            chromaticNotes[(rootIndex + 8) % 12]
        ];
    }

    // Reset dropdown values and classes
    function resetSelections(exceptElement) {
        const selects = [selectMajorScale, selectMinorScale, selectMajorChord, selectMinorChord, selectDimChord, selectAugChord];
        selects.forEach(sel => {
            if (sel && sel !== exceptElement) {
                sel.selectedIndex = 0;
            }
        });
        pianoKeys.forEach(k => k.classList.remove('mark'));
        if (progressionEl) progressionEl.textContent = '';
    }

    // Apply markings to matching keys
    function highlightKeys(notes) {
        pianoKeys.forEach(keyElement => {
            if (notes.some(note => matchNote(keyElement, note))) {
                keyElement.classList.add('mark');
            }
        });
    }

    // Focus first key helper
    function focusFirstKey() {
        const firstKey = document.querySelector('.piano-keys .key');
        if (firstKey) {
            firstKey.focus();
            firstKey.scrollIntoView({ behavior: 'smooth', block: 'center' });
        }
    }

    // Event Listeners
    if (selectMajorChord) {
        selectMajorChord.addEventListener('change', (e) => {
            const val = e.target.value;
            resetSelections(selectMajorChord);
            if (val && majorChords[val]) {
                highlightKeys(majorChords[val]);
                showChordInput.value = `${val} MAJOR`;
            } else {
                showChordInput.value = '';
            }
        });
    }

    if (selectMinorChord) {
        selectMinorChord.addEventListener('change', (e) => {
            const val = e.target.value;
            resetSelections(selectMinorChord);
            if (val && minorChords[val]) {
                highlightKeys(minorChords[val]);
                showChordInput.value = `${val} MINOR`;
            } else {
                showChordInput.value = '';
            }
        });
    }

    if (selectDimChord) {
        selectDimChord.addEventListener('change', (e) => {
            const val = e.target.value.toUpperCase();
            resetSelections(selectDimChord);
            const notes = getDiminishedChord(val);
            if (notes.length) {
                highlightKeys(notes);
                showChordInput.value = `${val} DIM`;
            } else {
                showChordInput.value = '';
            }
        });
    }

    if (selectAugChord) {
        selectAugChord.addEventListener('change', (e) => {
            const val = e.target.value.toUpperCase();
            resetSelections(selectAugChord);
            const notes = getAugmentedChord(val);
            if (notes.length) {
                highlightKeys(notes);
                showChordInput.value = `${val} AGU`;
            } else {
                showChordInput.value = '';
            }
        });
    }

    if (selectMajorScale) {
        selectMajorScale.addEventListener('change', (e) => {
            const val = e.target.value;
            resetSelections(selectMajorScale);
            const notes = getScaleNotes(val, [2, 2, 1, 2, 2, 2, 1]); // W-W-H-W-W-W-H
            if (notes.length) {
                highlightKeys(notes);
                showChordInput.value = `${val} MAJOR SCALE`;
                focusFirstKey();
                if (commonMajorProgressions[val] && progressionEl) {
                    progressionEl.textContent = `Common Progression: ${commonMajorProgressions[val].join(' → ')}`;
                }
            } else {
                showChordInput.value = '';
            }
        });
    }

    if (selectMinorScale) {
        selectMinorScale.addEventListener('change', (e) => {
            const val = e.target.value;
            resetSelections(selectMinorScale);
            const notes = getScaleNotes(val, [2, 1, 2, 2, 1, 2, 2]); // W-H-W-W-H-W-W
            if (notes.length) {
                highlightKeys(notes);
                showChordInput.value = `${val} MINOR SCALE`; // Fixed bug: was MAJOR SCALE
                focusFirstKey();
                if (commonMinorProgressions[val] && progressionEl) {
                    progressionEl.textContent = `Common Progression: ${commonMinorProgressions[val].join(' → ')}`;
                }
            } else {
                showChordInput.value = '';
            }
        });
    }
});
