(function () {
    'use strict';
    window.SonicPianoRoll = {
        getParentTrackByItemId: function (itemId, tracks) {
            if (!tracks || !itemId) return null;
            for (var i = 0; i < tracks.length; i++) {
                var items = tracks[i].midiItems || [];
                for (var j = 0; j < items.length; j++) {
                    if (items[j].id === itemId) return tracks[i];
                }
            }
            return null;
        },
        getParentTrackIdByItemId: function (itemId, tracks) {
            var trk = this.getParentTrackByItemId(itemId, tracks);
            return trk ? trk.id : null;
        },
        buildActiveScope: function (itemId, tracks) {
            var parentTrack = this.getParentTrackByItemId(itemId, tracks);
            if (!parentTrack) return null;
            var trackIndex = -1;
            for (var i = 0; i < tracks.length; i++) {
                if (tracks[i].id === parentTrack.id) { trackIndex = i; break; }
            }
            return {
                item_id: itemId,
                parent_track_id: parentTrack.id,
                midi_channel: trackIndex >= 0 ? trackIndex % 16 : 0,
                current_synth_engine: parentTrack.synth_engine || null,
                instrument_program: parentTrack.instrumentProgram,
                instrument_name: parentTrack.instrumentName
            };
        },
        getTrackMidiChannel: function (track, tracks) {
            if (track && track.midiChannel !== undefined) return track.midiChannel;
            if (!track || !tracks) return 0;
            for (var i = 0; i < tracks.length; i++) {
                if (tracks[i].id === track.id) return i % 16;
            }
            return 0;
        }
    };
})();
