{% load static %}
<div>
    {{ widget }}
    <progress id="upload-progress" value="0" max="100" style="width: 100%; display: none;"></progress>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function () {
        const input = document.querySelector('input[type="file"]');
        const progress = document.getElementById('upload-progress');

        if (input && progress) {
            const form = input.closest('form');

            form.addEventListener('submit', function (e) {
                e.preventDefault();  // Empêche l’envoi classique

                const formData = new FormData(form);
                const xhr = new XMLHttpRequest();

                xhr.open(form.method, form.action);
                xhr.upload.onprogress = function (event) {
                    if (event.lengthComputable) {
                        let percent = (event.loaded / event.total) * 100;
                        progress.style.display = 'block';
                        progress.value = percent;
                    }
                };

                xhr.onload = function () {
                    if (xhr.status === 200) {
                        location.reload();  // ou redirige si nécessaire
                    } else {
                        alert('Erreur lors de l’envoi du fichier.');
                    }
                };

                xhr.send(formData);
            });
        }
    });
</script>
