(() => {
    'use strict';

    const button = document.getElementById('orchestrator-start');
    if (!button) return;

    const csrf = window.AXIOM_ORCHESTRATOR_CSRF || '';
    const progressBar = document.getElementById('orchestrator-progress-bar');
    const progressText = document.getElementById('orchestrator-progress-text');
    const errorBox = document.getElementById('orchestrator-error');
    let running = false;

    async function post(url, values) {
        const response = await fetch(url, {
            method: 'POST',
            credentials: 'same-origin',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: new URLSearchParams(values).toString()
        });

        const payload = await response.json();

        if (!response.ok || payload.ok === false) {
            throw new Error(payload.error || 'Erreur de l’orchestrateur.');
        }

        return payload;
    }

    async function loop() {
        if (!running) return;

        try {
            const payload = await post(
                '/public/administration/plateforme/deploiement-orchestre/avancer',
                {
                    _csrf: csrf,
                    orchestration_id: button.dataset.id
                }
            );

            progressBar.style.width = `${Number(payload.progress || 0)}%`;
            progressText.textContent = `${Number(payload.progress || 0)} %`;

            if (payload.finished) {
                running = false;
                setTimeout(() => window.location.reload(), 800);
                return;
            }

            setTimeout(loop, 450);
        } catch (error) {
            running = false;
            errorBox.hidden = false;
            errorBox.textContent = error.message;
            button.disabled = false;
            button.textContent = 'Reprendre';
        }
    }

    button.addEventListener('click', () => {
        if (running) return;

        running = true;
        button.disabled = true;
        button.textContent = 'Déploiement en cours…';
        errorBox.hidden = true;
        errorBox.textContent = '';

        loop();
    });
})();
