(function () {
    "use strict";

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

        const ptpianTrack = document.getElementById("ptpianScaleTrack");
        const ptpianChannel = document.querySelector(".ptpian-scale-wrapper");
        const raagSelect = document.getElementById("ptpianRaagSelect");

        if (!ptpianTrack || !ptpianChannel) return;

        /* =========================
           INDIAN RAAG LIBRARY
           Each raag defines:
           - swaras: array of { semitones, num (chromatic pos 1-12), label }
           - info: short description shown below the dropdown
           
           Chromatic positions:
           1=Sa, 2=re♭, 3=Re, 4=ga♭, 5=Ga, 6=Ma, 7=Ma♯, 8=Pa, 9=dha♭, 10=Dha, 11=ni♭, 12=Ni
        ========================== */
        var raagLibrary = {

            // ── 10 Thaats (Parent Scales) ──

            bilawal: {
                name: 'Bilawal',
                info: 'Sa Re Ga Ma Pa Dha Ni (Natural Major)',
                swaras: [
                    { semitones: 0,  num: '1',  label: 'Sa'  },
                    { semitones: 2,  num: '3',  label: 'Re'  },
                    { semitones: 4,  num: '5',  label: 'Ga'  },
                    { semitones: 5,  num: '6',  label: 'Ma'  },
                    { semitones: 7,  num: '8',  label: 'Pa'  },
                    { semitones: 9,  num: '10', label: 'Dha' },
                    { semitones: 11, num: '12', label: 'Ni'  }
                ]
            },

            kalyan: {
                name: 'Kalyan / Yaman',
                info: 'Sa Re Ga Ma♯ Pa Dha Ni (Tivra Ma)',
                swaras: [
                    { semitones: 0,  num: '1',  label: 'Sa'  },
                    { semitones: 2,  num: '3',  label: 'Re'  },
                    { semitones: 4,  num: '5',  label: 'Ga'  },
                    { semitones: 6,  num: '7',  label: 'Ma♯' },
                    { semitones: 7,  num: '8',  label: 'Pa'  },
                    { semitones: 9,  num: '10', label: 'Dha' },
                    { semitones: 11, num: '12', label: 'Ni'  }
                ]
            },

            khamaj: {
                name: 'Khamaj',
                info: 'Sa Re Ga Ma Pa Dha ni♭ (Komal Ni)',
                swaras: [
                    { semitones: 0,  num: '1',  label: 'Sa'  },
                    { semitones: 2,  num: '3',  label: 'Re'  },
                    { semitones: 4,  num: '5',  label: 'Ga'  },
                    { semitones: 5,  num: '6',  label: 'Ma'  },
                    { semitones: 7,  num: '8',  label: 'Pa'  },
                    { semitones: 9,  num: '10', label: 'Dha' },
                    { semitones: 10, num: '11', label: 'ni♭' }
                ]
            },

            kafi: {
                name: 'Kafi',
                info: 'Sa Re ga♭ Ma Pa Dha ni♭ (Komal Ga & Ni)',
                swaras: [
                    { semitones: 0,  num: '1',  label: 'Sa'  },
                    { semitones: 2,  num: '3',  label: 'Re'  },
                    { semitones: 3,  num: '4',  label: 'ga♭' },
                    { semitones: 5,  num: '6',  label: 'Ma'  },
                    { semitones: 7,  num: '8',  label: 'Pa'  },
                    { semitones: 9,  num: '10', label: 'Dha' },
                    { semitones: 10, num: '11', label: 'ni♭' }
                ]
            },

            asavari: {
                name: 'Asavari',
                info: 'Sa Re ga♭ Ma Pa dha♭ ni♭ (Komal Ga, Dha, Ni)',
                swaras: [
                    { semitones: 0,  num: '1',  label: 'Sa'  },
                    { semitones: 2,  num: '3',  label: 'Re'  },
                    { semitones: 3,  num: '4',  label: 'ga♭' },
                    { semitones: 5,  num: '6',  label: 'Ma'  },
                    { semitones: 7,  num: '8',  label: 'Pa'  },
                    { semitones: 8,  num: '9',  label: 'dha♭'},
                    { semitones: 10, num: '11', label: 'ni♭' }
                ]
            },

            bhairavi: {
                name: 'Bhairavi',
                info: 'Sa re♭ ga♭ Ma Pa dha♭ ni♭ (All Komal)',
                swaras: [
                    { semitones: 0,  num: '1',  label: 'Sa'  },
                    { semitones: 1,  num: '2',  label: 're♭' },
                    { semitones: 3,  num: '4',  label: 'ga♭' },
                    { semitones: 5,  num: '6',  label: 'Ma'  },
                    { semitones: 7,  num: '8',  label: 'Pa'  },
                    { semitones: 8,  num: '9',  label: 'dha♭'},
                    { semitones: 10, num: '11', label: 'ni♭' }
                ]
            },

            bhairav: {
                name: 'Bhairav',
                info: 'Sa re♭ Ga Ma Pa dha♭ Ni (Komal Re & Dha)',
                swaras: [
                    { semitones: 0,  num: '1',  label: 'Sa'  },
                    { semitones: 1,  num: '2',  label: 're♭' },
                    { semitones: 4,  num: '5',  label: 'Ga'  },
                    { semitones: 5,  num: '6',  label: 'Ma'  },
                    { semitones: 7,  num: '8',  label: 'Pa'  },
                    { semitones: 8,  num: '9',  label: 'dha♭'},
                    { semitones: 11, num: '12', label: 'Ni'  }
                ]
            },

            todi: {
                name: 'Todi',
                info: 'Sa re♭ ga♭ Ma♯ Pa dha♭ Ni (Komal Re, Ga, Dha + Tivra Ma)',
                swaras: [
                    { semitones: 0,  num: '1',  label: 'Sa'  },
                    { semitones: 1,  num: '2',  label: 're♭' },
                    { semitones: 3,  num: '4',  label: 'ga♭' },
                    { semitones: 6,  num: '7',  label: 'Ma♯' },
                    { semitones: 7,  num: '8',  label: 'Pa'  },
                    { semitones: 8,  num: '9',  label: 'dha♭'},
                    { semitones: 11, num: '12', label: 'Ni'  }
                ]
            },

            marwa: {
                name: 'Marwa',
                info: 'Sa re♭ Ga Ma♯ Pa Dha Ni (Komal Re + Tivra Ma)',
                swaras: [
                    { semitones: 0,  num: '1',  label: 'Sa'  },
                    { semitones: 1,  num: '2',  label: 're♭' },
                    { semitones: 4,  num: '5',  label: 'Ga'  },
                    { semitones: 6,  num: '7',  label: 'Ma♯' },
                    { semitones: 7,  num: '8',  label: 'Pa'  },
                    { semitones: 9,  num: '10', label: 'Dha' },
                    { semitones: 11, num: '12', label: 'Ni'  }
                ]
            },

            purvi: {
                name: 'Purvi',
                info: 'Sa re♭ Ga Ma♯ Pa dha♭ Ni (Komal Re & Dha + Tivra Ma)',
                swaras: [
                    { semitones: 0,  num: '1',  label: 'Sa'  },
                    { semitones: 1,  num: '2',  label: 're♭' },
                    { semitones: 4,  num: '5',  label: 'Ga'  },
                    { semitones: 6,  num: '7',  label: 'Ma♯' },
                    { semitones: 7,  num: '8',  label: 'Pa'  },
                    { semitones: 8,  num: '9',  label: 'dha♭'},
                    { semitones: 11, num: '12', label: 'Ni'  }
                ]
            },

            // ── Popular Raags ──

            yaman: {
                name: 'Yaman',
                info: 'Sa Re Ga Ma♯ Pa Dha Ni – Evening raag, serene mood',
                swaras: [
                    { semitones: 0,  num: '1',  label: 'Sa'  },
                    { semitones: 2,  num: '3',  label: 'Re'  },
                    { semitones: 4,  num: '5',  label: 'Ga'  },
                    { semitones: 6,  num: '7',  label: 'Ma♯' },
                    { semitones: 7,  num: '8',  label: 'Pa'  },
                    { semitones: 9,  num: '10', label: 'Dha' },
                    { semitones: 11, num: '12', label: 'Ni'  }
                ]
            },

            bhupali: {
                name: 'Bhupali',
                info: 'Sa Re Ga Pa Dha – Pentatonic, devotional',
                swaras: [
                    { semitones: 0,  num: '1',  label: 'Sa'  },
                    { semitones: 2,  num: '3',  label: 'Re'  },
                    { semitones: 4,  num: '5',  label: 'Ga'  },
                    { semitones: 7,  num: '8',  label: 'Pa'  },
                    { semitones: 9,  num: '10', label: 'Dha' }
                ]
            },

            durga: {
                name: 'Durga',
                info: 'Sa Re Ma Pa Dha – Pentatonic, peaceful',
                swaras: [
                    { semitones: 0,  num: '1',  label: 'Sa'  },
                    { semitones: 2,  num: '3',  label: 'Re'  },
                    { semitones: 5,  num: '6',  label: 'Ma'  },
                    { semitones: 7,  num: '8',  label: 'Pa'  },
                    { semitones: 9,  num: '10', label: 'Dha' }
                ]
            },

            malkauns: {
                name: 'Malkauns',
                info: 'Sa ga♭ Ma dha♭ ni♭ – Pentatonic, midnight raag',
                swaras: [
                    { semitones: 0,  num: '1',  label: 'Sa'  },
                    { semitones: 3,  num: '4',  label: 'ga♭' },
                    { semitones: 5,  num: '6',  label: 'Ma'  },
                    { semitones: 8,  num: '9',  label: 'dha♭'},
                    { semitones: 10, num: '11', label: 'ni♭' }
                ]
            },

            desh: {
                name: 'Desh',
                info: 'Sa Re Ga Ma Pa Dha ni♭ – Rainy season raag',
                swaras: [
                    { semitones: 0,  num: '1',  label: 'Sa'  },
                    { semitones: 2,  num: '3',  label: 'Re'  },
                    { semitones: 4,  num: '5',  label: 'Ga'  },
                    { semitones: 5,  num: '6',  label: 'Ma'  },
                    { semitones: 7,  num: '8',  label: 'Pa'  },
                    { semitones: 9,  num: '10', label: 'Dha' },
                    { semitones: 10, num: '11', label: 'ni♭' }
                ]
            },

            bageshri: {
                name: 'Bageshri',
                info: 'Sa Re ga♭ Ma Pa Dha ni♭ – Night raag, romantic',
                swaras: [
                    { semitones: 0,  num: '1',  label: 'Sa'  },
                    { semitones: 2,  num: '3',  label: 'Re'  },
                    { semitones: 3,  num: '4',  label: 'ga♭' },
                    { semitones: 5,  num: '6',  label: 'Ma'  },
                    { semitones: 7,  num: '8',  label: 'Pa'  },
                    { semitones: 9,  num: '10', label: 'Dha' },
                    { semitones: 10, num: '11', label: 'ni♭' }
                ]
            },

            bihag: {
                name: 'Bihag',
                info: 'Sa Ga Ma Ma♯ Pa Ni – Night raag, joyful',
                swaras: [
                    { semitones: 0,  num: '1',  label: 'Sa'  },
                    { semitones: 4,  num: '5',  label: 'Ga'  },
                    { semitones: 5,  num: '6',  label: 'Ma'  },
                    { semitones: 6,  num: '7',  label: 'Ma♯' },
                    { semitones: 7,  num: '8',  label: 'Pa'  },
                    { semitones: 11, num: '12', label: 'Ni'  }
                ]
            },

            hansdhwani: {
                name: 'Hansdhwani',
                info: 'Sa Re Ga Pa Ni – Pentatonic, auspicious',
                swaras: [
                    { semitones: 0,  num: '1',  label: 'Sa'  },
                    { semitones: 2,  num: '3',  label: 'Re'  },
                    { semitones: 4,  num: '5',  label: 'Ga'  },
                    { semitones: 7,  num: '8',  label: 'Pa'  },
                    { semitones: 11, num: '12', label: 'Ni'  }
                ]
            },

            shivranjani: {
                name: 'Shivranjani',
                info: 'Sa Re ga♭ Pa Dha – Pentatonic, melancholic',
                swaras: [
                    { semitones: 0,  num: '1',  label: 'Sa'  },
                    { semitones: 2,  num: '3',  label: 'Re'  },
                    { semitones: 3,  num: '4',  label: 'ga♭' },
                    { semitones: 7,  num: '8',  label: 'Pa'  },
                    { semitones: 9,  num: '10', label: 'Dha' }
                ]
            },

            charukeshi: {
                name: 'Charukeshi',
                info: 'Sa Re Ga Ma Pa dha♭ ni♭ – Carnatic-inspired',
                swaras: [
                    { semitones: 0,  num: '1',  label: 'Sa'  },
                    { semitones: 2,  num: '3',  label: 'Re'  },
                    { semitones: 4,  num: '5',  label: 'Ga'  },
                    { semitones: 5,  num: '6',  label: 'Ma'  },
                    { semitones: 7,  num: '8',  label: 'Pa'  },
                    { semitones: 8,  num: '9',  label: 'dha♭'},
                    { semitones: 10, num: '11', label: 'ni♭' }
                ]
            }
        };

        // Default scale degrees: Bilawal / Major (1,3,5,6,8,10,12)
        var defaultScaleDegrees = [
            { semitones: 0,  num: '1',  label: 'sa'  },
            { semitones: 2,  num: '3',  label: 're'  },
            { semitones: 4,  num: '5',  label: 'ga'  },
            { semitones: 5,  num: '6',  label: 'ma'  },
            { semitones: 7,  num: '8',  label: 'pa'  },
            { semitones: 9,  num: '10', label: 'dha' },
            { semitones: 11, num: '12', label: 'ni'  }
        ];

        // Current active scale degrees
        var activeScaleDegrees = defaultScaleDegrees;

        // Current root key index (0 = first piano key = C)
        var rootKeyIndex = 0;

        /* =========================
           RAAG SELECTION HANDLER
        ========================== */
        if (raagSelect) {
            raagSelect.addEventListener("change", function () {
                var val = this.value;
                if (!val || val === '') {
                    // Reset to default scale (1,3,5,6,8,10,12)
                    activeScaleDegrees = defaultScaleDegrees;
                } else {
                    var selectedRaag = raagLibrary[val];
                    if (selectedRaag) {
                        activeScaleDegrees = selectedRaag.swaras;
                    }
                }
                // Re-render scale with new swaras
                ptpianRenderScale();
            });
        }

        /* =========================
           GET ALL PIANO KEY CENTERS
           Returns array of { el, centerX } for every key
           relative to the piano-keys container
        ========================== */
        function getKeyCenters() {
            var pianoKeys = document.querySelectorAll(".piano-keys .key");
            var pianoKeysContainer = document.querySelector(".piano-keys");
            if (!pianoKeysContainer || pianoKeys.length === 0) return [];

            var pianoRect = pianoKeysContainer.getBoundingClientRect();
            var centers = [];

            pianoKeys.forEach(function (keyEl, i) {
                var rect = keyEl.getBoundingClientRect();
                centers.push({
                    el: keyEl,
                    index: i,
                    centerX: rect.left - pianoRect.left + (rect.width / 2)
                });
            });

            return centers;
        }

        /* =========================
           RENDER SCALE AT ROOT INDEX
           Places scale buttons at the correct
           chromatic positions from rootKeyIndex
           using the active raag's swaras
        ========================== */
        function ptpianRenderScale() {

            var pianoKeys = document.querySelectorAll(".piano-keys .key");
            if (pianoKeys.length === 0) return;

            // If piano keys have no dimensions yet, retry
            var firstKey = pianoKeys[0];
            if (firstKey.getBoundingClientRect().width === 0) {
                setTimeout(ptpianRenderScale, 300);
                return;
            }

            ptpianTrack.innerHTML = "";

            // Reset transform (no dragging offset after re-render)
            ptpianTrack.style.transform = "";

            var pianoKeysContainer = document.querySelector(".piano-keys");
            var pianoRect = pianoKeysContainer.getBoundingClientRect();
            var wrapperRect = ptpianChannel.getBoundingClientRect();

            // Offset: piano-keys left edge relative to the wrapper
            var pianoOffsetLeft = pianoRect.left - wrapperRect.left;
            ptpianTrack.style.marginLeft = pianoOffsetLeft + "px";

            var keyCenters = getKeyCenters();
            var totalKeys = keyCenters.length;

            // Render each scale degree from the active raag
            activeScaleDegrees.forEach(function (degree) {

                var targetIndex = rootKeyIndex + degree.semitones;

                // Skip if target key is beyond the piano range
                if (targetIndex < 0 || targetIndex >= totalKeys) return;

                var centerX = keyCenters[targetIndex].centerX;

                var cell = document.createElement("div");
                cell.className = "ptpian-scale-cell filled-cell";

                cell.style.position = "absolute";
                cell.style.left = centerX + "px";
                cell.style.transform = "translateX(-50%)";

                cell.innerHTML =
                    '<span>' + degree.num + '</span>' +
                    '<span>' + degree.label + '</span>';

                ptpianTrack.appendChild(cell);
            });
        }

        /* =========================
           FIND NEAREST KEY TO X POSITION
           Returns index of the closest piano key
        ========================== */
        function findNearestKeyIndex(xRelativeToPiano) {
            var keyCenters = getKeyCenters();
            if (keyCenters.length === 0) return 0;

            var closestIndex = 0;
            var closestDist = Infinity;

            keyCenters.forEach(function (kc, i) {
                var dist = Math.abs(kc.centerX - xRelativeToPiano);
                if (dist < closestDist) {
                    closestDist = dist;
                    closestIndex = i;
                }
            });

            return closestIndex;
        }

        /* =========================
           GET MAX SEMITONES IN ACTIVE RAAG
           Used to clamp root so last note
           doesn't go beyond piano range
        ========================== */
        function getMaxSemitones() {
            var max = 0;
            activeScaleDegrees.forEach(function (d) {
                if (d.semitones > max) max = d.semitones;
            });
            return max;
        }

        /* =========================
           DRAG TO MOVE ROOT
           On drag end, snap the root (Sa)
           to the nearest piano key and re-render
        ========================== */
        var isDown = false;
        var startX = 0;
        var dragStartRootX = 0; // centerX of root key when drag starts

        // Mouse events
        ptpianChannel.addEventListener("mousedown", function (e) {
            // Don't start drag if clicking on the raag dropdown
            if (e.target.closest('.ptpian-raag-bar')) return;
            e.preventDefault();
            startDrag(e.pageX);
        });

        document.addEventListener("mousemove", function (e) {
            if (!isDown) return;
            onDragMove(e.pageX);
        });

        document.addEventListener("mouseup", function (e) {
            if (!isDown) return;
            endDrag(e.pageX);
        });

        // Touch events for mobile
        ptpianChannel.addEventListener("touchstart", function (e) {
            if (e.target.closest('.ptpian-raag-bar')) return;
            e.preventDefault();
            startDrag(e.touches[0].pageX);
        }, { passive: false });

        document.addEventListener("touchmove", function (e) {
            if (!isDown) return;
            onDragMove(e.touches[0].pageX);
        }, { passive: true });

        document.addEventListener("touchend", function (e) {
            if (!isDown) return;
            var touch = e.changedTouches[0];
            endDrag(touch.pageX);
        });

        function startDrag(pageX) {
            isDown = true;
            startX = pageX;

            // Remember where the root key center is right now
            var keyCenters = getKeyCenters();
            if (keyCenters.length > 0 && rootKeyIndex < keyCenters.length) {
                dragStartRootX = keyCenters[rootKeyIndex].centerX;
            }

            ptpianChannel.style.cursor = "grabbing";
        }

        function onDragMove(pageX) {
            var dx = pageX - startX;

            // Visual feedback: shift the track during drag
            ptpianTrack.style.transform = "translateX(" + dx + "px)";
        }

        function endDrag(pageX) {
            isDown = false;
            ptpianChannel.style.cursor = "grab";

            var dx = pageX - startX;

            // New desired position for root = original root center + drag offset
            var newRootX = dragStartRootX + dx;

            // Find nearest piano key to that position
            var newRootIndex = findNearestKeyIndex(newRootX);

            // Clamp: make sure the last scale degree doesn't exceed piano
            var pianoKeys = document.querySelectorAll(".piano-keys .key");
            var maxRoot = pianoKeys.length - getMaxSemitones() - 1;
            if (maxRoot < 0) maxRoot = 0;
            if (newRootIndex > maxRoot) newRootIndex = maxRoot;

            rootKeyIndex = newRootIndex;

            // Re-render at new root position
            ptpianRenderScale();
        }

        /* =========================
           INIT
        ========================== */
        ptpianRenderScale();

        // Re-render when the piano content becomes visible (after loader hides)
        var ptpianContent = document.querySelector(".ptpiano-content");
        if (ptpianContent) {
            var observer = new MutationObserver(function (mutations) {
                mutations.forEach(function (mutation) {
                    if (mutation.attributeName === "style" &&
                        ptpianContent.style.display !== "none") {
                        setTimeout(ptpianRenderScale, 50);
                    }
                });
            });
            observer.observe(ptpianContent, { attributes: true });
        }

        // Re-render after window load (ensures content is visible)
        window.addEventListener("load", function () {
            setTimeout(ptpianRenderScale, 100);
        });

        window.addEventListener("resize", function () {
            ptpianRenderScale();
        });

    });

})();