(() => {
    // TenantPilot shim: ensure Livewire interceptMessage callbacks run in a safe order.
    // This prevents Filament's notifications asset (and others) from calling an undefined
    // animation callback when onSuccess fires before onFinish.
    if (typeof window === 'undefined') {
        return;
    }

    const Livewire = window.Livewire;

    if (!Livewire || typeof Livewire.interceptMessage !== 'function') {
        return;
    }

    if (Livewire.__tenantpilotInterceptMessageShimApplied) {
        return;
    }

    const original = Livewire.interceptMessage.bind(Livewire);

    Livewire.interceptMessage = (handler) => {
        if (typeof handler !== 'function') {
            return original(handler);
        }

        return original((context) => {
            if (!context || typeof context !== 'object') {
                return handler(context);
            }

            const originalOnFinish = context.onFinish;
            const originalOnSuccess = context.onSuccess;

            if (typeof originalOnFinish !== 'function' || typeof originalOnSuccess !== 'function') {
                return handler(context);
            }

            const finishCallbacks = [];

            const onFinish = (callback) => {
                if (typeof callback === 'function') {
                    finishCallbacks.push(callback);
                }

                return originalOnFinish(callback);
            };

            const onSuccess = (callback) => {
                return originalOnSuccess((...args) => {
                    // Ensure any registered finish callbacks are run before success callbacks.
                    // We don't swallow errors; we just stabilize ordering.
                    for (const finishCallback of finishCallbacks) {
                        finishCallback(...args);
                    }

                    if (typeof callback === 'function') {
                        return callback(...args);
                    }
                });
            };

            return handler({
                ...context,
                onFinish,
                onSuccess,
            });
        });
    };

    Livewire.__tenantpilotInterceptMessageShimApplied = true;
})();
