/**
 * v5 — هر URL با مسیر /api به window.__ARKA_API_BASE (از .env در index.html) می‌رود.
 */
(function () {
    'use strict';
    if (window.__apiHttpGuardInstalled) return;
    window.__apiHttpGuardInstalled = true;
    window.__API_GUARD_VERSION = 5;

    var API_BASE = String(window.__ARKA_API_BASE || '').replace(/\/$/, '');
    if (!API_BASE) {
        console.error(
            '[api-http-guard] window.__ARKA_API_BASE is missing. Set .env and run: node scripts/write-arka-api-config.mjs'
        );
    }

    function apiSuffixFromPathname(pathname) {
        if (!pathname || pathname === '/api') return '';
        if (pathname.indexOf('/api/') === 0) return pathname.slice(4);
        return '';
    }

    function toIpApiUrl(url) {
        if (!url || typeof url !== 'string') return url;

        if (url.charAt(0) === '/' && (url === '/api' || url.indexOf('/api/') === 0)) {
            return API_BASE + apiSuffixFromPathname(url);
        }

        try {
            var u = new URL(url, location.href);
            var suffix = apiSuffixFromPathname(u.pathname);
            if (suffix === '' && u.pathname !== '/api') return url;

            var target = API_BASE + suffix + u.search + (u.hash || '');
            if (u.href === target) return url;
            return target;
        } catch (e) {
            var m = url.match(/\/api(\/.*)?(\?[^#]*)?(#.*)?$/i);
            if (m) {
                return API_BASE + (m[1] || '') + (m[2] || '') + (m[3] || '');
            }
            return url;
        }
    }

    window.__normalizeApiUrl = toIpApiUrl;
    window.__toHttpApiUrl = toIpApiUrl;

    function patchInput(input) {
        if (typeof input === 'string') return toIpApiUrl(input);
        if (typeof Request !== 'undefined' && input instanceof Request) {
            var next = toIpApiUrl(input.url);
            return next === input.url ? input : new Request(next, input);
        }
        return input;
    }

    var nativeFetch = window.fetch.bind(window);
    window.fetch = function (input, init) {
        return nativeFetch(patchInput(input), init);
    };

    if (typeof XMLHttpRequest !== 'undefined') {
        var open = XMLHttpRequest.prototype.open;
        XMLHttpRequest.prototype.open = function () {
            var a = Array.prototype.slice.call(arguments);
            if (typeof a[1] === 'string') a[1] = toIpApiUrl(a[1]);
            return open.apply(this, a);
        };
    }

    if (navigator && typeof navigator.sendBeacon === 'function') {
        var beacon = navigator.sendBeacon.bind(navigator);
        navigator.sendBeacon = function (url, data) {
            return beacon(toIpApiUrl(url), data);
        };
    }
})();
