// Sample form "busy" feedback.
//
// Each sample converts on a classic form POST whose response is usually a
// FILE DOWNLOAD (FileContentResult). A download does NOT navigate the page and
// fires NO completion event, so without help the "Create PDF" button just sits
// there while the server renders — no feedback, and the user can double-click.
//
// On submit we swap the submitting button's label to "Working …", block
// re-clicks, and round-trip a one-time token via a hidden field. The server
// (DownloadTokenPageFilter) echoes that token back as a cookie ON the file
// response; we poll for it to know the download was delivered and then restore
// the button — so it returns to normal exactly when the work is done, not on a
// guessed timeout. Pages that return a page result (validation error, the
// email sample, …) navigate/reload and reset the button naturally; a long
// fallback timeout covers anything unexpected.
(function () {
    'use strict';

    var BUSY_TEXT = 'Working …';
    var COOKIE = 'spdfDownloadToken';
    var POLL_MS = 200;
    var FALLBACK_MS = 60000;   // safety net if the cookie never arrives

    document.addEventListener('submit', function (e) {
        var form = e.target;
        if (!form || form.tagName !== 'FORM') return;

        var btn = e.submitter ||
            form.querySelector('button[type="submit"], input[type="submit"], .mybutton');
        if (!btn || btn.getAttribute('data-spdf-busy') === '1') return;

        // Round-trip token: added synchronously here so it's part of the POST.
        var token = newToken();
        setHidden(form, COOKIE, token);

        // Defer the label swap one tick: the browser serializes the form
        // synchronously after this handler, and for <input type="submit"> the
        // value is BOTH the label and the posted value — swapping now would
        // post "Working …". Deferring keeps the original posted value.
        window.setTimeout(function () { setBusy(btn); }, 0);

        var fallback = window.setTimeout(function () { stop(); }, FALLBACK_MS);
        var poll = window.setInterval(function () {
            if (readCookie(COOKIE) === token) { stop(); }
        }, POLL_MS);

        function stop() {
            window.clearTimeout(fallback);
            window.clearInterval(poll);
            expireCookie(COOKIE);
            restore(btn);
        }
    }, true);

    function setBusy(btn) {
        btn.setAttribute('data-spdf-busy', '1');
        if (btn.tagName === 'INPUT') {
            btn.setAttribute('data-spdf-label', btn.value);
            btn.value = BUSY_TEXT;
        } else {
            btn.setAttribute('data-spdf-label', btn.innerHTML);
            btn.textContent = BUSY_TEXT;
        }
        btn.classList.add('is-busy');
        btn.setAttribute('aria-busy', 'true');
        // Block double-submit WITHOUT disabling — a disabled submit button is
        // dropped from the POST body (its name/value won't be sent).
        btn.style.pointerEvents = 'none';
        btn.style.opacity = '0.7';
    }

    function restore(btn) {
        if (btn.getAttribute('data-spdf-busy') !== '1') return;
        var label = btn.getAttribute('data-spdf-label');
        if (label !== null) {
            if (btn.tagName === 'INPUT') btn.value = label;
            else btn.innerHTML = label;
        }
        btn.removeAttribute('data-spdf-busy');
        btn.removeAttribute('data-spdf-label');
        btn.removeAttribute('aria-busy');
        btn.classList.remove('is-busy');
        btn.style.pointerEvents = '';
        btn.style.opacity = '';
    }

    function setHidden(form, name, value) {
        var input = form.querySelector('input[type="hidden"][name="' + name + '"]');
        if (!input) {
            input = document.createElement('input');
            input.type = 'hidden';
            input.name = name;
            form.appendChild(input);
        }
        input.value = value;
    }

    function newToken() {
        if (window.crypto && window.crypto.randomUUID) return window.crypto.randomUUID();
        return 'd' + Date.now().toString(16) + Math.random().toString(16).slice(2);
    }

    function readCookie(name) {
        var m = document.cookie.match('(?:^|; )' + name + '=([^;]*)');
        return m ? decodeURIComponent(m[1]) : null;
    }

    function expireCookie(name) {
        document.cookie = name + '=; Max-Age=0; path=/';
    }

    // Restore on back/forward (bfcache) navigation so a cached page isn't stuck.
    window.addEventListener('pageshow', function (e) {
        if (e.persisted) {
            var busy = document.querySelectorAll('[data-spdf-busy="1"]');
            for (var i = 0; i < busy.length; i++) restore(busy[i]);
        }
    });
})();
