(function () {
    'use strict';
    const nativeFetch = window.fetch;
    if (typeof nativeFetch !== 'function') return;

    window.fetch = function (input, init) {
        const options = Object.assign({}, init || {});
        const method = String(options.method || 'GET').toUpperCase();
        if (!['GET', 'HEAD', 'OPTIONS'].includes(method)) {
            const url = typeof input === 'string' ? input : (input && input.url ? input.url : '');
            let sameOrigin = true;
            try { sameOrigin = new URL(url, window.location.href).origin === window.location.origin; } catch (_) {}
            if (sameOrigin) {
                const token = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '';
                const headers = new Headers(options.headers || (input instanceof Request ? input.headers : undefined));
                if (token && !headers.has('X-CSRF-Token')) headers.set('X-CSRF-Token', token);
                headers.set('X-Requested-With', 'XMLHttpRequest');
                options.headers = headers;
            }
        }
        return nativeFetch.call(this, input, options);
    };
})();
