// Downloads a file from a same-origin API endpoint as a real browser download. Why this
// helper exists: Blazor's NavigationManager intercepts plain <a href> clicks for internal
// URLs and tries to route them through the SignalR circuit, which can't deliver binary
// responses like PDFs. By fetching the response ourselves into a Blob and triggering a
// click on a temporary anchor with `download`, we sidestep the SPA router entirely.
//
// Usage from Razor:
//   await JS.InvokeVoidAsync("tmPdfDownload.fetch", "/api/performance/export.pdf", "performance.pdf");
window.tmPdfDownload = window.tmPdfDownload || {
    fetch: async function (url, filename) {
        try {
            const res = await window.fetch(url, {
                method: 'GET',
                credentials: 'same-origin',          // include the auth cookie
                cache: 'no-store',
                headers: { 'Accept': 'application/pdf' }
            });
            if (!res.ok) {
                console.error('PDF download failed:', res.status, res.statusText);
                alert('Download failed: HTTP ' + res.status);
                return;
            }
            const blob = await res.blob();
            const objectUrl = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = objectUrl;
            a.download = filename || 'download.pdf';
            document.body.appendChild(a);
            a.click();
            a.remove();
            // Revoke the blob URL a tick later so the click handler had time to fire.
            setTimeout(() => URL.revokeObjectURL(objectUrl), 1000);
        } catch (err) {
            console.error('PDF download threw:', err);
            alert('Download failed: ' + (err && err.message ? err.message : 'unknown error'));
        }
    }
};
