// Injected into proxied HTML to intercept fetch/XHR/WebSocket so absolute paths
// go through the proxy instead of hitting the host server directly.
// Also injects JWT auth headers from localStorage for authenticated requests.
export const proxyOverrideScript = (base: string) =>
  `<script>(function(){` +
  `var b=${JSON.stringify(base)},o=location.origin;` +
  `function gt(){try{return localStorage.getItem("BEARER_TOKEN")||localStorage.getItem("PERTENTO_EDITOR_AUTH_TOKEN")}catch(e){return null}}` +
  `function rw(u){` +
  `if(typeof u==="string"){` +
  `if(u.startsWith("/")&&!u.startsWith("//")&&!u.startsWith(b))return b+u;` +
  `if(u.startsWith(o+"/")&&!u.startsWith(o+b))return o+b+u.slice(o.length);` +
  `return u}` +
  `if(u instanceof URL&&u.origin===o&&!u.pathname.startsWith(b))` +
  `return new URL(o+b+u.pathname+u.search+u.hash);` +
  `if(u instanceof Request){var p=new URL(u.url);` +
  `if(p.origin===o&&!p.pathname.startsWith(b))` +
  `return new Request(o+b+p.pathname+p.search+p.hash,u)}` +
  `return u}` +
  `var F=window.fetch;window.fetch=function(i,n){` +
  `var t=gt();if(t){n=n||{};var h=new Headers(n.headers||{});` +
  `if(!h.has("Authorization"))h.set("Authorization","Bearer "+t);n.headers=h}` +
  `return F.call(this,rw(i),n)};` +
  `var XO=XMLHttpRequest.prototype.open,XS=XMLHttpRequest.prototype.send;` +
  `XMLHttpRequest.prototype.open=function(){arguments[1]=rw(arguments[1]);this._authSet=false;return XO.apply(this,arguments)};` +
  `XMLHttpRequest.prototype.send=function(d){` +
  `if(!this._authSet){var t=gt();if(t)try{this.setRequestHeader("Authorization","Bearer "+t)}catch(e){}}` +
  `return XS.call(this,d)};` +
  `var NWS=window.WebSocket;window.WebSocket=function(u,p){` +
  `if(typeof u==="string"&&(u.startsWith("ws://"+location.host)||u.startsWith("wss://"+location.host)||u.startsWith("/"))){` +
  `var t=gt();if(t){var sep=u.indexOf("?")>-1?"&":"?";u=u+sep+"token="+encodeURIComponent(t)}}` +
  `return p!==undefined?new NWS(u,p):new NWS(u)};` +
  `window.WebSocket.prototype=NWS.prototype;window.WebSocket.CONNECTING=NWS.CONNECTING;` +
  `window.WebSocket.OPEN=NWS.OPEN;window.WebSocket.CLOSING=NWS.CLOSING;window.WebSocket.CLOSED=NWS.CLOSED;` +
  `})()</script>`;

// HTML: rewrite src/href/action attributes with absolute paths + inject fetch/XHR override
export const rewriteHtml = (html: string, base: string) =>
  html
    .replace(/<head([^>]*)>/i, `<head$1>${proxyOverrideScript(base)}`)
    .replace(/(href|src|action)="\/(?!\/)/g, `$1="${base}/`)
    .replace(/(href|src|action)='\/(?!\/)/g, `$1='${base}/`)
    .replace(/url\(\//g, `url(${base}/`);

// JS/CSS: only rewrite /_bun/ asset paths (Bun dev server specific)
export const rewriteAssetPaths = (text: string, base: string) =>
  text.replace(/\/_bun\//g, `${base}/_bun/`);
