(function($) {
    'use strict';
    $(function() {
        console.log("Admin Resource JS loaded");
        var $levelSelect = $('#id_educational_level');
        var $subjectSelect = $('#id_subject');
        
        // Check if elements exist
        if (!$levelSelect.length) {
             console.warn("Educational Level field #id_educational_level not found");
        }
        if (!$subjectSelect.length) {
             console.warn("Subject field #id_subject not found");
        }
        if (!$levelSelect.length || !$subjectSelect.length) return;

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

        function updateSubjects(levelId, currentSubjectId) {
            console.log("Updating subjects for level:", levelId);
            // If no level selected, clear subjects
            if (!levelId) {
                $subjectSelect.html('<option value="">---------</option>');
                return;
            }

            $.getJSON('/ajax/get-subjects-by-level/', {level_id: levelId}, function(data) {
                console.log("Subjects fetched:", data.length);
                var options = '<option value="">---------</option>';
                $.each(data, function(index, subject) {
                    var selected = '';
                    // If we have a current subject ID, check if it matches
                    if (currentSubjectId && subject.id.toString() === currentSubjectId.toString()) {
                        selected = ' selected';
                    }
                    var name = isArabic ? subject.name_ar : subject.name_en;
                    options += '<option value="' + subject.id + '"' + selected + '>' + name + '</option>';
                });
                $subjectSelect.html(options);
            })
            .fail(function(jqxhr, textStatus, error) {
                var err = textStatus + ", " + error;
                console.error("Request Failed: " + err);
            });
        }

        $levelSelect.on('change', function() {
            var levelId = $(this).val();
            // When level changes, we reset the subject selection
            updateSubjects(levelId, null);
        });

        // Initial load
        var initialLevel = $levelSelect.val();
        var initialSubject = $subjectSelect.val();

        if (initialLevel) {
            updateSubjects(initialLevel, initialSubject);
        } else {
             if (!initialSubject) {
                 $subjectSelect.html('<option value="">---------</option>');
             }
        }
    });
})(django.jQuery);