/* ============================================================================
 * TraderAlign — global CSRF header injector.
 *
 * Loaded once, from public/sidebar.php (included by nearly every
 * authenticated page), right after the <meta name="csrf-token"> tag that
 * same file renders. Wraps window.fetch so every same-origin, state-
 * changing fetch() call across the whole app automatically carries an
 * X-CSRF-Token header — without needing to edit every individual fetch()
 * call site across dozens of files (colex.php, journal.php, trading-
 * center.php, add-prop-account.php, drafts.php, calculator-source.html,
 * strategy.php, etc.).
 *
 * Server-side check: src/Csrf.php::verify(), enforced centrally in
 * index.php for state-changing requests.
 *
 * Deliberately does nothing for:
 *   - GET/HEAD/OPTIONS requests (nothing to protect, and the header isn't
 *     needed there).
 *   - Cross-origin requests (Google Fonts, any future external API) — the
 *     token must never leave this origin.
 *   - A request that already explicitly set its own X-CSRF-Token header.
 * ============================================================================ */
(function () {
    if (typeof window.fetch !== 'function') return;

    // calculator-source.html is loaded inside a same-origin <iframe> from
    // public/calculator.php, as its own separate document/window — a
    // meta tag rendered into the PARENT page (by sidebar.php) is invisible
    // to code running inside the iframe's own document. Since both are
    // same-origin, the iframe can read the parent's DOM directly (no
    // postMessage handshake, no putting the token in a URL where it could
    // end up in a Referer header). Falls back to null (inert) if there's
    // no parent, or the parent has no token either — e.g. this exact file
    // requested directly as a top-level page outside the iframe.
    var meta = document.querySelector('meta[name="csrf-token"]');
    if (!meta && window.parent && window.parent !== window) {
        try { meta = window.parent.document.querySelector('meta[name="csrf-token"]'); } catch (e) { meta = null; }
    }
    var token = meta ? meta.getAttribute('content') : null;
    if (!token) return;

    var UNSAFE_METHODS = ['POST', 'PUT', 'PATCH', 'DELETE'];

    var originalFetch = window.fetch.bind(window);

    window.fetch = function (input, init) {
        try {
            var url = (typeof input === 'string') ? input : (input && input.url) || '';
            var isRelative = url.indexOf('://') === -1 && url.indexOf('//') !== 0;
            var isSameOrigin = isRelative || url.indexOf(window.location.origin) === 0;

            if (isSameOrigin) {
                var method = ((init && init.method) || (input && input.method) || 'GET').toUpperCase();
                if (UNSAFE_METHODS.indexOf(method) !== -1) {
                    init = init || {};
                    var headers = init.headers;
                    if (headers instanceof Headers) {
                        if (!headers.has('X-CSRF-Token')) headers.set('X-CSRF-Token', token);
                    } else {
                        headers = Object.assign({}, headers || {});
                        if (!('X-CSRF-Token' in headers) && !('x-csrf-token' in headers)) {
                            headers['X-CSRF-Token'] = token;
                        }
                    }
                    init.headers = headers;
                }
            }
        } catch (e) {
            // Never let a problem here block a real request — fall through
            // to the original, unmodified call.
        }
        return originalFetch(input, init);
    };
})();
