(function($) {
    'use strict';
    $(function() {
        var $levelSelect = $('#id_level');
        var $subjectSelect = $('#id_subscribed_subjects');
        // Check if we are in the admin change form
        if (!$levelSelect.length || !$subjectSelect.length) return;

        var isArabic = $('html').attr('lang') === 'ar' || $('body').hasClass('rtl');

        function updateSubjects(levelId, selectedValues) {
            if (!levelId) {
                $subjectSelect.html('');
                refreshSelectFilter();
                return;
            }

            $.getJSON('/ajax/get-subjects-by-level/', {level_id: levelId}, function(data) {
                var options = '';
                $.each(data, function(index, subject) {
                    var selected = '';
                    if (selectedValues && selectedValues.indexOf(subject.id.toString()) !== -1) {
                        selected = ' selected';
                    }
                    var name = isArabic ? subject.name_ar : subject.name_en;
                    options += '<option value="' + subject.id + '"' + selected + '>' + name + '</option>';
                });
                $subjectSelect.html(options);
                refreshSelectFilter();
            });
        }

        function refreshSelectFilter() {
            // Django's filter_horizontal uses SelectFilter2
            if (typeof SelectFilter2 !== 'undefined') {
                var fieldName = 'subscribed_subjects';
                // Remove the existing widget elements
                $('.selector').has('#id_' + fieldName + '_from').remove();
                
                // Re-initialize it
                // SelectFilter2.init(field_id, field_name, is_stacked)
                SelectFilter2.init('id_' + fieldName, fieldName, false);
            } else if (typeof SelectFilter !== 'undefined') {
                var fieldName = 'subscribed_subjects';
                $('.selector').has('#id_' + fieldName + '_from').remove();
                SelectFilter.init('id_' + fieldName, fieldName, false);
            }
        }

        $levelSelect.on('change', function() {
            var selectedValues = [];
            // When level changes, we might want to keep currently selected subjects if they still belong to the level?
            // Actually, usually when level changes, we reset subjects or only keep valid ones.
            // For now, let's reset to avoid confusion, or the user can re-select.
            updateSubjects($(this).val(), []);
        });

        // If we are editing an existing student, we should filter the subjects on load
        // but KEEP the currently selected ones.
        if ($levelSelect.val()) {
            // Get currently selected values from the "chosen" side if possible, 
            // or from the original select before it was widgetized.
            var selectedValues = [];
            $('#id_subscribed_subjects_to option').each(function() {
                selectedValues.push($(this).val());
            });
            
            // If empty (new form or nothing selected), try the main select
            if (selectedValues.length === 0) {
                $subjectSelect.find('option:selected').each(function() {
                    selectedValues.push($(this).val());
                });
            }
            
            updateSubjects($levelSelect.val(), selectedValues);
        }
    });
})(django.jQuery);
