/*global self, module */

const saveAs = (() => {
    "use strict";

    const isBrowser = typeof window !== "undefined" || typeof self !== "undefined";
    if (!isBrowser) {
        return undefined;
    }

    const view = (typeof self !== "undefined" && self)
        || (typeof window !== "undefined" && window);

    /**
     * Triggers a file download in the browser.
     * @param {Blob} blob - The Blob object to save.
     * @param {string} [name="download"] - The suggested file name.
     */
    const saveAs = (blob, name = "download") => {
        const objectUrl = URL.createObjectURL(blob);

        const link = document.createElement("a");
        link.href = objectUrl;
        link.download = name;
        link.style.display = "none";

        document.body.appendChild(link);

        link.dispatchEvent(new MouseEvent("click", {
            bubbles: true,
            cancelable: true,
            view
        }));

        link.remove();

        // Revoke the object URL after a delay to allow the download to start
        setTimeout(() => URL.revokeObjectURL(objectUrl), 40000);
    };

    return saveAs;
})();

if (typeof module !== "undefined") {
    module.exports = saveAs;
}