$(document).ready(function () {
    // Display the epic based on the selected project by default
    updateEpicDropdown();

    // Update the "Epic" dropdown when the "Project" dropdown changes
    $('#projectDropdown').on('change', function () {
        updateEpicDropdown();
    });

    function updateEpicDropdown() {
        var selectedProjectId = $('#projectDropdown').val();

        $.ajax({
            url: '/fetch_epics/',
            method: 'GET',
            data: { project_id: selectedProjectId },
            success: function (data) {
                // Clear existing options
                $('#epicDropdown').empty();

                // Add the new options based on the fetched data
                $.each(data.epics, function (index, epic) {
                    var selected = (epic.id == '{{ task.epic.id }}') ? 'selected' : '';
                    $('#epicDropdown').append('<option value="' + epic.id + '" ' + selected + '>' + epic.title + '</option>');
                });
            },
            error: function () {
                console.log('Error fetching epics');
            }
        });
    }
});
