import { config } from '../config';

/**
 * Synchronous script injected at the start of <head> so cart gRPC and analytics
 * cannot call native fetch/XHR before our origin rewrites load at </body>.
 */
export function buildEarlyNetworkGuard(): string {
  const wishlistPrefix = config.intercept.wishlistApiProxyPrefix;
  const zowiePrefix = config.intercept.zowieProxyPrefix;
  const archPrefix = config.intercept.archProxyPrefix;

  return `<script data-proxy="early">(function(){
  var p=location.pathname;
  if(p==='/pl/pl/checkout/cart')location.replace('/pl/pl/checkout/cart/');
  else if(p==='/pl/pl/checkout/order')location.replace('/pl/pl/checkout/order/');

  var SINSAY_RE=/^https?:\\/\\/(?:www\\.)?sinsay\\.com/i;
  var FASTEND_RE=/^https?:\\/\\/fastend\\.sinsay\\.com/i;
  var ARCH_RE=/^https?:\\/\\/arch\\.sinsay\\.com/i;
  var WISHLIST_API_RE=/^https?:\\/\\/wishlist-api\\.sinsay\\.com/i;
  var GETZOWIE_RE=/^https?:\\/\\/(?:eu1\\.)?chat\\.getzowie\\.com/i;
  var TRACKER_RE=/googleads\\.g\\.doubleclick\\.net|googleadservices\\.com|googletagmanager\\.com|google-analytics\\.com|doubleclick\\.net|facebook\\.com|connect\\.facebook\\.net|bat\\.bing\\.com|analytics\\.tiktok\\.com/i;

  function isTracker(u){try{return TRACKER_RE.test(String(u));}catch(e){return false;}}
  var PROTO_REL_SINSAY_RE=/^\\/\\/(?:www\\.)?sinsay\\.com/i;
  var PROTO_REL_FASTEND_RE=/^\\/\\/fastend\\.sinsay\\.com/i;
  var PROTO_REL_ARCH_RE=/^\\/\\/arch\\.sinsay\\.com/i;
  function fixLocalDevProto(u){
    if(typeof u!=='string'||!u)return u;
    return u.replace(/^https:\\/\\/(localhost|127(?:\\.\\d+){3})(?=[:/]|$)/i,'http://$1');
  }
  function normaliseUrl(u){
    if(typeof u!=='string')return u;
    return fixLocalDevProto(u
      .replace(SINSAY_RE,'')
      .replace(FASTEND_RE,'')
      .replace(ARCH_RE,'${archPrefix}')
      .replace(PROTO_REL_SINSAY_RE,'')
      .replace(PROTO_REL_FASTEND_RE,'')
      .replace(PROTO_REL_ARCH_RE,'${archPrefix}')
      .replace(WISHLIST_API_RE,'${wishlistPrefix}')
      .replace(GETZOWIE_RE,'${zowiePrefix}'));
  }
  function noopFetch(){return Promise.resolve(new Response('',{status:204,statusText:'No Content'}));}

  function forwardFetch(input,init){
    var url=input instanceof Request?input.url:String(input);
    if(isTracker(url))return noopFetch();
    var norm=normaliseUrl(url);
    if(!(input instanceof Request)){
      return nativeFetch(norm!==url?norm:input,init);
    }
    if(norm===url)return nativeFetch(input,init);
    var m=input.method;
    var base={
      method:m,
      headers:input.headers,
      mode:input.mode,
      credentials:input.credentials,
      cache:input.cache,
      redirect:input.redirect,
      referrer:input.referrer,
      integrity:input.integrity,
      keepalive:input.keepalive,
      signal:(init&&init.signal)||input.signal
    };
    if(m==='GET'||m==='HEAD'||input.body==null){
      return nativeFetch(norm,base);
    }
    return input.clone().arrayBuffer().then(function(buf){
      var opts=base;
      if(buf&&buf.byteLength)opts.body=buf;
      return nativeFetch(norm,opts);
    });
  }
  var nativeFetch=window.fetch.bind(window);
  window.fetch=function(input,init){return forwardFetch(input,init);};

  if(navigator.sendBeacon){
    var nativeBeacon=navigator.sendBeacon.bind(navigator);
    navigator.sendBeacon=function(url,data){
      if(isTracker(url))return true;
      return nativeBeacon(normaliseUrl(String(url)),data);
    };
  }

  try{
    var imgSrc=Object.getOwnPropertyDescriptor(HTMLImageElement.prototype,'src');
    if(imgSrc&&imgSrc.set){
      Object.defineProperty(HTMLImageElement.prototype,'src',{
        configurable:true,
        enumerable:imgSrc.enumerable,
        get:imgSrc.get,
        set:function(v){if(isTracker(v))return;return imgSrc.set.call(this,v);}
      });
    }
  }catch(e){}

  var XHR=window.XMLHttpRequest;
  if(XHR&&XHR.prototype&&XHR.prototype.open){
    var nativeOpen=XHR.prototype.open;
    XHR.prototype.open=function(method,url){
      var raw=String(url);
      if(isTracker(raw)){
        this.__trackerNoop=true;
        return nativeOpen.call(this,method,'about:blank');
      }
      var args=Array.prototype.slice.call(arguments);
      args[1]=normaliseUrl(raw);
      return nativeOpen.apply(this,args);
    };
    var nativeSend=XHR.prototype.send;
    XHR.prototype.send=function(body){
      if(this.__trackerNoop){
        try{Object.defineProperty(this,'status',{value:204});}catch(e){}
        try{Object.defineProperty(this,'readyState',{value:4});}catch(e){}
        if(typeof this.onreadystatechange==='function')this.onreadystatechange();
        if(typeof this.onload==='function')this.onload();
        return;
      }
      return nativeSend.apply(this,arguments);
    };
  }

  // Guest cart session (frontend + fastend cookies) — required before AddProduct.
  fetch('/pl/pl/varnish/ajax/newindex/',{credentials:'include'}).catch(function(){});
})();</script>`;
}
