(function(){
  // Detect base path robustly: derive prefix before '/modules/' if present,
  // otherwise fall back to project directory. Handles '/profixcrm/simple_crm'.
  var base = window.APP_BASE_PATH;
  if (!base) {
    try {
      var p = window.location.pathname || '';
      var idxMod = p.indexOf('/modules/');
      if (idxMod > 0) {
        base = p.slice(0, idxMod);
      } else {
        // If path contains '/simple_crm', use full prefix including parent (e.g., '/profixcrm/simple_crm')
        var idxCrm = p.indexOf('/simple_crm');
        if (idxCrm >= 0) {
          // include '/simple_crm' segment and any parent folder
          base = p.slice(0, idxCrm + '/simple_crm'.length);
        } else {
          // Fallback to directory of current path
          var idx = p.lastIndexOf('/');
          base = idx > 0 ? p.slice(0, idx) : '';
        }
      }
    } catch(e) {
      base = '';
    }
    window.APP_BASE_PATH = base;
  }

  // Normalize APP_BASE_PATH to avoid trailing slash issues
  if (typeof window.APP_BASE_PATH === 'string' && window.APP_BASE_PATH.endsWith('/')) {
    window.APP_BASE_PATH = window.APP_BASE_PATH.slice(0, -1);
  }

  var origFetch = window.fetch;
  window.fetch = function(input, init){
    try {
      var url = (typeof input === 'string') ? input : (input && input.url);
      var isModulesPath = url && (url.indexOf('/modules/') === 0 || url.indexOf('modules/') === 0);
      if (isModulesPath) {
        var path = (url.indexOf('/modules/') === 0) ? url : ('/' + url);
        var basePrefix = window.APP_BASE_PATH || '';
        // Prevent double-prefix when path already includes base
        var newUrl = (basePrefix && path.indexOf(basePrefix + '/') === 0) ? path : (basePrefix ? (basePrefix + path) : path);
        if (typeof input === 'string') {
          var nextInit = init || {};
          if (!('credentials' in nextInit)) nextInit.credentials = 'same-origin';
          if (!nextInit.headers) nextInit.headers = {};
          if (!('Accept' in nextInit.headers)) nextInit.headers['Accept'] = 'application/json';
          return origFetch(newUrl, nextInit);
        } else {
          var nextInitObj = Object.assign({}, init || {});
          if (!('credentials' in nextInitObj)) nextInitObj.credentials = 'same-origin';
          if (!nextInitObj.headers) nextInitObj.headers = {};
          if (!('Accept' in nextInitObj.headers)) nextInitObj.headers['Accept'] = 'application/json';
          var req = new Request(newUrl, nextInitObj);
          return origFetch(req);
        }
      }
    } catch(e) { /* swallow and continue */ }
    return origFetch(input, init);
  };
})();
