(function (global) {
    if (!global.clientexec) {
        global.clientexec = {};
    }

    // Ensure container is added to <body> on load
    function ensureContainer(position = "top") {
        let container = document.getElementById("notification-container");

        if (!container) {
            container = document.createElement("div");
            container.id = "notification-container";
            document.body.appendChild(container);
        }

        // Reset classes
        container.className = "position-fixed d-flex flex-column align-items-center";
        container.style.zIndex = "2000"; // keep above modals

        if (position === "center") {
            container.classList.add("top-50", "start-50", "translate-middle");
        } else {
            // Default: top-center
            container.classList.add("top-0", "start-50", "translate-middle-x", "mt-3");
        }

        return container;
    }

    function showNotification(message, type = "primary", delay = 3000, options = {}) {
        const position = options.position || "top";
        const container = ensureContainer(position);

        // Create toast element
        const toastEl = document.createElement("div");
        toastEl.className = `toast align-items-center text-bg-${type} border-0 mb-2 shadow`;
        toastEl.role = "alert";
        toastEl.ariaLive = "assertive";
        toastEl.ariaAtomic = "true";

        toastEl.innerHTML = `
            <div class="d-flex">
                <div class="toast-body">
                    ${message}
                </div>
                <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
            </div>
        `;

        container.appendChild(toastEl);

        // Initialize toast with Bootstrap
        const toast = new bootstrap.Toast(toastEl, { delay });
        toast.show();

        // Remove after hidden
        toastEl.addEventListener("hidden.bs.toast", () => {
            toastEl.remove();
        });

        return toast; // return reference if caller wants control
    }

    global.clientexec.showNotification = showNotification;
})(window);