tide-commander 0.84.1 → 0.84.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/browser-ponyfill-DIm4hKhx.js","assets/vendor-react-uS-d4TUT.js","assets/web-BUCfmE4M.js","assets/modulepreload-polyfill-B5Qt9EMX.js","assets/vendor-three-DJ4p3FLF.js"])))=>i.map(i=>d[i]);
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/browser-ponyfill-DIm4hKhx.js","assets/vendor-react-uS-d4TUT.js","assets/web-GtGat3e7.js","assets/modulepreload-polyfill-B5Qt9EMX.js","assets/vendor-three-DJ4p3FLF.js"])))=>i.map(i=>d[i]);
2
2
  var JD=Object.defineProperty;var eP=(s,e,t)=>e in s?JD(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var U=(s,e,t)=>eP(s,typeof e!="symbol"?e+"":e,t);import"./modulepreload-polyfill-B5Qt9EMX.js";import{r as mx,g as vd,a as EA,c as xS}from"./vendor-react-uS-d4TUT.js";import{T as tP,a as sy,b as _A,L as DA,c as Xu,F as Tp,M as zi,V as zs,C as Gt,d as Ii,S as ii,e as nP,P as PA,D as uc,f as sl,g as gt,I as ur,Q as al,h as sP,O as RA,i as fx,j as aP,B as ri,k as iP,l as Zu,N as rP,m as oP,n as lP,o as zn,p as LA,R as Wo,q as cP,r as uP,s as pm,t as hr,u as qo,v as dt,w as Ts,x as Ke,y as dP,z as Wa,A as ay,E as De,G as gx,H as eo,J as hP,K as wd,U as Fn,W as bx,X as yx,Y as OA,Z as pP,_ as mP,$ as fP,a0 as gP,a1 as IA,a2 as bP,a3 as vS,a4 as wS,a5 as kS,a6 as SS,a7 as iy,a8 as BA,a9 as yP,aa as Ep,ab as xP,ac as vP,ad as Qu,ae as ry,af as Un,ag as Xn,ah as il,ai as ss,aj as Gn,ak as wP,al as zA,am as kP,an as SP,ao as pr,ap as rl,aq as Yt,ar as FA,as as un,at as bc,au as jS,av as jP,aw as xx,ax as CP,ay as NP,az as bp,aA as _p,aB as oy,aC as dc,aD as $A,aE as CS,aF as AP,aG as MP,aH as Xo,aI as ic,aJ as TP,aK as NS,aL as ly,aM as EP,aN as _P,aO as DP,aP as PP,aQ as HA,aR as vx,aS as UA,aT as RP,aU as LP}from"./vendor-three-DJ4p3FLF.js";function OP(s,e){for(var t=0;t<e.length;t++){const n=e[t];if(typeof n!="string"&&!Array.isArray(n)){for(const a in n)if(a!=="default"&&!(a in s)){const i=Object.getOwnPropertyDescriptor(n,a);i&&Object.defineProperty(s,a,i.get?i:{enumerable:!0,get:()=>n[a]})}}}return Object.freeze(Object.defineProperty(s,Symbol.toStringTag,{value:"Module"}))}var Gg={exports:{}},Cu={};/**
3
3
  * @license React
4
4
  * react-jsx-runtime.production.js
@@ -39,7 +39,7 @@ Error generating stack: `+v.message+`
39
39
  *
40
40
  * This source code is licensed under the MIT license found in the
41
41
  * LICENSE file in the root directory of this source tree.
42
- */var KS;function jR(){if(KS)return Qg;KS=1;var s=mx();function e(p,f){return p===f&&(p!==0||1/p===1/f)||p!==p&&f!==f}var t=typeof Object.is=="function"?Object.is:e,n=s.useState,a=s.useEffect,i=s.useLayoutEffect,o=s.useDebugValue;function l(p,f){var b=f(),x=n({inst:{value:b,getSnapshot:f}}),w=x[0].inst,k=x[1];return i(function(){w.value=b,w.getSnapshot=f,c(w)&&k({inst:w})},[p,b,f]),a(function(){return c(w)&&k({inst:w}),p(function(){c(w)&&k({inst:w})})},[p]),o(b),b}function c(p){var f=p.getSnapshot;p=p.value;try{var b=f();return!t(p,b)}catch{return!0}}function d(p,f){return f()}var m=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?d:l;return Qg.useSyncExternalStore=s.useSyncExternalStore!==void 0?s.useSyncExternalStore:m,Qg}var XS;function CR(){return XS||(XS=1,Zg.exports=jR()),Zg.exports}var NR=CR();const AR=(s,e)=>ol(e)?e:hR(e)&&ol(e.defaultValue)?e.defaultValue:Array.isArray(s)?s[s.length-1]:s,MR={t:AR,ready:!1},TR=()=>()=>{},$e=(s,e={})=>{var D,E,R;const{i18n:t}=e,{i18n:n,defaultNS:a}=y.useContext(kR)||{},i=t||n||vR();i&&!i.reportNamespaces&&(i.reportNamespaces=new SR),i||VA(i,"NO_I18NEXT_INSTANCE","useTranslation: You will need to pass in an i18next instance by using initReactI18next");const o=y.useMemo(()=>{var O;return{...yR(),...(O=i==null?void 0:i.options)==null?void 0:O.react,...e}},[i,e]),{useSuspense:l,keyPrefix:c}=o,d=s||a||((D=i==null?void 0:i.options)==null?void 0:D.defaultNS),m=ol(d)?[d]:d||["translation"],p=y.useMemo(()=>m,m);(R=(E=i==null?void 0:i.reportNamespaces)==null?void 0:E.addUsedNamespaces)==null||R.call(E,p);const f=y.useRef(0),b=y.useCallback(O=>{if(!i)return TR;const{bindI18n:I,bindI18nStore:B}=o,Y=()=>{f.current+=1,O()};return I&&i.on(I,Y),B&&i.store.on(B,Y),()=>{I&&I.split(" ").forEach($=>i.off($,Y)),B&&B.split(" ").forEach($=>i.store.off($,Y))}},[i,o]),x=y.useRef(),w=y.useCallback(()=>{if(!i)return MR;const O=!!(i.isInitialized||i.initializedStoreOnce)&&p.every(K=>dR(K,i,o)),I=e.lng||i.language,B=f.current,Y=x.current;if(Y&&Y.ready===O&&Y.lng===I&&Y.keyPrefix===c&&Y.revision===B)return Y;const W={t:i.getFixedT(I,o.nsMode==="fallback"?p:p[0],c),ready:O,lng:I,keyPrefix:c,revision:B};return x.current=W,W},[i,p,c,o,e.lng]),[k,S]=y.useState(0),{t:j,ready:C}=NR.useSyncExternalStore(b,w,w);y.useEffect(()=>{if(i&&!C&&!l){const O=()=>S(I=>I+1);e.lng?VS(i,e.lng,p,O):dy(i,p,O)}},[i,e.lng,p,C,l,k]);const N=i||{},P=y.useRef(null),_=y.useRef(),L=O=>{const I=Object.getOwnPropertyDescriptors(O);I.__original&&delete I.__original;const B=Object.create(Object.getPrototypeOf(O),I);if(!Object.prototype.hasOwnProperty.call(B,"__original"))try{Object.defineProperty(B,"__original",{value:O,writable:!1,enumerable:!1,configurable:!1})}catch{}return B},M=y.useMemo(()=>{const O=N,I=O==null?void 0:O.language;let B=O;O&&(P.current&&P.current.__original===O?_.current!==I?(B=L(O),P.current=B,_.current=I):B=P.current:(B=L(O),P.current=B,_.current=I));const Y=[j,B,C];return Y.t=j,Y.i18n=B,Y.ready=C,Y},[j,N,C,N.resolvedLanguage,N.language,N.languages]);if(i&&l&&!C)throw new Promise(O=>{const I=()=>O();e.lng?VS(i,e.lng,p,I):dy(i,p,I)});return M};function py(s){"@babel/helpers - typeof";return py=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},py(s)}function ZA(){return typeof XMLHttpRequest=="function"||(typeof XMLHttpRequest>"u"?"undefined":py(XMLHttpRequest))==="object"}function ER(s){return!!s&&typeof s.then=="function"}function _R(s){return ER(s)?s:Promise.resolve(s)}const DR="modulepreload",PR=function(s){return"/"+s},ZS={},QA=function(e,t,n){let a=Promise.resolve();if(t&&t.length>0){let o=function(d){return Promise.all(d.map(m=>Promise.resolve(m).then(p=>({status:"fulfilled",value:p}),p=>({status:"rejected",reason:p}))))};document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),c=(l==null?void 0:l.nonce)||(l==null?void 0:l.getAttribute("nonce"));a=o(t.map(d=>{if(d=PR(d),d in ZS)return;ZS[d]=!0;const m=d.endsWith(".css"),p=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${p}`))return;const f=document.createElement("link");if(f.rel=m?"stylesheet":DR,m||(f.as="script"),f.crossOrigin="",f.href=d,c&&f.setAttribute("nonce",c),document.head.appendChild(f),m)return new Promise((b,x)=>{f.addEventListener("load",b),f.addEventListener("error",()=>x(new Error(`Unable to preload CSS for ${d}`)))})}))}function i(o){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=o,window.dispatchEvent(l),!l.defaultPrevented)throw o}return a.then(o=>{for(const l of o||[])l.status==="rejected"&&i(l.reason);return e().catch(i)})};function QS(s,e){var t=Object.keys(s);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(s);e&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),t.push.apply(t,n)}return t}function JS(s){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?QS(Object(t),!0).forEach(function(n){RR(s,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(t)):QS(Object(t)).forEach(function(n){Object.defineProperty(s,n,Object.getOwnPropertyDescriptor(t,n))})}return s}function RR(s,e,t){return(e=LR(e))in s?Object.defineProperty(s,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):s[e]=t,s}function LR(s){var e=OR(s,"string");return ll(e)=="symbol"?e:e+""}function OR(s,e){if(ll(s)!="object"||!s)return s;var t=s[Symbol.toPrimitive];if(t!==void 0){var n=t.call(s,e);if(ll(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(s)}function ll(s){"@babel/helpers - typeof";return ll=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},ll(s)}var lo=typeof fetch=="function"?fetch:void 0;typeof global<"u"&&global.fetch?lo=global.fetch:typeof window<"u"&&window.fetch&&(lo=window.fetch);var cd;ZA()&&(typeof global<"u"&&global.XMLHttpRequest?cd=global.XMLHttpRequest:typeof window<"u"&&window.XMLHttpRequest&&(cd=window.XMLHttpRequest));var Lp;typeof ActiveXObject=="function"&&(typeof global<"u"&&global.ActiveXObject?Lp=global.ActiveXObject:typeof window<"u"&&window.ActiveXObject&&(Lp=window.ActiveXObject));typeof lo!="function"&&(lo=void 0);if(!lo&&!cd&&!Lp)try{QA(()=>import("./browser-ponyfill-DIm4hKhx.js").then(s=>s.b),__vite__mapDeps([0,1])).then(function(s){lo=s.default}).catch(function(){})}catch{}var my=function(e,t){if(t&&ll(t)==="object"){var n="";for(var a in t)n+="&"+encodeURIComponent(a)+"="+encodeURIComponent(t[a]);if(!n)return e;e=e+(e.indexOf("?")!==-1?"&":"?")+n.slice(1)}return e},ej=function(e,t,n,a){var i=function(c){if(!c.ok)return n(c.statusText||"Error",{status:c.status});c.text().then(function(d){n(null,{status:c.status,data:d})}).catch(n)};if(a){var o=a(e,t);if(o instanceof Promise){o.then(i).catch(n);return}}typeof fetch=="function"?fetch(e,t).then(i).catch(n):lo(e,t).then(i).catch(n)},tj=!1,IR=function(e,t,n,a){e.queryStringParams&&(t=my(t,e.queryStringParams));var i=JS({},typeof e.customHeaders=="function"?e.customHeaders():e.customHeaders);typeof window>"u"&&typeof global<"u"&&typeof global.process<"u"&&global.process.versions&&global.process.versions.node&&(i["User-Agent"]="i18next-http-backend (node/".concat(global.process.version,"; ").concat(global.process.platform," ").concat(global.process.arch,")")),n&&(i["Content-Type"]="application/json");var o=typeof e.requestOptions=="function"?e.requestOptions(n):e.requestOptions,l=JS({method:n?"POST":"GET",body:n?e.stringify(n):void 0,headers:i},tj?{}:o),c=typeof e.alternateFetch=="function"&&e.alternateFetch.length>=1?e.alternateFetch:void 0;try{ej(t,l,a,c)}catch(d){if(!o||Object.keys(o).length===0||!d.message||d.message.indexOf("not implemented")<0)return a(d);try{Object.keys(o).forEach(function(m){delete l[m]}),ej(t,l,a,c),tj=!0}catch(m){a(m)}}},BR=function(e,t,n,a){n&&ll(n)==="object"&&(n=my("",n).slice(1)),e.queryStringParams&&(t=my(t,e.queryStringParams));try{var i=cd?new cd:new Lp("MSXML2.XMLHTTP.3.0");i.open(n?"POST":"GET",t,1),e.crossDomain||i.setRequestHeader("X-Requested-With","XMLHttpRequest"),i.withCredentials=!!e.withCredentials,n&&i.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),i.overrideMimeType&&i.overrideMimeType("application/json");var o=e.customHeaders;if(o=typeof o=="function"?o():o,o)for(var l in o)i.setRequestHeader(l,o[l]);i.onreadystatechange=function(){i.readyState>3&&a(i.status>=400?i.statusText:null,{status:i.status,data:i.responseText})},i.send(n)}catch(c){console&&console.log(c)}},zR=function(e,t,n,a){if(typeof n=="function"&&(a=n,n=void 0),a=a||function(){},lo&&t.indexOf("file:")!==0)return IR(e,t,n,a);if(ZA()||typeof ActiveXObject=="function")return BR(e,t,n,a);a(new Error("No fetch and no xhr implementation found!"))};function yc(s){"@babel/helpers - typeof";return yc=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},yc(s)}function nj(s,e){var t=Object.keys(s);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(s);e&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),t.push.apply(t,n)}return t}function Jg(s){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?nj(Object(t),!0).forEach(function(n){JA(s,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(t)):nj(Object(t)).forEach(function(n){Object.defineProperty(s,n,Object.getOwnPropertyDescriptor(t,n))})}return s}function FR(s,e){if(!(s instanceof e))throw new TypeError("Cannot call a class as a function")}function $R(s,e){for(var t=0;t<e.length;t++){var n=e[t];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(s,eM(n.key),n)}}function HR(s,e,t){return e&&$R(s.prototype,e),Object.defineProperty(s,"prototype",{writable:!1}),s}function JA(s,e,t){return(e=eM(e))in s?Object.defineProperty(s,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):s[e]=t,s}function eM(s){var e=UR(s,"string");return yc(e)=="symbol"?e:e+""}function UR(s,e){if(yc(s)!="object"||!s)return s;var t=s[Symbol.toPrimitive];if(t!==void 0){var n=t.call(s,e);if(yc(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(s)}var GR=function(){return{loadPath:"/locales/{{lng}}/{{ns}}.json",addPath:"/locales/add/{{lng}}/{{ns}}",parse:function(t){return JSON.parse(t)},stringify:JSON.stringify,parsePayload:function(t,n,a){return JA({},n,a||"")},parseLoadPayload:function(t,n){},request:zR,reloadInterval:typeof window<"u"?!1:3600*1e3,customHeaders:{},queryStringParams:{},crossDomain:!1,withCredentials:!1,overrideMimeType:!1,requestOptions:{mode:"cors",credentials:"same-origin",cache:"default"}}},tM=(function(){function s(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};FR(this,s),this.services=e,this.options=t,this.allOptions=n,this.type="backend",this.init(e,t,n)}return HR(s,[{key:"init",value:function(t){var n=this,a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(this.services=t,this.options=Jg(Jg(Jg({},GR()),this.options||{}),a),this.allOptions=i,this.services&&this.options.reloadInterval){var o=setInterval(function(){return n.reload()},this.options.reloadInterval);yc(o)==="object"&&typeof o.unref=="function"&&o.unref()}}},{key:"readMulti",value:function(t,n,a){this._readAny(t,t,n,n,a)}},{key:"read",value:function(t,n,a){this._readAny([t],t,[n],n,a)}},{key:"_readAny",value:function(t,n,a,i,o){var l=this,c=this.options.loadPath;typeof this.options.loadPath=="function"&&(c=this.options.loadPath(t,a)),c=_R(c),c.then(function(d){if(!d)return o(null,{});var m=l.services.interpolator.interpolate(d,{lng:t.join("+"),ns:a.join("+")});l.loadUrl(m,o,n,i)})}},{key:"loadUrl",value:function(t,n,a,i){var o=this,l=typeof a=="string"?[a]:a,c=typeof i=="string"?[i]:i,d=this.options.parseLoadPayload(l,c);this.options.request(this.options,t,d,function(m,p){if(p&&(p.status>=500&&p.status<600||!p.status))return n("failed loading "+t+"; status code: "+p.status,!0);if(p&&p.status>=400&&p.status<500)return n("failed loading "+t+"; status code: "+p.status,!1);if(!p&&m&&m.message){var f=m.message.toLowerCase(),b=["failed","fetch","network","load"].find(function(k){return f.indexOf(k)>-1});if(b)return n("failed loading "+t+": "+m.message,!0)}if(m)return n(m,!1);var x,w;try{typeof p.data=="string"?x=o.options.parse(p.data,a,i):x=p.data}catch{w="failed parsing "+t+" to json"}if(w)return n(w,!1);n(null,x)})}},{key:"create",value:function(t,n,a,i,o){var l=this;if(this.options.addPath){typeof t=="string"&&(t=[t]);var c=this.options.parsePayload(n,a,i),d=0,m=[],p=[];t.forEach(function(f){var b=l.options.addPath;typeof l.options.addPath=="function"&&(b=l.options.addPath(f,n));var x=l.services.interpolator.interpolate(b,{lng:f,ns:n});l.options.request(l.options,x,c,function(w,k){d+=1,m.push(w),p.push(k),d===t.length&&typeof o=="function"&&o(m,p)})})}}},{key:"reload",value:function(){var t=this,n=this.services,a=n.backendConnector,i=n.languageUtils,o=n.logger,l=a.language;if(!(l&&l.toLowerCase()==="cimode")){var c=[],d=function(p){var f=i.toResolveHierarchy(p);f.forEach(function(b){c.indexOf(b)<0&&c.push(b)})};d(l),this.allOptions.preload&&this.allOptions.preload.forEach(function(m){return d(m)}),c.forEach(function(m){t.allOptions.ns.forEach(function(p){a.read(m,p,"read",null,null,function(f,b){f&&o.warn("loading namespace ".concat(p," for language ").concat(m," failed"),f),!f&&b&&o.log("loaded namespace ".concat(p," for language ").concat(m),b),a.loaded("".concat(m,"|").concat(p),f,b)})})})}}}])})();tM.type="backend";const{slice:WR,forEach:qR}=[];function YR(s){return qR.call(WR.call(arguments,1),e=>{if(e)for(const t in e)s[t]===void 0&&(s[t]=e[t])}),s}function VR(s){return typeof s!="string"?!1:[/<\s*script.*?>/i,/<\s*\/\s*script\s*>/i,/<\s*img.*?on\w+\s*=/i,/<\s*\w+\s*on\w+\s*=.*?>/i,/javascript\s*:/i,/vbscript\s*:/i,/expression\s*\(/i,/eval\s*\(/i,/alert\s*\(/i,/document\.cookie/i,/document\.write\s*\(/i,/window\.location/i,/innerHTML/i].some(t=>t.test(s))}const sj=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/,KR=function(s,e){const n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{path:"/"},a=encodeURIComponent(e);let i=`${s}=${a}`;if(n.maxAge>0){const o=n.maxAge-0;if(Number.isNaN(o))throw new Error("maxAge should be a Number");i+=`; Max-Age=${Math.floor(o)}`}if(n.domain){if(!sj.test(n.domain))throw new TypeError("option domain is invalid");i+=`; Domain=${n.domain}`}if(n.path){if(!sj.test(n.path))throw new TypeError("option path is invalid");i+=`; Path=${n.path}`}if(n.expires){if(typeof n.expires.toUTCString!="function")throw new TypeError("option expires is invalid");i+=`; Expires=${n.expires.toUTCString()}`}if(n.httpOnly&&(i+="; HttpOnly"),n.secure&&(i+="; Secure"),n.sameSite)switch(typeof n.sameSite=="string"?n.sameSite.toLowerCase():n.sameSite){case!0:i+="; SameSite=Strict";break;case"lax":i+="; SameSite=Lax";break;case"strict":i+="; SameSite=Strict";break;case"none":i+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}return n.partitioned&&(i+="; Partitioned"),i},aj={create(s,e,t,n){let a=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{path:"/",sameSite:"strict"};t&&(a.expires=new Date,a.expires.setTime(a.expires.getTime()+t*60*1e3)),n&&(a.domain=n),document.cookie=KR(s,e,a)},read(s){const e=`${s}=`,t=document.cookie.split(";");for(let n=0;n<t.length;n++){let a=t[n];for(;a.charAt(0)===" ";)a=a.substring(1,a.length);if(a.indexOf(e)===0)return a.substring(e.length,a.length)}return null},remove(s,e){this.create(s,"",-1,e)}};var XR={name:"cookie",lookup(s){let{lookupCookie:e}=s;if(e&&typeof document<"u")return aj.read(e)||void 0},cacheUserLanguage(s,e){let{lookupCookie:t,cookieMinutes:n,cookieDomain:a,cookieOptions:i}=e;t&&typeof document<"u"&&aj.create(t,s,n,a,i)}},ZR={name:"querystring",lookup(s){var n;let{lookupQuerystring:e}=s,t;if(typeof window<"u"){let{search:a}=window.location;!window.location.search&&((n=window.location.hash)==null?void 0:n.indexOf("?"))>-1&&(a=window.location.hash.substring(window.location.hash.indexOf("?")));const o=a.substring(1).split("&");for(let l=0;l<o.length;l++){const c=o[l].indexOf("=");c>0&&o[l].substring(0,c)===e&&(t=o[l].substring(c+1))}}return t}},QR={name:"hash",lookup(s){var a;let{lookupHash:e,lookupFromHashIndex:t}=s,n;if(typeof window<"u"){const{hash:i}=window.location;if(i&&i.length>2){const o=i.substring(1);if(e){const l=o.split("&");for(let c=0;c<l.length;c++){const d=l[c].indexOf("=");d>0&&l[c].substring(0,d)===e&&(n=l[c].substring(d+1))}}if(n)return n;if(!n&&t>-1){const l=i.match(/\/([a-zA-Z-]*)/g);return Array.isArray(l)?(a=l[typeof t=="number"?t:0])==null?void 0:a.replace("/",""):void 0}}}return n}};let Yl=null;const ij=()=>{if(Yl!==null)return Yl;try{if(Yl=typeof window<"u"&&window.localStorage!==null,!Yl)return!1;const s="i18next.translate.boo";window.localStorage.setItem(s,"foo"),window.localStorage.removeItem(s)}catch{Yl=!1}return Yl};var JR={name:"localStorage",lookup(s){let{lookupLocalStorage:e}=s;if(e&&ij())return window.localStorage.getItem(e)||void 0},cacheUserLanguage(s,e){let{lookupLocalStorage:t}=e;t&&ij()&&window.localStorage.setItem(t,s)}};let Vl=null;const rj=()=>{if(Vl!==null)return Vl;try{if(Vl=typeof window<"u"&&window.sessionStorage!==null,!Vl)return!1;const s="i18next.translate.boo";window.sessionStorage.setItem(s,"foo"),window.sessionStorage.removeItem(s)}catch{Vl=!1}return Vl};var eL={name:"sessionStorage",lookup(s){let{lookupSessionStorage:e}=s;if(e&&rj())return window.sessionStorage.getItem(e)||void 0},cacheUserLanguage(s,e){let{lookupSessionStorage:t}=e;t&&rj()&&window.sessionStorage.setItem(t,s)}},tL={name:"navigator",lookup(s){const e=[];if(typeof navigator<"u"){const{languages:t,userLanguage:n,language:a}=navigator;if(t)for(let i=0;i<t.length;i++)e.push(t[i]);n&&e.push(n),a&&e.push(a)}return e.length>0?e:void 0}},nL={name:"htmlTag",lookup(s){let{htmlTag:e}=s,t;const n=e||(typeof document<"u"?document.documentElement:null);return n&&typeof n.getAttribute=="function"&&(t=n.getAttribute("lang")),t}},sL={name:"path",lookup(s){var a;let{lookupFromPathIndex:e}=s;if(typeof window>"u")return;const t=window.location.pathname.match(/\/([a-zA-Z-]*)/g);return Array.isArray(t)?(a=t[typeof e=="number"?e:0])==null?void 0:a.replace("/",""):void 0}},aL={name:"subdomain",lookup(s){var a,i;let{lookupFromSubdomainIndex:e}=s;const t=typeof e=="number"?e+1:1,n=typeof window<"u"&&((i=(a=window.location)==null?void 0:a.hostname)==null?void 0:i.match(/^(\w{2,5})\.(([a-z0-9-]{1,63}\.[a-z]{2,6})|localhost)/i));if(n)return n[t]}};let nM=!1;try{document.cookie,nM=!0}catch{}const sM=["querystring","cookie","localStorage","sessionStorage","navigator","htmlTag"];nM||sM.splice(1,1);const iL=()=>({order:sM,lookupQuerystring:"lng",lookupCookie:"i18next",lookupLocalStorage:"i18nextLng",lookupSessionStorage:"i18nextLng",caches:["localStorage"],excludeCacheFor:["cimode"],convertDetectedLanguage:s=>s});class aM{constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.type="languageDetector",this.detectors={},this.init(e,t)}init(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{languageUtils:{}},t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};this.services=e,this.options=YR(t,this.options||{},iL()),typeof this.options.convertDetectedLanguage=="string"&&this.options.convertDetectedLanguage.indexOf("15897")>-1&&(this.options.convertDetectedLanguage=a=>a.replace("-","_")),this.options.lookupFromUrlIndex&&(this.options.lookupFromPathIndex=this.options.lookupFromUrlIndex),this.i18nOptions=n,this.addDetector(XR),this.addDetector(ZR),this.addDetector(JR),this.addDetector(eL),this.addDetector(tL),this.addDetector(nL),this.addDetector(sL),this.addDetector(aL),this.addDetector(QR)}addDetector(e){return this.detectors[e.name]=e,this}detect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.options.order,t=[];return e.forEach(n=>{if(this.detectors[n]){let a=this.detectors[n].lookup(this.options);a&&typeof a=="string"&&(a=[a]),a&&(t=t.concat(a))}}),t=t.filter(n=>n!=null&&!VR(n)).map(n=>this.options.convertDetectedLanguage(n)),this.services&&this.services.languageUtils&&this.services.languageUtils.getBestMatchFromCodes?t:t.length>0?t[0]:null}cacheUserLanguage(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.options.caches;t&&(this.options.excludeCacheFor&&this.options.excludeCacheFor.indexOf(e)>-1||t.forEach(n=>{this.detectors[n]&&this.detectors[n].cacheUserLanguage(e,this.options)}))}}aM.type="languageDetector";const Op={idle:"#4aff9e",working:"#4a9eff",waiting:"#ff9e4a",waiting_permission:"#ffcc00",error:"#ff4a4a",offline:"#888888",orphaned:"#ff9e4a",default:"#888888"},co={running:"#4aff9e",stopped:"#888888",error:"#ff4a4a",unknown:"#ffaa00",starting:"#4a9eff",stopping:"#ffaa00"},iM={on_track:"#4aff9e",stalled:"#ff9e4a",blocked:"#ff4a4a",completed:"#4a9eff",idle:"#888888"},rL=["#4a9eff","#4aff9e","#ff9e4a","#ff4a9e","#9e4aff","#ff4a4a","#4affff","#ffff4a","#4ad7ff","#00e6a8","#ff6b4a","#ff66cc","#b84aff","#ff4a7a","#00d9ff","#e6ff4a","#1a3a6e","#1a5e3a","#6e3a1a","#6e1a4a","#4a1a6e","#6e1a1a","#1a5e5e","#5e5e1a","#1a4a6e","#145a47","#6e2c1a","#6e1a5e","#3b1a6e","#6e1a33","#14566e","#4f5e1a"],Gh={recent:"#50fa7b",short:"#f1fa8c",medium:"#ffb86c",long:"#ff5555"};function fm(s){const t=Math.floor((Date.now()-s)/1e3)/60;return t<1?Gh.recent:t<5?Gh.short:t<30?Gh.medium:Gh.long}function wx(s){return Op[s]??Op.default}let yp=null;function rM(){if(!yp)try{yp=globalThis.__i18n}catch{}return yp}function oL(s){yp=s}function lL(s){return s>=1e6?(s/1e6).toFixed(1)+"M":s>=1e3?(s/1e3).toFixed(1)+"K":s.toString()}function fy(s){return s>=1e6?(s/1e6).toFixed(1)+"M":s>=1e3?(s/1e3).toFixed(1)+"K":s.toString()}function oM(s){var a;const e=rM(),t=(a=e==null?void 0:e.t)==null?void 0:a.bind(e),n=Math.floor((Date.now()-s)/1e3);return n<60?t?t("common:time.seconds",{count:n}):`${n}s`:n<3600?t?t("common:time.minutes",{count:Math.floor(n/60)}):`${Math.floor(n/60)}m`:n<86400?t?t("common:time.hours",{count:Math.floor(n/3600)}):`${Math.floor(n/3600)}h`:t?t("common:time.days",{count:Math.floor(n/86400)}):`${Math.floor(n/86400)}d`}function gm(s){var d;const e=rM(),t=(d=e==null?void 0:e.t)==null?void 0:d.bind(e),n=Math.floor((Date.now()-s)/1e3);if(n<5)return t?t("common:time.justNow"):"just now";if(n<60)return t?t("common:time.secondsAgo",{count:n}):`${n}s ago`;const a=Math.floor(n/60);if(a<60){const m=n%60;return m>0?t?t("common:time.minutesSecondsAgo",{minutes:a,seconds:m}):`${a}m ${m}s ago`:t?t("common:time.minutesAgo",{count:a}):`${a}m ago`}const i=Math.floor(a/60),o=a%60;if(i<24)return o>0?t?t("common:time.hoursMinutesAgo",{hours:i,minutes:o}):`${i}h ${o}m ago`:t?t("common:time.hoursAgo",{count:i}):`${i}h ago`;const l=Math.floor(i/24),c=i%24;return c>0?t?t("common:time.daysHoursAgo",{days:l,hours:c}):`${l}d ${c}h ago`:t?t("common:time.daysAgo",{count:l}):`${l}d ago`}function io(s,e){return s?e?s.replace(/\s*\(?\s*~?\$[\d,.]+\s*\)?/g,"").replace(/\s*cost[:\s]+~?\$[\d,.]+/gi,"").replace(/\s*price[:\s]+~?\$[\d,.]+/gi,"").replace(/\s*\(~?\$[\d,.]+\s*(?:USD|cost|spent)?\)/gi,"").replace(/\s*-\s*~?\$[\d,.]+\s*$/g,"").replace(/[^\S\n]+/g," ").trim():s:""}wn.use(tM).use(aM).use(wR).init({fallbackLng:"en",ns:["common","tools","config","errors","notifications","dashboard","terminal"],defaultNS:"common",backend:{loadPath:"/locales/{{lng}}/{{ns}}.json"},detection:{order:["localStorage","navigator"],lookupLocalStorage:"tide-commander-language",caches:["localStorage"]},interpolation:{escapeValue:!1},react:{useSuspense:!0}}).then(()=>{oL(wn)});const vt={CONFIG:"tide-commander-config",SHOW_FPS:"tide-show-fps",SETTINGS:"tide-settings",SHORTCUTS:"tide-shortcuts",MOUSE_CONTROLS:"tide-mouse-controls",BACKEND_URL:"tide-backend-url",AUTH_TOKEN:"tide-auth-token",SCENE_VIEW_MODE:"tide-scene-view-mode",CAMERA_STATE:"tide-camera-state",CAMERA_STATE_2D:"tide-camera-state-2d",VIEW_MODE:"guake-view-mode",ADVANCED_VIEW:"guake-advanced-view",TERMINAL_HEIGHT:"guake-terminal-height",INPUT_TEXT_PREFIX:"guake-input-",PASTED_TEXTS_PREFIX:"guake-pasted-",COMMANDER_TAB:"commander-active-tab",COMMANDER_FILTERS:"commander-filters",LAST_CWD:"tide-last-cwd",GLOBAL_SUPERVISOR_COLLAPSED:"tide-global-supervisor-collapsed",TOOLS_COLLAPSED:"tide-tool-history-collapsed",FILES_COLLAPSED:"tide-file-history-collapsed",MOBILE_VIEW:"tide-mobile-view",TREE_PANEL_WIDTH:"tide-tree-panel-width",AGENT_ORDER:"tide-agent-order",AOP_CONFIG:"tide-aop-config",UNSEEN_AGENTS:"tide-unseen-agents"},gy="tide-backend-url-change";function ai(s,e){try{const t=localStorage.getItem(s);return t===null?e:JSON.parse(t)}catch{return e}}function la(s,e=""){try{return localStorage.getItem(s)??e}catch{return e}}function by(s,e=!1){try{const t=localStorage.getItem(s);return t===null?e:t==="true"}catch{return e}}function lM(s,e){try{const t=localStorage.getItem(s);if(t===null)return e;const n=Number(t);return isNaN(n)?e:n}catch{return e}}function Ei(s,e){try{localStorage.setItem(s,JSON.stringify(e))}catch(t){console.error(`Failed to save to localStorage: ${s}`,t)}}function Va(s,e){try{localStorage.setItem(s,e)}catch(t){console.error(`Failed to save to localStorage: ${s}`,t)}}function yy(s,e){try{localStorage.setItem(s,String(e))}catch(t){console.error(`Failed to save to localStorage: ${s}`,t)}}function cM(s,e){try{localStorage.setItem(s,String(e))}catch(t){console.error(`Failed to save to localStorage: ${s}`,t)}}function oj(s){try{localStorage.removeItem(s)}catch(e){console.error(`Failed to remove from localStorage: ${s}`,e)}}function hl(){const s=bm();return s?s.replace(/\/$/,""):`${window.location.protocol}//${window.location.host}`}function hi(){return la(vt.AUTH_TOKEN,"")}function bm(){return la(vt.BACKEND_URL,"")}function uM(s){const e=s.trim();Va(vt.BACKEND_URL,e),typeof window<"u"&&window.dispatchEvent(new CustomEvent(gy,{detail:e}))}function dM(s){if(typeof window>"u")return()=>{};const e=n=>{s(n.detail)},t=n=>{n.key===vt.BACKEND_URL&&s(n.newValue??"")};return window.addEventListener(gy,e),window.addEventListener("storage",t),()=>{window.removeEventListener(gy,e),window.removeEventListener("storage",t)}}function rt(s){return`${hl()}${s}`}async function bt(s,e){const t=hi(),n=new Headers(e==null?void 0:e.headers);return t&&n.set("X-Auth-Token",t),fetch(s,{...e,headers:n})}function kd(s){const e=hi();if(!e)return s;try{const t=!s.startsWith("http://")&&!s.startsWith("https://"),n=t?"http://dummy":void 0,a=new URL(s,n);return a.searchParams.set("token",e),t?a.pathname+a.search:a.toString()}catch{const t=s.includes("?")?"&":"?";return`${s}${t}token=${encodeURIComponent(e)}`}}function Ws(s=!1,e){const[t,n]=y.useState(s),[a,i]=y.useState(e),o=y.useCallback(d=>{d!==void 0&&i(d),n(!0)},[]),l=y.useCallback(()=>{n(!1)},[]),c=y.useCallback(()=>{n(d=>!d)},[]);return{isOpen:t,data:a,open:o,close:l,toggle:c,setData:i}}function cL(){const[s,e]=y.useState(null),t=y.useCallback(a=>{e(a)},[]),n=y.useCallback(()=>{e(null)},[]);return{isOpen:s!==null,id:s,open:t,close:n}}function uL(){const[s,e]=y.useState(!1),[t,n]=y.useState({x:0,y:0}),[a,i]=y.useState({x:0,z:0}),[o,l]=y.useState({type:"ground"}),c=y.useCallback((m,p,f)=>{n(m),i(p),l(f),e(!0)},[]),d=y.useCallback(()=>{e(!1)},[]);return{isOpen:s,screenPosition:t,worldPosition:a,target:o,open:c,close:d}}const si=[],dL=new Set;function Ip(){dL.forEach(s=>s())}function hL(s,e){const t=si.findIndex(n=>n.id===s);return t!==-1&&si.splice(t,1),si.push({id:s,close:e}),Ip(),()=>{const n=si.findIndex(a=>a.id===s);n!==-1&&(si.splice(n,1),Ip())}}function xy(){return si.length===0?!1:(si.pop().close(),Ip(),!0)}function pL(...s){const e=new Set(s);for(;si.length>0;){const t=si[si.length-1];if(e.has(t.id))break;si.pop().close()}Ip()}function En(s,e,t){const n=y.useRef(t);n.current=t,y.useEffect(()=>e?hL(s,()=>n.current()):void 0,[s,e])}let vy,wy;try{vy=require("@capacitor/haptics").Haptics,wy=require("@capacitor/haptics").ImpactStyle}catch{}function lj(s,e){const{threshold:t=80,maxVerticalMovement:n=50,enabled:a=!0,onSwipeLeft:i,onSwipeRight:o,onSwipeMove:l,onSwipeCancel:c}=e,d=y.useRef({startX:0,startY:0,startTime:0,isTracking:!1,hasMovedEnough:!1}),m=y.useCallback(b=>{if(b.touches.length!==1)return;const x=b.touches[0];d.current={startX:x.clientX,startY:x.clientY,startTime:Date.now(),isTracking:!0,hasMovedEnough:!1}},[]),p=y.useCallback(b=>{if(!d.current.isTracking||b.touches.length!==1)return;const x=b.touches[0],w=x.clientX-d.current.startX;if(Math.abs(x.clientY-d.current.startY)>n){d.current.isTracking=!1,d.current.hasMovedEnough&&(c==null||c());return}const j=window.innerWidth*.4,C=Math.max(-1,Math.min(1,w/j));Math.abs(w)>=12&&(d.current.hasMovedEnough=!0,l==null||l(C))},[n,l,c]),f=y.useCallback(b=>{const x=d.current.isTracking,w=d.current.hasMovedEnough;if(!x)return;const k=b.changedTouches[0],S=k.clientX-d.current.startX,j=Math.abs(k.clientY-d.current.startY),C=Date.now()-d.current.startTime;d.current.isTracking=!1,d.current.hasMovedEnough=!1,Math.abs(S)>=t&&j<=n&&C<500?(vy&&wy?vy.impact({style:wy.Light}).catch(()=>{navigator.vibrate&&navigator.vibrate(8)}):navigator.vibrate&&navigator.vibrate(8),S>0?o==null||o():i==null||i()):w&&(c==null||c())},[t,n,i,o,c]);y.useEffect(()=>{const b=s.current;if(!(!b||!a||!(window.innerWidth<=768&&"ontouchstart"in window)))return b.addEventListener("touchstart",m,{passive:!0}),b.addEventListener("touchmove",p,{passive:!0}),b.addEventListener("touchend",f,{passive:!0}),()=>{b.removeEventListener("touchstart",m),b.removeEventListener("touchmove",p),b.removeEventListener("touchend",f)}},[s,a,m,p,f])}const mL={width:400,height:300,copyStyleSheets:!0,keepOnTop:"focus"};function fL(){return"documentPictureInPicture"in window}function gL(s,e){for(const i of s.styleSheets)try{if(i.cssRules){const o=e.createElement("style");for(const l of i.cssRules)o.appendChild(e.createTextNode(l.cssText));e.head.appendChild(o)}}catch{if(i.href){const o=e.createElement("link");o.rel="stylesheet",o.href=i.href,e.head.appendChild(o)}}const t=s.documentElement.style.cssText;t&&(e.documentElement.style.cssText=t);const n=getComputedStyle(s.documentElement),a=[];for(let i=0;i<n.length;i++){const o=n[i];o.startsWith("--")&&a.push(`${o}: ${n.getPropertyValue(o)}`)}if(a.length>0){const i=e.createElement("style");i.textContent=`:root { ${a.join("; ")} }`,e.head.appendChild(i)}}function bL(){const[s,e]=y.useState(!1),[t,n]=y.useState(null),[a,i]=y.useState(null),o=y.useRef(null),l=fL(),c=y.useCallback(()=>{if(o.current){const p=o.current.__cleanupFns;p&&p.forEach(f=>f()),o.current.close(),o.current=null}n(null),i(null),e(!1)},[]),d=y.useCallback(async p=>{if(!l)return console.warn("Document Picture-in-Picture is not supported in this browser"),!1;o.current&&c();const f={...mL,...p};try{const x=await window.documentPictureInPicture.requestWindow({width:f.width,height:f.height,disallowReturnToOpener:!0});o.current=x,f.copyStyleSheets&&gL(document,x.document);const w=x.document.createElement("div");w.id="pip-root",w.style.width="100%",w.style.height="100%",x.document.body.appendChild(w),x.document.body.style.margin="0",x.document.body.style.padding="0",x.document.body.style.overflow="hidden",x.addEventListener("pagehide",()=>{o.current=null,n(null),i(null),e(!1)});const k=[];if(f.keepOnTop&&f.keepOnTop!=="none"){const S=f.keepOnTop==="raise",j=()=>{o.current&&!o.current.closed&&setTimeout(()=>{o.current&&!o.current.closed&&(o.current.focus(),S&&setTimeout(()=>window.focus(),10))},50)},C=()=>{document.visibilityState==="visible"&&o.current&&!o.current.closed&&setTimeout(()=>{o.current&&!o.current.closed&&(o.current.focus(),S&&setTimeout(()=>window.focus(),10))},100)};window.addEventListener("focus",j),document.addEventListener("visibilitychange",C),k.push(()=>window.removeEventListener("focus",j),()=>document.removeEventListener("visibilitychange",C))}return x.__cleanupFns=k,n(x),i(w),e(!0),!0}catch(b){return console.error("Failed to open Picture-in-Picture window:",b),!1}},[l,c]),m=y.useCallback(async p=>{s?c():await d(p)},[s,d,c]);return y.useEffect(()=>()=>{o.current&&o.current.close()},[]),y.useMemo(()=>({isOpen:s,pipWindow:t,pipContainer:a,isSupported:l,open:d,close:c,toggle:m}),[s,t,a,l,d,c,m])}function Mu(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,s=>{const e=Math.random()*16|0;return(s==="x"?e:e&3|8).toString(16)})}class yL{constructor(){U(this,"messages",new Map);U(this,"logs",[]);U(this,"maxMessagesPerAgent",200);U(this,"maxLogs",500);U(this,"enabled",!1);U(this,"listeners",new Set);U(this,"logListeners",new Set)}setEnabled(e){this.enabled=e,this.notifyListeners("all")}isEnabled(){return this.enabled}captureSent(e,t){if(this.enabled)try{const n=JSON.parse(t);console.log(`[AgentDebugger] SENT - agent: ${e.slice(0,4)}, type: ${n.type}, size: ${t.length}B`),this.addMessage(e,{id:Mu(),agentId:e,direction:"sent",type:n.type||"unknown",payload:n.payload||n,timestamp:Date.now(),size:t.length,raw:t})}catch(n){console.error("[AgentDebugger] Failed to parse SENT message:",String(n).slice(0,80)),this.addMessage(e,{id:Mu(),agentId:e,direction:"sent",type:"parse_error",payload:{error:String(n)},timestamp:Date.now(),size:t.length,raw:t})}}captureReceived(e,t){if(this.enabled)try{const n=JSON.parse(t);console.log(`[AgentDebugger] RECEIVED - agent: ${e.slice(0,4)}, type: ${n.type}, size: ${t.length}B`),this.addMessage(e,{id:Mu(),agentId:e,direction:"received",type:n.type||"unknown",payload:n.payload||n,timestamp:Date.now(),size:t.length,raw:t})}catch(n){console.error("[AgentDebugger] Failed to parse RECEIVED message:",String(n).slice(0,80)),this.addMessage(e,{id:Mu(),agentId:e,direction:"received",type:"parse_error",payload:{error:String(n)},timestamp:Date.now(),size:t.length,raw:t})}}addMessage(e,t){let n=this.messages.get(e);n||(n=[],this.messages.set(e,n)),n.push(t),console.log(`[AgentDebugger] Added message for ${e}, total: ${n.length}, type: ${t.type}, direction: ${t.direction}`),n.length>this.maxMessagesPerAgent&&n.shift(),this.notifyListeners(e)}getMessages(e){return this.messages.get(e)||[]}getStats(e){const t=this.getMessages(e),n=t.filter(o=>o.direction==="sent").length,a=t.filter(o=>o.direction==="received").length,i=[...new Set(t.map(o=>o.type))];return{total:t.length,sent:n,received:a,messageTypes:i}}clearMessages(e){this.messages.delete(e),this.notifyListeners(e)}clearAllMessages(){this.messages.clear(),this.notifyListeners("all")}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}notifyListeners(e){this.listeners.forEach(t=>t(e))}getAgentIds(){return Array.from(this.messages.keys())}log(e,t,n,a){const i={id:Mu(),level:e,message:t,data:n,timestamp:Date.now(),source:a};this.logs.push(i),this.logs.length>this.maxLogs&&this.logs.shift(),this.notifyLogListeners()}debug(e,t,n){this.log("debug",e,t,n)}info(e,t,n){this.log("info",e,t,n)}warn(e,t,n){this.log("warn",e,t,n)}error(e,t,n){this.log("error",e,t,n)}getLogs(){return this.logs}clearLogs(){this.logs=[],this.notifyLogListeners()}subscribeLogs(e){return this.logListeners.add(e),()=>this.logListeners.delete(e)}notifyLogListeners(){this.logListeners.forEach(e=>e())}}const Ms=new yL,ud={debug:(s,e,t)=>Ms.debug(s,e,t),info:(s,e,t)=>Ms.info(s,e,t),warn:(s,e,t)=>Ms.warn(s,e,t),error:(s,e,t)=>Ms.error(s,e,t)};/*! Capacitor: https://capacitorjs.com/ - MIT License */var xc;(function(s){s.Unimplemented="UNIMPLEMENTED",s.Unavailable="UNAVAILABLE"})(xc||(xc={}));class eb extends Error{constructor(e,t,n){super(e),this.message=e,this.code=t,this.data=n}}const xL=s=>{var e,t;return s!=null&&s.androidBridge?"android":!((t=(e=s==null?void 0:s.webkit)===null||e===void 0?void 0:e.messageHandlers)===null||t===void 0)&&t.bridge?"ios":"web"},vL=s=>{const e=s.CapacitorCustomPlatform||null,t=s.Capacitor||{},n=t.Plugins=t.Plugins||{},a=()=>e!==null?e.name:xL(s),i=()=>a()!=="web",o=p=>{const f=d.get(p);return!!(f!=null&&f.platforms.has(a())||l(p))},l=p=>{var f;return(f=t.PluginHeaders)===null||f===void 0?void 0:f.find(b=>b.name===p)},c=p=>s.console.error(p),d=new Map,m=(p,f={})=>{const b=d.get(p);if(b)return console.warn(`Capacitor plugin "${p}" already registered. Cannot register plugins twice.`),b.proxy;const x=a(),w=l(p);let k;const S=async()=>(!k&&x in f?k=typeof f[x]=="function"?k=await f[x]():k=f[x]:e!==null&&!k&&"web"in f&&(k=typeof f.web=="function"?k=await f.web():k=f.web),k),j=(M,D)=>{var E,R;if(w){const O=w==null?void 0:w.methods.find(I=>D===I.name);if(O)return O.rtype==="promise"?I=>t.nativePromise(p,D.toString(),I):(I,B)=>t.nativeCallback(p,D.toString(),I,B);if(M)return(E=M[D])===null||E===void 0?void 0:E.bind(M)}else{if(M)return(R=M[D])===null||R===void 0?void 0:R.bind(M);throw new eb(`"${p}" plugin is not implemented on ${x}`,xc.Unimplemented)}},C=M=>{let D;const E=(...R)=>{const O=S().then(I=>{const B=j(I,M);if(B){const Y=B(...R);return D=Y==null?void 0:Y.remove,Y}else throw new eb(`"${p}.${M}()" is not implemented on ${x}`,xc.Unimplemented)});return M==="addListener"&&(O.remove=async()=>D()),O};return E.toString=()=>`${M.toString()}() { [capacitor code] }`,Object.defineProperty(E,"name",{value:M,writable:!1,configurable:!1}),E},N=C("addListener"),P=C("removeListener"),_=(M,D)=>{const E=N({eventName:M},D),R=async()=>{const I=await E;P({eventName:M,callbackId:I},D)},O=new Promise(I=>E.then(()=>I({remove:R})));return O.remove=async()=>{console.warn("Using addListener() without 'await' is deprecated."),await R()},O},L=new Proxy({},{get(M,D){switch(D){case"$$typeof":return;case"toJSON":return()=>({});case"addListener":return w?_:N;case"removeListener":return P;default:return C(D)}}});return n[p]=L,d.set(p,{name:p,proxy:L,platforms:new Set([...Object.keys(f),...w?[x]:[]])}),L};return t.convertFileSrc||(t.convertFileSrc=p=>p),t.getPlatform=a,t.handleError=c,t.isNativePlatform=i,t.isPluginAvailable=o,t.registerPlugin=m,t.Exception=eb,t.DEBUG=!!t.DEBUG,t.isLoggingEnabled=!!t.isLoggingEnabled,t},wL=s=>s.Capacitor=vL(s),Aa=wL(typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}),Sd=Aa.registerPlugin;class kx{constructor(){this.listeners={},this.retainedEventArguments={},this.windowListeners={}}addListener(e,t){let n=!1;this.listeners[e]||(this.listeners[e]=[],n=!0),this.listeners[e].push(t);const i=this.windowListeners[e];i&&!i.registered&&this.addWindowListener(i),n&&this.sendRetainedArgumentsForEvent(e);const o=async()=>this.removeListener(e,t);return Promise.resolve({remove:o})}async removeAllListeners(){this.listeners={};for(const e in this.windowListeners)this.removeWindowListener(this.windowListeners[e]);this.windowListeners={}}notifyListeners(e,t,n){const a=this.listeners[e];if(!a){if(n){let i=this.retainedEventArguments[e];i||(i=[]),i.push(t),this.retainedEventArguments[e]=i}return}a.forEach(i=>i(t))}hasListeners(e){var t;return!!(!((t=this.listeners[e])===null||t===void 0)&&t.length)}registerWindowListener(e,t){this.windowListeners[t]={registered:!1,windowEventName:e,pluginEventName:t,handler:n=>{this.notifyListeners(t,n)}}}unimplemented(e="not implemented"){return new Aa.Exception(e,xc.Unimplemented)}unavailable(e="not available"){return new Aa.Exception(e,xc.Unavailable)}async removeListener(e,t){const n=this.listeners[e];if(!n)return;const a=n.indexOf(t);this.listeners[e].splice(a,1),this.listeners[e].length||this.removeWindowListener(this.windowListeners[e])}addWindowListener(e){window.addEventListener(e.windowEventName,e.handler),e.registered=!0}removeWindowListener(e){e&&(window.removeEventListener(e.windowEventName,e.handler),e.registered=!1)}sendRetainedArgumentsForEvent(e){const t=this.retainedEventArguments[e];t&&(delete this.retainedEventArguments[e],t.forEach(n=>{this.notifyListeners(e,n)}))}}const cj=s=>encodeURIComponent(s).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape),uj=s=>s.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent);class kL extends kx{async getCookies(){const e=document.cookie,t={};return e.split(";").forEach(n=>{if(n.length<=0)return;let[a,i]=n.replace(/=/,"CAP_COOKIE").split("CAP_COOKIE");a=uj(a).trim(),i=uj(i).trim(),t[a]=i}),t}async setCookie(e){try{const t=cj(e.key),n=cj(e.value),a=e.expires?`; expires=${e.expires.replace("expires=","")}`:"",i=(e.path||"/").replace("path=",""),o=e.url!=null&&e.url.length>0?`domain=${e.url}`:"";document.cookie=`${t}=${n||""}${a}; path=${i}; ${o};`}catch(t){return Promise.reject(t)}}async deleteCookie(e){try{document.cookie=`${e.key}=; Max-Age=0`}catch(t){return Promise.reject(t)}}async clearCookies(){try{const e=document.cookie.split(";")||[];for(const t of e)document.cookie=t.replace(/^ +/,"").replace(/=.*/,`=;expires=${new Date().toUTCString()};path=/`)}catch(e){return Promise.reject(e)}}async clearAllCookies(){try{await this.clearCookies()}catch(e){return Promise.reject(e)}}}Sd("CapacitorCookies",{web:()=>new kL});const SL=async s=>new Promise((e,t)=>{const n=new FileReader;n.onload=()=>{const a=n.result;e(a.indexOf(",")>=0?a.split(",")[1]:a)},n.onerror=a=>t(a),n.readAsDataURL(s)}),jL=(s={})=>{const e=Object.keys(s);return Object.keys(s).map(a=>a.toLocaleLowerCase()).reduce((a,i,o)=>(a[i]=s[e[o]],a),{})},CL=(s,e=!0)=>s?Object.entries(s).reduce((n,a)=>{const[i,o]=a;let l,c;return Array.isArray(o)?(c="",o.forEach(d=>{l=e?encodeURIComponent(d):d,c+=`${i}=${l}&`}),c.slice(0,-1)):(l=e?encodeURIComponent(o):o,c=`${i}=${l}`),`${n}&${c}`},"").substr(1):null,NL=(s,e={})=>{const t=Object.assign({method:s.method||"GET",headers:s.headers},e),a=jL(s.headers)["content-type"]||"";if(typeof s.data=="string")t.body=s.data;else if(a.includes("application/x-www-form-urlencoded")){const i=new URLSearchParams;for(const[o,l]of Object.entries(s.data||{}))i.set(o,l);t.body=i.toString()}else if(a.includes("multipart/form-data")||s.data instanceof FormData){const i=new FormData;if(s.data instanceof FormData)s.data.forEach((l,c)=>{i.append(c,l)});else for(const l of Object.keys(s.data))i.append(l,s.data[l]);t.body=i;const o=new Headers(t.headers);o.delete("content-type"),t.headers=o}else(a.includes("application/json")||typeof s.data=="object")&&(t.body=JSON.stringify(s.data));return t};class AL extends kx{async request(e){const t=NL(e,e.webFetchExtra),n=CL(e.params,e.shouldEncodeUrlParams),a=n?`${e.url}?${n}`:e.url,i=await fetch(a,t),o=i.headers.get("content-type")||"";let{responseType:l="text"}=i.ok?e:{};o.includes("application/json")&&(l="json");let c,d;switch(l){case"arraybuffer":case"blob":d=await i.blob(),c=await SL(d);break;case"json":c=await i.json();break;case"document":case"text":default:c=await i.text()}const m={};return i.headers.forEach((p,f)=>{m[f]=p}),{data:c,headers:m,status:i.status,url:i.url}}async get(e){return this.request(Object.assign(Object.assign({},e),{method:"GET"}))}async post(e){return this.request(Object.assign(Object.assign({},e),{method:"POST"}))}async put(e){return this.request(Object.assign(Object.assign({},e),{method:"PUT"}))}async patch(e){return this.request(Object.assign(Object.assign({},e),{method:"PATCH"}))}async delete(e){return this.request(Object.assign(Object.assign({},e),{method:"DELETE"}))}}const dj=Sd("CapacitorHttp",{web:()=>new AL});var hj;(function(s){s.Dark="DARK",s.Light="LIGHT",s.Default="DEFAULT"})(hj||(hj={}));var pj;(function(s){s.StatusBar="StatusBar",s.NavigationBar="NavigationBar"})(pj||(pj={}));class ML extends kx{async setStyle(){this.unavailable("not available for web")}async setAnimation(){this.unavailable("not available for web")}async show(){this.unavailable("not available for web")}async hide(){this.unavailable("not available for web")}}Sd("SystemBars",{web:()=>new ML});var mj;(function(s){s[s.Sunday=1]="Sunday",s[s.Monday=2]="Monday",s[s.Tuesday=3]="Tuesday",s[s.Wednesday=4]="Wednesday",s[s.Thursday=5]="Thursday",s[s.Friday=6]="Friday",s[s.Saturday=7]="Saturday"})(mj||(mj={}));const Sx=Sd("LocalNotifications",{web:()=>QA(()=>import("./web-BUCfmE4M.js"),__vite__mapDeps([2,3,1,4])).then(s=>new s.LocalNotificationsWeb)}),TL=Sd("ServerConfig");let EL=100;const _L="agent_alerts",ky="tide-notification-tap";function DL(){return typeof window<"u"&&window.innerWidth<=768&&"ontouchstart"in window}function hM(s){if(DL()){z.openTerminalOnMobile(s);return}if(document.querySelector(".commander-overlay")){z.requestCommanderExpand(s);return}z.selectAgent(s),z.setTerminalOpen(!0)}function jd(){try{return Aa.isNativePlatform()}catch{return!1}}async function PL(){if(jd())try{const s=await Sx.requestPermissions();return console.log("[Notifications] Permission result:",s.display),s.display==="granted"}catch(s){return console.error("[Notifications] Failed to request permissions:",s),!1}else return"Notification"in window?await Notification.requestPermission()==="granted":!1}async function RL(s){const{title:e,body:t,icon:n,data:a}=s;if(jd())try{const i=EL++;console.log("[Notifications] Scheduling native notification id="+i,e),await Sx.schedule({notifications:[{id:i,title:e,body:t,extra:a,channelId:_L,smallIcon:"ic_launcher",autoCancel:!0}]}),console.log("[Notifications] Notification scheduled successfully")}catch(i){console.error("[Notifications] Failed to schedule notification:",i)}else if("Notification"in window&&Notification.permission==="granted"){const i=new Notification(e,{body:t,icon:n,data:a});i.onclick=()=>{window.focus(),a&&window.dispatchEvent(new CustomEvent(ky,{detail:a}))}}}let tb=!1;async function LL(s){const e=[];if(tb)return()=>{};if(tb=!0,s){const t=n=>{const a=n;a.detail&&s(a.detail)};window.addEventListener(ky,t),e.push(()=>window.removeEventListener(ky,t))}if(jd())try{const t=await Sx.addListener("localNotificationActionPerformed",n=>{s&&n.notification.extra&&s(n.notification.extra)});e.push(()=>t.remove())}catch(t){console.error("[Notifications] Failed to add tap listener:",t)}return()=>{e.forEach(t=>t()),tb=!1}}function OL(s,e){jd()&&TL.syncConfig({url:s,token:e}).catch(t=>{console.warn("[Notifications] Failed to sync config to native service:",t)})}window.__tideWsState||(window.__tideWsState={ws:null,isConnecting:!1,reconnectAttempts:0,reconnectTimeout:null});const jx=()=>window.__tideWsState.ws,fj=s=>{window.__tideWsState.ws=s},IL=()=>window.__tideWsState.isConnecting,Tu=s=>{window.__tideWsState.isConnecting=s},Sy=()=>window.__tideWsState.reconnectAttempts,jy=s=>{window.__tideWsState.reconnectAttempts=s},pM=()=>window.__tideWsState.reconnectTimeout,mM=s=>{window.__tideWsState.reconnectTimeout=s},gj=10,Cx="tide_ws_has_connected";function bj(){return sessionStorage.getItem(Cx)==="true"}function BL(s){sessionStorage.setItem(Cx,"true")}function zL(){sessionStorage.removeItem(Cx)}let fM=null;const FL=s=>{fM=s},yj=()=>fM,He={onToast:null,onAgentCreated:null,onAgentUpdated:null,onAgentDeleted:null,onAgentsSync:null,onAreasSync:null,onSpawnError:null,onSpawnSuccess:null,onToolUse:null,onDirectoryNotFound:null,onDelegation:null,onCustomClassesSync:null,onReconnect:null,onAgentNotification:null,onBuildingUpdated:null,onSubagentStarted:null,onSubagentCompleted:null};function gM(s){s.onToast&&(He.onToast=s.onToast),s.onAgentCreated&&(He.onAgentCreated=s.onAgentCreated),s.onAgentUpdated&&(He.onAgentUpdated=s.onAgentUpdated),s.onAgentDeleted&&(He.onAgentDeleted=s.onAgentDeleted),s.onAgentsSync&&(He.onAgentsSync=s.onAgentsSync),s.onAreasSync&&(He.onAreasSync=s.onAreasSync),s.onSpawnError&&(He.onSpawnError=s.onSpawnError),s.onSpawnSuccess&&(He.onSpawnSuccess=s.onSpawnSuccess),s.onToolUse&&(He.onToolUse=s.onToolUse),s.onDirectoryNotFound&&(He.onDirectoryNotFound=s.onDirectoryNotFound),s.onDelegation&&(He.onDelegation=s.onDelegation),s.onCustomClassesSync&&(He.onCustomClassesSync=s.onCustomClassesSync),s.onReconnect&&(He.onReconnect=s.onReconnect),s.onAgentNotification&&(He.onAgentNotification=s.onAgentNotification),s.onBuildingUpdated&&(He.onBuildingUpdated=s.onBuildingUpdated),s.onSubagentStarted&&(He.onSubagentStarted=s.onSubagentStarted),s.onSubagentCompleted&&(He.onSubagentCompleted=s.onSubagentCompleted)}function $L(){He.onToast=null,He.onAgentCreated=null,He.onAgentUpdated=null,He.onAgentDeleted=null,He.onAgentsSync=null,He.onAreasSync=null,He.onSpawnError=null,He.onSpawnSuccess=null,He.onToolUse=null,He.onDirectoryNotFound=null,He.onDelegation=null,He.onCustomClassesSync=null,He.onReconnect=null,He.onAgentNotification=null,He.onSubagentStarted=null,He.onSubagentCompleted=null}function HL(){He.onAgentCreated=null,He.onAgentUpdated=null,He.onAgentDeleted=null,He.onAgentsSync=null,He.onAreasSync=null,He.onToolUse=null,He.onDelegation=null,He.onCustomClassesSync=null,He.onBuildingUpdated=null,He.onSubagentStarted=null,He.onSubagentCompleted=null}const Wh=new Map,UL=new Map,Cy={start(s){},end(s){},async measure(s,e){this.start(s);try{return await e()}finally{this.end(s)}},measureSync(s,e){this.start(s);try{return e()}finally{this.end(s)}},getMetrics(s){const e={},t=s?Wh.has(s)?[[s,Wh.get(s)]]:[]:Array.from(Wh.entries());for(const[n,a]of t){const i=[...a.samples].sort((d,m)=>d-m),o=Math.floor(i.length*.5),l=Math.floor(i.length*.95),c=Math.floor(i.length*.99);e[n]={count:a.count,avgMs:a.totalMs/a.count,minMs:a.minMs,maxMs:a.maxMs,lastMs:a.lastMs,p50Ms:i[o]||0,p95Ms:i[l]||0,p99Ms:i[c]||0}}return e},clear(){Wh.clear(),UL.clear()},report(){}};class GL{constructor(){U(this,"frames",[]);U(this,"lastFrameTime",0);U(this,"frameCount",0);U(this,"fps",0);U(this,"minFps",1/0);U(this,"maxFps",0);U(this,"fpsHistory",[]);U(this,"maxHistorySize",60)}tick(e=200){const t=performance.now();if(this.lastFrameTime>0){const n=t-this.lastFrameTime;n<e&&(this.frames.push(n),this.frames.length>60&&this.frames.shift())}this.lastFrameTime=t,this.frameCount++}update(){if(this.frames.length===0)return;const e=this.frames.reduce((t,n)=>t+n,0)/this.frames.length;this.fps=1e3/e,this.minFps=Math.min(this.minFps,this.fps),this.maxFps=Math.max(this.maxFps,this.fps),this.fpsHistory.push(this.fps),this.fpsHistory.length>this.maxHistorySize&&this.fpsHistory.shift()}getFPS(){return Math.round(this.fps)}getStats(){const e=this.fpsHistory.length>0?this.fpsHistory.reduce((t,n)=>t+n,0)/this.fpsHistory.length:this.fps;return{current:Math.round(this.fps),min:Math.round(this.minFps===1/0?0:this.minFps),max:Math.round(this.maxFps),avg:Math.round(e)}}reset(){this.frames=[],this.lastFrameTime=0,this.frameCount=0,this.fps=0,this.minFps=1/0,this.maxFps=0,this.fpsHistory=[]}}const rc=new GL;class WL{constructor(){U(this,"snapshots",[]);U(this,"maxSnapshots",120);U(this,"intervalId",null);U(this,"leakThresholdMB",50);U(this,"baselineUsedMB",0)}getUsage(){const e=performance.memory;return e?{usedMB:Math.round(e.usedJSHeapSize/1024/1024),totalMB:Math.round(e.totalJSHeapSize/1024/1024),limitMB:Math.round(e.jsHeapSizeLimit/1024/1024)}:null}log(){const e=this.getUsage();e&&console.log(`[Memory] Used: ${e.usedMB}MB / ${e.totalMB}MB (limit: ${e.limitMB}MB)`)}startMonitoring(e=1e3){if(this.intervalId)return;const t=this.getUsage();t&&(this.baselineUsedMB=t.usedMB),this.intervalId=setInterval(()=>{this.takeSnapshot()},e),console.log("[Memory] Monitoring started. Use memory.report() to see analysis.")}stopMonitoring(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null,console.log("[Memory] Monitoring stopped."))}takeSnapshot(){const e=this.getUsage();if(!e)return;const t={timestamp:Date.now(),heapUsedMB:e.usedMB,heapTotalMB:e.totalMB,heapLimitMB:e.limitMB};this.snapshots.push(t),this.snapshots.length>this.maxSnapshots&&this.snapshots.shift();const n=e.usedMB-this.baselineUsedMB;n>this.leakThresholdMB&&console.warn(`[Memory] Warning: Heap grew by ${n}MB since monitoring started (baseline: ${this.baselineUsedMB}MB, current: ${e.usedMB}MB)`)}getGrowthRate(){if(this.snapshots.length<10)return null;const e=this.snapshots[0],t=this.snapshots[this.snapshots.length-1],n=(t.timestamp-e.timestamp)/1e3/60;return n<.1?null:(t.heapUsedMB-e.heapUsedMB)/n}report(){const e=this.getUsage();if(!e){console.log("[Memory] Memory API not available (Chrome only)");return}console.group("%c[Memory Report]","color: #ff6600; font-weight: bold"),console.log(`Current: ${e.usedMB}MB / ${e.totalMB}MB (limit: ${e.limitMB}MB)`),console.log(`Baseline: ${this.baselineUsedMB}MB`),console.log(`Growth: ${e.usedMB-this.baselineUsedMB}MB since monitoring started`);const t=this.getGrowthRate();if(t!==null&&(console.log(`Growth Rate: ${t.toFixed(2)}MB/min`),t>5&&console.warn("POTENTIAL MEMORY LEAK: Growth rate exceeds 5MB/min")),this.snapshots.length>1){const n=Math.min(...this.snapshots.map(i=>i.heapUsedMB)),a=Math.max(...this.snapshots.map(i=>i.heapUsedMB));console.log(`Range: ${n}MB - ${a}MB (${a-n}MB variance)`)}console.groupEnd()}getThreeJsInfo(e){var t;return(t=e==null?void 0:e.info)!=null&&t.memory?{geometries:e.info.memory.geometries,textures:e.info.memory.textures}:null}reset(){this.snapshots=[];const e=this.getUsage();e&&(this.baselineUsedMB=e.usedMB),console.log("[Memory] Reset. New baseline:",this.baselineUsedMB,"MB")}}const nc=new WL;function Wu(s,e,t,n,a,i){}function bM(s,e){y.useRef(0),y.useEffect(()=>{},[s,5e3,!0])}if(typeof window<"u"){setInterval(()=>{try{performance.clearMarks(),performance.clearMeasures(),performance.clearResourceTimings()}catch{}},6e4);try{performance.setResourceTimingBufferSize(0)}catch{}}function yM(s){if(s.payload&&typeof s.payload=="object"){const e=s.payload;if(e.agentId)return e.agentId;if(e.id)return e.id}return null}function Nx(s){var t,n,a,i,o,l;const e=jx();if(!e){(t=yj())==null||t(),(n=He.onToast)==null||n.call(He,"error","Not Connected","Connecting to server... Please try again in a moment.");return}if(e.readyState!==WebSocket.OPEN){e.readyState===WebSocket.CONNECTING?(a=He.onToast)==null||a.call(He,"warning","Connecting...","WebSocket is still connecting. Please wait a moment and try again."):(e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING)&&((i=yj())==null||i(),(o=He.onToast)==null||o.call(He,"warning","Reconnecting...","Connection lost. Reconnecting to server..."));return}try{const c=JSON.stringify(s);if(Ms.isEnabled()){const m=yM(s);console.log("[AgentDebugger] SENT - type:",s.type,"agentId:",m,"payload:",s.payload),m&&Ms.captureSent(m,c)}e.send(c)}catch(c){(l=He.onToast)==null||l.call(He,"error","Send Failed",`Failed to send message: ${c}`)}}const qu=new Set,qL=5e3;function xj(s){if(!s.isDetached||!s.sessionId){qu.delete(s.id);return}qu.has(s.id)||(qu.add(s.id),Nx({type:"reattach_agent",payload:{agentId:s.id}}),setTimeout(()=>{qu.delete(s.id)},qL))}function YL(s){var e,t,n,a,i,o,l,c,d,m,p,f,b,x,w,k,S,j,C,N,P,_,L;switch(Cy.start(`ws:${s.type}`),s.type){case"agents_update":{const M=s.payload,D=M.filter(E=>E.class==="boss"||E.isBoss);D.length>0&&console.log("[WS agents_update] Boss agents received:",D.map(E=>({id:E.id,name:E.name,subordinateIds:E.subordinateIds}))),z.setAgents(M),(e=He.onAgentsSync)==null||e.call(He,M),z.loadToolHistory();for(const E of M)xj(E);break}case"agent_created":{const M=s.payload;console.log("[WebSocket] Agent created:",M),z.addAgent(M),z.selectAgent(M.id),(t=He.onAgentCreated)==null||t.call(He,M),(n=He.onSpawnSuccess)==null||n.call(He),window.__spawnModalSuccess&&(console.log("[WebSocket] Calling __spawnModalSuccess"),window.__spawnModalSuccess()),(a=He.onToast)==null||a.call(He,"success","Agent Deployed",`${M.name} is ready for commands`);break}case"agent_updated":{const M=s.payload,E=z.getState().agents.get(M.id),R=(E==null?void 0:E.status)!==M.status;console.log(`[Tide] Agent updated: ${M.name} (${M.id}) status=${M.status} (was ${E==null?void 0:E.status})${R?" ⚡ STATUS CHANGED":""}`),R&&console.log(`[Tide] 🔔 Status change for ${M.name}: ${E==null?void 0:E.status} → ${M.status}`),R&&(E==null?void 0:E.status)==="working"&&M.status==="idle"&&z.triggerHistoryRefresh(M.id);const O=E?E.position.x!==M.position.x||E.position.z!==M.position.z:!1;z.updateAgent(M),xj(M),(i=He.onAgentUpdated)==null||i.call(He,M,O);break}case"agent_deleted":{const{id:M}=s.payload;qu.delete(M),z.removeAgent(M),(o=He.onAgentDeleted)==null||o.call(He,M);break}case"activity":{const M=s.payload;z.addActivity(M);break}case"event":{const M=s.payload;if(ud.debug(`Event: ${M.type}`,{agentId:M.agentId,toolName:M.toolName},"ws:event"),M.type==="tool_start"&&M.toolName&&((l=He.onToolUse)==null||l.call(He,M.agentId,M.toolName,M.toolInput),z.addToolExecution(M.agentId,M.toolName,M.toolInput),M.toolInput)){const D=M.toolInput.file_path||M.toolInput.path;D&&(M.toolName==="Write"?z.addFileChange(M.agentId,"created",D):M.toolName==="Edit"?z.addFileChange(M.agentId,"modified",D):M.toolName==="Read"&&z.addFileChange(M.agentId,"read",D))}break}case"output":{const M=s.payload;ud.debug(`Output: "${M.text.slice(0,80)}..."`,{agentId:M.agentId,isStreaming:M.isStreaming,length:M.text.length,hasSkillUpdate:!!M.skillUpdate,uuid:M.uuid,toolName:M.toolName},"ws:output"),z.addOutput(M.agentId,{text:M.text,isStreaming:M.isStreaming,timestamp:M.timestamp,isDelegation:M.isDelegation,skillUpdate:M.skillUpdate,subagentName:M.subagentName,uuid:M.uuid,toolName:M.toolName,toolInput:M.toolInput,toolOutput:M.toolOutput});break}case"context_stats":{const{agentId:M,stats:D}=s.payload;console.log(`[Tide] Received context stats for agent ${M}: ${D.usedPercent}% used`),z.updateAgentContextStats(M,D);break}case"context_update":{const{agentId:M,contextUsed:D,contextLimit:E}=s.payload;z.updateAgentContext(M,D,E);break}case"error":{const M=s.payload;console.error("[WebSocket] Error from server:",M.message),(c=He.onToast)==null||c.call(He,"error","Error",M.message),(d=He.onSpawnError)==null||d.call(He),window.__spawnModalError&&(console.log("[WebSocket] Calling __spawnModalError"),window.__spawnModalError());break}case"directory_not_found":{const{path:M}=s.payload;console.log("[WebSocket] Directory not found:",M),(m=He.onDirectoryNotFound)==null||m.call(He,M),window.__spawnModalDirNotFound&&(console.log("[WebSocket] Calling __spawnModalDirNotFound"),window.__spawnModalDirNotFound(M));break}case"command_started":{const{agentId:M,command:D}=s.payload,E=D.trim();if(E==="/context"||E==="/cost"||E==="/compact")break;z.addUserPromptToOutput(M,D);break}case"session_updated":{const{agentId:M}=s.payload;z.loadToolHistory(),z.triggerHistoryRefresh(M);const D=z.getState().agents.get(M);D&&z.updateAgent({...D});break}case"supervisor_report":{const M=s.payload;z.setSupervisorReport(M);break}case"narrative_update":{const{agentId:M,narrative:D}=s.payload;z.addNarrative(M,D);break}case"supervisor_status":{const M=s.payload;z.setSupervisorStatus(M);break}case"agent_supervisor_history":{const M=s.payload;z.setAgentSupervisorHistory(M);break}case"agent_analysis":{const{agentId:M,analysis:D}=s.payload;z.addAgentAnalysis(M,D);break}case"areas_update":{const M=s.payload;z.setAreasFromServer(M),(p=He.onAreasSync)==null||p.call(He);break}case"buildings_update":{const M=s.payload;z.setBuildingsFromServer(M);break}case"building_created":{const M=s.payload;z.addBuilding(M);break}case"building_updated":{const M=s.payload;z.updateBuildingFromServer(M),(f=He.onBuildingUpdated)==null||f.call(He,M);break}case"building_deleted":{const{id:M}=s.payload;z.removeBuildingFromServer(M);break}case"building_logs":{const{buildingId:M,logs:D}=s.payload;z.addBuildingLogs(M,D);break}case"pm2_logs_chunk":{const{buildingId:M,chunk:D}=s.payload;z.appendStreamingLogChunk(M,D);break}case"pm2_logs_streaming":{const{buildingId:M,streaming:D}=s.payload;z.setStreamingStatus(M,D);break}case"docker_logs_chunk":{const{buildingId:M,chunk:D}=s.payload;z.appendStreamingLogChunk(M,D);break}case"docker_logs_streaming":{const{buildingId:M,streaming:D}=s.payload;z.setStreamingStatus(M,D);break}case"docker_containers_list":{const{containers:M,composeProjects:D}=s.payload;console.log(`[WebSocket] Received ${M.length} containers, ${D.length} compose projects`),z.setDockerContainersList(M,D);break}case"boss_building_logs_chunk":{const{bossBuildingId:M,subordinateBuildingId:D,subordinateBuildingName:E,chunk:R,isError:O}=s.payload;z.appendBossStreamingLogChunk(M,D,E,R,O);break}case"boss_building_subordinates_updated":{const{bossBuildingId:M,subordinateBuildingIds:D}=s.payload;z.updateBuilding(M,{subordinateBuildingIds:D});break}case"permission_request":{const M=s.payload;z.addPermissionRequest(M);break}case"permission_resolved":{const{requestId:M,approved:D}=s.payload;z.resolvePermissionRequest(M,D);break}case"delegation_decision":{const M=s.payload;z.handleDelegationDecision(M),M.status==="sent"&&((b=He.onToast)==null||b.call(He,"info","Task Delegated",`Delegated to ${M.selectedAgentName}: ${M.reasoning.slice(0,80)}...`),M.bossId&&M.selectedAgentId&&((x=He.onDelegation)==null||x.call(He,M.bossId,M.selectedAgentId)));break}case"boss_subordinates_updated":{const{bossId:M,subordinateIds:D}=s.payload;z.updateBossSubordinates(M,D);break}case"delegation_history":{const{bossId:M,decisions:D}=s.payload;z.setDelegationHistory(M,D);break}case"boss_spawned_agent":{const{agent:M,bossPosition:D}=s.payload;console.log("[WebSocket] Boss spawned agent:",M.name,"- walking to boss at",D),z.addAgent(M),(w=He.onAgentCreated)==null||w.call(He,M),Nx({type:"move_agent",payload:{agentId:M.id,position:D}}),(k=He.onToast)==null||k.call(He,"success","Agent Deployed",`${M.name} spawned by boss, walking to position`);break}case"agent_task_started":{const{bossId:M,subordinateId:D,subordinateName:E,taskDescription:R}=s.payload;console.log(`[WebSocket] Agent ${E} started task for boss ${M}: ${R.slice(0,50)}...`),z.handleAgentTaskStarted(M,D,E,R);break}case"agent_task_output":{const{bossId:M,subordinateId:D,output:E}=s.payload;z.handleAgentTaskOutput(M,D,E);break}case"agent_task_completed":{const{bossId:M,subordinateId:D,success:E}=s.payload;console.log(`[WebSocket] Agent task completed for boss ${M}, subordinate ${D}, success: ${E}`),z.handleAgentTaskCompleted(M,D,E);break}case"skills_update":{const M=s.payload;z.setSkillsFromServer(M);break}case"skill_created":{const M=s.payload;z.addSkillFromServer(M),console.log(`[WebSocket] Skill created: ${M.name}`);break}case"skill_updated":{const M=s.payload;z.updateSkillFromServer(M),console.log(`[WebSocket] Skill updated: ${M.name}`);break}case"skill_deleted":{const{id:M}=s.payload;z.removeSkillFromServer(M),console.log(`[WebSocket] Skill deleted: ${M}`);break}case"agent_skills":{const{agentId:M,skills:D}=s.payload;console.log(`[WebSocket] Agent ${M} has ${D.length} skills`);break}case"custom_agent_classes_update":{const M=s.payload;z.setCustomAgentClassesFromServer(M),console.log(`[WebSocket] Received ${M.length} custom agent classes`);const D=new Map;for(const E of M)D.set(E.id,E);(S=He.onCustomClassesSync)==null||S.call(He,D);break}case"custom_agent_class_created":{const M=s.payload;z.addCustomAgentClassFromServer(M),console.log(`[WebSocket] Custom agent class created: ${M.name}`),(j=He.onCustomClassesSync)==null||j.call(He,z.getState().customAgentClasses);break}case"custom_agent_class_updated":{const M=s.payload;z.updateCustomAgentClassFromServer(M),console.log(`[WebSocket] Custom agent class updated: ${M.name}`),(C=He.onCustomClassesSync)==null||C.call(He,z.getState().customAgentClasses);break}case"custom_agent_class_deleted":{const{id:M}=s.payload;z.removeCustomAgentClassFromServer(M),console.log(`[WebSocket] Custom agent class deleted: ${M}`),(N=He.onCustomClassesSync)==null||N.call(He,z.getState().customAgentClasses);break}case"global_usage":{const M=s.payload;console.log("[WebSocket] Global usage update:",M),z.setGlobalUsage(M);break}case"agent_notification":{const M=s.payload;console.log(`[WebSocket] Agent notification from ${M.agentName}: ${M.title}`),(P=He.onAgentNotification)==null||P.call(He,M);break}case"focus_agent":{const{agentId:M,openTerminal:D}=s.payload;if(!z.getState().agents.get(M)){console.warn(`[WebSocket] focus_agent ignored - agent not found: ${M}`);break}z.selectAgent(M),D&&z.setTerminalOpen(!0);const R=[0,80,220,500,1e3];for(const O of R)window.setTimeout(()=>{window.focus()},O);break}case"exec_task_started":{const{taskId:M,agentId:D,agentName:E,command:R,cwd:O}=s.payload;console.log(`[WebSocket] Exec task started: ${M} for agent ${E}: ${R.slice(0,50)}...`),z.handleExecTaskStarted(M,D,E,R,O);break}case"exec_task_output":{const{taskId:M,agentId:D,output:E,isError:R}=s.payload;z.handleExecTaskOutput(M,D,E,R);break}case"exec_task_completed":{const{taskId:M,agentId:D,exitCode:E,success:R}=s.payload;console.log(`[WebSocket] Exec task completed: ${M} for agent ${D}, success: ${R}`),z.handleExecTaskCompleted(M,D,E,R);break}case"subagent_started":{const M=s.payload;console.log(`[WebSocket] Subagent started: ${M.name} (${M.id}) for agent ${M.parentAgentId}`),z.addSubagent(M),(_=He.onSubagentStarted)==null||_.call(He,M);break}case"subagent_output":{const{subagentId:M,parentAgentId:D,text:E,timestamp:R}=s.payload,O=E.indexOf(":");if(O>0){const I=E.slice(0,O).trim(),B=E.slice(O+1).trim();z.addSubagentActivity(M,D,{toolName:I,description:B,timestamp:R})}else E.startsWith("Using ")&&z.addSubagentActivity(M,D,{toolName:E.slice(6).trim(),description:"",timestamp:R});break}case"subagent_completed":{const{subagentId:M,parentAgentId:D,success:E,resultPreview:R,subagentName:O,durationMs:I,tokensUsed:B,toolUseCount:Y}=s.payload;console.log(`[WebSocket] Subagent completed: ${M} for agent ${D}, success: ${E}`),(I||B||Y)&&z.updateSubagentStats(M,D,{durationMs:I||0,tokensUsed:B||0,toolUseCount:Y||0}),z.completeSubagent(M,D,E),(L=He.onSubagentCompleted)==null||L.call(He,M);const $=z.getSubagent(M)||z.getSubagentByToolUseId(M),W=O||($==null?void 0:$.name)||M,K=E?"✅":"❌",X=I?` (${(I/1e3).toFixed(0)}s · ${((B||0)/1e3).toFixed(1)}K tokens · ${Y||0} tools)`:"";z.addOutput(D,{text:`${K} Subagent ${W} ${E?"completed":"failed"}${X}`,isStreaming:!1,timestamp:Date.now(),subagentName:W,toolOutput:R});break}case"subagent_stream":{const{toolUseId:M,parentAgentId:D,entries:E}=s.payload;z.addSubagentStreamEntries(M,D,E);break}case"secrets_update":{const M=s.payload;z.setSecretsFromServer(M),console.log(`[WebSocket] Received ${M.length} secrets`);break}case"secret_created":{const M=s.payload;z.addSecretFromServer(M),console.log(`[WebSocket] Secret created: ${M.name}`);break}case"secret_updated":{const M=s.payload;z.updateSecretFromServer(M),console.log(`[WebSocket] Secret updated: ${M.name}`);break}case"secret_deleted":{const{id:M}=s.payload;z.removeSecretFromServer(M),console.log(`[WebSocket] Secret deleted: ${M}`);break}case"database_connection_result":{const{buildingId:M,connectionId:D,success:E,error:R,serverVersion:O}=s.payload;z.setConnectionStatus(M,D,{connected:E,error:R,serverVersion:O}),console.log(`[WebSocket] Database connection ${E?"succeeded":"failed"}: ${D}`);break}case"databases_list":{const{buildingId:M,connectionId:D,databases:E}=s.payload;z.setDatabases(M,D,E),console.log(`[WebSocket] Received ${E.length} databases for ${D}`);break}case"tables_list":{const{buildingId:M,connectionId:D,database:E,tables:R}=s.payload;z.setTables(M,D,E,R),console.log(`[WebSocket] Received ${R.length} tables for ${E}`);break}case"table_schema":{const{buildingId:M,connectionId:D,database:E,table:R,columns:O,indexes:I,foreignKeys:B}=s.payload;z.setTableSchema(M,D,E,R,{columns:O,indexes:I||[],foreignKeys:B||[]}),console.log(`[WebSocket] Received schema for ${R}`);break}case"query_result":{const{buildingId:M,result:D}=s.payload;z.setQueryResult(M,D),console.log(`[WebSocket] Query ${D.status}: ${D.rowCount??D.affectedRows??0} rows in ${D.duration}ms`);break}case"silent_query_result":{const{buildingId:M,query:D,requestId:E,success:R,affectedRows:O,error:I}=s.payload;z.setSilentQueryResult(M,{query:D,requestId:E,success:R,affectedRows:O,error:I}),console.log(`[WebSocket] Silent query ${R?"succeeded":"failed"}: ${O??0} affected rows`);break}case"query_history_update":{const{buildingId:M,history:D}=s.payload;z.setQueryHistory(M,D),console.log(`[WebSocket] Received ${D.length} query history entries for ${M}`);break}}Cy.end(`ws:${s.type}`)}FL(()=>dd());let vj=!1;function xM(){const s=jx();s&&s.readyState===WebSocket.OPEN&&s.close(1e3,"Page unloading");const e=pM();e&&clearTimeout(e),window.__tideWsState&&(window.__tideWsState.ws=null,window.__tideWsState.reconnectTimeout=null,window.__tideWsState.isConnecting=!1,window.__tideWsState.reconnectAttempts=0),zL()}function VL(){vj||(window.addEventListener("beforeunload",xM),vj=!0)}function vM(){xM(),z.setConnected(!1),z.stopStatusPolling()}function xp(){vM(),jy(0),setTimeout(()=>dd(),100)}function dd(){VL();const s=pM();s&&(clearTimeout(s),mM(null));const e=jx();if(IL()||e&&e.readyState===WebSocket.CONNECTING)return;if(e&&e.readyState===WebSocket.OPEN){bj()&&He.onReconnect&&He.onReconnect();return}jy(Sy()+1),Tu(!0);const t=bm(),n=hi(),a=6200;let i;if(t){const l=t.replace(/^https:\/\//,"wss://").replace(/^http:\/\//,"ws://");i=l.endsWith("/ws")?l:`${l.replace(/\/$/,"")}/ws`}else i=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws`;let o=null;try{n?o=new WebSocket(i,[`auth-${n}`]):o=new WebSocket(i)}catch{Tu(!1),wj();return}fj(o),o.onopen=()=>{var c,d,m;const l=bj();Tu(!1),jy(0),BL(),z.setConnected(!0),z.startStatusPolling(),z.clearAllPermissions(),l?((c=He.onToast)==null||c.call(He,"success","Reconnected","Connection restored - refreshing data..."),(d=He.onReconnect)==null||d.call(He)):(m=He.onToast)==null||m.call(He,"success","Connected","Connected to Tide Commander server"),OL(t,n)},o.onmessage=l=>{try{const c=JSON.parse(l.data);if(Ms.isEnabled()){const m=yM(c);console.log("[AgentDebugger] RECEIVED - type:",c.type,"agentId:",m,"payload:",c.payload),m&&Ms.captureReceived(m,l.data)}YL(c)}catch(c){const d=l.data.substring(0,200);console.error("[WS] Failed to parse message:",c),console.error("[WS] Raw data (first 200 chars):",d),console.error("[WS] Full data length:",l.data.length),l.data.length<5e3&&console.error("[WS] Full malformed message:",l.data)}},o.onclose=()=>{var c,d;Tu(!1),fj(null),z.setConnected(!1),z.stopStatusPolling();const l=Sy();l<gj?((c=He.onToast)==null||c.call(He,"warning","Disconnected",`Connection lost. Reconnecting... (attempt ${l+1}/${gj})`),wj()):(d=He.onToast)==null||d.call(He,"error","Connection Failed",`Could not connect to server. Please check if the backend is running on port ${a}.`)},o.onerror=()=>{Tu(!1)},z.setSendMessage(Nx)}function wj(){const s=Sy(),e=Math.min(1e3*Math.pow(2,s-1),3e4);mM(setTimeout(dd,e))}function kj(s,e){if(e===tP)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),s;if(e===sy||e===_A){let t=s.getIndex();if(t===null){const o=[],l=s.getAttribute("position");if(l!==void 0){for(let c=0;c<l.count;c++)o.push(c);s.setIndex(o),t=s.getIndex()}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."),s}const n=t.count-2,a=[];if(e===sy)for(let o=1;o<=n;o++)a.push(t.getX(0)),a.push(t.getX(o)),a.push(t.getX(o+1));else for(let o=0;o<n;o++)o%2===0?(a.push(t.getX(o)),a.push(t.getX(o+1)),a.push(t.getX(o+2))):(a.push(t.getX(o+2)),a.push(t.getX(o+1)),a.push(t.getX(o)));a.length/3!==n&&console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");const i=s.clone();return i.setIndex(a),i.clearGroups(),i}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",e),s}class Ax extends DA{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new JL(t)}),this.register(function(t){return new eO(t)}),this.register(function(t){return new cO(t)}),this.register(function(t){return new uO(t)}),this.register(function(t){return new dO(t)}),this.register(function(t){return new nO(t)}),this.register(function(t){return new sO(t)}),this.register(function(t){return new aO(t)}),this.register(function(t){return new iO(t)}),this.register(function(t){return new QL(t)}),this.register(function(t){return new rO(t)}),this.register(function(t){return new tO(t)}),this.register(function(t){return new lO(t)}),this.register(function(t){return new oO(t)}),this.register(function(t){return new XL(t)}),this.register(function(t){return new hO(t)}),this.register(function(t){return new pO(t)})}load(e,t,n,a){const i=this;let o;if(this.resourcePath!=="")o=this.resourcePath;else if(this.path!==""){const d=Xu.extractUrlBase(e);o=Xu.resolveURL(d,this.path)}else o=Xu.extractUrlBase(e);this.manager.itemStart(e);const l=function(d){a?a(d):console.error(d),i.manager.itemError(e),i.manager.itemEnd(e)},c=new Tp(this.manager);c.setPath(this.path),c.setResponseType("arraybuffer"),c.setRequestHeader(this.requestHeader),c.setWithCredentials(this.withCredentials),c.load(e,function(d){try{i.parse(d,o,function(m){t(m),i.manager.itemEnd(e)},l)}catch(m){l(m)}},n,l)}setDRACOLoader(e){return this.dracoLoader=e,this}setKTX2Loader(e){return this.ktx2Loader=e,this}setMeshoptDecoder(e){return this.meshoptDecoder=e,this}register(e){return this.pluginCallbacks.indexOf(e)===-1&&this.pluginCallbacks.push(e),this}unregister(e){return this.pluginCallbacks.indexOf(e)!==-1&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}parse(e,t,n,a){let i;const o={},l={},c=new TextDecoder;if(typeof e=="string")i=JSON.parse(e);else if(e instanceof ArrayBuffer)if(c.decode(new Uint8Array(e,0,4))===wM){try{o[nn.KHR_BINARY_GLTF]=new mO(e)}catch(p){a&&a(p);return}i=JSON.parse(o[nn.KHR_BINARY_GLTF].content)}else i=JSON.parse(c.decode(e));else i=e;if(i.asset===void 0||i.asset.version[0]<2){a&&a(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));return}const d=new AO(i,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});d.fileLoader.setRequestHeader(this.requestHeader);for(let m=0;m<this.pluginCallbacks.length;m++){const p=this.pluginCallbacks[m](d);p.name||console.error("THREE.GLTFLoader: Invalid plugin found: missing name"),l[p.name]=p,o[p.name]=!0}if(i.extensionsUsed)for(let m=0;m<i.extensionsUsed.length;++m){const p=i.extensionsUsed[m],f=i.extensionsRequired||[];switch(p){case nn.KHR_MATERIALS_UNLIT:o[p]=new ZL;break;case nn.KHR_DRACO_MESH_COMPRESSION:o[p]=new fO(i,this.dracoLoader);break;case nn.KHR_TEXTURE_TRANSFORM:o[p]=new gO;break;case nn.KHR_MESH_QUANTIZATION:o[p]=new bO;break;default:f.indexOf(p)>=0&&l[p]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+p+'".')}}d.setExtensions(o),d.setPlugins(l),d.parse(n,a)}parseAsync(e,t){const n=this;return new Promise(function(a,i){n.parse(e,t,a,i)})}}function KL(){let s={};return{get:function(e){return s[e]},add:function(e,t){s[e]=t},remove:function(e){delete s[e]},removeAll:function(){s={}}}}const nn={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_DISPERSION:"KHR_materials_dispersion",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"};class XL{constructor(e){this.parser=e,this.name=nn.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const e=this.parser,t=this.parser.json.nodes||[];for(let n=0,a=t.length;n<a;n++){const i=t[n];i.extensions&&i.extensions[this.name]&&i.extensions[this.name].light!==void 0&&e._addNodeRef(this.cache,i.extensions[this.name].light)}}_loadLight(e){const t=this.parser,n="light:"+e;let a=t.cache.get(n);if(a)return a;const i=t.json,c=((i.extensions&&i.extensions[this.name]||{}).lights||[])[e];let d;const m=new Gt(16777215);c.color!==void 0&&m.setRGB(c.color[0],c.color[1],c.color[2],Ii);const p=c.range!==void 0?c.range:0;switch(c.type){case"directional":d=new uc(m),d.target.position.set(0,0,-1),d.add(d.target);break;case"point":d=new PA(m),d.distance=p;break;case"spot":d=new nP(m),d.distance=p,c.spot=c.spot||{},c.spot.innerConeAngle=c.spot.innerConeAngle!==void 0?c.spot.innerConeAngle:0,c.spot.outerConeAngle=c.spot.outerConeAngle!==void 0?c.spot.outerConeAngle:Math.PI/4,d.angle=c.spot.outerConeAngle,d.penumbra=1-c.spot.innerConeAngle/c.spot.outerConeAngle,d.target.position.set(0,0,-1),d.add(d.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+c.type)}return d.position.set(0,0,0),d.decay=2,cr(d,c),c.intensity!==void 0&&(d.intensity=c.intensity),d.name=t.createUniqueName(c.name||"light_"+e),a=Promise.resolve(d),t.cache.add(n,a),a}getDependency(e,t){if(e==="light")return this._loadLight(t)}createNodeAttachment(e){const t=this,n=this.parser,i=n.json.nodes[e],l=(i.extensions&&i.extensions[this.name]||{}).light;return l===void 0?null:this._loadLight(l).then(function(c){return n._getNodeRef(t.cache,l,c)})}}class ZL{constructor(){this.name=nn.KHR_MATERIALS_UNLIT}getMaterialType(){return Ke}extendParams(e,t,n){const a=[];e.color=new Gt(1,1,1),e.opacity=1;const i=t.pbrMetallicRoughness;if(i){if(Array.isArray(i.baseColorFactor)){const o=i.baseColorFactor;e.color.setRGB(o[0],o[1],o[2],Ii),e.opacity=o[3]}i.baseColorTexture!==void 0&&a.push(n.assignTexture(e,"map",i.baseColorTexture,ii))}return Promise.all(a)}}class QL{constructor(e){this.parser=e,this.name=nn.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){const a=this.parser.json.materials[e];if(!a.extensions||!a.extensions[this.name])return Promise.resolve();const i=a.extensions[this.name].emissiveStrength;return i!==void 0&&(t.emissiveIntensity=i),Promise.resolve()}}class JL{constructor(e){this.parser=e,this.name=nn.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:zi}extendMaterialParams(e,t){const n=this.parser,a=n.json.materials[e];if(!a.extensions||!a.extensions[this.name])return Promise.resolve();const i=[],o=a.extensions[this.name];if(o.clearcoatFactor!==void 0&&(t.clearcoat=o.clearcoatFactor),o.clearcoatTexture!==void 0&&i.push(n.assignTexture(t,"clearcoatMap",o.clearcoatTexture)),o.clearcoatRoughnessFactor!==void 0&&(t.clearcoatRoughness=o.clearcoatRoughnessFactor),o.clearcoatRoughnessTexture!==void 0&&i.push(n.assignTexture(t,"clearcoatRoughnessMap",o.clearcoatRoughnessTexture)),o.clearcoatNormalTexture!==void 0&&(i.push(n.assignTexture(t,"clearcoatNormalMap",o.clearcoatNormalTexture)),o.clearcoatNormalTexture.scale!==void 0)){const l=o.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new zs(l,l)}return Promise.all(i)}}class eO{constructor(e){this.parser=e,this.name=nn.KHR_MATERIALS_DISPERSION}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:zi}extendMaterialParams(e,t){const a=this.parser.json.materials[e];if(!a.extensions||!a.extensions[this.name])return Promise.resolve();const i=a.extensions[this.name];return t.dispersion=i.dispersion!==void 0?i.dispersion:0,Promise.resolve()}}class tO{constructor(e){this.parser=e,this.name=nn.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:zi}extendMaterialParams(e,t){const n=this.parser,a=n.json.materials[e];if(!a.extensions||!a.extensions[this.name])return Promise.resolve();const i=[],o=a.extensions[this.name];return o.iridescenceFactor!==void 0&&(t.iridescence=o.iridescenceFactor),o.iridescenceTexture!==void 0&&i.push(n.assignTexture(t,"iridescenceMap",o.iridescenceTexture)),o.iridescenceIor!==void 0&&(t.iridescenceIOR=o.iridescenceIor),t.iridescenceThicknessRange===void 0&&(t.iridescenceThicknessRange=[100,400]),o.iridescenceThicknessMinimum!==void 0&&(t.iridescenceThicknessRange[0]=o.iridescenceThicknessMinimum),o.iridescenceThicknessMaximum!==void 0&&(t.iridescenceThicknessRange[1]=o.iridescenceThicknessMaximum),o.iridescenceThicknessTexture!==void 0&&i.push(n.assignTexture(t,"iridescenceThicknessMap",o.iridescenceThicknessTexture)),Promise.all(i)}}class nO{constructor(e){this.parser=e,this.name=nn.KHR_MATERIALS_SHEEN}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:zi}extendMaterialParams(e,t){const n=this.parser,a=n.json.materials[e];if(!a.extensions||!a.extensions[this.name])return Promise.resolve();const i=[];t.sheenColor=new Gt(0,0,0),t.sheenRoughness=0,t.sheen=1;const o=a.extensions[this.name];if(o.sheenColorFactor!==void 0){const l=o.sheenColorFactor;t.sheenColor.setRGB(l[0],l[1],l[2],Ii)}return o.sheenRoughnessFactor!==void 0&&(t.sheenRoughness=o.sheenRoughnessFactor),o.sheenColorTexture!==void 0&&i.push(n.assignTexture(t,"sheenColorMap",o.sheenColorTexture,ii)),o.sheenRoughnessTexture!==void 0&&i.push(n.assignTexture(t,"sheenRoughnessMap",o.sheenRoughnessTexture)),Promise.all(i)}}class sO{constructor(e){this.parser=e,this.name=nn.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:zi}extendMaterialParams(e,t){const n=this.parser,a=n.json.materials[e];if(!a.extensions||!a.extensions[this.name])return Promise.resolve();const i=[],o=a.extensions[this.name];return o.transmissionFactor!==void 0&&(t.transmission=o.transmissionFactor),o.transmissionTexture!==void 0&&i.push(n.assignTexture(t,"transmissionMap",o.transmissionTexture)),Promise.all(i)}}class aO{constructor(e){this.parser=e,this.name=nn.KHR_MATERIALS_VOLUME}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:zi}extendMaterialParams(e,t){const n=this.parser,a=n.json.materials[e];if(!a.extensions||!a.extensions[this.name])return Promise.resolve();const i=[],o=a.extensions[this.name];t.thickness=o.thicknessFactor!==void 0?o.thicknessFactor:0,o.thicknessTexture!==void 0&&i.push(n.assignTexture(t,"thicknessMap",o.thicknessTexture)),t.attenuationDistance=o.attenuationDistance||1/0;const l=o.attenuationColor||[1,1,1];return t.attenuationColor=new Gt().setRGB(l[0],l[1],l[2],Ii),Promise.all(i)}}class iO{constructor(e){this.parser=e,this.name=nn.KHR_MATERIALS_IOR}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:zi}extendMaterialParams(e,t){const a=this.parser.json.materials[e];if(!a.extensions||!a.extensions[this.name])return Promise.resolve();const i=a.extensions[this.name];return t.ior=i.ior!==void 0?i.ior:1.5,Promise.resolve()}}class rO{constructor(e){this.parser=e,this.name=nn.KHR_MATERIALS_SPECULAR}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:zi}extendMaterialParams(e,t){const n=this.parser,a=n.json.materials[e];if(!a.extensions||!a.extensions[this.name])return Promise.resolve();const i=[],o=a.extensions[this.name];t.specularIntensity=o.specularFactor!==void 0?o.specularFactor:1,o.specularTexture!==void 0&&i.push(n.assignTexture(t,"specularIntensityMap",o.specularTexture));const l=o.specularColorFactor||[1,1,1];return t.specularColor=new Gt().setRGB(l[0],l[1],l[2],Ii),o.specularColorTexture!==void 0&&i.push(n.assignTexture(t,"specularColorMap",o.specularColorTexture,ii)),Promise.all(i)}}class oO{constructor(e){this.parser=e,this.name=nn.EXT_MATERIALS_BUMP}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:zi}extendMaterialParams(e,t){const n=this.parser,a=n.json.materials[e];if(!a.extensions||!a.extensions[this.name])return Promise.resolve();const i=[],o=a.extensions[this.name];return t.bumpScale=o.bumpFactor!==void 0?o.bumpFactor:1,o.bumpTexture!==void 0&&i.push(n.assignTexture(t,"bumpMap",o.bumpTexture)),Promise.all(i)}}class lO{constructor(e){this.parser=e,this.name=nn.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:zi}extendMaterialParams(e,t){const n=this.parser,a=n.json.materials[e];if(!a.extensions||!a.extensions[this.name])return Promise.resolve();const i=[],o=a.extensions[this.name];return o.anisotropyStrength!==void 0&&(t.anisotropy=o.anisotropyStrength),o.anisotropyRotation!==void 0&&(t.anisotropyRotation=o.anisotropyRotation),o.anisotropyTexture!==void 0&&i.push(n.assignTexture(t,"anisotropyMap",o.anisotropyTexture)),Promise.all(i)}}class cO{constructor(e){this.parser=e,this.name=nn.KHR_TEXTURE_BASISU}loadTexture(e){const t=this.parser,n=t.json,a=n.textures[e];if(!a.extensions||!a.extensions[this.name])return null;const i=a.extensions[this.name],o=t.options.ktx2Loader;if(!o){if(n.extensionsRequired&&n.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(e,i.source,o)}}class uO{constructor(e){this.parser=e,this.name=nn.EXT_TEXTURE_WEBP,this.isSupported=null}loadTexture(e){const t=this.name,n=this.parser,a=n.json,i=a.textures[e];if(!i.extensions||!i.extensions[t])return null;const o=i.extensions[t],l=a.images[o.source];let c=n.textureLoader;if(l.uri){const d=n.options.manager.getHandler(l.uri);d!==null&&(c=d)}return this.detectSupport().then(function(d){if(d)return n.loadTextureImage(e,o.source,c);if(a.extensionsRequired&&a.extensionsRequired.indexOf(t)>=0)throw new Error("THREE.GLTFLoader: WebP required by asset but unsupported.");return n.loadTexture(e)})}detectSupport(){return this.isSupported||(this.isSupported=new Promise(function(e){const t=new Image;t.src="data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA",t.onload=t.onerror=function(){e(t.height===1)}})),this.isSupported}}class dO{constructor(e){this.parser=e,this.name=nn.EXT_TEXTURE_AVIF,this.isSupported=null}loadTexture(e){const t=this.name,n=this.parser,a=n.json,i=a.textures[e];if(!i.extensions||!i.extensions[t])return null;const o=i.extensions[t],l=a.images[o.source];let c=n.textureLoader;if(l.uri){const d=n.options.manager.getHandler(l.uri);d!==null&&(c=d)}return this.detectSupport().then(function(d){if(d)return n.loadTextureImage(e,o.source,c);if(a.extensionsRequired&&a.extensionsRequired.indexOf(t)>=0)throw new Error("THREE.GLTFLoader: AVIF required by asset but unsupported.");return n.loadTexture(e)})}detectSupport(){return this.isSupported||(this.isSupported=new Promise(function(e){const t=new Image;t.src="data:image/avif;base64,AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUIAAADybWV0YQAAAAAAAAAoaGRscgAAAAAAAAAAcGljdAAAAAAAAAAAAAAAAGxpYmF2aWYAAAAADnBpdG0AAAAAAAEAAAAeaWxvYwAAAABEAAABAAEAAAABAAABGgAAABcAAAAoaWluZgAAAAAAAQAAABppbmZlAgAAAAABAABhdjAxQ29sb3IAAAAAamlwcnAAAABLaXBjbwAAABRpc3BlAAAAAAAAAAEAAAABAAAAEHBpeGkAAAAAAwgICAAAAAxhdjFDgQAMAAAAABNjb2xybmNseAACAAIABoAAAAAXaXBtYQAAAAAAAAABAAEEAQKDBAAAAB9tZGF0EgAKCBgABogQEDQgMgkQAAAAB8dSLfI=",t.onload=t.onerror=function(){e(t.height===1)}})),this.isSupported}}class hO{constructor(e){this.name=nn.EXT_MESHOPT_COMPRESSION,this.parser=e}loadBufferView(e){const t=this.parser.json,n=t.bufferViews[e];if(n.extensions&&n.extensions[this.name]){const a=n.extensions[this.name],i=this.parser.getDependency("buffer",a.buffer),o=this.parser.options.meshoptDecoder;if(!o||!o.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return i.then(function(l){const c=a.byteOffset||0,d=a.byteLength||0,m=a.count,p=a.byteStride,f=new Uint8Array(l,c,d);return o.decodeGltfBufferAsync?o.decodeGltfBufferAsync(m,p,f,a.mode,a.filter).then(function(b){return b.buffer}):o.ready.then(function(){const b=new ArrayBuffer(m*p);return o.decodeGltfBuffer(new Uint8Array(b),m,p,f,a.mode,a.filter),b})})}else return null}}class pO{constructor(e){this.name=nn.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){const t=this.parser.json,n=t.nodes[e];if(!n.extensions||!n.extensions[this.name]||n.mesh===void 0)return null;const a=t.meshes[n.mesh];for(const d of a.primitives)if(d.mode!==$a.TRIANGLES&&d.mode!==$a.TRIANGLE_STRIP&&d.mode!==$a.TRIANGLE_FAN&&d.mode!==void 0)return null;const o=n.extensions[this.name].attributes,l=[],c={};for(const d in o)l.push(this.parser.getDependency("accessor",o[d]).then(m=>(c[d]=m,c[d])));return l.length<1?null:(l.push(this.parser.createNodeMesh(e)),Promise.all(l).then(d=>{const m=d.pop(),p=m.isGroup?m.children:[m],f=d[0].count,b=[];for(const x of p){const w=new sl,k=new gt,S=new al,j=new gt(1,1,1),C=new ur(x.geometry,x.material,f);for(let N=0;N<f;N++)c.TRANSLATION&&k.fromBufferAttribute(c.TRANSLATION,N),c.ROTATION&&S.fromBufferAttribute(c.ROTATION,N),c.SCALE&&j.fromBufferAttribute(c.SCALE,N),C.setMatrixAt(N,w.compose(k,S,j));for(const N in c)if(N==="_COLOR_0"){const P=c[N];C.instanceColor=new sP(P.array,P.itemSize,P.normalized)}else N!=="TRANSLATION"&&N!=="ROTATION"&&N!=="SCALE"&&x.geometry.setAttribute(N,c[N]);RA.prototype.copy.call(C,x),this.parser.assignFinalMaterial(C),b.push(C)}return m.isGroup?(m.clear(),m.add(...b),m):b[0]}))}}const wM="glTF",Eu=12,Sj={JSON:1313821514,BIN:5130562};class mO{constructor(e){this.name=nn.KHR_BINARY_GLTF,this.content=null,this.body=null;const t=new DataView(e,0,Eu),n=new TextDecoder;if(this.header={magic:n.decode(new Uint8Array(e.slice(0,4))),version:t.getUint32(4,!0),length:t.getUint32(8,!0)},this.header.magic!==wM)throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");if(this.header.version<2)throw new Error("THREE.GLTFLoader: Legacy binary file detected.");const a=this.header.length-Eu,i=new DataView(e,Eu);let o=0;for(;o<a;){const l=i.getUint32(o,!0);o+=4;const c=i.getUint32(o,!0);if(o+=4,c===Sj.JSON){const d=new Uint8Array(e,Eu+o,l);this.content=n.decode(d)}else if(c===Sj.BIN){const d=Eu+o;this.body=e.slice(d,d+l)}o+=l}if(this.content===null)throw new Error("THREE.GLTFLoader: JSON content not found.")}}class fO{constructor(e,t){if(!t)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=nn.KHR_DRACO_MESH_COMPRESSION,this.json=e,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(e,t){const n=this.json,a=this.dracoLoader,i=e.extensions[this.name].bufferView,o=e.extensions[this.name].attributes,l={},c={},d={};for(const m in o){const p=Ny[m]||m.toLowerCase();l[p]=o[m]}for(const m in e.attributes){const p=Ny[m]||m.toLowerCase();if(o[m]!==void 0){const f=n.accessors[e.attributes[m]],b=hc[f.componentType];d[p]=b.name,c[p]=f.normalized===!0}}return t.getDependency("bufferView",i).then(function(m){return new Promise(function(p,f){a.decodeDracoFile(m,function(b){for(const x in b.attributes){const w=b.attributes[x],k=c[x];k!==void 0&&(w.normalized=k)}p(b)},l,d,Ii,f)})})}}class gO{constructor(){this.name=nn.KHR_TEXTURE_TRANSFORM}extendTexture(e,t){return(t.texCoord===void 0||t.texCoord===e.channel)&&t.offset===void 0&&t.rotation===void 0&&t.scale===void 0||(e=e.clone(),t.texCoord!==void 0&&(e.channel=t.texCoord),t.offset!==void 0&&e.offset.fromArray(t.offset),t.rotation!==void 0&&(e.rotation=t.rotation),t.scale!==void 0&&e.repeat.fromArray(t.scale),e.needsUpdate=!0),e}}class bO{constructor(){this.name=nn.KHR_MESH_QUANTIZATION}}class kM extends yP{constructor(e,t,n,a){super(e,t,n,a)}copySampleValue_(e){const t=this.resultBuffer,n=this.sampleValues,a=this.valueSize,i=e*a*3+a;for(let o=0;o!==a;o++)t[o]=n[i+o];return t}interpolate_(e,t,n,a){const i=this.resultBuffer,o=this.sampleValues,l=this.valueSize,c=l*2,d=l*3,m=a-t,p=(n-t)/m,f=p*p,b=f*p,x=e*d,w=x-d,k=-2*b+3*f,S=b-f,j=1-k,C=S-f+p;for(let N=0;N!==l;N++){const P=o[w+N+l],_=o[w+N+c]*m,L=o[x+N+l],M=o[x+N]*m;i[N]=j*P+C*_+k*L+S*M}return i}}const yO=new al;class xO extends kM{interpolate_(e,t,n,a){const i=super.interpolate_(e,t,n,a);return yO.fromArray(i).normalize().toArray(i),i}}const $a={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6},hc={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},jj={9728:LA,9729:zn,9984:lP,9985:oP,9986:rP,9987:Zu},Cj={33071:uP,33648:cP,10497:Wo},nb={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},Ny={POSITION:"position",NORMAL:"normal",TANGENT:"tangent",TEXCOORD_0:"uv",TEXCOORD_1:"uv1",TEXCOORD_2:"uv2",TEXCOORD_3:"uv3",COLOR_0:"color",WEIGHTS_0:"skinWeight",JOINTS_0:"skinIndex"},Xr={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},vO={CUBICSPLINE:void 0,LINEAR:IA,STEP:gP},sb={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function wO(s){return s.DefaultMaterial===void 0&&(s.DefaultMaterial=new dt({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:BA})),s.DefaultMaterial}function Bo(s,e,t){for(const n in t.extensions)s[n]===void 0&&(e.userData.gltfExtensions=e.userData.gltfExtensions||{},e.userData.gltfExtensions[n]=t.extensions[n])}function cr(s,e){e.extras!==void 0&&(typeof e.extras=="object"?Object.assign(s.userData,e.extras):console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, "+e.extras))}function kO(s,e,t){let n=!1,a=!1,i=!1;for(let d=0,m=e.length;d<m;d++){const p=e[d];if(p.POSITION!==void 0&&(n=!0),p.NORMAL!==void 0&&(a=!0),p.COLOR_0!==void 0&&(i=!0),n&&a&&i)break}if(!n&&!a&&!i)return Promise.resolve(s);const o=[],l=[],c=[];for(let d=0,m=e.length;d<m;d++){const p=e[d];if(n){const f=p.POSITION!==void 0?t.getDependency("accessor",p.POSITION):s.attributes.position;o.push(f)}if(a){const f=p.NORMAL!==void 0?t.getDependency("accessor",p.NORMAL):s.attributes.normal;l.push(f)}if(i){const f=p.COLOR_0!==void 0?t.getDependency("accessor",p.COLOR_0):s.attributes.color;c.push(f)}}return Promise.all([Promise.all(o),Promise.all(l),Promise.all(c)]).then(function(d){const m=d[0],p=d[1],f=d[2];return n&&(s.morphAttributes.position=m),a&&(s.morphAttributes.normal=p),i&&(s.morphAttributes.color=f),s.morphTargetsRelative=!0,s})}function SO(s,e){if(s.updateMorphTargets(),e.weights!==void 0)for(let t=0,n=e.weights.length;t<n;t++)s.morphTargetInfluences[t]=e.weights[t];if(e.extras&&Array.isArray(e.extras.targetNames)){const t=e.extras.targetNames;if(s.morphTargetInfluences.length===t.length){s.morphTargetDictionary={};for(let n=0,a=t.length;n<a;n++)s.morphTargetDictionary[t[n]]=n}else console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.")}}function jO(s){let e;const t=s.extensions&&s.extensions[nn.KHR_DRACO_MESH_COMPRESSION];if(t?e="draco:"+t.bufferView+":"+t.indices+":"+ab(t.attributes):e=s.indices+":"+ab(s.attributes)+":"+s.mode,s.targets!==void 0)for(let n=0,a=s.targets.length;n<a;n++)e+=":"+ab(s.targets[n]);return e}function ab(s){let e="";const t=Object.keys(s).sort();for(let n=0,a=t.length;n<a;n++)e+=t[n]+":"+s[t[n]]+";";return e}function Ay(s){switch(s){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:throw new Error("THREE.GLTFLoader: Unsupported normalized accessor component type.")}}function CO(s){return s.search(/\.jpe?g($|\?)/i)>0||s.search(/^data\:image\/jpeg/)===0?"image/jpeg":s.search(/\.webp($|\?)/i)>0||s.search(/^data\:image\/webp/)===0?"image/webp":s.search(/\.ktx2($|\?)/i)>0||s.search(/^data\:image\/ktx2/)===0?"image/ktx2":"image/png"}const NO=new sl;class AO{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new KL,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let n=!1,a=-1,i=!1,o=-1;if(typeof navigator<"u"){const l=navigator.userAgent;n=/^((?!chrome|android).)*safari/i.test(l)===!0;const c=l.match(/Version\/(\d+)/);a=n&&c?parseInt(c[1],10):-1,i=l.indexOf("Firefox")>-1,o=i?l.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||n&&a<17||i&&o<98?this.textureLoader=new fx(this.options.manager):this.textureLoader=new aP(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new Tp(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials"&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){const n=this,a=this.json,i=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(o){return o._markDefs&&o._markDefs()}),Promise.all(this._invokeAll(function(o){return o.beforeRoot&&o.beforeRoot()})).then(function(){return Promise.all([n.getDependencies("scene"),n.getDependencies("animation"),n.getDependencies("camera")])}).then(function(o){const l={scene:o[0][a.scene||0],scenes:o[0],animations:o[1],cameras:o[2],asset:a.asset,parser:n,userData:{}};return Bo(i,l,a),cr(l,a),Promise.all(n._invokeAll(function(c){return c.afterRoot&&c.afterRoot(l)})).then(function(){for(const c of l.scenes)c.updateMatrixWorld();e(l)})}).catch(t)}_markDefs(){const e=this.json.nodes||[],t=this.json.skins||[],n=this.json.meshes||[];for(let a=0,i=t.length;a<i;a++){const o=t[a].joints;for(let l=0,c=o.length;l<c;l++)e[o[l]].isBone=!0}for(let a=0,i=e.length;a<i;a++){const o=e[a];o.mesh!==void 0&&(this._addNodeRef(this.meshCache,o.mesh),o.skin!==void 0&&(n[o.mesh].isSkinnedMesh=!0)),o.camera!==void 0&&this._addNodeRef(this.cameraCache,o.camera)}}_addNodeRef(e,t){t!==void 0&&(e.refs[t]===void 0&&(e.refs[t]=e.uses[t]=0),e.refs[t]++)}_getNodeRef(e,t,n){if(e.refs[t]<=1)return n;const a=n.clone(),i=(o,l)=>{const c=this.associations.get(o);c!=null&&this.associations.set(l,c);for(const[d,m]of o.children.entries())i(m,l.children[d])};return i(n,a),a.name+="_instance_"+e.uses[t]++,a}_invokeOne(e){const t=Object.values(this.plugins);t.push(this);for(let n=0;n<t.length;n++){const a=e(t[n]);if(a)return a}return null}_invokeAll(e){const t=Object.values(this.plugins);t.unshift(this);const n=[];for(let a=0;a<t.length;a++){const i=e(t[a]);i&&n.push(i)}return n}getDependency(e,t){const n=e+":"+t;let a=this.cache.get(n);if(!a){switch(e){case"scene":a=this.loadScene(t);break;case"node":a=this._invokeOne(function(i){return i.loadNode&&i.loadNode(t)});break;case"mesh":a=this._invokeOne(function(i){return i.loadMesh&&i.loadMesh(t)});break;case"accessor":a=this.loadAccessor(t);break;case"bufferView":a=this._invokeOne(function(i){return i.loadBufferView&&i.loadBufferView(t)});break;case"buffer":a=this.loadBuffer(t);break;case"material":a=this._invokeOne(function(i){return i.loadMaterial&&i.loadMaterial(t)});break;case"texture":a=this._invokeOne(function(i){return i.loadTexture&&i.loadTexture(t)});break;case"skin":a=this.loadSkin(t);break;case"animation":a=this._invokeOne(function(i){return i.loadAnimation&&i.loadAnimation(t)});break;case"camera":a=this.loadCamera(t);break;default:if(a=this._invokeOne(function(i){return i!=this&&i.getDependency&&i.getDependency(e,t)}),!a)throw new Error("Unknown type: "+e);break}this.cache.add(n,a)}return a}getDependencies(e){let t=this.cache.get(e);if(!t){const n=this,a=this.json[e+(e==="mesh"?"es":"s")]||[];t=Promise.all(a.map(function(i,o){return n.getDependency(e,o)})),this.cache.add(e,t)}return t}loadBuffer(e){const t=this.json.buffers[e],n=this.fileLoader;if(t.type&&t.type!=="arraybuffer")throw new Error("THREE.GLTFLoader: "+t.type+" buffer type is not supported.");if(t.uri===void 0&&e===0)return Promise.resolve(this.extensions[nn.KHR_BINARY_GLTF].body);const a=this.options;return new Promise(function(i,o){n.load(Xu.resolveURL(t.uri,a.path),i,void 0,function(){o(new Error('THREE.GLTFLoader: Failed to load buffer "'+t.uri+'".'))})})}loadBufferView(e){const t=this.json.bufferViews[e];return this.getDependency("buffer",t.buffer).then(function(n){const a=t.byteLength||0,i=t.byteOffset||0;return n.slice(i,i+a)})}loadAccessor(e){const t=this,n=this.json,a=this.json.accessors[e];if(a.bufferView===void 0&&a.sparse===void 0){const o=nb[a.type],l=hc[a.componentType],c=a.normalized===!0,d=new l(a.count*o);return Promise.resolve(new ri(d,o,c))}const i=[];return a.bufferView!==void 0?i.push(this.getDependency("bufferView",a.bufferView)):i.push(null),a.sparse!==void 0&&(i.push(this.getDependency("bufferView",a.sparse.indices.bufferView)),i.push(this.getDependency("bufferView",a.sparse.values.bufferView))),Promise.all(i).then(function(o){const l=o[0],c=nb[a.type],d=hc[a.componentType],m=d.BYTES_PER_ELEMENT,p=m*c,f=a.byteOffset||0,b=a.bufferView!==void 0?n.bufferViews[a.bufferView].byteStride:void 0,x=a.normalized===!0;let w,k;if(b&&b!==p){const S=Math.floor(f/b),j="InterleavedBuffer:"+a.bufferView+":"+a.componentType+":"+S+":"+a.count;let C=t.cache.get(j);C||(w=new d(l,S*b,a.count*b/m),C=new iP(w,b/m),t.cache.add(j,C)),k=new bP(C,c,f%b/m,x)}else l===null?w=new d(a.count*c):w=new d(l,f,a.count*c),k=new ri(w,c,x);if(a.sparse!==void 0){const S=nb.SCALAR,j=hc[a.sparse.indices.componentType],C=a.sparse.indices.byteOffset||0,N=a.sparse.values.byteOffset||0,P=new j(o[1],C,a.sparse.count*S),_=new d(o[2],N,a.sparse.count*c);l!==null&&(k=new ri(k.array.slice(),k.itemSize,k.normalized)),k.normalized=!1;for(let L=0,M=P.length;L<M;L++){const D=P[L];if(k.setX(D,_[L*c]),c>=2&&k.setY(D,_[L*c+1]),c>=3&&k.setZ(D,_[L*c+2]),c>=4&&k.setW(D,_[L*c+3]),c>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}k.normalized=x}return k})}loadTexture(e){const t=this.json,n=this.options,i=t.textures[e].source,o=t.images[i];let l=this.textureLoader;if(o.uri){const c=n.manager.getHandler(o.uri);c!==null&&(l=c)}return this.loadTextureImage(e,i,l)}loadTextureImage(e,t,n){const a=this,i=this.json,o=i.textures[e],l=i.images[t],c=(l.uri||l.bufferView)+":"+o.sampler;if(this.textureCache[c])return this.textureCache[c];const d=this.loadImageSource(t,n).then(function(m){m.flipY=!1,m.name=o.name||l.name||"",m.name===""&&typeof l.uri=="string"&&l.uri.startsWith("data:image/")===!1&&(m.name=l.uri);const f=(i.samplers||{})[o.sampler]||{};return m.magFilter=jj[f.magFilter]||zn,m.minFilter=jj[f.minFilter]||Zu,m.wrapS=Cj[f.wrapS]||Wo,m.wrapT=Cj[f.wrapT]||Wo,m.generateMipmaps=!m.isCompressedTexture&&m.minFilter!==LA&&m.minFilter!==zn,a.associations.set(m,{textures:e}),m}).catch(function(){return null});return this.textureCache[c]=d,d}loadImageSource(e,t){const n=this,a=this.json,i=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(p=>p.clone());const o=a.images[e],l=self.URL||self.webkitURL;let c=o.uri||"",d=!1;if(o.bufferView!==void 0)c=n.getDependency("bufferView",o.bufferView).then(function(p){d=!0;const f=new Blob([p],{type:o.mimeType});return c=l.createObjectURL(f),c});else if(o.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");const m=Promise.resolve(c).then(function(p){return new Promise(function(f,b){let x=f;t.isImageBitmapLoader===!0&&(x=function(w){const k=new vS(w);k.needsUpdate=!0,f(k)}),t.load(Xu.resolveURL(p,i.path),x,void 0,b)})}).then(function(p){return d===!0&&l.revokeObjectURL(c),cr(p,o),p.userData.mimeType=o.mimeType||CO(o.uri),p}).catch(function(p){throw console.error("THREE.GLTFLoader: Couldn't load texture",c),p});return this.sourceCache[e]=m,m}assignTexture(e,t,n,a){const i=this;return this.getDependency("texture",n.index).then(function(o){if(!o)return null;if(n.texCoord!==void 0&&n.texCoord>0&&(o=o.clone(),o.channel=n.texCoord),i.extensions[nn.KHR_TEXTURE_TRANSFORM]){const l=n.extensions!==void 0?n.extensions[nn.KHR_TEXTURE_TRANSFORM]:void 0;if(l){const c=i.associations.get(o);o=i.extensions[nn.KHR_TEXTURE_TRANSFORM].extendTexture(o,l),i.associations.set(o,c)}}return a!==void 0&&(o.colorSpace=a),e[t]=o,o})}assignFinalMaterial(e){const t=e.geometry;let n=e.material;const a=t.attributes.tangent===void 0,i=t.attributes.color!==void 0,o=t.attributes.normal===void 0;if(e.isPoints){const l="PointsMaterial:"+n.uuid;let c=this.cache.get(l);c||(c=new pm,hr.prototype.copy.call(c,n),c.color.copy(n.color),c.map=n.map,c.sizeAttenuation=!1,this.cache.add(l,c)),n=c}else if(e.isLine){const l="LineBasicMaterial:"+n.uuid;let c=this.cache.get(l);c||(c=new qo,hr.prototype.copy.call(c,n),c.color.copy(n.color),c.map=n.map,this.cache.add(l,c)),n=c}if(a||i||o){let l="ClonedMaterial:"+n.uuid+":";a&&(l+="derivative-tangents:"),i&&(l+="vertex-colors:"),o&&(l+="flat-shading:");let c=this.cache.get(l);c||(c=n.clone(),i&&(c.vertexColors=!0),o&&(c.flatShading=!0),a&&(c.normalScale&&(c.normalScale.y*=-1),c.clearcoatNormalScale&&(c.clearcoatNormalScale.y*=-1)),this.cache.add(l,c),this.associations.set(c,this.associations.get(n))),n=c}e.material=n}getMaterialType(){return dt}loadMaterial(e){const t=this,n=this.json,a=this.extensions,i=n.materials[e];let o;const l={},c=i.extensions||{},d=[];if(c[nn.KHR_MATERIALS_UNLIT]){const p=a[nn.KHR_MATERIALS_UNLIT];o=p.getMaterialType(),d.push(p.extendParams(l,i,t))}else{const p=i.pbrMetallicRoughness||{};if(l.color=new Gt(1,1,1),l.opacity=1,Array.isArray(p.baseColorFactor)){const f=p.baseColorFactor;l.color.setRGB(f[0],f[1],f[2],Ii),l.opacity=f[3]}p.baseColorTexture!==void 0&&d.push(t.assignTexture(l,"map",p.baseColorTexture,ii)),l.metalness=p.metallicFactor!==void 0?p.metallicFactor:1,l.roughness=p.roughnessFactor!==void 0?p.roughnessFactor:1,p.metallicRoughnessTexture!==void 0&&(d.push(t.assignTexture(l,"metalnessMap",p.metallicRoughnessTexture)),d.push(t.assignTexture(l,"roughnessMap",p.metallicRoughnessTexture))),o=this._invokeOne(function(f){return f.getMaterialType&&f.getMaterialType(e)}),d.push(Promise.all(this._invokeAll(function(f){return f.extendMaterialParams&&f.extendMaterialParams(e,l)})))}i.doubleSided===!0&&(l.side=Ts);const m=i.alphaMode||sb.OPAQUE;if(m===sb.BLEND?(l.transparent=!0,l.depthWrite=!1):(l.transparent=!1,m===sb.MASK&&(l.alphaTest=i.alphaCutoff!==void 0?i.alphaCutoff:.5)),i.normalTexture!==void 0&&o!==Ke&&(d.push(t.assignTexture(l,"normalMap",i.normalTexture)),l.normalScale=new zs(1,1),i.normalTexture.scale!==void 0)){const p=i.normalTexture.scale;l.normalScale.set(p,p)}if(i.occlusionTexture!==void 0&&o!==Ke&&(d.push(t.assignTexture(l,"aoMap",i.occlusionTexture)),i.occlusionTexture.strength!==void 0&&(l.aoMapIntensity=i.occlusionTexture.strength)),i.emissiveFactor!==void 0&&o!==Ke){const p=i.emissiveFactor;l.emissive=new Gt().setRGB(p[0],p[1],p[2],Ii)}return i.emissiveTexture!==void 0&&o!==Ke&&d.push(t.assignTexture(l,"emissiveMap",i.emissiveTexture,ii)),Promise.all(d).then(function(){const p=new o(l);return i.name&&(p.name=i.name),cr(p,i),t.associations.set(p,{materials:e}),i.extensions&&Bo(a,p,i),p})}createUniqueName(e){const t=dP.sanitizeNodeName(e||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){const t=this,n=this.extensions,a=this.primitiveCache;function i(l){return n[nn.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(l,t).then(function(c){return Nj(c,l,t)})}const o=[];for(let l=0,c=e.length;l<c;l++){const d=e[l],m=jO(d),p=a[m];if(p)o.push(p.promise);else{let f;d.extensions&&d.extensions[nn.KHR_DRACO_MESH_COMPRESSION]?f=i(d):f=Nj(new Wa,d,t),a[m]={primitive:d,promise:f},o.push(f)}}return Promise.all(o)}loadMesh(e){const t=this,n=this.json,a=this.extensions,i=n.meshes[e],o=i.primitives,l=[];for(let c=0,d=o.length;c<d;c++){const m=o[c].material===void 0?wO(this.cache):this.getDependency("material",o[c].material);l.push(m)}return l.push(t.loadGeometries(o)),Promise.all(l).then(function(c){const d=c.slice(0,c.length-1),m=c[c.length-1],p=[];for(let b=0,x=m.length;b<x;b++){const w=m[b],k=o[b];let S;const j=d[b];if(k.mode===$a.TRIANGLES||k.mode===$a.TRIANGLE_STRIP||k.mode===$a.TRIANGLE_FAN||k.mode===void 0)S=i.isSkinnedMesh===!0?new ay(w,j):new De(w,j),S.isSkinnedMesh===!0&&S.normalizeSkinWeights(),k.mode===$a.TRIANGLE_STRIP?S.geometry=kj(S.geometry,_A):k.mode===$a.TRIANGLE_FAN&&(S.geometry=kj(S.geometry,sy));else if(k.mode===$a.LINES)S=new gx(w,j);else if(k.mode===$a.LINE_STRIP)S=new eo(w,j);else if(k.mode===$a.LINE_LOOP)S=new hP(w,j);else if(k.mode===$a.POINTS)S=new wd(w,j);else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+k.mode);Object.keys(S.geometry.morphAttributes).length>0&&SO(S,i),S.name=t.createUniqueName(i.name||"mesh_"+e),cr(S,i),k.extensions&&Bo(a,S,k),t.assignFinalMaterial(S),p.push(S)}for(let b=0,x=p.length;b<x;b++)t.associations.set(p[b],{meshes:e,primitives:b});if(p.length===1)return i.extensions&&Bo(a,p[0],i),p[0];const f=new Fn;i.extensions&&Bo(a,f,i),t.associations.set(f,{meshes:e});for(let b=0,x=p.length;b<x;b++)f.add(p[b]);return f})}loadCamera(e){let t;const n=this.json.cameras[e],a=n[n.type];if(!a){console.warn("THREE.GLTFLoader: Missing camera parameters.");return}return n.type==="perspective"?t=new bx(yx.radToDeg(a.yfov),a.aspectRatio||1,a.znear||1,a.zfar||2e6):n.type==="orthographic"&&(t=new OA(-a.xmag,a.xmag,a.ymag,-a.ymag,a.znear,a.zfar)),n.name&&(t.name=this.createUniqueName(n.name)),cr(t,n),Promise.resolve(t)}loadSkin(e){const t=this.json.skins[e],n=[];for(let a=0,i=t.joints.length;a<i;a++)n.push(this._loadNodeShallow(t.joints[a]));return t.inverseBindMatrices!==void 0?n.push(this.getDependency("accessor",t.inverseBindMatrices)):n.push(null),Promise.all(n).then(function(a){const i=a.pop(),o=a,l=[],c=[];for(let d=0,m=o.length;d<m;d++){const p=o[d];if(p){l.push(p);const f=new sl;i!==null&&f.fromArray(i.array,d*16),c.push(f)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',t.joints[d])}return new pP(l,c)})}loadAnimation(e){const t=this.json,n=this,a=t.animations[e],i=a.name?a.name:"animation_"+e,o=[],l=[],c=[],d=[],m=[];for(let p=0,f=a.channels.length;p<f;p++){const b=a.channels[p],x=a.samplers[b.sampler],w=b.target,k=w.node,S=a.parameters!==void 0?a.parameters[x.input]:x.input,j=a.parameters!==void 0?a.parameters[x.output]:x.output;w.node!==void 0&&(o.push(this.getDependency("node",k)),l.push(this.getDependency("accessor",S)),c.push(this.getDependency("accessor",j)),d.push(x),m.push(w))}return Promise.all([Promise.all(o),Promise.all(l),Promise.all(c),Promise.all(d),Promise.all(m)]).then(function(p){const f=p[0],b=p[1],x=p[2],w=p[3],k=p[4],S=[];for(let j=0,C=f.length;j<C;j++){const N=f[j],P=b[j],_=x[j],L=w[j],M=k[j];if(N===void 0)continue;N.updateMatrix&&N.updateMatrix();const D=n._createAnimationTracks(N,P,_,L,M);if(D)for(let E=0;E<D.length;E++)S.push(D[E])}return new mP(i,void 0,S)})}createNodeMesh(e){const t=this.json,n=this,a=t.nodes[e];return a.mesh===void 0?null:n.getDependency("mesh",a.mesh).then(function(i){const o=n._getNodeRef(n.meshCache,a.mesh,i);return a.weights!==void 0&&o.traverse(function(l){if(l.isMesh)for(let c=0,d=a.weights.length;c<d;c++)l.morphTargetInfluences[c]=a.weights[c]}),o})}loadNode(e){const t=this.json,n=this,a=t.nodes[e],i=n._loadNodeShallow(e),o=[],l=a.children||[];for(let d=0,m=l.length;d<m;d++)o.push(n.getDependency("node",l[d]));const c=a.skin===void 0?Promise.resolve(null):n.getDependency("skin",a.skin);return Promise.all([i,Promise.all(o),c]).then(function(d){const m=d[0],p=d[1],f=d[2];f!==null&&m.traverse(function(b){b.isSkinnedMesh&&b.bind(f,NO)});for(let b=0,x=p.length;b<x;b++)m.add(p[b]);return m})}_loadNodeShallow(e){const t=this.json,n=this.extensions,a=this;if(this.nodeCache[e]!==void 0)return this.nodeCache[e];const i=t.nodes[e],o=i.name?a.createUniqueName(i.name):"",l=[],c=a._invokeOne(function(d){return d.createNodeMesh&&d.createNodeMesh(e)});return c&&l.push(c),i.camera!==void 0&&l.push(a.getDependency("camera",i.camera).then(function(d){return a._getNodeRef(a.cameraCache,i.camera,d)})),a._invokeAll(function(d){return d.createNodeAttachment&&d.createNodeAttachment(e)}).forEach(function(d){l.push(d)}),this.nodeCache[e]=Promise.all(l).then(function(d){let m;if(i.isBone===!0?m=new fP:d.length>1?m=new Fn:d.length===1?m=d[0]:m=new RA,m!==d[0])for(let p=0,f=d.length;p<f;p++)m.add(d[p]);if(i.name&&(m.userData.name=i.name,m.name=o),cr(m,i),i.extensions&&Bo(n,m,i),i.matrix!==void 0){const p=new sl;p.fromArray(i.matrix),m.applyMatrix4(p)}else i.translation!==void 0&&m.position.fromArray(i.translation),i.rotation!==void 0&&m.quaternion.fromArray(i.rotation),i.scale!==void 0&&m.scale.fromArray(i.scale);return a.associations.has(m)||a.associations.set(m,{}),a.associations.get(m).nodes=e,m}),this.nodeCache[e]}loadScene(e){const t=this.extensions,n=this.json.scenes[e],a=this,i=new Fn;n.name&&(i.name=a.createUniqueName(n.name)),cr(i,n),n.extensions&&Bo(t,i,n);const o=n.nodes||[],l=[];for(let c=0,d=o.length;c<d;c++)l.push(a.getDependency("node",o[c]));return Promise.all(l).then(function(c){for(let m=0,p=c.length;m<p;m++)i.add(c[m]);const d=m=>{const p=new Map;for(const[f,b]of a.associations)(f instanceof hr||f instanceof vS)&&p.set(f,b);return m.traverse(f=>{const b=a.associations.get(f);b!=null&&p.set(f,b)}),p};return a.associations=d(i),i})}_createAnimationTracks(e,t,n,a,i){const o=[],l=e.name?e.name:e.uuid,c=[];Xr[i.path]===Xr.weights?e.traverse(function(f){f.morphTargetInfluences&&c.push(f.name?f.name:f.uuid)}):c.push(l);let d;switch(Xr[i.path]){case Xr.weights:d=kS;break;case Xr.rotation:d=SS;break;case Xr.position:case Xr.scale:d=wS;break;default:switch(n.itemSize){case 1:d=kS;break;case 2:case 3:default:d=wS;break}break}const m=a.interpolation!==void 0?vO[a.interpolation]:IA,p=this._getArrayFromAccessor(n);for(let f=0,b=c.length;f<b;f++){const x=new d(c[f]+"."+Xr[i.path],t.array,p,m);a.interpolation==="CUBICSPLINE"&&this._createCubicSplineTrackInterpolant(x),o.push(x)}return o}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){const n=Ay(t.constructor),a=new Float32Array(t.length);for(let i=0,o=t.length;i<o;i++)a[i]=t[i]*n;t=a}return t}_createCubicSplineTrackInterpolant(e){e.createInterpolant=function(n){const a=this instanceof SS?xO:kM;return new a(this.times,this.values,this.getValueSize()/3,n)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function MO(s,e,t){const n=e.attributes,a=new Ep;if(n.POSITION!==void 0){const l=t.json.accessors[n.POSITION],c=l.min,d=l.max;if(c!==void 0&&d!==void 0){if(a.set(new gt(c[0],c[1],c[2]),new gt(d[0],d[1],d[2])),l.normalized){const m=Ay(hc[l.componentType]);a.min.multiplyScalar(m),a.max.multiplyScalar(m)}}else{console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");return}}else return;const i=e.targets;if(i!==void 0){const l=new gt,c=new gt;for(let d=0,m=i.length;d<m;d++){const p=i[d];if(p.POSITION!==void 0){const f=t.json.accessors[p.POSITION],b=f.min,x=f.max;if(b!==void 0&&x!==void 0){if(c.setX(Math.max(Math.abs(b[0]),Math.abs(x[0]))),c.setY(Math.max(Math.abs(b[1]),Math.abs(x[1]))),c.setZ(Math.max(Math.abs(b[2]),Math.abs(x[2]))),f.normalized){const w=Ay(hc[f.componentType]);c.multiplyScalar(w)}l.max(c)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}a.expandByVector(l)}s.boundingBox=a;const o=new xP;a.getCenter(o.center),o.radius=a.min.distanceTo(a.max)/2,s.boundingSphere=o}function Nj(s,e,t){const n=e.attributes,a=[];function i(o,l){return t.getDependency("accessor",o).then(function(c){s.setAttribute(l,c)})}for(const o in n){const l=Ny[o]||o.toLowerCase();l in s.attributes||a.push(i(n[o],l))}if(e.indices!==void 0&&!s.index){const o=t.getDependency("accessor",e.indices).then(function(l){s.setIndex(l)});a.push(o)}return iy.workingColorSpace!==Ii&&"COLOR_0"in n&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${iy.workingColorSpace}" not supported.`),cr(s,e),MO(s,e,t),Promise.all(a).then(function(){return e.targets!==void 0?kO(s,e.targets,t):s})}const ib=new WeakMap;class Mx extends DA{constructor(e){super(e),this.decoderPath="",this.decoderConfig={},this.decoderBinary=null,this.decoderPending=null,this.workerLimit=4,this.workerPool=[],this.workerNextTaskID=1,this.workerSourceURL="",this.defaultAttributeIDs={position:"POSITION",normal:"NORMAL",color:"COLOR",uv:"TEX_COORD"},this.defaultAttributeTypes={position:"Float32Array",normal:"Float32Array",color:"Float32Array",uv:"Float32Array"}}setDecoderPath(e){return this.decoderPath=e,this}setDecoderConfig(e){return this.decoderConfig=e,this}setWorkerLimit(e){return this.workerLimit=e,this}load(e,t,n,a){const i=new Tp(this.manager);i.setPath(this.path),i.setResponseType("arraybuffer"),i.setRequestHeader(this.requestHeader),i.setWithCredentials(this.withCredentials),i.load(e,o=>{this.parse(o,t,a)},n,a)}parse(e,t,n=()=>{}){this.decodeDracoFile(e,t,null,null,ii,n).catch(n)}decodeDracoFile(e,t,n,a,i=Ii,o=()=>{}){const l={attributeIDs:n||this.defaultAttributeIDs,attributeTypes:a||this.defaultAttributeTypes,useUniqueIDs:!!n,vertexColorSpace:i};return this.decodeGeometry(e,l).then(t).catch(o)}decodeGeometry(e,t){const n=JSON.stringify(t);if(ib.has(e)){const c=ib.get(e);if(c.key===n)return c.promise;if(e.byteLength===0)throw new Error("THREE.DRACOLoader: Unable to re-decode a buffer with different settings. Buffer has already been transferred.")}let a;const i=this.workerNextTaskID++,o=e.byteLength,l=this._getWorker(i,o).then(c=>(a=c,new Promise((d,m)=>{a._callbacks[i]={resolve:d,reject:m},a.postMessage({type:"decode",id:i,taskConfig:t,buffer:e},[e])}))).then(c=>this._createGeometry(c.geometry));return l.catch(()=>!0).then(()=>{a&&i&&this._releaseTask(a,i)}),ib.set(e,{key:n,promise:l}),l}_createGeometry(e){const t=new Wa;e.index&&t.setIndex(new ri(e.index.array,1));for(let n=0;n<e.attributes.length;n++){const a=e.attributes[n],i=a.name,o=a.array,l=a.itemSize,c=new ri(o,l);i==="color"&&(this._assignVertexColorSpace(c,a.vertexColorSpace),c.normalized=!(o instanceof Float32Array)),t.setAttribute(i,c)}return t}_assignVertexColorSpace(e,t){if(t!==ii)return;const n=new Gt;for(let a=0,i=e.count;a<i;a++)n.fromBufferAttribute(e,a),iy.toWorkingColorSpace(n,ii),e.setXYZ(a,n.r,n.g,n.b)}_loadLibrary(e,t){const n=new Tp(this.manager);return n.setPath(this.decoderPath),n.setResponseType(t),n.setWithCredentials(this.withCredentials),new Promise((a,i)=>{n.load(e,a,void 0,i)})}preload(){return this._initDecoder(),this}_initDecoder(){if(this.decoderPending)return this.decoderPending;const e=typeof WebAssembly!="object"||this.decoderConfig.type==="js",t=[];return e?t.push(this._loadLibrary("draco_decoder.js","text")):(t.push(this._loadLibrary("draco_wasm_wrapper.js","text")),t.push(this._loadLibrary("draco_decoder.wasm","arraybuffer"))),this.decoderPending=Promise.all(t).then(n=>{const a=n[0];e||(this.decoderConfig.wasmBinary=n[1]);const i=TO.toString(),o=["/* draco decoder */",a,"","/* worker */",i.substring(i.indexOf("{")+1,i.lastIndexOf("}"))].join(`
42
+ */var KS;function jR(){if(KS)return Qg;KS=1;var s=mx();function e(p,f){return p===f&&(p!==0||1/p===1/f)||p!==p&&f!==f}var t=typeof Object.is=="function"?Object.is:e,n=s.useState,a=s.useEffect,i=s.useLayoutEffect,o=s.useDebugValue;function l(p,f){var b=f(),x=n({inst:{value:b,getSnapshot:f}}),w=x[0].inst,k=x[1];return i(function(){w.value=b,w.getSnapshot=f,c(w)&&k({inst:w})},[p,b,f]),a(function(){return c(w)&&k({inst:w}),p(function(){c(w)&&k({inst:w})})},[p]),o(b),b}function c(p){var f=p.getSnapshot;p=p.value;try{var b=f();return!t(p,b)}catch{return!0}}function d(p,f){return f()}var m=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?d:l;return Qg.useSyncExternalStore=s.useSyncExternalStore!==void 0?s.useSyncExternalStore:m,Qg}var XS;function CR(){return XS||(XS=1,Zg.exports=jR()),Zg.exports}var NR=CR();const AR=(s,e)=>ol(e)?e:hR(e)&&ol(e.defaultValue)?e.defaultValue:Array.isArray(s)?s[s.length-1]:s,MR={t:AR,ready:!1},TR=()=>()=>{},$e=(s,e={})=>{var D,E,R;const{i18n:t}=e,{i18n:n,defaultNS:a}=y.useContext(kR)||{},i=t||n||vR();i&&!i.reportNamespaces&&(i.reportNamespaces=new SR),i||VA(i,"NO_I18NEXT_INSTANCE","useTranslation: You will need to pass in an i18next instance by using initReactI18next");const o=y.useMemo(()=>{var O;return{...yR(),...(O=i==null?void 0:i.options)==null?void 0:O.react,...e}},[i,e]),{useSuspense:l,keyPrefix:c}=o,d=s||a||((D=i==null?void 0:i.options)==null?void 0:D.defaultNS),m=ol(d)?[d]:d||["translation"],p=y.useMemo(()=>m,m);(R=(E=i==null?void 0:i.reportNamespaces)==null?void 0:E.addUsedNamespaces)==null||R.call(E,p);const f=y.useRef(0),b=y.useCallback(O=>{if(!i)return TR;const{bindI18n:I,bindI18nStore:B}=o,Y=()=>{f.current+=1,O()};return I&&i.on(I,Y),B&&i.store.on(B,Y),()=>{I&&I.split(" ").forEach($=>i.off($,Y)),B&&B.split(" ").forEach($=>i.store.off($,Y))}},[i,o]),x=y.useRef(),w=y.useCallback(()=>{if(!i)return MR;const O=!!(i.isInitialized||i.initializedStoreOnce)&&p.every(K=>dR(K,i,o)),I=e.lng||i.language,B=f.current,Y=x.current;if(Y&&Y.ready===O&&Y.lng===I&&Y.keyPrefix===c&&Y.revision===B)return Y;const W={t:i.getFixedT(I,o.nsMode==="fallback"?p:p[0],c),ready:O,lng:I,keyPrefix:c,revision:B};return x.current=W,W},[i,p,c,o,e.lng]),[k,S]=y.useState(0),{t:j,ready:C}=NR.useSyncExternalStore(b,w,w);y.useEffect(()=>{if(i&&!C&&!l){const O=()=>S(I=>I+1);e.lng?VS(i,e.lng,p,O):dy(i,p,O)}},[i,e.lng,p,C,l,k]);const N=i||{},P=y.useRef(null),_=y.useRef(),L=O=>{const I=Object.getOwnPropertyDescriptors(O);I.__original&&delete I.__original;const B=Object.create(Object.getPrototypeOf(O),I);if(!Object.prototype.hasOwnProperty.call(B,"__original"))try{Object.defineProperty(B,"__original",{value:O,writable:!1,enumerable:!1,configurable:!1})}catch{}return B},M=y.useMemo(()=>{const O=N,I=O==null?void 0:O.language;let B=O;O&&(P.current&&P.current.__original===O?_.current!==I?(B=L(O),P.current=B,_.current=I):B=P.current:(B=L(O),P.current=B,_.current=I));const Y=[j,B,C];return Y.t=j,Y.i18n=B,Y.ready=C,Y},[j,N,C,N.resolvedLanguage,N.language,N.languages]);if(i&&l&&!C)throw new Promise(O=>{const I=()=>O();e.lng?VS(i,e.lng,p,I):dy(i,p,I)});return M};function py(s){"@babel/helpers - typeof";return py=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},py(s)}function ZA(){return typeof XMLHttpRequest=="function"||(typeof XMLHttpRequest>"u"?"undefined":py(XMLHttpRequest))==="object"}function ER(s){return!!s&&typeof s.then=="function"}function _R(s){return ER(s)?s:Promise.resolve(s)}const DR="modulepreload",PR=function(s){return"/"+s},ZS={},QA=function(e,t,n){let a=Promise.resolve();if(t&&t.length>0){let o=function(d){return Promise.all(d.map(m=>Promise.resolve(m).then(p=>({status:"fulfilled",value:p}),p=>({status:"rejected",reason:p}))))};document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),c=(l==null?void 0:l.nonce)||(l==null?void 0:l.getAttribute("nonce"));a=o(t.map(d=>{if(d=PR(d),d in ZS)return;ZS[d]=!0;const m=d.endsWith(".css"),p=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${p}`))return;const f=document.createElement("link");if(f.rel=m?"stylesheet":DR,m||(f.as="script"),f.crossOrigin="",f.href=d,c&&f.setAttribute("nonce",c),document.head.appendChild(f),m)return new Promise((b,x)=>{f.addEventListener("load",b),f.addEventListener("error",()=>x(new Error(`Unable to preload CSS for ${d}`)))})}))}function i(o){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=o,window.dispatchEvent(l),!l.defaultPrevented)throw o}return a.then(o=>{for(const l of o||[])l.status==="rejected"&&i(l.reason);return e().catch(i)})};function QS(s,e){var t=Object.keys(s);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(s);e&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),t.push.apply(t,n)}return t}function JS(s){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?QS(Object(t),!0).forEach(function(n){RR(s,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(t)):QS(Object(t)).forEach(function(n){Object.defineProperty(s,n,Object.getOwnPropertyDescriptor(t,n))})}return s}function RR(s,e,t){return(e=LR(e))in s?Object.defineProperty(s,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):s[e]=t,s}function LR(s){var e=OR(s,"string");return ll(e)=="symbol"?e:e+""}function OR(s,e){if(ll(s)!="object"||!s)return s;var t=s[Symbol.toPrimitive];if(t!==void 0){var n=t.call(s,e);if(ll(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(s)}function ll(s){"@babel/helpers - typeof";return ll=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},ll(s)}var lo=typeof fetch=="function"?fetch:void 0;typeof global<"u"&&global.fetch?lo=global.fetch:typeof window<"u"&&window.fetch&&(lo=window.fetch);var cd;ZA()&&(typeof global<"u"&&global.XMLHttpRequest?cd=global.XMLHttpRequest:typeof window<"u"&&window.XMLHttpRequest&&(cd=window.XMLHttpRequest));var Lp;typeof ActiveXObject=="function"&&(typeof global<"u"&&global.ActiveXObject?Lp=global.ActiveXObject:typeof window<"u"&&window.ActiveXObject&&(Lp=window.ActiveXObject));typeof lo!="function"&&(lo=void 0);if(!lo&&!cd&&!Lp)try{QA(()=>import("./browser-ponyfill-DIm4hKhx.js").then(s=>s.b),__vite__mapDeps([0,1])).then(function(s){lo=s.default}).catch(function(){})}catch{}var my=function(e,t){if(t&&ll(t)==="object"){var n="";for(var a in t)n+="&"+encodeURIComponent(a)+"="+encodeURIComponent(t[a]);if(!n)return e;e=e+(e.indexOf("?")!==-1?"&":"?")+n.slice(1)}return e},ej=function(e,t,n,a){var i=function(c){if(!c.ok)return n(c.statusText||"Error",{status:c.status});c.text().then(function(d){n(null,{status:c.status,data:d})}).catch(n)};if(a){var o=a(e,t);if(o instanceof Promise){o.then(i).catch(n);return}}typeof fetch=="function"?fetch(e,t).then(i).catch(n):lo(e,t).then(i).catch(n)},tj=!1,IR=function(e,t,n,a){e.queryStringParams&&(t=my(t,e.queryStringParams));var i=JS({},typeof e.customHeaders=="function"?e.customHeaders():e.customHeaders);typeof window>"u"&&typeof global<"u"&&typeof global.process<"u"&&global.process.versions&&global.process.versions.node&&(i["User-Agent"]="i18next-http-backend (node/".concat(global.process.version,"; ").concat(global.process.platform," ").concat(global.process.arch,")")),n&&(i["Content-Type"]="application/json");var o=typeof e.requestOptions=="function"?e.requestOptions(n):e.requestOptions,l=JS({method:n?"POST":"GET",body:n?e.stringify(n):void 0,headers:i},tj?{}:o),c=typeof e.alternateFetch=="function"&&e.alternateFetch.length>=1?e.alternateFetch:void 0;try{ej(t,l,a,c)}catch(d){if(!o||Object.keys(o).length===0||!d.message||d.message.indexOf("not implemented")<0)return a(d);try{Object.keys(o).forEach(function(m){delete l[m]}),ej(t,l,a,c),tj=!0}catch(m){a(m)}}},BR=function(e,t,n,a){n&&ll(n)==="object"&&(n=my("",n).slice(1)),e.queryStringParams&&(t=my(t,e.queryStringParams));try{var i=cd?new cd:new Lp("MSXML2.XMLHTTP.3.0");i.open(n?"POST":"GET",t,1),e.crossDomain||i.setRequestHeader("X-Requested-With","XMLHttpRequest"),i.withCredentials=!!e.withCredentials,n&&i.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),i.overrideMimeType&&i.overrideMimeType("application/json");var o=e.customHeaders;if(o=typeof o=="function"?o():o,o)for(var l in o)i.setRequestHeader(l,o[l]);i.onreadystatechange=function(){i.readyState>3&&a(i.status>=400?i.statusText:null,{status:i.status,data:i.responseText})},i.send(n)}catch(c){console&&console.log(c)}},zR=function(e,t,n,a){if(typeof n=="function"&&(a=n,n=void 0),a=a||function(){},lo&&t.indexOf("file:")!==0)return IR(e,t,n,a);if(ZA()||typeof ActiveXObject=="function")return BR(e,t,n,a);a(new Error("No fetch and no xhr implementation found!"))};function yc(s){"@babel/helpers - typeof";return yc=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},yc(s)}function nj(s,e){var t=Object.keys(s);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(s);e&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),t.push.apply(t,n)}return t}function Jg(s){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?nj(Object(t),!0).forEach(function(n){JA(s,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(t)):nj(Object(t)).forEach(function(n){Object.defineProperty(s,n,Object.getOwnPropertyDescriptor(t,n))})}return s}function FR(s,e){if(!(s instanceof e))throw new TypeError("Cannot call a class as a function")}function $R(s,e){for(var t=0;t<e.length;t++){var n=e[t];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(s,eM(n.key),n)}}function HR(s,e,t){return e&&$R(s.prototype,e),Object.defineProperty(s,"prototype",{writable:!1}),s}function JA(s,e,t){return(e=eM(e))in s?Object.defineProperty(s,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):s[e]=t,s}function eM(s){var e=UR(s,"string");return yc(e)=="symbol"?e:e+""}function UR(s,e){if(yc(s)!="object"||!s)return s;var t=s[Symbol.toPrimitive];if(t!==void 0){var n=t.call(s,e);if(yc(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(s)}var GR=function(){return{loadPath:"/locales/{{lng}}/{{ns}}.json",addPath:"/locales/add/{{lng}}/{{ns}}",parse:function(t){return JSON.parse(t)},stringify:JSON.stringify,parsePayload:function(t,n,a){return JA({},n,a||"")},parseLoadPayload:function(t,n){},request:zR,reloadInterval:typeof window<"u"?!1:3600*1e3,customHeaders:{},queryStringParams:{},crossDomain:!1,withCredentials:!1,overrideMimeType:!1,requestOptions:{mode:"cors",credentials:"same-origin",cache:"default"}}},tM=(function(){function s(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};FR(this,s),this.services=e,this.options=t,this.allOptions=n,this.type="backend",this.init(e,t,n)}return HR(s,[{key:"init",value:function(t){var n=this,a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(this.services=t,this.options=Jg(Jg(Jg({},GR()),this.options||{}),a),this.allOptions=i,this.services&&this.options.reloadInterval){var o=setInterval(function(){return n.reload()},this.options.reloadInterval);yc(o)==="object"&&typeof o.unref=="function"&&o.unref()}}},{key:"readMulti",value:function(t,n,a){this._readAny(t,t,n,n,a)}},{key:"read",value:function(t,n,a){this._readAny([t],t,[n],n,a)}},{key:"_readAny",value:function(t,n,a,i,o){var l=this,c=this.options.loadPath;typeof this.options.loadPath=="function"&&(c=this.options.loadPath(t,a)),c=_R(c),c.then(function(d){if(!d)return o(null,{});var m=l.services.interpolator.interpolate(d,{lng:t.join("+"),ns:a.join("+")});l.loadUrl(m,o,n,i)})}},{key:"loadUrl",value:function(t,n,a,i){var o=this,l=typeof a=="string"?[a]:a,c=typeof i=="string"?[i]:i,d=this.options.parseLoadPayload(l,c);this.options.request(this.options,t,d,function(m,p){if(p&&(p.status>=500&&p.status<600||!p.status))return n("failed loading "+t+"; status code: "+p.status,!0);if(p&&p.status>=400&&p.status<500)return n("failed loading "+t+"; status code: "+p.status,!1);if(!p&&m&&m.message){var f=m.message.toLowerCase(),b=["failed","fetch","network","load"].find(function(k){return f.indexOf(k)>-1});if(b)return n("failed loading "+t+": "+m.message,!0)}if(m)return n(m,!1);var x,w;try{typeof p.data=="string"?x=o.options.parse(p.data,a,i):x=p.data}catch{w="failed parsing "+t+" to json"}if(w)return n(w,!1);n(null,x)})}},{key:"create",value:function(t,n,a,i,o){var l=this;if(this.options.addPath){typeof t=="string"&&(t=[t]);var c=this.options.parsePayload(n,a,i),d=0,m=[],p=[];t.forEach(function(f){var b=l.options.addPath;typeof l.options.addPath=="function"&&(b=l.options.addPath(f,n));var x=l.services.interpolator.interpolate(b,{lng:f,ns:n});l.options.request(l.options,x,c,function(w,k){d+=1,m.push(w),p.push(k),d===t.length&&typeof o=="function"&&o(m,p)})})}}},{key:"reload",value:function(){var t=this,n=this.services,a=n.backendConnector,i=n.languageUtils,o=n.logger,l=a.language;if(!(l&&l.toLowerCase()==="cimode")){var c=[],d=function(p){var f=i.toResolveHierarchy(p);f.forEach(function(b){c.indexOf(b)<0&&c.push(b)})};d(l),this.allOptions.preload&&this.allOptions.preload.forEach(function(m){return d(m)}),c.forEach(function(m){t.allOptions.ns.forEach(function(p){a.read(m,p,"read",null,null,function(f,b){f&&o.warn("loading namespace ".concat(p," for language ").concat(m," failed"),f),!f&&b&&o.log("loaded namespace ".concat(p," for language ").concat(m),b),a.loaded("".concat(m,"|").concat(p),f,b)})})})}}}])})();tM.type="backend";const{slice:WR,forEach:qR}=[];function YR(s){return qR.call(WR.call(arguments,1),e=>{if(e)for(const t in e)s[t]===void 0&&(s[t]=e[t])}),s}function VR(s){return typeof s!="string"?!1:[/<\s*script.*?>/i,/<\s*\/\s*script\s*>/i,/<\s*img.*?on\w+\s*=/i,/<\s*\w+\s*on\w+\s*=.*?>/i,/javascript\s*:/i,/vbscript\s*:/i,/expression\s*\(/i,/eval\s*\(/i,/alert\s*\(/i,/document\.cookie/i,/document\.write\s*\(/i,/window\.location/i,/innerHTML/i].some(t=>t.test(s))}const sj=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/,KR=function(s,e){const n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{path:"/"},a=encodeURIComponent(e);let i=`${s}=${a}`;if(n.maxAge>0){const o=n.maxAge-0;if(Number.isNaN(o))throw new Error("maxAge should be a Number");i+=`; Max-Age=${Math.floor(o)}`}if(n.domain){if(!sj.test(n.domain))throw new TypeError("option domain is invalid");i+=`; Domain=${n.domain}`}if(n.path){if(!sj.test(n.path))throw new TypeError("option path is invalid");i+=`; Path=${n.path}`}if(n.expires){if(typeof n.expires.toUTCString!="function")throw new TypeError("option expires is invalid");i+=`; Expires=${n.expires.toUTCString()}`}if(n.httpOnly&&(i+="; HttpOnly"),n.secure&&(i+="; Secure"),n.sameSite)switch(typeof n.sameSite=="string"?n.sameSite.toLowerCase():n.sameSite){case!0:i+="; SameSite=Strict";break;case"lax":i+="; SameSite=Lax";break;case"strict":i+="; SameSite=Strict";break;case"none":i+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}return n.partitioned&&(i+="; Partitioned"),i},aj={create(s,e,t,n){let a=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{path:"/",sameSite:"strict"};t&&(a.expires=new Date,a.expires.setTime(a.expires.getTime()+t*60*1e3)),n&&(a.domain=n),document.cookie=KR(s,e,a)},read(s){const e=`${s}=`,t=document.cookie.split(";");for(let n=0;n<t.length;n++){let a=t[n];for(;a.charAt(0)===" ";)a=a.substring(1,a.length);if(a.indexOf(e)===0)return a.substring(e.length,a.length)}return null},remove(s,e){this.create(s,"",-1,e)}};var XR={name:"cookie",lookup(s){let{lookupCookie:e}=s;if(e&&typeof document<"u")return aj.read(e)||void 0},cacheUserLanguage(s,e){let{lookupCookie:t,cookieMinutes:n,cookieDomain:a,cookieOptions:i}=e;t&&typeof document<"u"&&aj.create(t,s,n,a,i)}},ZR={name:"querystring",lookup(s){var n;let{lookupQuerystring:e}=s,t;if(typeof window<"u"){let{search:a}=window.location;!window.location.search&&((n=window.location.hash)==null?void 0:n.indexOf("?"))>-1&&(a=window.location.hash.substring(window.location.hash.indexOf("?")));const o=a.substring(1).split("&");for(let l=0;l<o.length;l++){const c=o[l].indexOf("=");c>0&&o[l].substring(0,c)===e&&(t=o[l].substring(c+1))}}return t}},QR={name:"hash",lookup(s){var a;let{lookupHash:e,lookupFromHashIndex:t}=s,n;if(typeof window<"u"){const{hash:i}=window.location;if(i&&i.length>2){const o=i.substring(1);if(e){const l=o.split("&");for(let c=0;c<l.length;c++){const d=l[c].indexOf("=");d>0&&l[c].substring(0,d)===e&&(n=l[c].substring(d+1))}}if(n)return n;if(!n&&t>-1){const l=i.match(/\/([a-zA-Z-]*)/g);return Array.isArray(l)?(a=l[typeof t=="number"?t:0])==null?void 0:a.replace("/",""):void 0}}}return n}};let Yl=null;const ij=()=>{if(Yl!==null)return Yl;try{if(Yl=typeof window<"u"&&window.localStorage!==null,!Yl)return!1;const s="i18next.translate.boo";window.localStorage.setItem(s,"foo"),window.localStorage.removeItem(s)}catch{Yl=!1}return Yl};var JR={name:"localStorage",lookup(s){let{lookupLocalStorage:e}=s;if(e&&ij())return window.localStorage.getItem(e)||void 0},cacheUserLanguage(s,e){let{lookupLocalStorage:t}=e;t&&ij()&&window.localStorage.setItem(t,s)}};let Vl=null;const rj=()=>{if(Vl!==null)return Vl;try{if(Vl=typeof window<"u"&&window.sessionStorage!==null,!Vl)return!1;const s="i18next.translate.boo";window.sessionStorage.setItem(s,"foo"),window.sessionStorage.removeItem(s)}catch{Vl=!1}return Vl};var eL={name:"sessionStorage",lookup(s){let{lookupSessionStorage:e}=s;if(e&&rj())return window.sessionStorage.getItem(e)||void 0},cacheUserLanguage(s,e){let{lookupSessionStorage:t}=e;t&&rj()&&window.sessionStorage.setItem(t,s)}},tL={name:"navigator",lookup(s){const e=[];if(typeof navigator<"u"){const{languages:t,userLanguage:n,language:a}=navigator;if(t)for(let i=0;i<t.length;i++)e.push(t[i]);n&&e.push(n),a&&e.push(a)}return e.length>0?e:void 0}},nL={name:"htmlTag",lookup(s){let{htmlTag:e}=s,t;const n=e||(typeof document<"u"?document.documentElement:null);return n&&typeof n.getAttribute=="function"&&(t=n.getAttribute("lang")),t}},sL={name:"path",lookup(s){var a;let{lookupFromPathIndex:e}=s;if(typeof window>"u")return;const t=window.location.pathname.match(/\/([a-zA-Z-]*)/g);return Array.isArray(t)?(a=t[typeof e=="number"?e:0])==null?void 0:a.replace("/",""):void 0}},aL={name:"subdomain",lookup(s){var a,i;let{lookupFromSubdomainIndex:e}=s;const t=typeof e=="number"?e+1:1,n=typeof window<"u"&&((i=(a=window.location)==null?void 0:a.hostname)==null?void 0:i.match(/^(\w{2,5})\.(([a-z0-9-]{1,63}\.[a-z]{2,6})|localhost)/i));if(n)return n[t]}};let nM=!1;try{document.cookie,nM=!0}catch{}const sM=["querystring","cookie","localStorage","sessionStorage","navigator","htmlTag"];nM||sM.splice(1,1);const iL=()=>({order:sM,lookupQuerystring:"lng",lookupCookie:"i18next",lookupLocalStorage:"i18nextLng",lookupSessionStorage:"i18nextLng",caches:["localStorage"],excludeCacheFor:["cimode"],convertDetectedLanguage:s=>s});class aM{constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.type="languageDetector",this.detectors={},this.init(e,t)}init(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{languageUtils:{}},t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};this.services=e,this.options=YR(t,this.options||{},iL()),typeof this.options.convertDetectedLanguage=="string"&&this.options.convertDetectedLanguage.indexOf("15897")>-1&&(this.options.convertDetectedLanguage=a=>a.replace("-","_")),this.options.lookupFromUrlIndex&&(this.options.lookupFromPathIndex=this.options.lookupFromUrlIndex),this.i18nOptions=n,this.addDetector(XR),this.addDetector(ZR),this.addDetector(JR),this.addDetector(eL),this.addDetector(tL),this.addDetector(nL),this.addDetector(sL),this.addDetector(aL),this.addDetector(QR)}addDetector(e){return this.detectors[e.name]=e,this}detect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.options.order,t=[];return e.forEach(n=>{if(this.detectors[n]){let a=this.detectors[n].lookup(this.options);a&&typeof a=="string"&&(a=[a]),a&&(t=t.concat(a))}}),t=t.filter(n=>n!=null&&!VR(n)).map(n=>this.options.convertDetectedLanguage(n)),this.services&&this.services.languageUtils&&this.services.languageUtils.getBestMatchFromCodes?t:t.length>0?t[0]:null}cacheUserLanguage(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.options.caches;t&&(this.options.excludeCacheFor&&this.options.excludeCacheFor.indexOf(e)>-1||t.forEach(n=>{this.detectors[n]&&this.detectors[n].cacheUserLanguage(e,this.options)}))}}aM.type="languageDetector";const Op={idle:"#4aff9e",working:"#4a9eff",waiting:"#ff9e4a",waiting_permission:"#ffcc00",error:"#ff4a4a",offline:"#888888",orphaned:"#ff9e4a",default:"#888888"},co={running:"#4aff9e",stopped:"#888888",error:"#ff4a4a",unknown:"#ffaa00",starting:"#4a9eff",stopping:"#ffaa00"},iM={on_track:"#4aff9e",stalled:"#ff9e4a",blocked:"#ff4a4a",completed:"#4a9eff",idle:"#888888"},rL=["#4a9eff","#4aff9e","#ff9e4a","#ff4a9e","#9e4aff","#ff4a4a","#4affff","#ffff4a","#4ad7ff","#00e6a8","#ff6b4a","#ff66cc","#b84aff","#ff4a7a","#00d9ff","#e6ff4a","#1a3a6e","#1a5e3a","#6e3a1a","#6e1a4a","#4a1a6e","#6e1a1a","#1a5e5e","#5e5e1a","#1a4a6e","#145a47","#6e2c1a","#6e1a5e","#3b1a6e","#6e1a33","#14566e","#4f5e1a"],Gh={recent:"#50fa7b",short:"#f1fa8c",medium:"#ffb86c",long:"#ff5555"};function fm(s){const t=Math.floor((Date.now()-s)/1e3)/60;return t<1?Gh.recent:t<5?Gh.short:t<30?Gh.medium:Gh.long}function wx(s){return Op[s]??Op.default}let yp=null;function rM(){if(!yp)try{yp=globalThis.__i18n}catch{}return yp}function oL(s){yp=s}function lL(s){return s>=1e6?(s/1e6).toFixed(1)+"M":s>=1e3?(s/1e3).toFixed(1)+"K":s.toString()}function fy(s){return s>=1e6?(s/1e6).toFixed(1)+"M":s>=1e3?(s/1e3).toFixed(1)+"K":s.toString()}function oM(s){var a;const e=rM(),t=(a=e==null?void 0:e.t)==null?void 0:a.bind(e),n=Math.floor((Date.now()-s)/1e3);return n<60?t?t("common:time.seconds",{count:n}):`${n}s`:n<3600?t?t("common:time.minutes",{count:Math.floor(n/60)}):`${Math.floor(n/60)}m`:n<86400?t?t("common:time.hours",{count:Math.floor(n/3600)}):`${Math.floor(n/3600)}h`:t?t("common:time.days",{count:Math.floor(n/86400)}):`${Math.floor(n/86400)}d`}function gm(s){var d;const e=rM(),t=(d=e==null?void 0:e.t)==null?void 0:d.bind(e),n=Math.floor((Date.now()-s)/1e3);if(n<5)return t?t("common:time.justNow"):"just now";if(n<60)return t?t("common:time.secondsAgo",{count:n}):`${n}s ago`;const a=Math.floor(n/60);if(a<60){const m=n%60;return m>0?t?t("common:time.minutesSecondsAgo",{minutes:a,seconds:m}):`${a}m ${m}s ago`:t?t("common:time.minutesAgo",{count:a}):`${a}m ago`}const i=Math.floor(a/60),o=a%60;if(i<24)return o>0?t?t("common:time.hoursMinutesAgo",{hours:i,minutes:o}):`${i}h ${o}m ago`:t?t("common:time.hoursAgo",{count:i}):`${i}h ago`;const l=Math.floor(i/24),c=i%24;return c>0?t?t("common:time.daysHoursAgo",{days:l,hours:c}):`${l}d ${c}h ago`:t?t("common:time.daysAgo",{count:l}):`${l}d ago`}function io(s,e){return s?e?s.replace(/\s*\(?\s*~?\$[\d,.]+\s*\)?/g,"").replace(/\s*cost[:\s]+~?\$[\d,.]+/gi,"").replace(/\s*price[:\s]+~?\$[\d,.]+/gi,"").replace(/\s*\(~?\$[\d,.]+\s*(?:USD|cost|spent)?\)/gi,"").replace(/\s*-\s*~?\$[\d,.]+\s*$/g,"").replace(/[^\S\n]+/g," ").trim():s:""}wn.use(tM).use(aM).use(wR).init({fallbackLng:"en",ns:["common","tools","config","errors","notifications","dashboard","terminal"],defaultNS:"common",backend:{loadPath:"/locales/{{lng}}/{{ns}}.json"},detection:{order:["localStorage","navigator"],lookupLocalStorage:"tide-commander-language",caches:["localStorage"]},interpolation:{escapeValue:!1},react:{useSuspense:!0}}).then(()=>{oL(wn)});const vt={CONFIG:"tide-commander-config",SHOW_FPS:"tide-show-fps",SETTINGS:"tide-settings",SHORTCUTS:"tide-shortcuts",MOUSE_CONTROLS:"tide-mouse-controls",BACKEND_URL:"tide-backend-url",AUTH_TOKEN:"tide-auth-token",SCENE_VIEW_MODE:"tide-scene-view-mode",CAMERA_STATE:"tide-camera-state",CAMERA_STATE_2D:"tide-camera-state-2d",VIEW_MODE:"guake-view-mode",ADVANCED_VIEW:"guake-advanced-view",TERMINAL_HEIGHT:"guake-terminal-height",INPUT_TEXT_PREFIX:"guake-input-",PASTED_TEXTS_PREFIX:"guake-pasted-",COMMANDER_TAB:"commander-active-tab",COMMANDER_FILTERS:"commander-filters",LAST_CWD:"tide-last-cwd",GLOBAL_SUPERVISOR_COLLAPSED:"tide-global-supervisor-collapsed",TOOLS_COLLAPSED:"tide-tool-history-collapsed",FILES_COLLAPSED:"tide-file-history-collapsed",MOBILE_VIEW:"tide-mobile-view",TREE_PANEL_WIDTH:"tide-tree-panel-width",AGENT_ORDER:"tide-agent-order",AOP_CONFIG:"tide-aop-config",UNSEEN_AGENTS:"tide-unseen-agents"},gy="tide-backend-url-change";function ai(s,e){try{const t=localStorage.getItem(s);return t===null?e:JSON.parse(t)}catch{return e}}function la(s,e=""){try{return localStorage.getItem(s)??e}catch{return e}}function by(s,e=!1){try{const t=localStorage.getItem(s);return t===null?e:t==="true"}catch{return e}}function lM(s,e){try{const t=localStorage.getItem(s);if(t===null)return e;const n=Number(t);return isNaN(n)?e:n}catch{return e}}function Ei(s,e){try{localStorage.setItem(s,JSON.stringify(e))}catch(t){console.error(`Failed to save to localStorage: ${s}`,t)}}function Va(s,e){try{localStorage.setItem(s,e)}catch(t){console.error(`Failed to save to localStorage: ${s}`,t)}}function yy(s,e){try{localStorage.setItem(s,String(e))}catch(t){console.error(`Failed to save to localStorage: ${s}`,t)}}function cM(s,e){try{localStorage.setItem(s,String(e))}catch(t){console.error(`Failed to save to localStorage: ${s}`,t)}}function oj(s){try{localStorage.removeItem(s)}catch(e){console.error(`Failed to remove from localStorage: ${s}`,e)}}function hl(){const s=bm();return s?s.replace(/\/$/,""):`${window.location.protocol}//${window.location.host}`}function hi(){return la(vt.AUTH_TOKEN,"")}function bm(){return la(vt.BACKEND_URL,"")}function uM(s){const e=s.trim();Va(vt.BACKEND_URL,e),typeof window<"u"&&window.dispatchEvent(new CustomEvent(gy,{detail:e}))}function dM(s){if(typeof window>"u")return()=>{};const e=n=>{s(n.detail)},t=n=>{n.key===vt.BACKEND_URL&&s(n.newValue??"")};return window.addEventListener(gy,e),window.addEventListener("storage",t),()=>{window.removeEventListener(gy,e),window.removeEventListener("storage",t)}}function rt(s){return`${hl()}${s}`}async function bt(s,e){const t=hi(),n=new Headers(e==null?void 0:e.headers);return t&&n.set("X-Auth-Token",t),fetch(s,{...e,headers:n})}function kd(s){const e=hi();if(!e)return s;try{const t=!s.startsWith("http://")&&!s.startsWith("https://"),n=t?"http://dummy":void 0,a=new URL(s,n);return a.searchParams.set("token",e),t?a.pathname+a.search:a.toString()}catch{const t=s.includes("?")?"&":"?";return`${s}${t}token=${encodeURIComponent(e)}`}}function Ws(s=!1,e){const[t,n]=y.useState(s),[a,i]=y.useState(e),o=y.useCallback(d=>{d!==void 0&&i(d),n(!0)},[]),l=y.useCallback(()=>{n(!1)},[]),c=y.useCallback(()=>{n(d=>!d)},[]);return{isOpen:t,data:a,open:o,close:l,toggle:c,setData:i}}function cL(){const[s,e]=y.useState(null),t=y.useCallback(a=>{e(a)},[]),n=y.useCallback(()=>{e(null)},[]);return{isOpen:s!==null,id:s,open:t,close:n}}function uL(){const[s,e]=y.useState(!1),[t,n]=y.useState({x:0,y:0}),[a,i]=y.useState({x:0,z:0}),[o,l]=y.useState({type:"ground"}),c=y.useCallback((m,p,f)=>{n(m),i(p),l(f),e(!0)},[]),d=y.useCallback(()=>{e(!1)},[]);return{isOpen:s,screenPosition:t,worldPosition:a,target:o,open:c,close:d}}const si=[],dL=new Set;function Ip(){dL.forEach(s=>s())}function hL(s,e){const t=si.findIndex(n=>n.id===s);return t!==-1&&si.splice(t,1),si.push({id:s,close:e}),Ip(),()=>{const n=si.findIndex(a=>a.id===s);n!==-1&&(si.splice(n,1),Ip())}}function xy(){return si.length===0?!1:(si.pop().close(),Ip(),!0)}function pL(...s){const e=new Set(s);for(;si.length>0;){const t=si[si.length-1];if(e.has(t.id))break;si.pop().close()}Ip()}function En(s,e,t){const n=y.useRef(t);n.current=t,y.useEffect(()=>e?hL(s,()=>n.current()):void 0,[s,e])}let vy,wy;try{vy=require("@capacitor/haptics").Haptics,wy=require("@capacitor/haptics").ImpactStyle}catch{}function lj(s,e){const{threshold:t=80,maxVerticalMovement:n=50,enabled:a=!0,onSwipeLeft:i,onSwipeRight:o,onSwipeMove:l,onSwipeCancel:c}=e,d=y.useRef({startX:0,startY:0,startTime:0,isTracking:!1,hasMovedEnough:!1}),m=y.useCallback(b=>{if(b.touches.length!==1)return;const x=b.touches[0];d.current={startX:x.clientX,startY:x.clientY,startTime:Date.now(),isTracking:!0,hasMovedEnough:!1}},[]),p=y.useCallback(b=>{if(!d.current.isTracking||b.touches.length!==1)return;const x=b.touches[0],w=x.clientX-d.current.startX;if(Math.abs(x.clientY-d.current.startY)>n){d.current.isTracking=!1,d.current.hasMovedEnough&&(c==null||c());return}const j=window.innerWidth*.4,C=Math.max(-1,Math.min(1,w/j));Math.abs(w)>=12&&(d.current.hasMovedEnough=!0,l==null||l(C))},[n,l,c]),f=y.useCallback(b=>{const x=d.current.isTracking,w=d.current.hasMovedEnough;if(!x)return;const k=b.changedTouches[0],S=k.clientX-d.current.startX,j=Math.abs(k.clientY-d.current.startY),C=Date.now()-d.current.startTime;d.current.isTracking=!1,d.current.hasMovedEnough=!1,Math.abs(S)>=t&&j<=n&&C<500?(vy&&wy?vy.impact({style:wy.Light}).catch(()=>{navigator.vibrate&&navigator.vibrate(8)}):navigator.vibrate&&navigator.vibrate(8),S>0?o==null||o():i==null||i()):w&&(c==null||c())},[t,n,i,o,c]);y.useEffect(()=>{const b=s.current;if(!(!b||!a||!(window.innerWidth<=768&&"ontouchstart"in window)))return b.addEventListener("touchstart",m,{passive:!0}),b.addEventListener("touchmove",p,{passive:!0}),b.addEventListener("touchend",f,{passive:!0}),()=>{b.removeEventListener("touchstart",m),b.removeEventListener("touchmove",p),b.removeEventListener("touchend",f)}},[s,a,m,p,f])}const mL={width:400,height:300,copyStyleSheets:!0,keepOnTop:"focus"};function fL(){return"documentPictureInPicture"in window}function gL(s,e){for(const i of s.styleSheets)try{if(i.cssRules){const o=e.createElement("style");for(const l of i.cssRules)o.appendChild(e.createTextNode(l.cssText));e.head.appendChild(o)}}catch{if(i.href){const o=e.createElement("link");o.rel="stylesheet",o.href=i.href,e.head.appendChild(o)}}const t=s.documentElement.style.cssText;t&&(e.documentElement.style.cssText=t);const n=getComputedStyle(s.documentElement),a=[];for(let i=0;i<n.length;i++){const o=n[i];o.startsWith("--")&&a.push(`${o}: ${n.getPropertyValue(o)}`)}if(a.length>0){const i=e.createElement("style");i.textContent=`:root { ${a.join("; ")} }`,e.head.appendChild(i)}}function bL(){const[s,e]=y.useState(!1),[t,n]=y.useState(null),[a,i]=y.useState(null),o=y.useRef(null),l=fL(),c=y.useCallback(()=>{if(o.current){const p=o.current.__cleanupFns;p&&p.forEach(f=>f()),o.current.close(),o.current=null}n(null),i(null),e(!1)},[]),d=y.useCallback(async p=>{if(!l)return console.warn("Document Picture-in-Picture is not supported in this browser"),!1;o.current&&c();const f={...mL,...p};try{const x=await window.documentPictureInPicture.requestWindow({width:f.width,height:f.height,disallowReturnToOpener:!0});o.current=x,f.copyStyleSheets&&gL(document,x.document);const w=x.document.createElement("div");w.id="pip-root",w.style.width="100%",w.style.height="100%",x.document.body.appendChild(w),x.document.body.style.margin="0",x.document.body.style.padding="0",x.document.body.style.overflow="hidden",x.addEventListener("pagehide",()=>{o.current=null,n(null),i(null),e(!1)});const k=[];if(f.keepOnTop&&f.keepOnTop!=="none"){const S=f.keepOnTop==="raise",j=()=>{o.current&&!o.current.closed&&setTimeout(()=>{o.current&&!o.current.closed&&(o.current.focus(),S&&setTimeout(()=>window.focus(),10))},50)},C=()=>{document.visibilityState==="visible"&&o.current&&!o.current.closed&&setTimeout(()=>{o.current&&!o.current.closed&&(o.current.focus(),S&&setTimeout(()=>window.focus(),10))},100)};window.addEventListener("focus",j),document.addEventListener("visibilitychange",C),k.push(()=>window.removeEventListener("focus",j),()=>document.removeEventListener("visibilitychange",C))}return x.__cleanupFns=k,n(x),i(w),e(!0),!0}catch(b){return console.error("Failed to open Picture-in-Picture window:",b),!1}},[l,c]),m=y.useCallback(async p=>{s?c():await d(p)},[s,d,c]);return y.useEffect(()=>()=>{o.current&&o.current.close()},[]),y.useMemo(()=>({isOpen:s,pipWindow:t,pipContainer:a,isSupported:l,open:d,close:c,toggle:m}),[s,t,a,l,d,c,m])}function Mu(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,s=>{const e=Math.random()*16|0;return(s==="x"?e:e&3|8).toString(16)})}class yL{constructor(){U(this,"messages",new Map);U(this,"logs",[]);U(this,"maxMessagesPerAgent",200);U(this,"maxLogs",500);U(this,"enabled",!1);U(this,"listeners",new Set);U(this,"logListeners",new Set)}setEnabled(e){this.enabled=e,this.notifyListeners("all")}isEnabled(){return this.enabled}captureSent(e,t){if(this.enabled)try{const n=JSON.parse(t);console.log(`[AgentDebugger] SENT - agent: ${e.slice(0,4)}, type: ${n.type}, size: ${t.length}B`),this.addMessage(e,{id:Mu(),agentId:e,direction:"sent",type:n.type||"unknown",payload:n.payload||n,timestamp:Date.now(),size:t.length,raw:t})}catch(n){console.error("[AgentDebugger] Failed to parse SENT message:",String(n).slice(0,80)),this.addMessage(e,{id:Mu(),agentId:e,direction:"sent",type:"parse_error",payload:{error:String(n)},timestamp:Date.now(),size:t.length,raw:t})}}captureReceived(e,t){if(this.enabled)try{const n=JSON.parse(t);console.log(`[AgentDebugger] RECEIVED - agent: ${e.slice(0,4)}, type: ${n.type}, size: ${t.length}B`),this.addMessage(e,{id:Mu(),agentId:e,direction:"received",type:n.type||"unknown",payload:n.payload||n,timestamp:Date.now(),size:t.length,raw:t})}catch(n){console.error("[AgentDebugger] Failed to parse RECEIVED message:",String(n).slice(0,80)),this.addMessage(e,{id:Mu(),agentId:e,direction:"received",type:"parse_error",payload:{error:String(n)},timestamp:Date.now(),size:t.length,raw:t})}}addMessage(e,t){let n=this.messages.get(e);n||(n=[],this.messages.set(e,n)),n.push(t),console.log(`[AgentDebugger] Added message for ${e}, total: ${n.length}, type: ${t.type}, direction: ${t.direction}`),n.length>this.maxMessagesPerAgent&&n.shift(),this.notifyListeners(e)}getMessages(e){return this.messages.get(e)||[]}getStats(e){const t=this.getMessages(e),n=t.filter(o=>o.direction==="sent").length,a=t.filter(o=>o.direction==="received").length,i=[...new Set(t.map(o=>o.type))];return{total:t.length,sent:n,received:a,messageTypes:i}}clearMessages(e){this.messages.delete(e),this.notifyListeners(e)}clearAllMessages(){this.messages.clear(),this.notifyListeners("all")}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}notifyListeners(e){this.listeners.forEach(t=>t(e))}getAgentIds(){return Array.from(this.messages.keys())}log(e,t,n,a){const i={id:Mu(),level:e,message:t,data:n,timestamp:Date.now(),source:a};this.logs.push(i),this.logs.length>this.maxLogs&&this.logs.shift(),this.notifyLogListeners()}debug(e,t,n){this.log("debug",e,t,n)}info(e,t,n){this.log("info",e,t,n)}warn(e,t,n){this.log("warn",e,t,n)}error(e,t,n){this.log("error",e,t,n)}getLogs(){return this.logs}clearLogs(){this.logs=[],this.notifyLogListeners()}subscribeLogs(e){return this.logListeners.add(e),()=>this.logListeners.delete(e)}notifyLogListeners(){this.logListeners.forEach(e=>e())}}const Ms=new yL,ud={debug:(s,e,t)=>Ms.debug(s,e,t),info:(s,e,t)=>Ms.info(s,e,t),warn:(s,e,t)=>Ms.warn(s,e,t),error:(s,e,t)=>Ms.error(s,e,t)};/*! Capacitor: https://capacitorjs.com/ - MIT License */var xc;(function(s){s.Unimplemented="UNIMPLEMENTED",s.Unavailable="UNAVAILABLE"})(xc||(xc={}));class eb extends Error{constructor(e,t,n){super(e),this.message=e,this.code=t,this.data=n}}const xL=s=>{var e,t;return s!=null&&s.androidBridge?"android":!((t=(e=s==null?void 0:s.webkit)===null||e===void 0?void 0:e.messageHandlers)===null||t===void 0)&&t.bridge?"ios":"web"},vL=s=>{const e=s.CapacitorCustomPlatform||null,t=s.Capacitor||{},n=t.Plugins=t.Plugins||{},a=()=>e!==null?e.name:xL(s),i=()=>a()!=="web",o=p=>{const f=d.get(p);return!!(f!=null&&f.platforms.has(a())||l(p))},l=p=>{var f;return(f=t.PluginHeaders)===null||f===void 0?void 0:f.find(b=>b.name===p)},c=p=>s.console.error(p),d=new Map,m=(p,f={})=>{const b=d.get(p);if(b)return console.warn(`Capacitor plugin "${p}" already registered. Cannot register plugins twice.`),b.proxy;const x=a(),w=l(p);let k;const S=async()=>(!k&&x in f?k=typeof f[x]=="function"?k=await f[x]():k=f[x]:e!==null&&!k&&"web"in f&&(k=typeof f.web=="function"?k=await f.web():k=f.web),k),j=(M,D)=>{var E,R;if(w){const O=w==null?void 0:w.methods.find(I=>D===I.name);if(O)return O.rtype==="promise"?I=>t.nativePromise(p,D.toString(),I):(I,B)=>t.nativeCallback(p,D.toString(),I,B);if(M)return(E=M[D])===null||E===void 0?void 0:E.bind(M)}else{if(M)return(R=M[D])===null||R===void 0?void 0:R.bind(M);throw new eb(`"${p}" plugin is not implemented on ${x}`,xc.Unimplemented)}},C=M=>{let D;const E=(...R)=>{const O=S().then(I=>{const B=j(I,M);if(B){const Y=B(...R);return D=Y==null?void 0:Y.remove,Y}else throw new eb(`"${p}.${M}()" is not implemented on ${x}`,xc.Unimplemented)});return M==="addListener"&&(O.remove=async()=>D()),O};return E.toString=()=>`${M.toString()}() { [capacitor code] }`,Object.defineProperty(E,"name",{value:M,writable:!1,configurable:!1}),E},N=C("addListener"),P=C("removeListener"),_=(M,D)=>{const E=N({eventName:M},D),R=async()=>{const I=await E;P({eventName:M,callbackId:I},D)},O=new Promise(I=>E.then(()=>I({remove:R})));return O.remove=async()=>{console.warn("Using addListener() without 'await' is deprecated."),await R()},O},L=new Proxy({},{get(M,D){switch(D){case"$$typeof":return;case"toJSON":return()=>({});case"addListener":return w?_:N;case"removeListener":return P;default:return C(D)}}});return n[p]=L,d.set(p,{name:p,proxy:L,platforms:new Set([...Object.keys(f),...w?[x]:[]])}),L};return t.convertFileSrc||(t.convertFileSrc=p=>p),t.getPlatform=a,t.handleError=c,t.isNativePlatform=i,t.isPluginAvailable=o,t.registerPlugin=m,t.Exception=eb,t.DEBUG=!!t.DEBUG,t.isLoggingEnabled=!!t.isLoggingEnabled,t},wL=s=>s.Capacitor=vL(s),Aa=wL(typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}),Sd=Aa.registerPlugin;class kx{constructor(){this.listeners={},this.retainedEventArguments={},this.windowListeners={}}addListener(e,t){let n=!1;this.listeners[e]||(this.listeners[e]=[],n=!0),this.listeners[e].push(t);const i=this.windowListeners[e];i&&!i.registered&&this.addWindowListener(i),n&&this.sendRetainedArgumentsForEvent(e);const o=async()=>this.removeListener(e,t);return Promise.resolve({remove:o})}async removeAllListeners(){this.listeners={};for(const e in this.windowListeners)this.removeWindowListener(this.windowListeners[e]);this.windowListeners={}}notifyListeners(e,t,n){const a=this.listeners[e];if(!a){if(n){let i=this.retainedEventArguments[e];i||(i=[]),i.push(t),this.retainedEventArguments[e]=i}return}a.forEach(i=>i(t))}hasListeners(e){var t;return!!(!((t=this.listeners[e])===null||t===void 0)&&t.length)}registerWindowListener(e,t){this.windowListeners[t]={registered:!1,windowEventName:e,pluginEventName:t,handler:n=>{this.notifyListeners(t,n)}}}unimplemented(e="not implemented"){return new Aa.Exception(e,xc.Unimplemented)}unavailable(e="not available"){return new Aa.Exception(e,xc.Unavailable)}async removeListener(e,t){const n=this.listeners[e];if(!n)return;const a=n.indexOf(t);this.listeners[e].splice(a,1),this.listeners[e].length||this.removeWindowListener(this.windowListeners[e])}addWindowListener(e){window.addEventListener(e.windowEventName,e.handler),e.registered=!0}removeWindowListener(e){e&&(window.removeEventListener(e.windowEventName,e.handler),e.registered=!1)}sendRetainedArgumentsForEvent(e){const t=this.retainedEventArguments[e];t&&(delete this.retainedEventArguments[e],t.forEach(n=>{this.notifyListeners(e,n)}))}}const cj=s=>encodeURIComponent(s).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape),uj=s=>s.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent);class kL extends kx{async getCookies(){const e=document.cookie,t={};return e.split(";").forEach(n=>{if(n.length<=0)return;let[a,i]=n.replace(/=/,"CAP_COOKIE").split("CAP_COOKIE");a=uj(a).trim(),i=uj(i).trim(),t[a]=i}),t}async setCookie(e){try{const t=cj(e.key),n=cj(e.value),a=e.expires?`; expires=${e.expires.replace("expires=","")}`:"",i=(e.path||"/").replace("path=",""),o=e.url!=null&&e.url.length>0?`domain=${e.url}`:"";document.cookie=`${t}=${n||""}${a}; path=${i}; ${o};`}catch(t){return Promise.reject(t)}}async deleteCookie(e){try{document.cookie=`${e.key}=; Max-Age=0`}catch(t){return Promise.reject(t)}}async clearCookies(){try{const e=document.cookie.split(";")||[];for(const t of e)document.cookie=t.replace(/^ +/,"").replace(/=.*/,`=;expires=${new Date().toUTCString()};path=/`)}catch(e){return Promise.reject(e)}}async clearAllCookies(){try{await this.clearCookies()}catch(e){return Promise.reject(e)}}}Sd("CapacitorCookies",{web:()=>new kL});const SL=async s=>new Promise((e,t)=>{const n=new FileReader;n.onload=()=>{const a=n.result;e(a.indexOf(",")>=0?a.split(",")[1]:a)},n.onerror=a=>t(a),n.readAsDataURL(s)}),jL=(s={})=>{const e=Object.keys(s);return Object.keys(s).map(a=>a.toLocaleLowerCase()).reduce((a,i,o)=>(a[i]=s[e[o]],a),{})},CL=(s,e=!0)=>s?Object.entries(s).reduce((n,a)=>{const[i,o]=a;let l,c;return Array.isArray(o)?(c="",o.forEach(d=>{l=e?encodeURIComponent(d):d,c+=`${i}=${l}&`}),c.slice(0,-1)):(l=e?encodeURIComponent(o):o,c=`${i}=${l}`),`${n}&${c}`},"").substr(1):null,NL=(s,e={})=>{const t=Object.assign({method:s.method||"GET",headers:s.headers},e),a=jL(s.headers)["content-type"]||"";if(typeof s.data=="string")t.body=s.data;else if(a.includes("application/x-www-form-urlencoded")){const i=new URLSearchParams;for(const[o,l]of Object.entries(s.data||{}))i.set(o,l);t.body=i.toString()}else if(a.includes("multipart/form-data")||s.data instanceof FormData){const i=new FormData;if(s.data instanceof FormData)s.data.forEach((l,c)=>{i.append(c,l)});else for(const l of Object.keys(s.data))i.append(l,s.data[l]);t.body=i;const o=new Headers(t.headers);o.delete("content-type"),t.headers=o}else(a.includes("application/json")||typeof s.data=="object")&&(t.body=JSON.stringify(s.data));return t};class AL extends kx{async request(e){const t=NL(e,e.webFetchExtra),n=CL(e.params,e.shouldEncodeUrlParams),a=n?`${e.url}?${n}`:e.url,i=await fetch(a,t),o=i.headers.get("content-type")||"";let{responseType:l="text"}=i.ok?e:{};o.includes("application/json")&&(l="json");let c,d;switch(l){case"arraybuffer":case"blob":d=await i.blob(),c=await SL(d);break;case"json":c=await i.json();break;case"document":case"text":default:c=await i.text()}const m={};return i.headers.forEach((p,f)=>{m[f]=p}),{data:c,headers:m,status:i.status,url:i.url}}async get(e){return this.request(Object.assign(Object.assign({},e),{method:"GET"}))}async post(e){return this.request(Object.assign(Object.assign({},e),{method:"POST"}))}async put(e){return this.request(Object.assign(Object.assign({},e),{method:"PUT"}))}async patch(e){return this.request(Object.assign(Object.assign({},e),{method:"PATCH"}))}async delete(e){return this.request(Object.assign(Object.assign({},e),{method:"DELETE"}))}}const dj=Sd("CapacitorHttp",{web:()=>new AL});var hj;(function(s){s.Dark="DARK",s.Light="LIGHT",s.Default="DEFAULT"})(hj||(hj={}));var pj;(function(s){s.StatusBar="StatusBar",s.NavigationBar="NavigationBar"})(pj||(pj={}));class ML extends kx{async setStyle(){this.unavailable("not available for web")}async setAnimation(){this.unavailable("not available for web")}async show(){this.unavailable("not available for web")}async hide(){this.unavailable("not available for web")}}Sd("SystemBars",{web:()=>new ML});var mj;(function(s){s[s.Sunday=1]="Sunday",s[s.Monday=2]="Monday",s[s.Tuesday=3]="Tuesday",s[s.Wednesday=4]="Wednesday",s[s.Thursday=5]="Thursday",s[s.Friday=6]="Friday",s[s.Saturday=7]="Saturday"})(mj||(mj={}));const Sx=Sd("LocalNotifications",{web:()=>QA(()=>import("./web-GtGat3e7.js"),__vite__mapDeps([2,3,1,4])).then(s=>new s.LocalNotificationsWeb)}),TL=Sd("ServerConfig");let EL=100;const _L="agent_alerts",ky="tide-notification-tap";function DL(){return typeof window<"u"&&window.innerWidth<=768&&"ontouchstart"in window}function hM(s){if(DL()){z.openTerminalOnMobile(s);return}if(document.querySelector(".commander-overlay")){z.requestCommanderExpand(s);return}z.selectAgent(s),z.setTerminalOpen(!0)}function jd(){try{return Aa.isNativePlatform()}catch{return!1}}async function PL(){if(jd())try{const s=await Sx.requestPermissions();return console.log("[Notifications] Permission result:",s.display),s.display==="granted"}catch(s){return console.error("[Notifications] Failed to request permissions:",s),!1}else return"Notification"in window?await Notification.requestPermission()==="granted":!1}async function RL(s){const{title:e,body:t,icon:n,data:a}=s;if(jd())try{const i=EL++;console.log("[Notifications] Scheduling native notification id="+i,e),await Sx.schedule({notifications:[{id:i,title:e,body:t,extra:a,channelId:_L,smallIcon:"ic_launcher",autoCancel:!0}]}),console.log("[Notifications] Notification scheduled successfully")}catch(i){console.error("[Notifications] Failed to schedule notification:",i)}else if("Notification"in window&&Notification.permission==="granted"){const i=new Notification(e,{body:t,icon:n,data:a});i.onclick=()=>{window.focus(),a&&window.dispatchEvent(new CustomEvent(ky,{detail:a}))}}}let tb=!1;async function LL(s){const e=[];if(tb)return()=>{};if(tb=!0,s){const t=n=>{const a=n;a.detail&&s(a.detail)};window.addEventListener(ky,t),e.push(()=>window.removeEventListener(ky,t))}if(jd())try{const t=await Sx.addListener("localNotificationActionPerformed",n=>{s&&n.notification.extra&&s(n.notification.extra)});e.push(()=>t.remove())}catch(t){console.error("[Notifications] Failed to add tap listener:",t)}return()=>{e.forEach(t=>t()),tb=!1}}function OL(s,e){jd()&&TL.syncConfig({url:s,token:e}).catch(t=>{console.warn("[Notifications] Failed to sync config to native service:",t)})}window.__tideWsState||(window.__tideWsState={ws:null,isConnecting:!1,reconnectAttempts:0,reconnectTimeout:null});const jx=()=>window.__tideWsState.ws,fj=s=>{window.__tideWsState.ws=s},IL=()=>window.__tideWsState.isConnecting,Tu=s=>{window.__tideWsState.isConnecting=s},Sy=()=>window.__tideWsState.reconnectAttempts,jy=s=>{window.__tideWsState.reconnectAttempts=s},pM=()=>window.__tideWsState.reconnectTimeout,mM=s=>{window.__tideWsState.reconnectTimeout=s},gj=10,Cx="tide_ws_has_connected";function bj(){return sessionStorage.getItem(Cx)==="true"}function BL(s){sessionStorage.setItem(Cx,"true")}function zL(){sessionStorage.removeItem(Cx)}let fM=null;const FL=s=>{fM=s},yj=()=>fM,He={onToast:null,onAgentCreated:null,onAgentUpdated:null,onAgentDeleted:null,onAgentsSync:null,onAreasSync:null,onSpawnError:null,onSpawnSuccess:null,onToolUse:null,onDirectoryNotFound:null,onDelegation:null,onCustomClassesSync:null,onReconnect:null,onAgentNotification:null,onBuildingUpdated:null,onSubagentStarted:null,onSubagentCompleted:null};function gM(s){s.onToast&&(He.onToast=s.onToast),s.onAgentCreated&&(He.onAgentCreated=s.onAgentCreated),s.onAgentUpdated&&(He.onAgentUpdated=s.onAgentUpdated),s.onAgentDeleted&&(He.onAgentDeleted=s.onAgentDeleted),s.onAgentsSync&&(He.onAgentsSync=s.onAgentsSync),s.onAreasSync&&(He.onAreasSync=s.onAreasSync),s.onSpawnError&&(He.onSpawnError=s.onSpawnError),s.onSpawnSuccess&&(He.onSpawnSuccess=s.onSpawnSuccess),s.onToolUse&&(He.onToolUse=s.onToolUse),s.onDirectoryNotFound&&(He.onDirectoryNotFound=s.onDirectoryNotFound),s.onDelegation&&(He.onDelegation=s.onDelegation),s.onCustomClassesSync&&(He.onCustomClassesSync=s.onCustomClassesSync),s.onReconnect&&(He.onReconnect=s.onReconnect),s.onAgentNotification&&(He.onAgentNotification=s.onAgentNotification),s.onBuildingUpdated&&(He.onBuildingUpdated=s.onBuildingUpdated),s.onSubagentStarted&&(He.onSubagentStarted=s.onSubagentStarted),s.onSubagentCompleted&&(He.onSubagentCompleted=s.onSubagentCompleted)}function $L(){He.onToast=null,He.onAgentCreated=null,He.onAgentUpdated=null,He.onAgentDeleted=null,He.onAgentsSync=null,He.onAreasSync=null,He.onSpawnError=null,He.onSpawnSuccess=null,He.onToolUse=null,He.onDirectoryNotFound=null,He.onDelegation=null,He.onCustomClassesSync=null,He.onReconnect=null,He.onAgentNotification=null,He.onSubagentStarted=null,He.onSubagentCompleted=null}function HL(){He.onAgentCreated=null,He.onAgentUpdated=null,He.onAgentDeleted=null,He.onAgentsSync=null,He.onAreasSync=null,He.onToolUse=null,He.onDelegation=null,He.onCustomClassesSync=null,He.onBuildingUpdated=null,He.onSubagentStarted=null,He.onSubagentCompleted=null}const Wh=new Map,UL=new Map,Cy={start(s){},end(s){},async measure(s,e){this.start(s);try{return await e()}finally{this.end(s)}},measureSync(s,e){this.start(s);try{return e()}finally{this.end(s)}},getMetrics(s){const e={},t=s?Wh.has(s)?[[s,Wh.get(s)]]:[]:Array.from(Wh.entries());for(const[n,a]of t){const i=[...a.samples].sort((d,m)=>d-m),o=Math.floor(i.length*.5),l=Math.floor(i.length*.95),c=Math.floor(i.length*.99);e[n]={count:a.count,avgMs:a.totalMs/a.count,minMs:a.minMs,maxMs:a.maxMs,lastMs:a.lastMs,p50Ms:i[o]||0,p95Ms:i[l]||0,p99Ms:i[c]||0}}return e},clear(){Wh.clear(),UL.clear()},report(){}};class GL{constructor(){U(this,"frames",[]);U(this,"lastFrameTime",0);U(this,"frameCount",0);U(this,"fps",0);U(this,"minFps",1/0);U(this,"maxFps",0);U(this,"fpsHistory",[]);U(this,"maxHistorySize",60)}tick(e=200){const t=performance.now();if(this.lastFrameTime>0){const n=t-this.lastFrameTime;n<e&&(this.frames.push(n),this.frames.length>60&&this.frames.shift())}this.lastFrameTime=t,this.frameCount++}update(){if(this.frames.length===0)return;const e=this.frames.reduce((t,n)=>t+n,0)/this.frames.length;this.fps=1e3/e,this.minFps=Math.min(this.minFps,this.fps),this.maxFps=Math.max(this.maxFps,this.fps),this.fpsHistory.push(this.fps),this.fpsHistory.length>this.maxHistorySize&&this.fpsHistory.shift()}getFPS(){return Math.round(this.fps)}getStats(){const e=this.fpsHistory.length>0?this.fpsHistory.reduce((t,n)=>t+n,0)/this.fpsHistory.length:this.fps;return{current:Math.round(this.fps),min:Math.round(this.minFps===1/0?0:this.minFps),max:Math.round(this.maxFps),avg:Math.round(e)}}reset(){this.frames=[],this.lastFrameTime=0,this.frameCount=0,this.fps=0,this.minFps=1/0,this.maxFps=0,this.fpsHistory=[]}}const rc=new GL;class WL{constructor(){U(this,"snapshots",[]);U(this,"maxSnapshots",120);U(this,"intervalId",null);U(this,"leakThresholdMB",50);U(this,"baselineUsedMB",0)}getUsage(){const e=performance.memory;return e?{usedMB:Math.round(e.usedJSHeapSize/1024/1024),totalMB:Math.round(e.totalJSHeapSize/1024/1024),limitMB:Math.round(e.jsHeapSizeLimit/1024/1024)}:null}log(){const e=this.getUsage();e&&console.log(`[Memory] Used: ${e.usedMB}MB / ${e.totalMB}MB (limit: ${e.limitMB}MB)`)}startMonitoring(e=1e3){if(this.intervalId)return;const t=this.getUsage();t&&(this.baselineUsedMB=t.usedMB),this.intervalId=setInterval(()=>{this.takeSnapshot()},e),console.log("[Memory] Monitoring started. Use memory.report() to see analysis.")}stopMonitoring(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null,console.log("[Memory] Monitoring stopped."))}takeSnapshot(){const e=this.getUsage();if(!e)return;const t={timestamp:Date.now(),heapUsedMB:e.usedMB,heapTotalMB:e.totalMB,heapLimitMB:e.limitMB};this.snapshots.push(t),this.snapshots.length>this.maxSnapshots&&this.snapshots.shift();const n=e.usedMB-this.baselineUsedMB;n>this.leakThresholdMB&&console.warn(`[Memory] Warning: Heap grew by ${n}MB since monitoring started (baseline: ${this.baselineUsedMB}MB, current: ${e.usedMB}MB)`)}getGrowthRate(){if(this.snapshots.length<10)return null;const e=this.snapshots[0],t=this.snapshots[this.snapshots.length-1],n=(t.timestamp-e.timestamp)/1e3/60;return n<.1?null:(t.heapUsedMB-e.heapUsedMB)/n}report(){const e=this.getUsage();if(!e){console.log("[Memory] Memory API not available (Chrome only)");return}console.group("%c[Memory Report]","color: #ff6600; font-weight: bold"),console.log(`Current: ${e.usedMB}MB / ${e.totalMB}MB (limit: ${e.limitMB}MB)`),console.log(`Baseline: ${this.baselineUsedMB}MB`),console.log(`Growth: ${e.usedMB-this.baselineUsedMB}MB since monitoring started`);const t=this.getGrowthRate();if(t!==null&&(console.log(`Growth Rate: ${t.toFixed(2)}MB/min`),t>5&&console.warn("POTENTIAL MEMORY LEAK: Growth rate exceeds 5MB/min")),this.snapshots.length>1){const n=Math.min(...this.snapshots.map(i=>i.heapUsedMB)),a=Math.max(...this.snapshots.map(i=>i.heapUsedMB));console.log(`Range: ${n}MB - ${a}MB (${a-n}MB variance)`)}console.groupEnd()}getThreeJsInfo(e){var t;return(t=e==null?void 0:e.info)!=null&&t.memory?{geometries:e.info.memory.geometries,textures:e.info.memory.textures}:null}reset(){this.snapshots=[];const e=this.getUsage();e&&(this.baselineUsedMB=e.usedMB),console.log("[Memory] Reset. New baseline:",this.baselineUsedMB,"MB")}}const nc=new WL;function Wu(s,e,t,n,a,i){}function bM(s,e){y.useRef(0),y.useEffect(()=>{},[s,5e3,!0])}if(typeof window<"u"){setInterval(()=>{try{performance.clearMarks(),performance.clearMeasures(),performance.clearResourceTimings()}catch{}},6e4);try{performance.setResourceTimingBufferSize(0)}catch{}}function yM(s){if(s.payload&&typeof s.payload=="object"){const e=s.payload;if(e.agentId)return e.agentId;if(e.id)return e.id}return null}function Nx(s){var t,n,a,i,o,l;const e=jx();if(!e){(t=yj())==null||t(),(n=He.onToast)==null||n.call(He,"error","Not Connected","Connecting to server... Please try again in a moment.");return}if(e.readyState!==WebSocket.OPEN){e.readyState===WebSocket.CONNECTING?(a=He.onToast)==null||a.call(He,"warning","Connecting...","WebSocket is still connecting. Please wait a moment and try again."):(e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING)&&((i=yj())==null||i(),(o=He.onToast)==null||o.call(He,"warning","Reconnecting...","Connection lost. Reconnecting to server..."));return}try{const c=JSON.stringify(s);if(Ms.isEnabled()){const m=yM(s);console.log("[AgentDebugger] SENT - type:",s.type,"agentId:",m,"payload:",s.payload),m&&Ms.captureSent(m,c)}e.send(c)}catch(c){(l=He.onToast)==null||l.call(He,"error","Send Failed",`Failed to send message: ${c}`)}}const qu=new Set,qL=5e3;function xj(s){if(!s.isDetached||!s.sessionId){qu.delete(s.id);return}qu.has(s.id)||(qu.add(s.id),Nx({type:"reattach_agent",payload:{agentId:s.id}}),setTimeout(()=>{qu.delete(s.id)},qL))}function YL(s){var e,t,n,a,i,o,l,c,d,m,p,f,b,x,w,k,S,j,C,N,P,_,L;switch(Cy.start(`ws:${s.type}`),s.type){case"agents_update":{const M=s.payload,D=M.filter(E=>E.class==="boss"||E.isBoss);D.length>0&&console.log("[WS agents_update] Boss agents received:",D.map(E=>({id:E.id,name:E.name,subordinateIds:E.subordinateIds}))),z.setAgents(M),(e=He.onAgentsSync)==null||e.call(He,M),z.loadToolHistory();for(const E of M)xj(E);break}case"agent_created":{const M=s.payload;console.log("[WebSocket] Agent created:",M),z.addAgent(M),z.selectAgent(M.id),(t=He.onAgentCreated)==null||t.call(He,M),(n=He.onSpawnSuccess)==null||n.call(He),window.__spawnModalSuccess&&(console.log("[WebSocket] Calling __spawnModalSuccess"),window.__spawnModalSuccess()),(a=He.onToast)==null||a.call(He,"success","Agent Deployed",`${M.name} is ready for commands`);break}case"agent_updated":{const M=s.payload,E=z.getState().agents.get(M.id),R=(E==null?void 0:E.status)!==M.status;console.log(`[Tide] Agent updated: ${M.name} (${M.id}) status=${M.status} (was ${E==null?void 0:E.status})${R?" ⚡ STATUS CHANGED":""}`),R&&console.log(`[Tide] 🔔 Status change for ${M.name}: ${E==null?void 0:E.status} → ${M.status}`),R&&(E==null?void 0:E.status)==="working"&&M.status==="idle"&&z.triggerHistoryRefresh(M.id);const O=E?E.position.x!==M.position.x||E.position.z!==M.position.z:!1;z.updateAgent(M),xj(M),(i=He.onAgentUpdated)==null||i.call(He,M,O);break}case"agent_deleted":{const{id:M}=s.payload;qu.delete(M),z.removeAgent(M),(o=He.onAgentDeleted)==null||o.call(He,M);break}case"activity":{const M=s.payload;z.addActivity(M);break}case"event":{const M=s.payload;if(ud.debug(`Event: ${M.type}`,{agentId:M.agentId,toolName:M.toolName},"ws:event"),M.type==="tool_start"&&M.toolName&&((l=He.onToolUse)==null||l.call(He,M.agentId,M.toolName,M.toolInput),z.addToolExecution(M.agentId,M.toolName,M.toolInput),M.toolInput)){const D=M.toolInput.file_path||M.toolInput.path;D&&(M.toolName==="Write"?z.addFileChange(M.agentId,"created",D):M.toolName==="Edit"?z.addFileChange(M.agentId,"modified",D):M.toolName==="Read"&&z.addFileChange(M.agentId,"read",D))}break}case"output":{const M=s.payload;ud.debug(`Output: "${M.text.slice(0,80)}..."`,{agentId:M.agentId,isStreaming:M.isStreaming,length:M.text.length,hasSkillUpdate:!!M.skillUpdate,uuid:M.uuid,toolName:M.toolName},"ws:output"),z.addOutput(M.agentId,{text:M.text,isStreaming:M.isStreaming,timestamp:M.timestamp,isDelegation:M.isDelegation,skillUpdate:M.skillUpdate,subagentName:M.subagentName,uuid:M.uuid,toolName:M.toolName,toolInput:M.toolInput,toolOutput:M.toolOutput});break}case"context_stats":{const{agentId:M,stats:D}=s.payload;console.log(`[Tide] Received context stats for agent ${M}: ${D.usedPercent}% used`),z.updateAgentContextStats(M,D);break}case"context_update":{const{agentId:M,contextUsed:D,contextLimit:E}=s.payload;z.updateAgentContext(M,D,E);break}case"error":{const M=s.payload;console.error("[WebSocket] Error from server:",M.message),(c=He.onToast)==null||c.call(He,"error","Error",M.message),(d=He.onSpawnError)==null||d.call(He),window.__spawnModalError&&(console.log("[WebSocket] Calling __spawnModalError"),window.__spawnModalError());break}case"directory_not_found":{const{path:M}=s.payload;console.log("[WebSocket] Directory not found:",M),(m=He.onDirectoryNotFound)==null||m.call(He,M),window.__spawnModalDirNotFound&&(console.log("[WebSocket] Calling __spawnModalDirNotFound"),window.__spawnModalDirNotFound(M));break}case"command_started":{const{agentId:M,command:D}=s.payload,E=D.trim();if(E==="/context"||E==="/cost"||E==="/compact")break;z.addUserPromptToOutput(M,D);break}case"session_updated":{const{agentId:M}=s.payload;z.loadToolHistory(),z.triggerHistoryRefresh(M);const D=z.getState().agents.get(M);D&&z.updateAgent({...D});break}case"supervisor_report":{const M=s.payload;z.setSupervisorReport(M);break}case"narrative_update":{const{agentId:M,narrative:D}=s.payload;z.addNarrative(M,D);break}case"supervisor_status":{const M=s.payload;z.setSupervisorStatus(M);break}case"agent_supervisor_history":{const M=s.payload;z.setAgentSupervisorHistory(M);break}case"agent_analysis":{const{agentId:M,analysis:D}=s.payload;z.addAgentAnalysis(M,D);break}case"areas_update":{const M=s.payload;z.setAreasFromServer(M),(p=He.onAreasSync)==null||p.call(He);break}case"buildings_update":{const M=s.payload;z.setBuildingsFromServer(M);break}case"building_created":{const M=s.payload;z.addBuilding(M);break}case"building_updated":{const M=s.payload;z.updateBuildingFromServer(M),(f=He.onBuildingUpdated)==null||f.call(He,M);break}case"building_deleted":{const{id:M}=s.payload;z.removeBuildingFromServer(M);break}case"building_logs":{const{buildingId:M,logs:D}=s.payload;z.addBuildingLogs(M,D);break}case"pm2_logs_chunk":{const{buildingId:M,chunk:D}=s.payload;z.appendStreamingLogChunk(M,D);break}case"pm2_logs_streaming":{const{buildingId:M,streaming:D}=s.payload;z.setStreamingStatus(M,D);break}case"docker_logs_chunk":{const{buildingId:M,chunk:D}=s.payload;z.appendStreamingLogChunk(M,D);break}case"docker_logs_streaming":{const{buildingId:M,streaming:D}=s.payload;z.setStreamingStatus(M,D);break}case"docker_containers_list":{const{containers:M,composeProjects:D}=s.payload;console.log(`[WebSocket] Received ${M.length} containers, ${D.length} compose projects`),z.setDockerContainersList(M,D);break}case"boss_building_logs_chunk":{const{bossBuildingId:M,subordinateBuildingId:D,subordinateBuildingName:E,chunk:R,isError:O}=s.payload;z.appendBossStreamingLogChunk(M,D,E,R,O);break}case"boss_building_subordinates_updated":{const{bossBuildingId:M,subordinateBuildingIds:D}=s.payload;z.updateBuilding(M,{subordinateBuildingIds:D});break}case"permission_request":{const M=s.payload;z.addPermissionRequest(M);break}case"permission_resolved":{const{requestId:M,approved:D}=s.payload;z.resolvePermissionRequest(M,D);break}case"delegation_decision":{const M=s.payload;z.handleDelegationDecision(M),M.status==="sent"&&((b=He.onToast)==null||b.call(He,"info","Task Delegated",`Delegated to ${M.selectedAgentName}: ${M.reasoning.slice(0,80)}...`),M.bossId&&M.selectedAgentId&&((x=He.onDelegation)==null||x.call(He,M.bossId,M.selectedAgentId)));break}case"boss_subordinates_updated":{const{bossId:M,subordinateIds:D}=s.payload;z.updateBossSubordinates(M,D);break}case"delegation_history":{const{bossId:M,decisions:D}=s.payload;z.setDelegationHistory(M,D);break}case"boss_spawned_agent":{const{agent:M,bossPosition:D}=s.payload;console.log("[WebSocket] Boss spawned agent:",M.name,"- walking to boss at",D),z.addAgent(M),(w=He.onAgentCreated)==null||w.call(He,M),Nx({type:"move_agent",payload:{agentId:M.id,position:D}}),(k=He.onToast)==null||k.call(He,"success","Agent Deployed",`${M.name} spawned by boss, walking to position`);break}case"agent_task_started":{const{bossId:M,subordinateId:D,subordinateName:E,taskDescription:R}=s.payload;console.log(`[WebSocket] Agent ${E} started task for boss ${M}: ${R.slice(0,50)}...`),z.handleAgentTaskStarted(M,D,E,R);break}case"agent_task_output":{const{bossId:M,subordinateId:D,output:E}=s.payload;z.handleAgentTaskOutput(M,D,E);break}case"agent_task_completed":{const{bossId:M,subordinateId:D,success:E}=s.payload;console.log(`[WebSocket] Agent task completed for boss ${M}, subordinate ${D}, success: ${E}`),z.handleAgentTaskCompleted(M,D,E);break}case"skills_update":{const M=s.payload;z.setSkillsFromServer(M);break}case"skill_created":{const M=s.payload;z.addSkillFromServer(M),console.log(`[WebSocket] Skill created: ${M.name}`);break}case"skill_updated":{const M=s.payload;z.updateSkillFromServer(M),console.log(`[WebSocket] Skill updated: ${M.name}`);break}case"skill_deleted":{const{id:M}=s.payload;z.removeSkillFromServer(M),console.log(`[WebSocket] Skill deleted: ${M}`);break}case"agent_skills":{const{agentId:M,skills:D}=s.payload;console.log(`[WebSocket] Agent ${M} has ${D.length} skills`);break}case"custom_agent_classes_update":{const M=s.payload;z.setCustomAgentClassesFromServer(M),console.log(`[WebSocket] Received ${M.length} custom agent classes`);const D=new Map;for(const E of M)D.set(E.id,E);(S=He.onCustomClassesSync)==null||S.call(He,D);break}case"custom_agent_class_created":{const M=s.payload;z.addCustomAgentClassFromServer(M),console.log(`[WebSocket] Custom agent class created: ${M.name}`),(j=He.onCustomClassesSync)==null||j.call(He,z.getState().customAgentClasses);break}case"custom_agent_class_updated":{const M=s.payload;z.updateCustomAgentClassFromServer(M),console.log(`[WebSocket] Custom agent class updated: ${M.name}`),(C=He.onCustomClassesSync)==null||C.call(He,z.getState().customAgentClasses);break}case"custom_agent_class_deleted":{const{id:M}=s.payload;z.removeCustomAgentClassFromServer(M),console.log(`[WebSocket] Custom agent class deleted: ${M}`),(N=He.onCustomClassesSync)==null||N.call(He,z.getState().customAgentClasses);break}case"global_usage":{const M=s.payload;console.log("[WebSocket] Global usage update:",M),z.setGlobalUsage(M);break}case"agent_notification":{const M=s.payload;console.log(`[WebSocket] Agent notification from ${M.agentName}: ${M.title}`),(P=He.onAgentNotification)==null||P.call(He,M);break}case"focus_agent":{const{agentId:M,openTerminal:D}=s.payload;if(!z.getState().agents.get(M)){console.warn(`[WebSocket] focus_agent ignored - agent not found: ${M}`);break}z.selectAgent(M),D&&z.setTerminalOpen(!0);const R=[0,80,220,500,1e3];for(const O of R)window.setTimeout(()=>{window.focus()},O);break}case"exec_task_started":{const{taskId:M,agentId:D,agentName:E,command:R,cwd:O}=s.payload;console.log(`[WebSocket] Exec task started: ${M} for agent ${E}: ${R.slice(0,50)}...`),z.handleExecTaskStarted(M,D,E,R,O);break}case"exec_task_output":{const{taskId:M,agentId:D,output:E,isError:R}=s.payload;z.handleExecTaskOutput(M,D,E,R);break}case"exec_task_completed":{const{taskId:M,agentId:D,exitCode:E,success:R}=s.payload;console.log(`[WebSocket] Exec task completed: ${M} for agent ${D}, success: ${R}`),z.handleExecTaskCompleted(M,D,E,R);break}case"subagent_started":{const M=s.payload;console.log(`[WebSocket] Subagent started: ${M.name} (${M.id}) for agent ${M.parentAgentId}`),z.addSubagent(M),(_=He.onSubagentStarted)==null||_.call(He,M);break}case"subagent_output":{const{subagentId:M,parentAgentId:D,text:E,timestamp:R}=s.payload,O=E.indexOf(":");if(O>0){const I=E.slice(0,O).trim(),B=E.slice(O+1).trim();z.addSubagentActivity(M,D,{toolName:I,description:B,timestamp:R})}else E.startsWith("Using ")&&z.addSubagentActivity(M,D,{toolName:E.slice(6).trim(),description:"",timestamp:R});break}case"subagent_completed":{const{subagentId:M,parentAgentId:D,success:E,resultPreview:R,subagentName:O,durationMs:I,tokensUsed:B,toolUseCount:Y}=s.payload;console.log(`[WebSocket] Subagent completed: ${M} for agent ${D}, success: ${E}`),(I||B||Y)&&z.updateSubagentStats(M,D,{durationMs:I||0,tokensUsed:B||0,toolUseCount:Y||0}),z.completeSubagent(M,D,E),(L=He.onSubagentCompleted)==null||L.call(He,M);const $=z.getSubagent(M)||z.getSubagentByToolUseId(M),W=O||($==null?void 0:$.name)||M,K=E?"✅":"❌",X=I?` (${(I/1e3).toFixed(0)}s · ${((B||0)/1e3).toFixed(1)}K tokens · ${Y||0} tools)`:"";z.addOutput(D,{text:`${K} Subagent ${W} ${E?"completed":"failed"}${X}`,isStreaming:!1,timestamp:Date.now(),subagentName:W,toolOutput:R});break}case"subagent_stream":{const{toolUseId:M,parentAgentId:D,entries:E}=s.payload;z.addSubagentStreamEntries(M,D,E);break}case"secrets_update":{const M=s.payload;z.setSecretsFromServer(M),console.log(`[WebSocket] Received ${M.length} secrets`);break}case"secret_created":{const M=s.payload;z.addSecretFromServer(M),console.log(`[WebSocket] Secret created: ${M.name}`);break}case"secret_updated":{const M=s.payload;z.updateSecretFromServer(M),console.log(`[WebSocket] Secret updated: ${M.name}`);break}case"secret_deleted":{const{id:M}=s.payload;z.removeSecretFromServer(M),console.log(`[WebSocket] Secret deleted: ${M}`);break}case"database_connection_result":{const{buildingId:M,connectionId:D,success:E,error:R,serverVersion:O}=s.payload;z.setConnectionStatus(M,D,{connected:E,error:R,serverVersion:O}),console.log(`[WebSocket] Database connection ${E?"succeeded":"failed"}: ${D}`);break}case"databases_list":{const{buildingId:M,connectionId:D,databases:E}=s.payload;z.setDatabases(M,D,E),console.log(`[WebSocket] Received ${E.length} databases for ${D}`);break}case"tables_list":{const{buildingId:M,connectionId:D,database:E,tables:R}=s.payload;z.setTables(M,D,E,R),console.log(`[WebSocket] Received ${R.length} tables for ${E}`);break}case"table_schema":{const{buildingId:M,connectionId:D,database:E,table:R,columns:O,indexes:I,foreignKeys:B}=s.payload;z.setTableSchema(M,D,E,R,{columns:O,indexes:I||[],foreignKeys:B||[]}),console.log(`[WebSocket] Received schema for ${R}`);break}case"query_result":{const{buildingId:M,result:D}=s.payload;z.setQueryResult(M,D),console.log(`[WebSocket] Query ${D.status}: ${D.rowCount??D.affectedRows??0} rows in ${D.duration}ms`);break}case"silent_query_result":{const{buildingId:M,query:D,requestId:E,success:R,affectedRows:O,error:I}=s.payload;z.setSilentQueryResult(M,{query:D,requestId:E,success:R,affectedRows:O,error:I}),console.log(`[WebSocket] Silent query ${R?"succeeded":"failed"}: ${O??0} affected rows`);break}case"query_history_update":{const{buildingId:M,history:D}=s.payload;z.setQueryHistory(M,D),console.log(`[WebSocket] Received ${D.length} query history entries for ${M}`);break}}Cy.end(`ws:${s.type}`)}FL(()=>dd());let vj=!1;function xM(){const s=jx();s&&s.readyState===WebSocket.OPEN&&s.close(1e3,"Page unloading");const e=pM();e&&clearTimeout(e),window.__tideWsState&&(window.__tideWsState.ws=null,window.__tideWsState.reconnectTimeout=null,window.__tideWsState.isConnecting=!1,window.__tideWsState.reconnectAttempts=0),zL()}function VL(){vj||(window.addEventListener("beforeunload",xM),vj=!0)}function vM(){xM(),z.setConnected(!1),z.stopStatusPolling()}function xp(){vM(),jy(0),setTimeout(()=>dd(),100)}function dd(){VL();const s=pM();s&&(clearTimeout(s),mM(null));const e=jx();if(IL()||e&&e.readyState===WebSocket.CONNECTING)return;if(e&&e.readyState===WebSocket.OPEN){bj()&&He.onReconnect&&He.onReconnect();return}jy(Sy()+1),Tu(!0);const t=bm(),n=hi(),a=6200;let i;if(t){const l=t.replace(/^https:\/\//,"wss://").replace(/^http:\/\//,"ws://");i=l.endsWith("/ws")?l:`${l.replace(/\/$/,"")}/ws`}else i=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws`;let o=null;try{n?o=new WebSocket(i,[`auth-${n}`]):o=new WebSocket(i)}catch{Tu(!1),wj();return}fj(o),o.onopen=()=>{var c,d,m;const l=bj();Tu(!1),jy(0),BL(),z.setConnected(!0),z.startStatusPolling(),z.clearAllPermissions(),l?((c=He.onToast)==null||c.call(He,"success","Reconnected","Connection restored - refreshing data..."),(d=He.onReconnect)==null||d.call(He)):(m=He.onToast)==null||m.call(He,"success","Connected","Connected to Tide Commander server"),OL(t,n)},o.onmessage=l=>{try{const c=JSON.parse(l.data);if(Ms.isEnabled()){const m=yM(c);console.log("[AgentDebugger] RECEIVED - type:",c.type,"agentId:",m,"payload:",c.payload),m&&Ms.captureReceived(m,l.data)}YL(c)}catch(c){const d=l.data.substring(0,200);console.error("[WS] Failed to parse message:",c),console.error("[WS] Raw data (first 200 chars):",d),console.error("[WS] Full data length:",l.data.length),l.data.length<5e3&&console.error("[WS] Full malformed message:",l.data)}},o.onclose=()=>{var c,d;Tu(!1),fj(null),z.setConnected(!1),z.stopStatusPolling();const l=Sy();l<gj?((c=He.onToast)==null||c.call(He,"warning","Disconnected",`Connection lost. Reconnecting... (attempt ${l+1}/${gj})`),wj()):(d=He.onToast)==null||d.call(He,"error","Connection Failed",`Could not connect to server. Please check if the backend is running on port ${a}.`)},o.onerror=()=>{Tu(!1)},z.setSendMessage(Nx)}function wj(){const s=Sy(),e=Math.min(1e3*Math.pow(2,s-1),3e4);mM(setTimeout(dd,e))}function kj(s,e){if(e===tP)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),s;if(e===sy||e===_A){let t=s.getIndex();if(t===null){const o=[],l=s.getAttribute("position");if(l!==void 0){for(let c=0;c<l.count;c++)o.push(c);s.setIndex(o),t=s.getIndex()}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."),s}const n=t.count-2,a=[];if(e===sy)for(let o=1;o<=n;o++)a.push(t.getX(0)),a.push(t.getX(o)),a.push(t.getX(o+1));else for(let o=0;o<n;o++)o%2===0?(a.push(t.getX(o)),a.push(t.getX(o+1)),a.push(t.getX(o+2))):(a.push(t.getX(o+2)),a.push(t.getX(o+1)),a.push(t.getX(o)));a.length/3!==n&&console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");const i=s.clone();return i.setIndex(a),i.clearGroups(),i}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",e),s}class Ax extends DA{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new JL(t)}),this.register(function(t){return new eO(t)}),this.register(function(t){return new cO(t)}),this.register(function(t){return new uO(t)}),this.register(function(t){return new dO(t)}),this.register(function(t){return new nO(t)}),this.register(function(t){return new sO(t)}),this.register(function(t){return new aO(t)}),this.register(function(t){return new iO(t)}),this.register(function(t){return new QL(t)}),this.register(function(t){return new rO(t)}),this.register(function(t){return new tO(t)}),this.register(function(t){return new lO(t)}),this.register(function(t){return new oO(t)}),this.register(function(t){return new XL(t)}),this.register(function(t){return new hO(t)}),this.register(function(t){return new pO(t)})}load(e,t,n,a){const i=this;let o;if(this.resourcePath!=="")o=this.resourcePath;else if(this.path!==""){const d=Xu.extractUrlBase(e);o=Xu.resolveURL(d,this.path)}else o=Xu.extractUrlBase(e);this.manager.itemStart(e);const l=function(d){a?a(d):console.error(d),i.manager.itemError(e),i.manager.itemEnd(e)},c=new Tp(this.manager);c.setPath(this.path),c.setResponseType("arraybuffer"),c.setRequestHeader(this.requestHeader),c.setWithCredentials(this.withCredentials),c.load(e,function(d){try{i.parse(d,o,function(m){t(m),i.manager.itemEnd(e)},l)}catch(m){l(m)}},n,l)}setDRACOLoader(e){return this.dracoLoader=e,this}setKTX2Loader(e){return this.ktx2Loader=e,this}setMeshoptDecoder(e){return this.meshoptDecoder=e,this}register(e){return this.pluginCallbacks.indexOf(e)===-1&&this.pluginCallbacks.push(e),this}unregister(e){return this.pluginCallbacks.indexOf(e)!==-1&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}parse(e,t,n,a){let i;const o={},l={},c=new TextDecoder;if(typeof e=="string")i=JSON.parse(e);else if(e instanceof ArrayBuffer)if(c.decode(new Uint8Array(e,0,4))===wM){try{o[nn.KHR_BINARY_GLTF]=new mO(e)}catch(p){a&&a(p);return}i=JSON.parse(o[nn.KHR_BINARY_GLTF].content)}else i=JSON.parse(c.decode(e));else i=e;if(i.asset===void 0||i.asset.version[0]<2){a&&a(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));return}const d=new AO(i,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});d.fileLoader.setRequestHeader(this.requestHeader);for(let m=0;m<this.pluginCallbacks.length;m++){const p=this.pluginCallbacks[m](d);p.name||console.error("THREE.GLTFLoader: Invalid plugin found: missing name"),l[p.name]=p,o[p.name]=!0}if(i.extensionsUsed)for(let m=0;m<i.extensionsUsed.length;++m){const p=i.extensionsUsed[m],f=i.extensionsRequired||[];switch(p){case nn.KHR_MATERIALS_UNLIT:o[p]=new ZL;break;case nn.KHR_DRACO_MESH_COMPRESSION:o[p]=new fO(i,this.dracoLoader);break;case nn.KHR_TEXTURE_TRANSFORM:o[p]=new gO;break;case nn.KHR_MESH_QUANTIZATION:o[p]=new bO;break;default:f.indexOf(p)>=0&&l[p]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+p+'".')}}d.setExtensions(o),d.setPlugins(l),d.parse(n,a)}parseAsync(e,t){const n=this;return new Promise(function(a,i){n.parse(e,t,a,i)})}}function KL(){let s={};return{get:function(e){return s[e]},add:function(e,t){s[e]=t},remove:function(e){delete s[e]},removeAll:function(){s={}}}}const nn={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_DISPERSION:"KHR_materials_dispersion",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"};class XL{constructor(e){this.parser=e,this.name=nn.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const e=this.parser,t=this.parser.json.nodes||[];for(let n=0,a=t.length;n<a;n++){const i=t[n];i.extensions&&i.extensions[this.name]&&i.extensions[this.name].light!==void 0&&e._addNodeRef(this.cache,i.extensions[this.name].light)}}_loadLight(e){const t=this.parser,n="light:"+e;let a=t.cache.get(n);if(a)return a;const i=t.json,c=((i.extensions&&i.extensions[this.name]||{}).lights||[])[e];let d;const m=new Gt(16777215);c.color!==void 0&&m.setRGB(c.color[0],c.color[1],c.color[2],Ii);const p=c.range!==void 0?c.range:0;switch(c.type){case"directional":d=new uc(m),d.target.position.set(0,0,-1),d.add(d.target);break;case"point":d=new PA(m),d.distance=p;break;case"spot":d=new nP(m),d.distance=p,c.spot=c.spot||{},c.spot.innerConeAngle=c.spot.innerConeAngle!==void 0?c.spot.innerConeAngle:0,c.spot.outerConeAngle=c.spot.outerConeAngle!==void 0?c.spot.outerConeAngle:Math.PI/4,d.angle=c.spot.outerConeAngle,d.penumbra=1-c.spot.innerConeAngle/c.spot.outerConeAngle,d.target.position.set(0,0,-1),d.add(d.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+c.type)}return d.position.set(0,0,0),d.decay=2,cr(d,c),c.intensity!==void 0&&(d.intensity=c.intensity),d.name=t.createUniqueName(c.name||"light_"+e),a=Promise.resolve(d),t.cache.add(n,a),a}getDependency(e,t){if(e==="light")return this._loadLight(t)}createNodeAttachment(e){const t=this,n=this.parser,i=n.json.nodes[e],l=(i.extensions&&i.extensions[this.name]||{}).light;return l===void 0?null:this._loadLight(l).then(function(c){return n._getNodeRef(t.cache,l,c)})}}class ZL{constructor(){this.name=nn.KHR_MATERIALS_UNLIT}getMaterialType(){return Ke}extendParams(e,t,n){const a=[];e.color=new Gt(1,1,1),e.opacity=1;const i=t.pbrMetallicRoughness;if(i){if(Array.isArray(i.baseColorFactor)){const o=i.baseColorFactor;e.color.setRGB(o[0],o[1],o[2],Ii),e.opacity=o[3]}i.baseColorTexture!==void 0&&a.push(n.assignTexture(e,"map",i.baseColorTexture,ii))}return Promise.all(a)}}class QL{constructor(e){this.parser=e,this.name=nn.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){const a=this.parser.json.materials[e];if(!a.extensions||!a.extensions[this.name])return Promise.resolve();const i=a.extensions[this.name].emissiveStrength;return i!==void 0&&(t.emissiveIntensity=i),Promise.resolve()}}class JL{constructor(e){this.parser=e,this.name=nn.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:zi}extendMaterialParams(e,t){const n=this.parser,a=n.json.materials[e];if(!a.extensions||!a.extensions[this.name])return Promise.resolve();const i=[],o=a.extensions[this.name];if(o.clearcoatFactor!==void 0&&(t.clearcoat=o.clearcoatFactor),o.clearcoatTexture!==void 0&&i.push(n.assignTexture(t,"clearcoatMap",o.clearcoatTexture)),o.clearcoatRoughnessFactor!==void 0&&(t.clearcoatRoughness=o.clearcoatRoughnessFactor),o.clearcoatRoughnessTexture!==void 0&&i.push(n.assignTexture(t,"clearcoatRoughnessMap",o.clearcoatRoughnessTexture)),o.clearcoatNormalTexture!==void 0&&(i.push(n.assignTexture(t,"clearcoatNormalMap",o.clearcoatNormalTexture)),o.clearcoatNormalTexture.scale!==void 0)){const l=o.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new zs(l,l)}return Promise.all(i)}}class eO{constructor(e){this.parser=e,this.name=nn.KHR_MATERIALS_DISPERSION}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:zi}extendMaterialParams(e,t){const a=this.parser.json.materials[e];if(!a.extensions||!a.extensions[this.name])return Promise.resolve();const i=a.extensions[this.name];return t.dispersion=i.dispersion!==void 0?i.dispersion:0,Promise.resolve()}}class tO{constructor(e){this.parser=e,this.name=nn.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:zi}extendMaterialParams(e,t){const n=this.parser,a=n.json.materials[e];if(!a.extensions||!a.extensions[this.name])return Promise.resolve();const i=[],o=a.extensions[this.name];return o.iridescenceFactor!==void 0&&(t.iridescence=o.iridescenceFactor),o.iridescenceTexture!==void 0&&i.push(n.assignTexture(t,"iridescenceMap",o.iridescenceTexture)),o.iridescenceIor!==void 0&&(t.iridescenceIOR=o.iridescenceIor),t.iridescenceThicknessRange===void 0&&(t.iridescenceThicknessRange=[100,400]),o.iridescenceThicknessMinimum!==void 0&&(t.iridescenceThicknessRange[0]=o.iridescenceThicknessMinimum),o.iridescenceThicknessMaximum!==void 0&&(t.iridescenceThicknessRange[1]=o.iridescenceThicknessMaximum),o.iridescenceThicknessTexture!==void 0&&i.push(n.assignTexture(t,"iridescenceThicknessMap",o.iridescenceThicknessTexture)),Promise.all(i)}}class nO{constructor(e){this.parser=e,this.name=nn.KHR_MATERIALS_SHEEN}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:zi}extendMaterialParams(e,t){const n=this.parser,a=n.json.materials[e];if(!a.extensions||!a.extensions[this.name])return Promise.resolve();const i=[];t.sheenColor=new Gt(0,0,0),t.sheenRoughness=0,t.sheen=1;const o=a.extensions[this.name];if(o.sheenColorFactor!==void 0){const l=o.sheenColorFactor;t.sheenColor.setRGB(l[0],l[1],l[2],Ii)}return o.sheenRoughnessFactor!==void 0&&(t.sheenRoughness=o.sheenRoughnessFactor),o.sheenColorTexture!==void 0&&i.push(n.assignTexture(t,"sheenColorMap",o.sheenColorTexture,ii)),o.sheenRoughnessTexture!==void 0&&i.push(n.assignTexture(t,"sheenRoughnessMap",o.sheenRoughnessTexture)),Promise.all(i)}}class sO{constructor(e){this.parser=e,this.name=nn.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:zi}extendMaterialParams(e,t){const n=this.parser,a=n.json.materials[e];if(!a.extensions||!a.extensions[this.name])return Promise.resolve();const i=[],o=a.extensions[this.name];return o.transmissionFactor!==void 0&&(t.transmission=o.transmissionFactor),o.transmissionTexture!==void 0&&i.push(n.assignTexture(t,"transmissionMap",o.transmissionTexture)),Promise.all(i)}}class aO{constructor(e){this.parser=e,this.name=nn.KHR_MATERIALS_VOLUME}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:zi}extendMaterialParams(e,t){const n=this.parser,a=n.json.materials[e];if(!a.extensions||!a.extensions[this.name])return Promise.resolve();const i=[],o=a.extensions[this.name];t.thickness=o.thicknessFactor!==void 0?o.thicknessFactor:0,o.thicknessTexture!==void 0&&i.push(n.assignTexture(t,"thicknessMap",o.thicknessTexture)),t.attenuationDistance=o.attenuationDistance||1/0;const l=o.attenuationColor||[1,1,1];return t.attenuationColor=new Gt().setRGB(l[0],l[1],l[2],Ii),Promise.all(i)}}class iO{constructor(e){this.parser=e,this.name=nn.KHR_MATERIALS_IOR}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:zi}extendMaterialParams(e,t){const a=this.parser.json.materials[e];if(!a.extensions||!a.extensions[this.name])return Promise.resolve();const i=a.extensions[this.name];return t.ior=i.ior!==void 0?i.ior:1.5,Promise.resolve()}}class rO{constructor(e){this.parser=e,this.name=nn.KHR_MATERIALS_SPECULAR}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:zi}extendMaterialParams(e,t){const n=this.parser,a=n.json.materials[e];if(!a.extensions||!a.extensions[this.name])return Promise.resolve();const i=[],o=a.extensions[this.name];t.specularIntensity=o.specularFactor!==void 0?o.specularFactor:1,o.specularTexture!==void 0&&i.push(n.assignTexture(t,"specularIntensityMap",o.specularTexture));const l=o.specularColorFactor||[1,1,1];return t.specularColor=new Gt().setRGB(l[0],l[1],l[2],Ii),o.specularColorTexture!==void 0&&i.push(n.assignTexture(t,"specularColorMap",o.specularColorTexture,ii)),Promise.all(i)}}class oO{constructor(e){this.parser=e,this.name=nn.EXT_MATERIALS_BUMP}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:zi}extendMaterialParams(e,t){const n=this.parser,a=n.json.materials[e];if(!a.extensions||!a.extensions[this.name])return Promise.resolve();const i=[],o=a.extensions[this.name];return t.bumpScale=o.bumpFactor!==void 0?o.bumpFactor:1,o.bumpTexture!==void 0&&i.push(n.assignTexture(t,"bumpMap",o.bumpTexture)),Promise.all(i)}}class lO{constructor(e){this.parser=e,this.name=nn.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:zi}extendMaterialParams(e,t){const n=this.parser,a=n.json.materials[e];if(!a.extensions||!a.extensions[this.name])return Promise.resolve();const i=[],o=a.extensions[this.name];return o.anisotropyStrength!==void 0&&(t.anisotropy=o.anisotropyStrength),o.anisotropyRotation!==void 0&&(t.anisotropyRotation=o.anisotropyRotation),o.anisotropyTexture!==void 0&&i.push(n.assignTexture(t,"anisotropyMap",o.anisotropyTexture)),Promise.all(i)}}class cO{constructor(e){this.parser=e,this.name=nn.KHR_TEXTURE_BASISU}loadTexture(e){const t=this.parser,n=t.json,a=n.textures[e];if(!a.extensions||!a.extensions[this.name])return null;const i=a.extensions[this.name],o=t.options.ktx2Loader;if(!o){if(n.extensionsRequired&&n.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(e,i.source,o)}}class uO{constructor(e){this.parser=e,this.name=nn.EXT_TEXTURE_WEBP,this.isSupported=null}loadTexture(e){const t=this.name,n=this.parser,a=n.json,i=a.textures[e];if(!i.extensions||!i.extensions[t])return null;const o=i.extensions[t],l=a.images[o.source];let c=n.textureLoader;if(l.uri){const d=n.options.manager.getHandler(l.uri);d!==null&&(c=d)}return this.detectSupport().then(function(d){if(d)return n.loadTextureImage(e,o.source,c);if(a.extensionsRequired&&a.extensionsRequired.indexOf(t)>=0)throw new Error("THREE.GLTFLoader: WebP required by asset but unsupported.");return n.loadTexture(e)})}detectSupport(){return this.isSupported||(this.isSupported=new Promise(function(e){const t=new Image;t.src="data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA",t.onload=t.onerror=function(){e(t.height===1)}})),this.isSupported}}class dO{constructor(e){this.parser=e,this.name=nn.EXT_TEXTURE_AVIF,this.isSupported=null}loadTexture(e){const t=this.name,n=this.parser,a=n.json,i=a.textures[e];if(!i.extensions||!i.extensions[t])return null;const o=i.extensions[t],l=a.images[o.source];let c=n.textureLoader;if(l.uri){const d=n.options.manager.getHandler(l.uri);d!==null&&(c=d)}return this.detectSupport().then(function(d){if(d)return n.loadTextureImage(e,o.source,c);if(a.extensionsRequired&&a.extensionsRequired.indexOf(t)>=0)throw new Error("THREE.GLTFLoader: AVIF required by asset but unsupported.");return n.loadTexture(e)})}detectSupport(){return this.isSupported||(this.isSupported=new Promise(function(e){const t=new Image;t.src="data:image/avif;base64,AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUIAAADybWV0YQAAAAAAAAAoaGRscgAAAAAAAAAAcGljdAAAAAAAAAAAAAAAAGxpYmF2aWYAAAAADnBpdG0AAAAAAAEAAAAeaWxvYwAAAABEAAABAAEAAAABAAABGgAAABcAAAAoaWluZgAAAAAAAQAAABppbmZlAgAAAAABAABhdjAxQ29sb3IAAAAAamlwcnAAAABLaXBjbwAAABRpc3BlAAAAAAAAAAEAAAABAAAAEHBpeGkAAAAAAwgICAAAAAxhdjFDgQAMAAAAABNjb2xybmNseAACAAIABoAAAAAXaXBtYQAAAAAAAAABAAEEAQKDBAAAAB9tZGF0EgAKCBgABogQEDQgMgkQAAAAB8dSLfI=",t.onload=t.onerror=function(){e(t.height===1)}})),this.isSupported}}class hO{constructor(e){this.name=nn.EXT_MESHOPT_COMPRESSION,this.parser=e}loadBufferView(e){const t=this.parser.json,n=t.bufferViews[e];if(n.extensions&&n.extensions[this.name]){const a=n.extensions[this.name],i=this.parser.getDependency("buffer",a.buffer),o=this.parser.options.meshoptDecoder;if(!o||!o.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return i.then(function(l){const c=a.byteOffset||0,d=a.byteLength||0,m=a.count,p=a.byteStride,f=new Uint8Array(l,c,d);return o.decodeGltfBufferAsync?o.decodeGltfBufferAsync(m,p,f,a.mode,a.filter).then(function(b){return b.buffer}):o.ready.then(function(){const b=new ArrayBuffer(m*p);return o.decodeGltfBuffer(new Uint8Array(b),m,p,f,a.mode,a.filter),b})})}else return null}}class pO{constructor(e){this.name=nn.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){const t=this.parser.json,n=t.nodes[e];if(!n.extensions||!n.extensions[this.name]||n.mesh===void 0)return null;const a=t.meshes[n.mesh];for(const d of a.primitives)if(d.mode!==$a.TRIANGLES&&d.mode!==$a.TRIANGLE_STRIP&&d.mode!==$a.TRIANGLE_FAN&&d.mode!==void 0)return null;const o=n.extensions[this.name].attributes,l=[],c={};for(const d in o)l.push(this.parser.getDependency("accessor",o[d]).then(m=>(c[d]=m,c[d])));return l.length<1?null:(l.push(this.parser.createNodeMesh(e)),Promise.all(l).then(d=>{const m=d.pop(),p=m.isGroup?m.children:[m],f=d[0].count,b=[];for(const x of p){const w=new sl,k=new gt,S=new al,j=new gt(1,1,1),C=new ur(x.geometry,x.material,f);for(let N=0;N<f;N++)c.TRANSLATION&&k.fromBufferAttribute(c.TRANSLATION,N),c.ROTATION&&S.fromBufferAttribute(c.ROTATION,N),c.SCALE&&j.fromBufferAttribute(c.SCALE,N),C.setMatrixAt(N,w.compose(k,S,j));for(const N in c)if(N==="_COLOR_0"){const P=c[N];C.instanceColor=new sP(P.array,P.itemSize,P.normalized)}else N!=="TRANSLATION"&&N!=="ROTATION"&&N!=="SCALE"&&x.geometry.setAttribute(N,c[N]);RA.prototype.copy.call(C,x),this.parser.assignFinalMaterial(C),b.push(C)}return m.isGroup?(m.clear(),m.add(...b),m):b[0]}))}}const wM="glTF",Eu=12,Sj={JSON:1313821514,BIN:5130562};class mO{constructor(e){this.name=nn.KHR_BINARY_GLTF,this.content=null,this.body=null;const t=new DataView(e,0,Eu),n=new TextDecoder;if(this.header={magic:n.decode(new Uint8Array(e.slice(0,4))),version:t.getUint32(4,!0),length:t.getUint32(8,!0)},this.header.magic!==wM)throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");if(this.header.version<2)throw new Error("THREE.GLTFLoader: Legacy binary file detected.");const a=this.header.length-Eu,i=new DataView(e,Eu);let o=0;for(;o<a;){const l=i.getUint32(o,!0);o+=4;const c=i.getUint32(o,!0);if(o+=4,c===Sj.JSON){const d=new Uint8Array(e,Eu+o,l);this.content=n.decode(d)}else if(c===Sj.BIN){const d=Eu+o;this.body=e.slice(d,d+l)}o+=l}if(this.content===null)throw new Error("THREE.GLTFLoader: JSON content not found.")}}class fO{constructor(e,t){if(!t)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=nn.KHR_DRACO_MESH_COMPRESSION,this.json=e,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(e,t){const n=this.json,a=this.dracoLoader,i=e.extensions[this.name].bufferView,o=e.extensions[this.name].attributes,l={},c={},d={};for(const m in o){const p=Ny[m]||m.toLowerCase();l[p]=o[m]}for(const m in e.attributes){const p=Ny[m]||m.toLowerCase();if(o[m]!==void 0){const f=n.accessors[e.attributes[m]],b=hc[f.componentType];d[p]=b.name,c[p]=f.normalized===!0}}return t.getDependency("bufferView",i).then(function(m){return new Promise(function(p,f){a.decodeDracoFile(m,function(b){for(const x in b.attributes){const w=b.attributes[x],k=c[x];k!==void 0&&(w.normalized=k)}p(b)},l,d,Ii,f)})})}}class gO{constructor(){this.name=nn.KHR_TEXTURE_TRANSFORM}extendTexture(e,t){return(t.texCoord===void 0||t.texCoord===e.channel)&&t.offset===void 0&&t.rotation===void 0&&t.scale===void 0||(e=e.clone(),t.texCoord!==void 0&&(e.channel=t.texCoord),t.offset!==void 0&&e.offset.fromArray(t.offset),t.rotation!==void 0&&(e.rotation=t.rotation),t.scale!==void 0&&e.repeat.fromArray(t.scale),e.needsUpdate=!0),e}}class bO{constructor(){this.name=nn.KHR_MESH_QUANTIZATION}}class kM extends yP{constructor(e,t,n,a){super(e,t,n,a)}copySampleValue_(e){const t=this.resultBuffer,n=this.sampleValues,a=this.valueSize,i=e*a*3+a;for(let o=0;o!==a;o++)t[o]=n[i+o];return t}interpolate_(e,t,n,a){const i=this.resultBuffer,o=this.sampleValues,l=this.valueSize,c=l*2,d=l*3,m=a-t,p=(n-t)/m,f=p*p,b=f*p,x=e*d,w=x-d,k=-2*b+3*f,S=b-f,j=1-k,C=S-f+p;for(let N=0;N!==l;N++){const P=o[w+N+l],_=o[w+N+c]*m,L=o[x+N+l],M=o[x+N]*m;i[N]=j*P+C*_+k*L+S*M}return i}}const yO=new al;class xO extends kM{interpolate_(e,t,n,a){const i=super.interpolate_(e,t,n,a);return yO.fromArray(i).normalize().toArray(i),i}}const $a={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6},hc={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},jj={9728:LA,9729:zn,9984:lP,9985:oP,9986:rP,9987:Zu},Cj={33071:uP,33648:cP,10497:Wo},nb={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},Ny={POSITION:"position",NORMAL:"normal",TANGENT:"tangent",TEXCOORD_0:"uv",TEXCOORD_1:"uv1",TEXCOORD_2:"uv2",TEXCOORD_3:"uv3",COLOR_0:"color",WEIGHTS_0:"skinWeight",JOINTS_0:"skinIndex"},Xr={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},vO={CUBICSPLINE:void 0,LINEAR:IA,STEP:gP},sb={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function wO(s){return s.DefaultMaterial===void 0&&(s.DefaultMaterial=new dt({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:BA})),s.DefaultMaterial}function Bo(s,e,t){for(const n in t.extensions)s[n]===void 0&&(e.userData.gltfExtensions=e.userData.gltfExtensions||{},e.userData.gltfExtensions[n]=t.extensions[n])}function cr(s,e){e.extras!==void 0&&(typeof e.extras=="object"?Object.assign(s.userData,e.extras):console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, "+e.extras))}function kO(s,e,t){let n=!1,a=!1,i=!1;for(let d=0,m=e.length;d<m;d++){const p=e[d];if(p.POSITION!==void 0&&(n=!0),p.NORMAL!==void 0&&(a=!0),p.COLOR_0!==void 0&&(i=!0),n&&a&&i)break}if(!n&&!a&&!i)return Promise.resolve(s);const o=[],l=[],c=[];for(let d=0,m=e.length;d<m;d++){const p=e[d];if(n){const f=p.POSITION!==void 0?t.getDependency("accessor",p.POSITION):s.attributes.position;o.push(f)}if(a){const f=p.NORMAL!==void 0?t.getDependency("accessor",p.NORMAL):s.attributes.normal;l.push(f)}if(i){const f=p.COLOR_0!==void 0?t.getDependency("accessor",p.COLOR_0):s.attributes.color;c.push(f)}}return Promise.all([Promise.all(o),Promise.all(l),Promise.all(c)]).then(function(d){const m=d[0],p=d[1],f=d[2];return n&&(s.morphAttributes.position=m),a&&(s.morphAttributes.normal=p),i&&(s.morphAttributes.color=f),s.morphTargetsRelative=!0,s})}function SO(s,e){if(s.updateMorphTargets(),e.weights!==void 0)for(let t=0,n=e.weights.length;t<n;t++)s.morphTargetInfluences[t]=e.weights[t];if(e.extras&&Array.isArray(e.extras.targetNames)){const t=e.extras.targetNames;if(s.morphTargetInfluences.length===t.length){s.morphTargetDictionary={};for(let n=0,a=t.length;n<a;n++)s.morphTargetDictionary[t[n]]=n}else console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.")}}function jO(s){let e;const t=s.extensions&&s.extensions[nn.KHR_DRACO_MESH_COMPRESSION];if(t?e="draco:"+t.bufferView+":"+t.indices+":"+ab(t.attributes):e=s.indices+":"+ab(s.attributes)+":"+s.mode,s.targets!==void 0)for(let n=0,a=s.targets.length;n<a;n++)e+=":"+ab(s.targets[n]);return e}function ab(s){let e="";const t=Object.keys(s).sort();for(let n=0,a=t.length;n<a;n++)e+=t[n]+":"+s[t[n]]+";";return e}function Ay(s){switch(s){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:throw new Error("THREE.GLTFLoader: Unsupported normalized accessor component type.")}}function CO(s){return s.search(/\.jpe?g($|\?)/i)>0||s.search(/^data\:image\/jpeg/)===0?"image/jpeg":s.search(/\.webp($|\?)/i)>0||s.search(/^data\:image\/webp/)===0?"image/webp":s.search(/\.ktx2($|\?)/i)>0||s.search(/^data\:image\/ktx2/)===0?"image/ktx2":"image/png"}const NO=new sl;class AO{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new KL,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let n=!1,a=-1,i=!1,o=-1;if(typeof navigator<"u"){const l=navigator.userAgent;n=/^((?!chrome|android).)*safari/i.test(l)===!0;const c=l.match(/Version\/(\d+)/);a=n&&c?parseInt(c[1],10):-1,i=l.indexOf("Firefox")>-1,o=i?l.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||n&&a<17||i&&o<98?this.textureLoader=new fx(this.options.manager):this.textureLoader=new aP(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new Tp(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials"&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){const n=this,a=this.json,i=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(o){return o._markDefs&&o._markDefs()}),Promise.all(this._invokeAll(function(o){return o.beforeRoot&&o.beforeRoot()})).then(function(){return Promise.all([n.getDependencies("scene"),n.getDependencies("animation"),n.getDependencies("camera")])}).then(function(o){const l={scene:o[0][a.scene||0],scenes:o[0],animations:o[1],cameras:o[2],asset:a.asset,parser:n,userData:{}};return Bo(i,l,a),cr(l,a),Promise.all(n._invokeAll(function(c){return c.afterRoot&&c.afterRoot(l)})).then(function(){for(const c of l.scenes)c.updateMatrixWorld();e(l)})}).catch(t)}_markDefs(){const e=this.json.nodes||[],t=this.json.skins||[],n=this.json.meshes||[];for(let a=0,i=t.length;a<i;a++){const o=t[a].joints;for(let l=0,c=o.length;l<c;l++)e[o[l]].isBone=!0}for(let a=0,i=e.length;a<i;a++){const o=e[a];o.mesh!==void 0&&(this._addNodeRef(this.meshCache,o.mesh),o.skin!==void 0&&(n[o.mesh].isSkinnedMesh=!0)),o.camera!==void 0&&this._addNodeRef(this.cameraCache,o.camera)}}_addNodeRef(e,t){t!==void 0&&(e.refs[t]===void 0&&(e.refs[t]=e.uses[t]=0),e.refs[t]++)}_getNodeRef(e,t,n){if(e.refs[t]<=1)return n;const a=n.clone(),i=(o,l)=>{const c=this.associations.get(o);c!=null&&this.associations.set(l,c);for(const[d,m]of o.children.entries())i(m,l.children[d])};return i(n,a),a.name+="_instance_"+e.uses[t]++,a}_invokeOne(e){const t=Object.values(this.plugins);t.push(this);for(let n=0;n<t.length;n++){const a=e(t[n]);if(a)return a}return null}_invokeAll(e){const t=Object.values(this.plugins);t.unshift(this);const n=[];for(let a=0;a<t.length;a++){const i=e(t[a]);i&&n.push(i)}return n}getDependency(e,t){const n=e+":"+t;let a=this.cache.get(n);if(!a){switch(e){case"scene":a=this.loadScene(t);break;case"node":a=this._invokeOne(function(i){return i.loadNode&&i.loadNode(t)});break;case"mesh":a=this._invokeOne(function(i){return i.loadMesh&&i.loadMesh(t)});break;case"accessor":a=this.loadAccessor(t);break;case"bufferView":a=this._invokeOne(function(i){return i.loadBufferView&&i.loadBufferView(t)});break;case"buffer":a=this.loadBuffer(t);break;case"material":a=this._invokeOne(function(i){return i.loadMaterial&&i.loadMaterial(t)});break;case"texture":a=this._invokeOne(function(i){return i.loadTexture&&i.loadTexture(t)});break;case"skin":a=this.loadSkin(t);break;case"animation":a=this._invokeOne(function(i){return i.loadAnimation&&i.loadAnimation(t)});break;case"camera":a=this.loadCamera(t);break;default:if(a=this._invokeOne(function(i){return i!=this&&i.getDependency&&i.getDependency(e,t)}),!a)throw new Error("Unknown type: "+e);break}this.cache.add(n,a)}return a}getDependencies(e){let t=this.cache.get(e);if(!t){const n=this,a=this.json[e+(e==="mesh"?"es":"s")]||[];t=Promise.all(a.map(function(i,o){return n.getDependency(e,o)})),this.cache.add(e,t)}return t}loadBuffer(e){const t=this.json.buffers[e],n=this.fileLoader;if(t.type&&t.type!=="arraybuffer")throw new Error("THREE.GLTFLoader: "+t.type+" buffer type is not supported.");if(t.uri===void 0&&e===0)return Promise.resolve(this.extensions[nn.KHR_BINARY_GLTF].body);const a=this.options;return new Promise(function(i,o){n.load(Xu.resolveURL(t.uri,a.path),i,void 0,function(){o(new Error('THREE.GLTFLoader: Failed to load buffer "'+t.uri+'".'))})})}loadBufferView(e){const t=this.json.bufferViews[e];return this.getDependency("buffer",t.buffer).then(function(n){const a=t.byteLength||0,i=t.byteOffset||0;return n.slice(i,i+a)})}loadAccessor(e){const t=this,n=this.json,a=this.json.accessors[e];if(a.bufferView===void 0&&a.sparse===void 0){const o=nb[a.type],l=hc[a.componentType],c=a.normalized===!0,d=new l(a.count*o);return Promise.resolve(new ri(d,o,c))}const i=[];return a.bufferView!==void 0?i.push(this.getDependency("bufferView",a.bufferView)):i.push(null),a.sparse!==void 0&&(i.push(this.getDependency("bufferView",a.sparse.indices.bufferView)),i.push(this.getDependency("bufferView",a.sparse.values.bufferView))),Promise.all(i).then(function(o){const l=o[0],c=nb[a.type],d=hc[a.componentType],m=d.BYTES_PER_ELEMENT,p=m*c,f=a.byteOffset||0,b=a.bufferView!==void 0?n.bufferViews[a.bufferView].byteStride:void 0,x=a.normalized===!0;let w,k;if(b&&b!==p){const S=Math.floor(f/b),j="InterleavedBuffer:"+a.bufferView+":"+a.componentType+":"+S+":"+a.count;let C=t.cache.get(j);C||(w=new d(l,S*b,a.count*b/m),C=new iP(w,b/m),t.cache.add(j,C)),k=new bP(C,c,f%b/m,x)}else l===null?w=new d(a.count*c):w=new d(l,f,a.count*c),k=new ri(w,c,x);if(a.sparse!==void 0){const S=nb.SCALAR,j=hc[a.sparse.indices.componentType],C=a.sparse.indices.byteOffset||0,N=a.sparse.values.byteOffset||0,P=new j(o[1],C,a.sparse.count*S),_=new d(o[2],N,a.sparse.count*c);l!==null&&(k=new ri(k.array.slice(),k.itemSize,k.normalized)),k.normalized=!1;for(let L=0,M=P.length;L<M;L++){const D=P[L];if(k.setX(D,_[L*c]),c>=2&&k.setY(D,_[L*c+1]),c>=3&&k.setZ(D,_[L*c+2]),c>=4&&k.setW(D,_[L*c+3]),c>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}k.normalized=x}return k})}loadTexture(e){const t=this.json,n=this.options,i=t.textures[e].source,o=t.images[i];let l=this.textureLoader;if(o.uri){const c=n.manager.getHandler(o.uri);c!==null&&(l=c)}return this.loadTextureImage(e,i,l)}loadTextureImage(e,t,n){const a=this,i=this.json,o=i.textures[e],l=i.images[t],c=(l.uri||l.bufferView)+":"+o.sampler;if(this.textureCache[c])return this.textureCache[c];const d=this.loadImageSource(t,n).then(function(m){m.flipY=!1,m.name=o.name||l.name||"",m.name===""&&typeof l.uri=="string"&&l.uri.startsWith("data:image/")===!1&&(m.name=l.uri);const f=(i.samplers||{})[o.sampler]||{};return m.magFilter=jj[f.magFilter]||zn,m.minFilter=jj[f.minFilter]||Zu,m.wrapS=Cj[f.wrapS]||Wo,m.wrapT=Cj[f.wrapT]||Wo,m.generateMipmaps=!m.isCompressedTexture&&m.minFilter!==LA&&m.minFilter!==zn,a.associations.set(m,{textures:e}),m}).catch(function(){return null});return this.textureCache[c]=d,d}loadImageSource(e,t){const n=this,a=this.json,i=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(p=>p.clone());const o=a.images[e],l=self.URL||self.webkitURL;let c=o.uri||"",d=!1;if(o.bufferView!==void 0)c=n.getDependency("bufferView",o.bufferView).then(function(p){d=!0;const f=new Blob([p],{type:o.mimeType});return c=l.createObjectURL(f),c});else if(o.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");const m=Promise.resolve(c).then(function(p){return new Promise(function(f,b){let x=f;t.isImageBitmapLoader===!0&&(x=function(w){const k=new vS(w);k.needsUpdate=!0,f(k)}),t.load(Xu.resolveURL(p,i.path),x,void 0,b)})}).then(function(p){return d===!0&&l.revokeObjectURL(c),cr(p,o),p.userData.mimeType=o.mimeType||CO(o.uri),p}).catch(function(p){throw console.error("THREE.GLTFLoader: Couldn't load texture",c),p});return this.sourceCache[e]=m,m}assignTexture(e,t,n,a){const i=this;return this.getDependency("texture",n.index).then(function(o){if(!o)return null;if(n.texCoord!==void 0&&n.texCoord>0&&(o=o.clone(),o.channel=n.texCoord),i.extensions[nn.KHR_TEXTURE_TRANSFORM]){const l=n.extensions!==void 0?n.extensions[nn.KHR_TEXTURE_TRANSFORM]:void 0;if(l){const c=i.associations.get(o);o=i.extensions[nn.KHR_TEXTURE_TRANSFORM].extendTexture(o,l),i.associations.set(o,c)}}return a!==void 0&&(o.colorSpace=a),e[t]=o,o})}assignFinalMaterial(e){const t=e.geometry;let n=e.material;const a=t.attributes.tangent===void 0,i=t.attributes.color!==void 0,o=t.attributes.normal===void 0;if(e.isPoints){const l="PointsMaterial:"+n.uuid;let c=this.cache.get(l);c||(c=new pm,hr.prototype.copy.call(c,n),c.color.copy(n.color),c.map=n.map,c.sizeAttenuation=!1,this.cache.add(l,c)),n=c}else if(e.isLine){const l="LineBasicMaterial:"+n.uuid;let c=this.cache.get(l);c||(c=new qo,hr.prototype.copy.call(c,n),c.color.copy(n.color),c.map=n.map,this.cache.add(l,c)),n=c}if(a||i||o){let l="ClonedMaterial:"+n.uuid+":";a&&(l+="derivative-tangents:"),i&&(l+="vertex-colors:"),o&&(l+="flat-shading:");let c=this.cache.get(l);c||(c=n.clone(),i&&(c.vertexColors=!0),o&&(c.flatShading=!0),a&&(c.normalScale&&(c.normalScale.y*=-1),c.clearcoatNormalScale&&(c.clearcoatNormalScale.y*=-1)),this.cache.add(l,c),this.associations.set(c,this.associations.get(n))),n=c}e.material=n}getMaterialType(){return dt}loadMaterial(e){const t=this,n=this.json,a=this.extensions,i=n.materials[e];let o;const l={},c=i.extensions||{},d=[];if(c[nn.KHR_MATERIALS_UNLIT]){const p=a[nn.KHR_MATERIALS_UNLIT];o=p.getMaterialType(),d.push(p.extendParams(l,i,t))}else{const p=i.pbrMetallicRoughness||{};if(l.color=new Gt(1,1,1),l.opacity=1,Array.isArray(p.baseColorFactor)){const f=p.baseColorFactor;l.color.setRGB(f[0],f[1],f[2],Ii),l.opacity=f[3]}p.baseColorTexture!==void 0&&d.push(t.assignTexture(l,"map",p.baseColorTexture,ii)),l.metalness=p.metallicFactor!==void 0?p.metallicFactor:1,l.roughness=p.roughnessFactor!==void 0?p.roughnessFactor:1,p.metallicRoughnessTexture!==void 0&&(d.push(t.assignTexture(l,"metalnessMap",p.metallicRoughnessTexture)),d.push(t.assignTexture(l,"roughnessMap",p.metallicRoughnessTexture))),o=this._invokeOne(function(f){return f.getMaterialType&&f.getMaterialType(e)}),d.push(Promise.all(this._invokeAll(function(f){return f.extendMaterialParams&&f.extendMaterialParams(e,l)})))}i.doubleSided===!0&&(l.side=Ts);const m=i.alphaMode||sb.OPAQUE;if(m===sb.BLEND?(l.transparent=!0,l.depthWrite=!1):(l.transparent=!1,m===sb.MASK&&(l.alphaTest=i.alphaCutoff!==void 0?i.alphaCutoff:.5)),i.normalTexture!==void 0&&o!==Ke&&(d.push(t.assignTexture(l,"normalMap",i.normalTexture)),l.normalScale=new zs(1,1),i.normalTexture.scale!==void 0)){const p=i.normalTexture.scale;l.normalScale.set(p,p)}if(i.occlusionTexture!==void 0&&o!==Ke&&(d.push(t.assignTexture(l,"aoMap",i.occlusionTexture)),i.occlusionTexture.strength!==void 0&&(l.aoMapIntensity=i.occlusionTexture.strength)),i.emissiveFactor!==void 0&&o!==Ke){const p=i.emissiveFactor;l.emissive=new Gt().setRGB(p[0],p[1],p[2],Ii)}return i.emissiveTexture!==void 0&&o!==Ke&&d.push(t.assignTexture(l,"emissiveMap",i.emissiveTexture,ii)),Promise.all(d).then(function(){const p=new o(l);return i.name&&(p.name=i.name),cr(p,i),t.associations.set(p,{materials:e}),i.extensions&&Bo(a,p,i),p})}createUniqueName(e){const t=dP.sanitizeNodeName(e||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){const t=this,n=this.extensions,a=this.primitiveCache;function i(l){return n[nn.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(l,t).then(function(c){return Nj(c,l,t)})}const o=[];for(let l=0,c=e.length;l<c;l++){const d=e[l],m=jO(d),p=a[m];if(p)o.push(p.promise);else{let f;d.extensions&&d.extensions[nn.KHR_DRACO_MESH_COMPRESSION]?f=i(d):f=Nj(new Wa,d,t),a[m]={primitive:d,promise:f},o.push(f)}}return Promise.all(o)}loadMesh(e){const t=this,n=this.json,a=this.extensions,i=n.meshes[e],o=i.primitives,l=[];for(let c=0,d=o.length;c<d;c++){const m=o[c].material===void 0?wO(this.cache):this.getDependency("material",o[c].material);l.push(m)}return l.push(t.loadGeometries(o)),Promise.all(l).then(function(c){const d=c.slice(0,c.length-1),m=c[c.length-1],p=[];for(let b=0,x=m.length;b<x;b++){const w=m[b],k=o[b];let S;const j=d[b];if(k.mode===$a.TRIANGLES||k.mode===$a.TRIANGLE_STRIP||k.mode===$a.TRIANGLE_FAN||k.mode===void 0)S=i.isSkinnedMesh===!0?new ay(w,j):new De(w,j),S.isSkinnedMesh===!0&&S.normalizeSkinWeights(),k.mode===$a.TRIANGLE_STRIP?S.geometry=kj(S.geometry,_A):k.mode===$a.TRIANGLE_FAN&&(S.geometry=kj(S.geometry,sy));else if(k.mode===$a.LINES)S=new gx(w,j);else if(k.mode===$a.LINE_STRIP)S=new eo(w,j);else if(k.mode===$a.LINE_LOOP)S=new hP(w,j);else if(k.mode===$a.POINTS)S=new wd(w,j);else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+k.mode);Object.keys(S.geometry.morphAttributes).length>0&&SO(S,i),S.name=t.createUniqueName(i.name||"mesh_"+e),cr(S,i),k.extensions&&Bo(a,S,k),t.assignFinalMaterial(S),p.push(S)}for(let b=0,x=p.length;b<x;b++)t.associations.set(p[b],{meshes:e,primitives:b});if(p.length===1)return i.extensions&&Bo(a,p[0],i),p[0];const f=new Fn;i.extensions&&Bo(a,f,i),t.associations.set(f,{meshes:e});for(let b=0,x=p.length;b<x;b++)f.add(p[b]);return f})}loadCamera(e){let t;const n=this.json.cameras[e],a=n[n.type];if(!a){console.warn("THREE.GLTFLoader: Missing camera parameters.");return}return n.type==="perspective"?t=new bx(yx.radToDeg(a.yfov),a.aspectRatio||1,a.znear||1,a.zfar||2e6):n.type==="orthographic"&&(t=new OA(-a.xmag,a.xmag,a.ymag,-a.ymag,a.znear,a.zfar)),n.name&&(t.name=this.createUniqueName(n.name)),cr(t,n),Promise.resolve(t)}loadSkin(e){const t=this.json.skins[e],n=[];for(let a=0,i=t.joints.length;a<i;a++)n.push(this._loadNodeShallow(t.joints[a]));return t.inverseBindMatrices!==void 0?n.push(this.getDependency("accessor",t.inverseBindMatrices)):n.push(null),Promise.all(n).then(function(a){const i=a.pop(),o=a,l=[],c=[];for(let d=0,m=o.length;d<m;d++){const p=o[d];if(p){l.push(p);const f=new sl;i!==null&&f.fromArray(i.array,d*16),c.push(f)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',t.joints[d])}return new pP(l,c)})}loadAnimation(e){const t=this.json,n=this,a=t.animations[e],i=a.name?a.name:"animation_"+e,o=[],l=[],c=[],d=[],m=[];for(let p=0,f=a.channels.length;p<f;p++){const b=a.channels[p],x=a.samplers[b.sampler],w=b.target,k=w.node,S=a.parameters!==void 0?a.parameters[x.input]:x.input,j=a.parameters!==void 0?a.parameters[x.output]:x.output;w.node!==void 0&&(o.push(this.getDependency("node",k)),l.push(this.getDependency("accessor",S)),c.push(this.getDependency("accessor",j)),d.push(x),m.push(w))}return Promise.all([Promise.all(o),Promise.all(l),Promise.all(c),Promise.all(d),Promise.all(m)]).then(function(p){const f=p[0],b=p[1],x=p[2],w=p[3],k=p[4],S=[];for(let j=0,C=f.length;j<C;j++){const N=f[j],P=b[j],_=x[j],L=w[j],M=k[j];if(N===void 0)continue;N.updateMatrix&&N.updateMatrix();const D=n._createAnimationTracks(N,P,_,L,M);if(D)for(let E=0;E<D.length;E++)S.push(D[E])}return new mP(i,void 0,S)})}createNodeMesh(e){const t=this.json,n=this,a=t.nodes[e];return a.mesh===void 0?null:n.getDependency("mesh",a.mesh).then(function(i){const o=n._getNodeRef(n.meshCache,a.mesh,i);return a.weights!==void 0&&o.traverse(function(l){if(l.isMesh)for(let c=0,d=a.weights.length;c<d;c++)l.morphTargetInfluences[c]=a.weights[c]}),o})}loadNode(e){const t=this.json,n=this,a=t.nodes[e],i=n._loadNodeShallow(e),o=[],l=a.children||[];for(let d=0,m=l.length;d<m;d++)o.push(n.getDependency("node",l[d]));const c=a.skin===void 0?Promise.resolve(null):n.getDependency("skin",a.skin);return Promise.all([i,Promise.all(o),c]).then(function(d){const m=d[0],p=d[1],f=d[2];f!==null&&m.traverse(function(b){b.isSkinnedMesh&&b.bind(f,NO)});for(let b=0,x=p.length;b<x;b++)m.add(p[b]);return m})}_loadNodeShallow(e){const t=this.json,n=this.extensions,a=this;if(this.nodeCache[e]!==void 0)return this.nodeCache[e];const i=t.nodes[e],o=i.name?a.createUniqueName(i.name):"",l=[],c=a._invokeOne(function(d){return d.createNodeMesh&&d.createNodeMesh(e)});return c&&l.push(c),i.camera!==void 0&&l.push(a.getDependency("camera",i.camera).then(function(d){return a._getNodeRef(a.cameraCache,i.camera,d)})),a._invokeAll(function(d){return d.createNodeAttachment&&d.createNodeAttachment(e)}).forEach(function(d){l.push(d)}),this.nodeCache[e]=Promise.all(l).then(function(d){let m;if(i.isBone===!0?m=new fP:d.length>1?m=new Fn:d.length===1?m=d[0]:m=new RA,m!==d[0])for(let p=0,f=d.length;p<f;p++)m.add(d[p]);if(i.name&&(m.userData.name=i.name,m.name=o),cr(m,i),i.extensions&&Bo(n,m,i),i.matrix!==void 0){const p=new sl;p.fromArray(i.matrix),m.applyMatrix4(p)}else i.translation!==void 0&&m.position.fromArray(i.translation),i.rotation!==void 0&&m.quaternion.fromArray(i.rotation),i.scale!==void 0&&m.scale.fromArray(i.scale);return a.associations.has(m)||a.associations.set(m,{}),a.associations.get(m).nodes=e,m}),this.nodeCache[e]}loadScene(e){const t=this.extensions,n=this.json.scenes[e],a=this,i=new Fn;n.name&&(i.name=a.createUniqueName(n.name)),cr(i,n),n.extensions&&Bo(t,i,n);const o=n.nodes||[],l=[];for(let c=0,d=o.length;c<d;c++)l.push(a.getDependency("node",o[c]));return Promise.all(l).then(function(c){for(let m=0,p=c.length;m<p;m++)i.add(c[m]);const d=m=>{const p=new Map;for(const[f,b]of a.associations)(f instanceof hr||f instanceof vS)&&p.set(f,b);return m.traverse(f=>{const b=a.associations.get(f);b!=null&&p.set(f,b)}),p};return a.associations=d(i),i})}_createAnimationTracks(e,t,n,a,i){const o=[],l=e.name?e.name:e.uuid,c=[];Xr[i.path]===Xr.weights?e.traverse(function(f){f.morphTargetInfluences&&c.push(f.name?f.name:f.uuid)}):c.push(l);let d;switch(Xr[i.path]){case Xr.weights:d=kS;break;case Xr.rotation:d=SS;break;case Xr.position:case Xr.scale:d=wS;break;default:switch(n.itemSize){case 1:d=kS;break;case 2:case 3:default:d=wS;break}break}const m=a.interpolation!==void 0?vO[a.interpolation]:IA,p=this._getArrayFromAccessor(n);for(let f=0,b=c.length;f<b;f++){const x=new d(c[f]+"."+Xr[i.path],t.array,p,m);a.interpolation==="CUBICSPLINE"&&this._createCubicSplineTrackInterpolant(x),o.push(x)}return o}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){const n=Ay(t.constructor),a=new Float32Array(t.length);for(let i=0,o=t.length;i<o;i++)a[i]=t[i]*n;t=a}return t}_createCubicSplineTrackInterpolant(e){e.createInterpolant=function(n){const a=this instanceof SS?xO:kM;return new a(this.times,this.values,this.getValueSize()/3,n)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function MO(s,e,t){const n=e.attributes,a=new Ep;if(n.POSITION!==void 0){const l=t.json.accessors[n.POSITION],c=l.min,d=l.max;if(c!==void 0&&d!==void 0){if(a.set(new gt(c[0],c[1],c[2]),new gt(d[0],d[1],d[2])),l.normalized){const m=Ay(hc[l.componentType]);a.min.multiplyScalar(m),a.max.multiplyScalar(m)}}else{console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");return}}else return;const i=e.targets;if(i!==void 0){const l=new gt,c=new gt;for(let d=0,m=i.length;d<m;d++){const p=i[d];if(p.POSITION!==void 0){const f=t.json.accessors[p.POSITION],b=f.min,x=f.max;if(b!==void 0&&x!==void 0){if(c.setX(Math.max(Math.abs(b[0]),Math.abs(x[0]))),c.setY(Math.max(Math.abs(b[1]),Math.abs(x[1]))),c.setZ(Math.max(Math.abs(b[2]),Math.abs(x[2]))),f.normalized){const w=Ay(hc[f.componentType]);c.multiplyScalar(w)}l.max(c)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}a.expandByVector(l)}s.boundingBox=a;const o=new xP;a.getCenter(o.center),o.radius=a.min.distanceTo(a.max)/2,s.boundingSphere=o}function Nj(s,e,t){const n=e.attributes,a=[];function i(o,l){return t.getDependency("accessor",o).then(function(c){s.setAttribute(l,c)})}for(const o in n){const l=Ny[o]||o.toLowerCase();l in s.attributes||a.push(i(n[o],l))}if(e.indices!==void 0&&!s.index){const o=t.getDependency("accessor",e.indices).then(function(l){s.setIndex(l)});a.push(o)}return iy.workingColorSpace!==Ii&&"COLOR_0"in n&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${iy.workingColorSpace}" not supported.`),cr(s,e),MO(s,e,t),Promise.all(a).then(function(){return e.targets!==void 0?kO(s,e.targets,t):s})}const ib=new WeakMap;class Mx extends DA{constructor(e){super(e),this.decoderPath="",this.decoderConfig={},this.decoderBinary=null,this.decoderPending=null,this.workerLimit=4,this.workerPool=[],this.workerNextTaskID=1,this.workerSourceURL="",this.defaultAttributeIDs={position:"POSITION",normal:"NORMAL",color:"COLOR",uv:"TEX_COORD"},this.defaultAttributeTypes={position:"Float32Array",normal:"Float32Array",color:"Float32Array",uv:"Float32Array"}}setDecoderPath(e){return this.decoderPath=e,this}setDecoderConfig(e){return this.decoderConfig=e,this}setWorkerLimit(e){return this.workerLimit=e,this}load(e,t,n,a){const i=new Tp(this.manager);i.setPath(this.path),i.setResponseType("arraybuffer"),i.setRequestHeader(this.requestHeader),i.setWithCredentials(this.withCredentials),i.load(e,o=>{this.parse(o,t,a)},n,a)}parse(e,t,n=()=>{}){this.decodeDracoFile(e,t,null,null,ii,n).catch(n)}decodeDracoFile(e,t,n,a,i=Ii,o=()=>{}){const l={attributeIDs:n||this.defaultAttributeIDs,attributeTypes:a||this.defaultAttributeTypes,useUniqueIDs:!!n,vertexColorSpace:i};return this.decodeGeometry(e,l).then(t).catch(o)}decodeGeometry(e,t){const n=JSON.stringify(t);if(ib.has(e)){const c=ib.get(e);if(c.key===n)return c.promise;if(e.byteLength===0)throw new Error("THREE.DRACOLoader: Unable to re-decode a buffer with different settings. Buffer has already been transferred.")}let a;const i=this.workerNextTaskID++,o=e.byteLength,l=this._getWorker(i,o).then(c=>(a=c,new Promise((d,m)=>{a._callbacks[i]={resolve:d,reject:m},a.postMessage({type:"decode",id:i,taskConfig:t,buffer:e},[e])}))).then(c=>this._createGeometry(c.geometry));return l.catch(()=>!0).then(()=>{a&&i&&this._releaseTask(a,i)}),ib.set(e,{key:n,promise:l}),l}_createGeometry(e){const t=new Wa;e.index&&t.setIndex(new ri(e.index.array,1));for(let n=0;n<e.attributes.length;n++){const a=e.attributes[n],i=a.name,o=a.array,l=a.itemSize,c=new ri(o,l);i==="color"&&(this._assignVertexColorSpace(c,a.vertexColorSpace),c.normalized=!(o instanceof Float32Array)),t.setAttribute(i,c)}return t}_assignVertexColorSpace(e,t){if(t!==ii)return;const n=new Gt;for(let a=0,i=e.count;a<i;a++)n.fromBufferAttribute(e,a),iy.toWorkingColorSpace(n,ii),e.setXYZ(a,n.r,n.g,n.b)}_loadLibrary(e,t){const n=new Tp(this.manager);return n.setPath(this.decoderPath),n.setResponseType(t),n.setWithCredentials(this.withCredentials),new Promise((a,i)=>{n.load(e,a,void 0,i)})}preload(){return this._initDecoder(),this}_initDecoder(){if(this.decoderPending)return this.decoderPending;const e=typeof WebAssembly!="object"||this.decoderConfig.type==="js",t=[];return e?t.push(this._loadLibrary("draco_decoder.js","text")):(t.push(this._loadLibrary("draco_wasm_wrapper.js","text")),t.push(this._loadLibrary("draco_decoder.wasm","arraybuffer"))),this.decoderPending=Promise.all(t).then(n=>{const a=n[0];e||(this.decoderConfig.wasmBinary=n[1]);const i=TO.toString(),o=["/* draco decoder */",a,"","/* worker */",i.substring(i.indexOf("{")+1,i.lastIndexOf("}"))].join(`
43
43
  `);this.workerSourceURL=URL.createObjectURL(new Blob([o]))}),this.decoderPending}_getWorker(e,t){return this._initDecoder().then(()=>{if(this.workerPool.length<this.workerLimit){const a=new Worker(this.workerSourceURL);a._callbacks={},a._taskCosts={},a._taskLoad=0,a.postMessage({type:"init",decoderConfig:this.decoderConfig}),a.onmessage=function(i){const o=i.data;switch(o.type){case"decode":a._callbacks[o.id].resolve(o);break;case"error":a._callbacks[o.id].reject(o);break;default:console.error('THREE.DRACOLoader: Unexpected message, "'+o.type+'"')}},this.workerPool.push(a)}else this.workerPool.sort(function(a,i){return a._taskLoad>i._taskLoad?-1:1});const n=this.workerPool[this.workerPool.length-1];return n._taskCosts[e]=t,n._taskLoad+=t,n})}_releaseTask(e,t){e._taskLoad-=e._taskCosts[t],delete e._callbacks[t],delete e._taskCosts[t]}debug(){console.log("Task load: ",this.workerPool.map(e=>e._taskLoad))}dispose(){for(let e=0;e<this.workerPool.length;++e)this.workerPool[e].terminate();return this.workerPool.length=0,this.workerSourceURL!==""&&URL.revokeObjectURL(this.workerSourceURL),this}}function TO(){let s,e;onmessage=function(o){const l=o.data;switch(l.type){case"init":s=l.decoderConfig,e=new Promise(function(m){s.onModuleLoaded=function(p){m({draco:p})},DracoDecoderModule(s)});break;case"decode":const c=l.buffer,d=l.taskConfig;e.then(m=>{const p=m.draco,f=new p.Decoder;try{const b=t(p,f,new Int8Array(c),d),x=b.attributes.map(w=>w.array.buffer);b.index&&x.push(b.index.array.buffer),self.postMessage({type:"decode",id:l.id,geometry:b},x)}catch(b){console.error(b),self.postMessage({type:"error",id:l.id,error:b.message})}finally{p.destroy(f)}});break}};function t(o,l,c,d){const m=d.attributeIDs,p=d.attributeTypes;let f,b;const x=l.GetEncodedGeometryType(c);if(x===o.TRIANGULAR_MESH)f=new o.Mesh,b=l.DecodeArrayToMesh(c,c.byteLength,f);else if(x===o.POINT_CLOUD)f=new o.PointCloud,b=l.DecodeArrayToPointCloud(c,c.byteLength,f);else throw new Error("THREE.DRACOLoader: Unexpected geometry type.");if(!b.ok()||f.ptr===0)throw new Error("THREE.DRACOLoader: Decoding failed: "+b.error_msg());const w={index:null,attributes:[]};for(const k in m){const S=self[p[k]];let j,C;if(d.useUniqueIDs)C=m[k],j=l.GetAttributeByUniqueId(f,C);else{if(C=l.GetAttributeId(f,o[m[k]]),C===-1)continue;j=l.GetAttribute(f,C)}const N=a(o,l,f,k,S,j);k==="color"&&(N.vertexColorSpace=d.vertexColorSpace),w.attributes.push(N)}return x===o.TRIANGULAR_MESH&&(w.index=n(o,l,f)),o.destroy(f),w}function n(o,l,c){const m=c.num_faces()*3,p=m*4,f=o._malloc(p);l.GetTrianglesUInt32Array(c,p,f);const b=new Uint32Array(o.HEAPF32.buffer,f,m).slice();return o._free(f),{array:b,itemSize:1}}function a(o,l,c,d,m,p){const f=p.num_components(),x=c.num_points()*f,w=x*m.BYTES_PER_ELEMENT,k=i(o,m),S=o._malloc(w);l.GetAttributeDataArrayForAllPoints(c,p,k,w,S);const j=new m(o.HEAPF32.buffer,S,x).slice();return o._free(S),{name:d,array:j,itemSize:f}}function i(o,l){switch(l){case Float32Array:return o.DT_FLOAT32;case Int8Array:return o.DT_INT8;case Int16Array:return o.DT_INT16;case Int32Array:return o.DT_INT32;case Uint8Array:return o.DT_UINT8;case Uint16Array:return o.DT_UINT16;case Uint32Array:return o.DT_UINT32}}}var Tx=(function(){var s="b9H79Tebbbe8Fv9Gbb9Gvuuuuueu9Giuuub9Geueu9Giuuueuikqbeeedddillviebeoweuec:q;iekr;leDo9TW9T9VV95dbH9F9F939H79T9F9J9H229F9Jt9VV7bb8A9TW79O9V9Wt9F9KW9J9V9KW9wWVtW949c919M9MWVbeY9TW79O9V9Wt9F9KW9J9V9KW69U9KW949c919M9MWVbdE9TW79O9V9Wt9F9KW9J9V9KW69U9KW949tWG91W9U9JWbiL9TW79O9V9Wt9F9KW9J9V9KWS9P2tWV9p9JtblK9TW79O9V9Wt9F9KW9J9V9KWS9P2tWV9r919HtbvL9TW79O9V9Wt9F9KW9J9V9KWS9P2tWVT949Wbol79IV9Rbrq:P8Yqdbk;3sezu8Jjjjjbcj;eb9Rgv8Kjjjjbc9:hodnadcefal0mbcuhoaiRbbc:Ge9hmbavaialfgrad9Radz1jjjbhwcj;abad9UhoaicefhldnadTmbaoc;WFbGgocjdaocjd6EhDcbhqinaqae9pmeaDaeaq9RaqaDfae6Egkcsfgocl4cifcd4hxdndndndnaoc9WGgmTmbcbhPcehsawcjdfhzalhHinaraH9Rax6midnaraHaxfgl9RcK6mbczhoinawcj;cbfaogifgoc9WfhOdndndndndnaHaic9WfgAco4fRbbaAci4coG4ciGPlbedibkaO9cb83ibaOcwf9cb83ibxikaOalRblalRbbgAco4gCaCciSgCE86bbaocGfalclfaCfgORbbaAcl4ciGgCaCciSgCE86bbaocVfaOaCfgORbbaAcd4ciGgCaCciSgCE86bbaoc7faOaCfgORbbaAciGgAaAciSgAE86bbaoctfaOaAfgARbbalRbegOco4gCaCciSgCE86bbaoc91faAaCfgARbbaOcl4ciGgCaCciSgCE86bbaoc4faAaCfgARbbaOcd4ciGgCaCciSgCE86bbaoc93faAaCfgARbbaOciGgOaOciSgOE86bbaoc94faAaOfgARbbalRbdgOco4gCaCciSgCE86bbaoc95faAaCfgARbbaOcl4ciGgCaCciSgCE86bbaoc96faAaCfgARbbaOcd4ciGgCaCciSgCE86bbaoc97faAaCfgARbbaOciGgOaOciSgOE86bbaoc98faAaOfgORbbalRbiglco4gAaAciSgAE86bbaoc99faOaAfgORbbalcl4ciGgAaAciSgAE86bbaoc9:faOaAfgORbbalcd4ciGgAaAciSgAE86bbaocufaOaAfgoRbbalciGglalciSglE86bbaoalfhlxdkaOalRbwalRbbgAcl4gCaCcsSgCE86bbaocGfalcwfaCfgORbbaAcsGgAaAcsSgAE86bbaocVfaOaAfgORbbalRbegAcl4gCaCcsSgCE86bbaoc7faOaCfgORbbaAcsGgAaAcsSgAE86bbaoctfaOaAfgORbbalRbdgAcl4gCaCcsSgCE86bbaoc91faOaCfgORbbaAcsGgAaAcsSgAE86bbaoc4faOaAfgORbbalRbigAcl4gCaCcsSgCE86bbaoc93faOaCfgORbbaAcsGgAaAcsSgAE86bbaoc94faOaAfgORbbalRblgAcl4gCaCcsSgCE86bbaoc95faOaCfgORbbaAcsGgAaAcsSgAE86bbaoc96faOaAfgORbbalRbvgAcl4gCaCcsSgCE86bbaoc97faOaCfgORbbaAcsGgAaAcsSgAE86bbaoc98faOaAfgORbbalRbogAcl4gCaCcsSgCE86bbaoc99faOaCfgORbbaAcsGgAaAcsSgAE86bbaoc9:faOaAfgORbbalRbrglcl4gAaAcsSgAE86bbaocufaOaAfgoRbbalcsGglalcsSglE86bbaoalfhlxekaOal8Pbb83bbaOcwfalcwf8Pbb83bbalczfhlkdnaiam9pmbaiczfhoaral9RcL0mekkaiam6mialTmidnakTmbawaPfRbbhOcbhoazhiinaiawcj;cbfaofRbbgAce4cbaAceG9R7aOfgO86bbaiadfhiaocefgoak9hmbkkazcefhzaPcefgPad6hsalhHaPad9hmexvkkcbhlasceGmdxikalaxad2fhCdnakTmbcbhHcehsawcjdfhminaral9Rax6mialTmdalaxfhlawaHfRbbhOcbhoamhiinaiawcj;cbfaofRbbgAce4cbaAceG9R7aOfgO86bbaiadfhiaocefgoak9hmbkamcefhmaHcefgHad6hsaHad9hmbkaChlxikcbhocehsinaral9Rax6mdalTmealaxfhlaocefgoad6hsadao9hmbkaChlxdkcbhlasceGTmekc9:hoxikabaqad2fawcjdfakad2z1jjjb8Aawawcjdfakcufad2fadz1jjjb8Aakaqfhqalmbkc9:hoxekcbc99aral9Radcaadca0ESEhokavcj;ebf8Kjjjjbaok;yzeHu8Jjjjjbc;ae9Rgv8Kjjjjbc9:hodnaeci9UgrcHfal0mbcuhoaiRbbgwc;WeGc;Ge9hmbawcsGgDce0mbavc;abfcFecjez:jjjjb8AavcUf9cu83ibavc8Wf9cu83ibavcyf9cu83ibavcaf9cu83ibavcKf9cu83ibavczf9cu83ibav9cu83iwav9cu83ibaialfc9WfhqaicefgwarfhodnaeTmbcmcsaDceSEhkcbhxcbhmcbhDcbhicbhlindnaoaq9nmbc9:hoxikdndnawRbbgrc;Ve0mbavc;abfalarcl4cu7fcsGcitfgPydlhsaPydbhzdnarcsGgPak9pmbavaiarcu7fcsGcdtfydbaxaPEhraPThPdndnadcd9hmbabaDcetfgHaz87ebaHcdfas87ebaHclfar87ebxekabaDcdtfgHazBdbaHclfasBdbaHcwfarBdbkaxaPfhxavc;abfalcitfgHarBdbaHasBdlavaicdtfarBdbavc;abfalcefcsGglcitfgHazBdbaHarBdlaiaPfhialcefhlxdkdndnaPcsSmbamaPfaPc987fcefhmxekaocefhrao8SbbgPcFeGhHdndnaPcu9mmbarhoxekaocvfhoaHcFbGhHcrhPdninar8SbbgOcFbGaPtaHVhHaOcu9kmearcefhraPcrfgPc8J9hmbxdkkarcefhokaHce4cbaHceG9R7amfhmkdndnadcd9hmbabaDcetfgraz87ebarcdfas87ebarclfam87ebxekabaDcdtfgrazBdbarclfasBdbarcwfamBdbkavc;abfalcitfgramBdbarasBdlavaicdtfamBdbavc;abfalcefcsGglcitfgrazBdbaramBdlaicefhialcefhlxekdnarcpe0mbaxcefgOavaiaqarcsGfRbbgPcl49RcsGcdtfydbaPcz6gHEhravaiaP9RcsGcdtfydbaOaHfgsaPcsGgOEhPaOThOdndnadcd9hmbabaDcetfgzax87ebazcdfar87ebazclfaP87ebxekabaDcdtfgzaxBdbazclfarBdbazcwfaPBdbkavaicdtfaxBdbavc;abfalcitfgzarBdbazaxBdlavaicefgicsGcdtfarBdbavc;abfalcefcsGcitfgzaPBdbazarBdlavaiaHfcsGgicdtfaPBdbavc;abfalcdfcsGglcitfgraxBdbaraPBdlalcefhlaiaOfhiasaOfhxxekaxcbaoRbbgzEgAarc;:eSgrfhsazcsGhCazcl4hXdndnazcs0mbascefhOxekashOavaiaX9RcsGcdtfydbhskdndnaCmbaOcefhxxekaOhxavaiaz9RcsGcdtfydbhOkdndnarTmbaocefhrxekaocdfhrao8SbegHcFeGhPdnaHcu9kmbaocofhAaPcFbGhPcrhodninar8SbbgHcFbGaotaPVhPaHcu9kmearcefhraocrfgoc8J9hmbkaAhrxekarcefhrkaPce4cbaPceG9R7amfgmhAkdndnaXcsSmbarhPxekarcefhPar8SbbgocFeGhHdnaocu9kmbarcvfhsaHcFbGhHcrhodninaP8SbbgrcFbGaotaHVhHarcu9kmeaPcefhPaocrfgoc8J9hmbkashPxekaPcefhPkaHce4cbaHceG9R7amfgmhskdndnaCcsSmbaPhoxekaPcefhoaP8SbbgrcFeGhHdnarcu9kmbaPcvfhOaHcFbGhHcrhrdninao8SbbgPcFbGartaHVhHaPcu9kmeaocefhoarcrfgrc8J9hmbkaOhoxekaocefhokaHce4cbaHceG9R7amfgmhOkdndnadcd9hmbabaDcetfgraA87ebarcdfas87ebarclfaO87ebxekabaDcdtfgraABdbarclfasBdbarcwfaOBdbkavc;abfalcitfgrasBdbaraABdlavaicdtfaABdbavc;abfalcefcsGcitfgraOBdbarasBdlavaicefgicsGcdtfasBdbavc;abfalcdfcsGcitfgraABdbaraOBdlavaiazcz6aXcsSVfgicsGcdtfaOBdbaiaCTaCcsSVfhialcifhlkawcefhwalcsGhlaicsGhiaDcifgDae6mbkkcbc99aoaqSEhokavc;aef8Kjjjjbaok:llevu8Jjjjjbcz9Rhvc9:hodnaecvfal0mbcuhoaiRbbc;:eGc;qe9hmbav9cb83iwaicefhraialfc98fhwdnaeTmbdnadcdSmbcbhDindnaraw6mbc9:skarcefhoar8SbbglcFeGhidndnalcu9mmbaohrxekarcvfhraicFbGhicrhldninao8SbbgdcFbGaltaiVhiadcu9kmeaocefhoalcrfglc8J9hmbxdkkaocefhrkabaDcdtfaicd4cbaice4ceG9R7avcwfaiceGcdtVgoydbfglBdbaoalBdbaDcefgDae9hmbxdkkcbhDindnaraw6mbc9:skarcefhoar8SbbglcFeGhidndnalcu9mmbaohrxekarcvfhraicFbGhicrhldninao8SbbgdcFbGaltaiVhiadcu9kmeaocefhoalcrfglc8J9hmbxdkkaocefhrkabaDcetfaicd4cbaice4ceG9R7avcwfaiceGcdtVgoydbfgl87ebaoalBdbaDcefgDae9hmbkkcbc99arawSEhokaok:Lvoeue99dud99eud99dndnadcl9hmbaeTmeindndnabcdfgd8Sbb:Yab8Sbbgi:Ygl:l:tabcefgv8Sbbgo:Ygr:l:tgwJbb;:9cawawNJbbbbawawJbbbb9GgDEgq:mgkaqaicb9iEalMgwawNakaqaocb9iEarMgqaqNMM:r:vglNJbbbZJbbb:;aDEMgr:lJbbb9p9DTmbar:Ohixekcjjjj94hikadai86bbdndnaqalNJbbbZJbbb:;aqJbbbb9GEMgq:lJbbb9p9DTmbaq:Ohdxekcjjjj94hdkavad86bbdndnawalNJbbbZJbbb:;awJbbbb9GEMgw:lJbbb9p9DTmbaw:Ohdxekcjjjj94hdkabad86bbabclfhbaecufgembxdkkaeTmbindndnabclfgd8Ueb:Yab8Uebgi:Ygl:l:tabcdfgv8Uebgo:Ygr:l:tgwJb;:FSawawNJbbbbawawJbbbb9GgDEgq:mgkaqaicb9iEalMgwawNakaqaocb9iEarMgqaqNMM:r:vglNJbbbZJbbb:;aDEMgr:lJbbb9p9DTmbar:Ohixekcjjjj94hikadai87ebdndnaqalNJbbbZJbbb:;aqJbbbb9GEMgq:lJbbb9p9DTmbaq:Ohdxekcjjjj94hdkavad87ebdndnawalNJbbbZJbbb:;awJbbbb9GEMgw:lJbbb9p9DTmbaw:Ohdxekcjjjj94hdkabad87ebabcwfhbaecufgembkkk;siliui99iue99dnaeTmbcbhiabhlindndnJ;Zl81Zalcof8UebgvciV:Y:vgoal8Ueb:YNgrJb;:FSNJbbbZJbbb:;arJbbbb9GEMgw:lJbbb9p9DTmbaw:OhDxekcjjjj94hDkalclf8Uebhqalcdf8UebhkabavcefciGaiVcetfaD87ebdndnaoak:YNgwJb;:FSNJbbbZJbbb:;awJbbbb9GEMgx:lJbbb9p9DTmbax:Ohkxekcjjjj94hkkabavcdfciGaiVcetfak87ebdndnaoaq:YNgoJb;:FSNJbbbZJbbb:;aoJbbbb9GEMgx:lJbbb9p9DTmbax:Ohqxekcjjjj94hqkabavcufciGaiVcetfaq87ebdndnJbbjZararN:tawawN:taoaoN:tgrJbbbbarJbbbb9GE:rJb;:FSNJbbbZMgr:lJbbb9p9DTmbar:Ohqxekcjjjj94hqkabavciGaiVcetfaq87ebalcwfhlaiclfhiaecufgembkkk9mbdnadcd4ae2geTmbinababydbgdcwtcw91:Yadce91cjjj;8ifcjjj98G::NUdbabclfhbaecufgembkkk9teiucbcbydj1jjbgeabcifc98GfgbBdj1jjbdndnabZbcztgd9nmbcuhiabad9RcFFifcz4nbcuSmekaehikaik;LeeeudndnaeabVciGTmbabhixekdndnadcz9pmbabhixekabhiinaiaeydbBdbaiclfaeclfydbBdbaicwfaecwfydbBdbaicxfaecxfydbBdbaiczfhiaeczfheadc9Wfgdcs0mbkkadcl6mbinaiaeydbBdbaeclfheaiclfhiadc98fgdci0mbkkdnadTmbinaiaeRbb86bbaicefhiaecefheadcufgdmbkkabk;aeedudndnabciGTmbabhixekaecFeGc:b:c:ew2hldndnadcz9pmbabhixekabhiinaialBdbaicxfalBdbaicwfalBdbaiclfalBdbaiczfhiadc9Wfgdcs0mbkkadcl6mbinaialBdbaiclfhiadc98fgdci0mbkkdnadTmbinaiae86bbaicefhiadcufgdmbkkabkkkebcjwklz9Kbb",e="b9H79TebbbeKl9Gbb9Gvuuuuueu9Giuuub9Geueuikqbbebeedddilve9Weeeviebeoweuec:q;Aekr;leDo9TW9T9VV95dbH9F9F939H79T9F9J9H229F9Jt9VV7bb8A9TW79O9V9Wt9F9KW9J9V9KW9wWVtW949c919M9MWVbdY9TW79O9V9Wt9F9KW9J9V9KW69U9KW949c919M9MWVblE9TW79O9V9Wt9F9KW9J9V9KW69U9KW949tWG91W9U9JWbvL9TW79O9V9Wt9F9KW9J9V9KWS9P2tWV9p9JtboK9TW79O9V9Wt9F9KW9J9V9KWS9P2tWV9r919HtbrL9TW79O9V9Wt9F9KW9J9V9KWS9P2tWVT949Wbwl79IV9RbDq;t9tqlbzik9:evu8Jjjjjbcz9Rhbcbheincbhdcbhiinabcwfadfaicjuaead4ceGglE86bbaialfhiadcefgdcw9hmbkaec:q:yjjbfai86bbaecitc:q1jjbfab8Piw83ibaecefgecjd9hmbkk;h8JlHud97euo978Jjjjjbcj;kb9Rgv8Kjjjjbc9:hodnadcefal0mbcuhoaiRbbc:Ge9hmbavaialfgrad9Rad;8qbbcj;abad9UhoaicefhldnadTmbaoc;WFbGgocjdaocjd6EhwcbhDinaDae9pmeawaeaD9RaDawfae6Egqcsfgoc9WGgkci2hxakcethmaocl4cifcd4hPabaDad2fhscbhzdnincehHalhOcbhAdninaraO9RaP6miavcj;cbfaAak2fhCaOaPfhlcbhidnakc;ab6mbaral9Rc;Gb6mbcbhoinaCaofhidndndndndnaOaoco4fRbbgXciGPlbedibkaipxbbbbbbbbbbbbbbbbpklbxikaialpbblalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLgQcdp:meaQpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9ogLpxiiiiiiiiiiiiiiiip8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibaKc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spklbalclfaYpQbfaKc:q:yjjbfRbbfhlxdkaialpbbwalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9ogLpxssssssssssssssssp8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibaKc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spklbalcwfaYpQbfaKc:q:yjjbfRbbfhlxekaialpbbbpklbalczfhlkdndndndndnaXcd4ciGPlbedibkaipxbbbbbbbbbbbbbbbbpklzxikaialpbblalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLgQcdp:meaQpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9ogLpxiiiiiiiiiiiiiiiip8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibaKc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spklzalclfaYpQbfaKc:q:yjjbfRbbfhlxdkaialpbbwalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9ogLpxssssssssssssssssp8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibaKc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spklzalcwfaYpQbfaKc:q:yjjbfRbbfhlxekaialpbbbpklzalczfhlkdndndndndnaXcl4ciGPlbedibkaipxbbbbbbbbbbbbbbbbpklaxikaialpbblalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLgQcdp:meaQpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9ogLpxiiiiiiiiiiiiiiiip8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibaKc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spklaalclfaYpQbfaKc:q:yjjbfRbbfhlxdkaialpbbwalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9ogLpxssssssssssssssssp8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibaKc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spklaalcwfaYpQbfaKc:q:yjjbfRbbfhlxekaialpbbbpklaalczfhlkdndndndndnaXco4Plbedibkaipxbbbbbbbbbbbbbbbbpkl8WxikaialpbblalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLgQcdp:meaQpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9ogLpxiiiiiiiiiiiiiiiip8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgXcitc:q1jjbfpbibaXc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgXcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spkl8WalclfaYpQbfaXc:q:yjjbfRbbfhlxdkaialpbbwalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9ogLpxssssssssssssssssp8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgXcitc:q1jjbfpbibaXc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgXcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spkl8WalcwfaYpQbfaXc:q:yjjbfRbbfhlxekaialpbbbpkl8Walczfhlkaoc;abfhiaocjefak0meaihoaral9Rc;Fb0mbkkdndnaiak9pmbaici4hoinaral9RcK6mdaCaifhXdndndndndnaOaico4fRbbaocoG4ciGPlbedibkaXpxbbbbbbbbbbbbbbbbpklbxikaXalpbblalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLgQcdp:meaQpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9ogLpxiiiiiiiiiiiiiiiip8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibaKc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spklbalclfaYpQbfaKc:q:yjjbfRbbfhlxdkaXalpbbwalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9ogLpxssssssssssssssssp8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibaKc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spklbalcwfaYpQbfaKc:q:yjjbfRbbfhlxekaXalpbbbpklbalczfhlkaocdfhoaiczfgiak6mbkkalTmbaAci6hHalhOaAcefgohAaoclSmdxekkcbhlaHceGmdkdnakTmbavcjdfazfhiavazfpbdbhYcbhXinaiavcj;cbfaXfgopblbgLcep9TaLpxeeeeeeeeeeeeeeeegQp9op9Hp9rgLaoakfpblbg8Acep9Ta8AaQp9op9Hp9rg8ApmbzeHdOiAlCvXoQrLgEaoamfpblbg3cep9Ta3aQp9op9Hp9rg3aoaxfpblbg5cep9Ta5aQp9op9Hp9rg5pmbzeHdOiAlCvXoQrLg8EpmbezHdiOAlvCXorQLgQaQpmbedibedibedibediaYp9UgYp9AdbbaiadfgoaYaQaQpmlvorlvorlvorlvorp9UgYp9AdbbaoadfgoaYaQaQpmwDqkwDqkwDqkwDqkp9UgYp9AdbbaoadfgoaYaQaQpmxmPsxmPsxmPsxmPsp9UgYp9AdbbaoadfgoaYaEa8EpmwDKYqk8AExm35Ps8E8FgQaQpmbedibedibedibedip9UgYp9AdbbaoadfgoaYaQaQpmlvorlvorlvorlvorp9UgYp9AdbbaoadfgoaYaQaQpmwDqkwDqkwDqkwDqkp9UgYp9AdbbaoadfgoaYaQaQpmxmPsxmPsxmPsxmPsp9UgYp9AdbbaoadfgoaYaLa8ApmwKDYq8AkEx3m5P8Es8FgLa3a5pmwKDYq8AkEx3m5P8Es8Fg8ApmbezHdiOAlvCXorQLgQaQpmbedibedibedibedip9UgYp9AdbbaoadfgoaYaQaQpmlvorlvorlvorlvorp9UgYp9AdbbaoadfgoaYaQaQpmwDqkwDqkwDqkwDqkp9UgYp9AdbbaoadfgoaYaQaQpmxmPsxmPsxmPsxmPsp9UgYp9AdbbaoadfgoaYaLa8ApmwDKYqk8AExm35Ps8E8FgQaQpmbedibedibedibedip9UgYp9AdbbaoadfgoaYaQaQpmlvorlvorlvorlvorp9UgYp9AdbbaoadfgoaYaQaQpmwDqkwDqkwDqkwDqkp9UgYp9AdbbaoadfgoaYaQaQpmxmPsxmPsxmPsxmPsp9UgYp9AdbbaoadfhiaXczfgXak6mbkkazclfgzad6mbkasavcjdfaqad2;8qbbavavcjdfaqcufad2fad;8qbbaqaDfhDc9:hoalmexikkc9:hoxekcbc99aral9Radcaadca0ESEhokavcj;kbf8Kjjjjbaokwbz:bjjjbk;uzeHu8Jjjjjbc;ae9Rgv8Kjjjjbc9:hodnaeci9UgrcHfal0mbcuhoaiRbbgwc;WeGc;Ge9hmbawcsGgDce0mbavc;abfcFecje;8kbavcUf9cu83ibavc8Wf9cu83ibavcyf9cu83ibavcaf9cu83ibavcKf9cu83ibavczf9cu83ibav9cu83iwav9cu83ibaialfc9WfhqaicefgwarfhodnaeTmbcmcsaDceSEhkcbhxcbhmcbhDcbhicbhlindnaoaq9nmbc9:hoxikdndnawRbbgrc;Ve0mbavc;abfalarcl4cu7fcsGcitfgPydlhsaPydbhzdnarcsGgPak9pmbavaiarcu7fcsGcdtfydbaxaPEhraPThPdndnadcd9hmbabaDcetfgHaz87ebaHcdfas87ebaHclfar87ebxekabaDcdtfgHazBdbaHclfasBdbaHcwfarBdbkaxaPfhxavc;abfalcitfgHarBdbaHasBdlavaicdtfarBdbavc;abfalcefcsGglcitfgHazBdbaHarBdlaiaPfhialcefhlxdkdndnaPcsSmbamaPfaPc987fcefhmxekaocefhrao8SbbgPcFeGhHdndnaPcu9mmbarhoxekaocvfhoaHcFbGhHcrhPdninar8SbbgOcFbGaPtaHVhHaOcu9kmearcefhraPcrfgPc8J9hmbxdkkarcefhokaHce4cbaHceG9R7amfhmkdndnadcd9hmbabaDcetfgraz87ebarcdfas87ebarclfam87ebxekabaDcdtfgrazBdbarclfasBdbarcwfamBdbkavc;abfalcitfgramBdbarasBdlavaicdtfamBdbavc;abfalcefcsGglcitfgrazBdbaramBdlaicefhialcefhlxekdnarcpe0mbaxcefgOavaiaqarcsGfRbbgPcl49RcsGcdtfydbaPcz6gHEhravaiaP9RcsGcdtfydbaOaHfgsaPcsGgOEhPaOThOdndnadcd9hmbabaDcetfgzax87ebazcdfar87ebazclfaP87ebxekabaDcdtfgzaxBdbazclfarBdbazcwfaPBdbkavaicdtfaxBdbavc;abfalcitfgzarBdbazaxBdlavaicefgicsGcdtfarBdbavc;abfalcefcsGcitfgzaPBdbazarBdlavaiaHfcsGgicdtfaPBdbavc;abfalcdfcsGglcitfgraxBdbaraPBdlalcefhlaiaOfhiasaOfhxxekaxcbaoRbbgzEgAarc;:eSgrfhsazcsGhCazcl4hXdndnazcs0mbascefhOxekashOavaiaX9RcsGcdtfydbhskdndnaCmbaOcefhxxekaOhxavaiaz9RcsGcdtfydbhOkdndnarTmbaocefhrxekaocdfhrao8SbegHcFeGhPdnaHcu9kmbaocofhAaPcFbGhPcrhodninar8SbbgHcFbGaotaPVhPaHcu9kmearcefhraocrfgoc8J9hmbkaAhrxekarcefhrkaPce4cbaPceG9R7amfgmhAkdndnaXcsSmbarhPxekarcefhPar8SbbgocFeGhHdnaocu9kmbarcvfhsaHcFbGhHcrhodninaP8SbbgrcFbGaotaHVhHarcu9kmeaPcefhPaocrfgoc8J9hmbkashPxekaPcefhPkaHce4cbaHceG9R7amfgmhskdndnaCcsSmbaPhoxekaPcefhoaP8SbbgrcFeGhHdnarcu9kmbaPcvfhOaHcFbGhHcrhrdninao8SbbgPcFbGartaHVhHaPcu9kmeaocefhoarcrfgrc8J9hmbkaOhoxekaocefhokaHce4cbaHceG9R7amfgmhOkdndnadcd9hmbabaDcetfgraA87ebarcdfas87ebarclfaO87ebxekabaDcdtfgraABdbarclfasBdbarcwfaOBdbkavc;abfalcitfgrasBdbaraABdlavaicdtfaABdbavc;abfalcefcsGcitfgraOBdbarasBdlavaicefgicsGcdtfasBdbavc;abfalcdfcsGcitfgraABdbaraOBdlavaiazcz6aXcsSVfgicsGcdtfaOBdbaiaCTaCcsSVfhialcifhlkawcefhwalcsGhlaicsGhiaDcifgDae6mbkkcbc99aoaqSEhokavc;aef8Kjjjjbaok:llevu8Jjjjjbcz9Rhvc9:hodnaecvfal0mbcuhoaiRbbc;:eGc;qe9hmbav9cb83iwaicefhraialfc98fhwdnaeTmbdnadcdSmbcbhDindnaraw6mbc9:skarcefhoar8SbbglcFeGhidndnalcu9mmbaohrxekarcvfhraicFbGhicrhldninao8SbbgdcFbGaltaiVhiadcu9kmeaocefhoalcrfglc8J9hmbxdkkaocefhrkabaDcdtfaicd4cbaice4ceG9R7avcwfaiceGcdtVgoydbfglBdbaoalBdbaDcefgDae9hmbxdkkcbhDindnaraw6mbc9:skarcefhoar8SbbglcFeGhidndnalcu9mmbaohrxekarcvfhraicFbGhicrhldninao8SbbgdcFbGaltaiVhiadcu9kmeaocefhoalcrfglc8J9hmbxdkkaocefhrkabaDcetfaicd4cbaice4ceG9R7avcwfaiceGcdtVgoydbfgl87ebaoalBdbaDcefgDae9hmbkkcbc99arawSEhokaok:EPliuo97eue978Jjjjjbca9Rhidndnadcl9hmbdnaec98GglTmbcbhvabhdinadadpbbbgocKp:RecKp:Sep;6egraocwp:RecKp:Sep;6earp;Geaoczp:RecKp:Sep;6egwp;Gep;Kep;LegDpxbbbbbbbbbbbbbbbbp:2egqarpxbbbjbbbjbbbjbbbjgkp9op9rp;Kegrpxbb;:9cbb;:9cbb;:9cbb;:9cararp;MeaDaDp;Meawaqawakp9op9rp;Kegrarp;Mep;Kep;Kep;Jep;Negwp;Mepxbbn0bbn0bbn0bbn0gqp;KepxFbbbFbbbFbbbFbbbp9oaopxbbbFbbbFbbbFbbbFp9op9qarawp;Meaqp;Kecwp:RepxbFbbbFbbbFbbbFbbp9op9qaDawp;Meaqp;Keczp:RepxbbFbbbFbbbFbbbFbp9op9qpkbbadczfhdavclfgval6mbkkalae9pmeaiaeciGgvcdtgdVcbczad9R;8kbaiabalcdtfglad;8qbbdnavTmbaiaipblbgocKp:RecKp:Sep;6egraocwp:RecKp:Sep;6earp;Geaoczp:RecKp:Sep;6egwp;Gep;Kep;LegDpxbbbbbbbbbbbbbbbbp:2egqarpxbbbjbbbjbbbjbbbjgkp9op9rp;Kegrpxbb;:9cbb;:9cbb;:9cbb;:9cararp;MeaDaDp;Meawaqawakp9op9rp;Kegrarp;Mep;Kep;Kep;Jep;Negwp;Mepxbbn0bbn0bbn0bbn0gqp;KepxFbbbFbbbFbbbFbbbp9oaopxbbbFbbbFbbbFbbbFp9op9qarawp;Meaqp;Kecwp:RepxbFbbbFbbbFbbbFbbp9op9qaDawp;Meaqp;Keczp:RepxbbFbbbFbbbFbbbFbp9op9qpklbkalaiad;8qbbskdnaec98GgxTmbcbhvabhdinadczfglalpbbbgopxbbbbbbFFbbbbbbFFgkp9oadpbbbgDaopmlvorxmPsCXQL358E8FpxFubbFubbFubbFubbp9op;6eaDaopmbediwDqkzHOAKY8AEgoczp:Sep;6egrp;Geaoczp:Reczp:Sep;6egwp;Gep;Kep;Legopxb;:FSb;:FSb;:FSb;:FSawaopxbbbbbbbbbbbbbbbbp:2egqawpxbbbjbbbjbbbjbbbjgmp9op9rp;Kegwawp;Meaoaop;Mearaqaramp9op9rp;Kegoaop;Mep;Kep;Kep;Jep;Negrp;Mepxbbn0bbn0bbn0bbn0gqp;Keczp:Reawarp;Meaqp;KepxFFbbFFbbFFbbFFbbp9op9qgwaoarp;Meaqp;KepxFFbbFFbbFFbbFFbbp9ogopmwDKYqk8AExm35Ps8E8Fp9qpkbbadaDakp9oawaopmbezHdiOAlvCXorQLp9qpkbbadcafhdavclfgvax6mbkkaxae9pmbaiaeciGgvcitgdfcbcaad9R;8kbaiabaxcitfglad;8qbbdnavTmbaiaipblzgopxbbbbbbFFbbbbbbFFgkp9oaipblbgDaopmlvorxmPsCXQL358E8FpxFubbFubbFubbFubbp9op;6eaDaopmbediwDqkzHOAKY8AEgoczp:Sep;6egrp;Geaoczp:Reczp:Sep;6egwp;Gep;Kep;Legopxb;:FSb;:FSb;:FSb;:FSawaopxbbbbbbbbbbbbbbbbp:2egqawpxbbbjbbbjbbbjbbbjgmp9op9rp;Kegwawp;Meaoaop;Mearaqaramp9op9rp;Kegoaop;Mep;Kep;Kep;Jep;Negrp;Mepxbbn0bbn0bbn0bbn0gqp;Keczp:Reawarp;Meaqp;KepxFFbbFFbbFFbbFFbbp9op9qgwaoarp;Meaqp;KepxFFbbFFbbFFbbFFbbp9ogopmwDKYqk8AExm35Ps8E8Fp9qpklzaiaDakp9oawaopmbezHdiOAlvCXorQLp9qpklbkalaiad;8qbbkk;4wllue97euv978Jjjjjbc8W9Rhidnaec98GglTmbcbhvabhoinaiaopbbbgraoczfgwpbbbgDpmlvorxmPsCXQL358E8Fgqczp:Segkclp:RepklbaopxbbjZbbjZbbjZbbjZpx;Zl81Z;Zl81Z;Zl81Z;Zl81Zakpxibbbibbbibbbibbbp9qp;6ep;NegkaraDpmbediwDqkzHOAKY8AEgrczp:Reczp:Sep;6ep;MegDaDp;Meakarczp:Sep;6ep;Megxaxp;Meakaqczp:Reczp:Sep;6ep;Megqaqp;Mep;Kep;Kep;Lepxbbbbbbbbbbbbbbbbp:4ep;Jepxb;:FSb;:FSb;:FSb;:FSgkp;Mepxbbn0bbn0bbn0bbn0grp;KepxFFbbFFbbFFbbFFbbgmp9oaxakp;Mearp;Keczp:Rep9qgxaqakp;Mearp;Keczp:ReaDakp;Mearp;Keamp9op9qgkpmbezHdiOAlvCXorQLgrp5baipblbpEb:T:j83ibaocwfarp5eaipblbpEe:T:j83ibawaxakpmwDKYqk8AExm35Ps8E8Fgkp5baipblbpEd:T:j83ibaocKfakp5eaipblbpEi:T:j83ibaocafhoavclfgval6mbkkdnalae9pmbaiaeciGgvcitgofcbcaao9R;8kbaiabalcitfgwao;8qbbdnavTmbaiaipblbgraipblzgDpmlvorxmPsCXQL358E8Fgqczp:Segkclp:RepklaaipxbbjZbbjZbbjZbbjZpx;Zl81Z;Zl81Z;Zl81Z;Zl81Zakpxibbbibbbibbbibbbp9qp;6ep;NegkaraDpmbediwDqkzHOAKY8AEgrczp:Reczp:Sep;6ep;MegDaDp;Meakarczp:Sep;6ep;Megxaxp;Meakaqczp:Reczp:Sep;6ep;Megqaqp;Mep;Kep;Kep;Lepxbbbbbbbbbbbbbbbbp:4ep;Jepxb;:FSb;:FSb;:FSb;:FSgkp;Mepxbbn0bbn0bbn0bbn0grp;KepxFFbbFFbbFFbbFFbbgmp9oaxakp;Mearp;Keczp:Rep9qgxaqakp;Mearp;Keczp:ReaDakp;Mearp;Keamp9op9qgkpmbezHdiOAlvCXorQLgrp5baipblapEb:T:j83ibaiarp5eaipblapEe:T:j83iwaiaxakpmwDKYqk8AExm35Ps8E8Fgkp5baipblapEd:T:j83izaiakp5eaipblapEi:T:j83iKkawaiao;8qbbkk:Pddiue978Jjjjjbc;ab9Rhidnadcd4ae2glc98GgvTmbcbhdabheinaeaepbbbgocwp:Recwp:Sep;6eaocep:SepxbbjZbbjZbbjZbbjZp:UepxbbjFbbjFbbjFbbjFp9op;Mepkbbaeczfheadclfgdav6mbkkdnaval9pmbaialciGgdcdtgeVcbc;abae9R;8kbaiabavcdtfgvae;8qbbdnadTmbaiaipblbgocwp:Recwp:Sep;6eaocep:SepxbbjZbbjZbbjZbbjZp:UepxbbjFbbjFbbjFbbjFp9op;Mepklbkavaiae;8qbbkk9teiucbcbydj1jjbgeabcifc98GfgbBdj1jjbdndnabZbcztgd9nmbcuhiabad9RcFFifcz4nbcuSmekaehikaikkkebcjwklz9Tbb",t=new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,3,2,0,0,5,3,1,0,1,12,1,0,10,22,2,12,0,65,0,65,0,65,0,252,10,0,0,11,7,0,65,0,253,15,26,11]),n=new Uint8Array([32,0,65,2,1,106,34,33,3,128,11,4,13,64,6,253,10,7,15,116,127,5,8,12,40,16,19,54,20,9,27,255,113,17,42,67,24,23,146,148,18,14,22,45,70,69,56,114,101,21,25,63,75,136,108,28,118,29,73,115]);if(typeof WebAssembly!="object")return{supported:!1};var a=WebAssembly.validate(t)?e:s,i,o=WebAssembly.instantiate(l(a),{}).then(function(S){i=S.instance,i.exports.__wasm_call_ctors()});function l(S){for(var j=new Uint8Array(S.length),C=0;C<S.length;++C){var N=S.charCodeAt(C);j[C]=N>96?N-97:N>64?N-39:N+4}for(var P=0,C=0;C<S.length;++C)j[P++]=j[C]<60?n[j[C]]:(j[C]-60)*64+j[++C];return j.buffer.slice(0,P)}function c(S,j,C,N,P,_){var L=i.exports.sbrk,M=C+3&-4,D=L(M*N),E=L(P.length),R=new Uint8Array(i.exports.memory.buffer);R.set(P,E);var O=S(D,C,N,E,P.length);if(O==0&&_&&_(D,M,N),j.set(R.subarray(D,D+C*N)),L(D-L(0)),O!=0)throw new Error("Malformed buffer data: "+O)}var d={NONE:"",OCTAHEDRAL:"meshopt_decodeFilterOct",QUATERNION:"meshopt_decodeFilterQuat",EXPONENTIAL:"meshopt_decodeFilterExp"},m={ATTRIBUTES:"meshopt_decodeVertexBuffer",TRIANGLES:"meshopt_decodeIndexBuffer",INDICES:"meshopt_decodeIndexSequence"},p=[],f=0;function b(S){var j={object:new Worker(S),pending:0,requests:{}};return j.object.onmessage=function(C){var N=C.data;j.pending-=N.count,j.requests[N.id][N.action](N.value),delete j.requests[N.id]},j}function x(S){for(var j="var instance; var ready = WebAssembly.instantiate(new Uint8Array(["+new Uint8Array(l(a))+"]), {}).then(function(result) { instance = result.instance; instance.exports.__wasm_call_ctors(); });self.onmessage = workerProcess;"+c.toString()+k.toString(),C=new Blob([j],{type:"text/javascript"}),N=URL.createObjectURL(C),P=0;P<S;++P)p[P]=b(N);URL.revokeObjectURL(N)}function w(S,j,C,N,P){for(var _=p[0],L=1;L<p.length;++L)p[L].pending<_.pending&&(_=p[L]);return new Promise(function(M,D){var E=new Uint8Array(C),R=f++;_.pending+=S,_.requests[R]={resolve:M,reject:D},_.object.postMessage({id:R,count:S,size:j,source:E,mode:N,filter:P},[E.buffer])})}function k(S){o.then(function(){var j=S.data;try{var C=new Uint8Array(j.count*j.size);c(i.exports[j.mode],C,j.count,j.size,j.source,i.exports[j.filter]),self.postMessage({id:j.id,count:j.count,action:"resolve",value:C},[C.buffer])}catch(N){self.postMessage({id:j.id,count:j.count,action:"reject",value:N})}})}return{ready:o,supported:!0,useWorkers:function(S){x(S)},decodeVertexBuffer:function(S,j,C,N,P){c(i.exports.meshopt_decodeVertexBuffer,S,j,C,N,i.exports[d[P]])},decodeIndexBuffer:function(S,j,C,N){c(i.exports.meshopt_decodeIndexBuffer,S,j,C,N)},decodeIndexSequence:function(S,j,C,N){c(i.exports.meshopt_decodeIndexSequence,S,j,C,N)},decodeGltfBuffer:function(S,j,C,N,P,_){c(i.exports[m[P]],S,j,C,N,i.exports[d[_]])},decodeGltfBufferAsync:function(S,j,C,N,P){return p.length>0?w(S,j,C,m[N],d[P]):o.then(function(){var _=new Uint8Array(S*j);return c(i.exports[m[N]],_,S,j,C,i.exports[d[P]]),_})}}})();function Aj(s){const e=new Map,t=new Map,n=s.clone();return SM(s,n,function(a,i){e.set(i,a),t.set(a,i)}),n.traverse(function(a){if(!a.isSkinnedMesh)return;const i=a,o=e.get(a),l=o.skeleton.bones;i.skeleton=o.skeleton.clone(),i.bindMatrix.copy(o.bindMatrix),i.skeleton.bones=l.map(function(c){return t.get(c)}),i.bind(i.skeleton,i.bindMatrix)}),n}function SM(s,e,t){t(s,e);for(let n=0;n<s.children.length;n++)SM(s.children[n],e.children[n],t)}const Ka={scout:{icon:"🔍",color:4890367,description:"Explores and searches codebase"},builder:{icon:"🔨",color:16752202,description:"Creates and builds features"},debugger:{icon:"🐛",color:16730698,description:"Finds and fixes bugs"},architect:{icon:"📐",color:10373887,description:"Plans and designs systems"},warrior:{icon:"⚔️",color:16730782,description:"Tackles tough problems"},support:{icon:"💚",color:4915102,description:"Helps and assists others"},boss:{icon:"👑",color:16766720,description:"Manages and delegates to subordinates"}},Ex=["Alex","Sam","Jordan","Taylor","Casey","Morgan","Riley","Quinn","Avery","Blake","Cameron","Drew","Emery","Finley","Harper","Jamie","Kai","Logan","Max","Nico","Parker","Reese","Sage","Sky"],Zo=Ex,oc={scout:"character-male-a.glb",builder:"character-male-b.glb",debugger:"character-female-a.glb",architect:"character-male-c.glb",warrior:"character-female-b.glb",support:"character-female-c.glb",boss:"character-male-c.glb"},Qo=[{id:"scout",model:"character-male-a.glb",name:"Explorer",gender:"Male"},{id:"builder",model:"character-male-b.glb",name:"Crafter",gender:"Male"},{id:"architect",model:"character-male-c.glb",name:"Planner",gender:"Male"},{id:"debugger",model:"character-female-a.glb",name:"Analyst",gender:"Female"},{id:"warrior",model:"character-female-b.glb",name:"Fighter",gender:"Female"},{id:"support",model:"character-female-c.glb",name:"Healer",gender:"Female"}],ki=[{file:"character-male-a.glb",name:"Male A (Explorer)",gender:"Male"},{file:"character-male-b.glb",name:"Male B (Crafter)",gender:"Male"},{file:"character-male-c.glb",name:"Male C (Planner)",gender:"Male"},{file:"character-male-d.glb",name:"Male D",gender:"Male"},{file:"character-male-e.glb",name:"Male E",gender:"Male"},{file:"character-male-f.glb",name:"Male F",gender:"Male"},{file:"character-female-a.glb",name:"Female A (Analyst)",gender:"Female"},{file:"character-female-b.glb",name:"Female B (Fighter)",gender:"Female"},{file:"character-female-c.glb",name:"Female C (Healer)",gender:"Female"},{file:"character-female-d.glb",name:"Female D",gender:"Female"},{file:"character-female-e.glb",name:"Female E",gender:"Female"},{file:"character-female-f.glb",name:"Female F",gender:"Female"}],EO=3,lc=5,_O=1e3,_x=50,Ni=1.2;class DO{constructor(){U(this,"models",new Map);U(this,"customModels",new Map);U(this,"loaded",!1);U(this,"loadingPromise",null);U(this,"loader");U(this,"dracoLoader");U(this,"loadingCustomModels",new Map);this.loader=new Ax,this.dracoLoader=new Mx,this.dracoLoader.setDecoderPath("https://www.gstatic.com/draco/versioned/decoders/1.5.7/"),this.loader.setDRACOLoader(this.dracoLoader),this.loader.setMeshoptDecoder(Tx)}get isLoaded(){return this.loaded}async loadAll(){if(this.loaded){console.log("[CharacterLoader] Already loaded, skipping");return}if(this.loadingPromise)return console.log("[CharacterLoader] Already loading, waiting for existing promise"),this.loadingPromise;const e=[...new Set([...Object.values(oc),...ki.map(t=>t.file)])];return console.log(`[CharacterLoader] Starting to load ${e.length} models`),this.loadingPromise=Promise.all(e.map(t=>this.loadModel(t))).then(()=>{this.loaded=!0,console.log(`[CharacterLoader] All models loaded. Cache size: ${this.models.size}`)}),this.loadingPromise}loadModel(e){return new Promise(t=>{const n=`/assets/characters/${e}`;console.log(`[CharacterLoader] Loading model: ${n}`),this.loader.load(n,a=>{console.log(`[CharacterLoader] Successfully loaded: ${e}`);const i=this.prepareModel(a.scene);this.models.set(e,{scene:i,animations:a.animations}),t()},a=>{},a=>{console.error(`[CharacterLoader] Failed to load ${e}:`,a),t()})})}prepareModel(e){return e.scale.setScalar(1),e.position.set(0,0,0),e.rotation.set(0,0,0),e.visible=!1,e.traverse(t=>{if(t instanceof De&&(t.castShadow=!0,t.receiveShadow=!0,t.material)){const n=t.material;n.map&&(n.map.colorSpace=ii),n.isMeshStandardMaterial&&(n.roughness=n.roughness??.6,n.metalness=n.metalness??0,n.envMapIntensity=.8,n.needsUpdate=!0)}}),e}clone(e){const t=oc[e];return this.cloneByModelFile(t)}cloneByModelFile(e){const t=this.models.get(e);if(!t)return console.warn(`[CharacterLoader] Model not found: ${e}`),null;const n=Aj(t.scene);return n.visible=!0,n.position.set(0,0,0),n.rotation.set(0,0,0),n.traverse(a=>{a.visible=!0,a instanceof De&&a.material&&(Array.isArray(a.material)?a.material=a.material.map(i=>i.clone()):a.material=a.material.clone())}),{mesh:n,animations:t.animations}}getAnimations(e){const t=oc[e],n=this.models.get(t);return(n==null?void 0:n.animations)??null}hasModel(e){const t=oc[e];return this.models.has(t)}async loadCustomModel(e){if(this.customModels.has(e))return;const t=this.loadingCustomModels.get(e);if(t)return t;const n=new Promise(a=>{this.loader.load(kd(rt(`/api/custom-models/${e}`)),i=>{const o=this.prepareModel(i.scene);this.customModels.set(e,{scene:o,animations:i.animations}),console.log(`[CharacterLoader] Loaded custom model for class: ${e} (${i.animations.length} animations)`),a()},void 0,i=>{console.error(`[CharacterLoader] Failed to load custom model for ${e}:`,i),a()})});this.loadingCustomModels.set(e,n);try{await n}finally{this.loadingCustomModels.delete(e)}}hasCustomModel(e){return this.customModels.has(e)}cloneCustomModel(e){const t=this.customModels.get(e);if(!t)return null;const n=Aj(t.scene);return n.visible=!0,n.position.set(0,0,0),n.rotation.set(0,0,0),n.traverse(a=>{a.visible=!0,a instanceof De&&a.material&&(Array.isArray(a.material)?a.material=a.material.map(i=>i.clone()):a.material=a.material.clone())}),{mesh:n,animations:t.animations}}getCustomModelAnimations(e){const t=this.customModels.get(e);return(t==null?void 0:t.animations)??null}unloadCustomModel(e){const t=this.customModels.get(e);t&&(this.disposeCachedModel(t),this.customModels.delete(e),console.log(`[CharacterLoader] Unloaded custom model for class: ${e}`))}disposeCachedModel(e){e.scene.traverse(t=>{var n;t instanceof De&&((n=t.geometry)==null||n.dispose(),Array.isArray(t.material)?t.material.forEach(a=>this.disposeMaterial(a)):t.material&&this.disposeMaterial(t.material))})}disposeMaterial(e){var t,n,a,i,o,l,c,d,m,p,f;(e instanceof dt||e instanceof Ke||e instanceof vP)&&((t=e.map)==null||t.dispose(),"normalMap"in e&&((n=e.normalMap)==null||n.dispose()),"roughnessMap"in e&&((a=e.roughnessMap)==null||a.dispose()),"metalnessMap"in e&&((i=e.metalnessMap)==null||i.dispose()),"emissiveMap"in e&&((o=e.emissiveMap)==null||o.dispose()),"aoMap"in e&&((l=e.aoMap)==null||l.dispose()),"lightMap"in e&&((c=e.lightMap)==null||c.dispose()),"bumpMap"in e&&((d=e.bumpMap)==null||d.dispose()),"displacementMap"in e&&((m=e.displacementMap)==null||m.dispose()),"alphaMap"in e&&((p=e.alphaMap)==null||p.dispose()),"envMap"in e&&((f=e.envMap)==null||f.dispose())),e.dispose()}dispose(){for(const[e,t]of this.models)this.disposeCachedModel(t),console.log(`[CharacterLoader] Disposed model template: ${e}`);this.models.clear();for(const[e,t]of this.customModels)this.disposeCachedModel(t),console.log(`[CharacterLoader] Disposed custom model: ${e}`);this.customModels.clear(),this.dracoLoader.dispose(),this.loaded=!1,this.loadingPromise=null,this.loadingCustomModels.clear(),console.log("[CharacterLoader] All model caches disposed")}getCacheStats(){return{builtInModels:this.models.size,customModels:this.customModels.size,modelNames:Array.from(this.models.keys()),customModelIds:Array.from(this.customModels.keys())}}}const PO="character-male-a.glb";class RO{constructor(e){U(this,"customClasses",new Map);this.characterLoader=e}setCustomClasses(e){this.customClasses=e}getClassConfig(e){const t=Ka[e];if(t)return t;const n=this.customClasses.get(e);if(n){const a=parseInt(n.color.replace("#",""),16);return{icon:n.icon,color:isNaN(a)?8947848:a,description:n.description}}return{icon:"❓",color:8947848,description:"Unknown class"}}getModelInfo(e){const t=oc[e];if(t)return{file:t,isCustomModel:!1};const n=this.customClasses.get(e);if(n){if(n.customModelPath)return{file:n.customModelPath,isCustomModel:!0,customClassId:n.id,scale:n.modelScale,offset:n.modelOffset};if(n.model)return{file:n.model,isCustomModel:!1,scale:n.modelScale,offset:n.modelOffset}}return{file:PO,isCustomModel:!1}}createCharacterBody(e,t){const n=this.getModelInfo(e.class);let a=null;if(n.isCustomModel&&n.customClassId&&(a=this.characterLoader.cloneCustomModel(n.customClassId)),a||(a=this.characterLoader.cloneByModelFile(n.file)),a){a.mesh.name="characterBody";const c=n.scale??1;a.mesh.userData.customModelScale=c,a.mesh.userData.isCustomModel=n.isCustomModel,n.offset&&(n.offset.x!==0||n.offset.y!==0||n.offset.z!==0)&&a.mesh.position.set(n.offset.x,n.offset.z,n.offset.y);const d=this.customClasses.get(e.class);d!=null&&d.animationMapping&&(a.mesh.userData.animationMapping=d.animationMapping);const m=new Qu(a.mesh),p=new Map;for(const f of a.animations){const b=f.name.toLowerCase();p.set(b,f),p.set(f.name,f)}return{body:a.mesh,mixer:m,animations:p}}const i=new ry(.5,1,4,16),o=new dt({color:t,roughness:.4,metalness:.3}),l=new De(i,o);return l.position.y=1,l.castShadow=!0,l.receiveShadow=!0,l.name="characterBody",{body:l,mixer:null,animations:new Map}}calculateModelHeight(e,t){return t?2:1.5}upgradeToCharacterModel(e,t){const n=e.getObjectByName("characterBody");if(!(n instanceof De)||!(n.geometry instanceof ry))return null;const a=this.characterLoader.clone(t.class);if(!a)return null;e.remove(n),n.geometry.dispose(),n.material.dispose(),a.mesh.name="characterBody",e.add(a.mesh);const i=new Qu(a.mesh),o=new Map;for(const l of a.animations){const c=l.name.toLowerCase();o.set(c,l)}return{group:e,mixer:i,animations:o,currentAction:null}}replaceAgentModel(e,t){const{group:n}=e,a=this.getModelInfo(t.class);let i=null;if(a.isCustomModel&&a.customClassId&&(i=this.characterLoader.cloneCustomModel(a.customClassId)),i||(i=this.characterLoader.cloneByModelFile(a.file)),!i)return console.warn(`[ModelLoader] Could not load model for class ${t.class}, keeping current model`),n.userData.agentClass=t.class,null;const o=n.getObjectByName("characterBody");o&&(n.remove(o),o.traverse(p=>{var f;(p instanceof De||p instanceof ay)&&((f=p.geometry)==null||f.dispose(),Array.isArray(p.material)?p.material.forEach(b=>this.disposeMaterial(b)):p.material&&this.disposeMaterial(p.material))})),e.mixer&&(e.mixer.stopAllAction(),e.mixer.uncacheRoot(n)),i.mesh.name="characterBody";const l=a.scale??1;i.mesh.userData.customModelScale=l,i.mesh.userData.isCustomModel=a.isCustomModel,a.offset&&(a.offset.x!==0||a.offset.y!==0||a.offset.z!==0)&&i.mesh.position.set(a.offset.x,a.offset.z,a.offset.y);const c=this.customClasses.get(t.class);c!=null&&c.animationMapping&&(i.mesh.userData.animationMapping=c.animationMapping),n.add(i.mesh);const d=new Qu(i.mesh),m=new Map;for(const p of i.animations){const f=p.name.toLowerCase();m.set(f,p),m.set(p.name,p)}return n.userData.agentClass=t.class,console.log(`[ModelLoader] Agent ${t.name} model updated to ${a.file}`),{group:n,mixer:d,animations:m,currentAction:null}}disposeAgentMesh(e){for(e.mixer&&(e.mixer.stopAllAction(),e.mixer.uncacheRoot(e.group)),e.group.traverse(t=>{var n,a;t instanceof De?((n=t.geometry)==null||n.dispose(),Array.isArray(t.material)?t.material.forEach(i=>this.disposeMaterial(i)):t.material&&this.disposeMaterial(t.material)):t instanceof Un?this.disposeMaterial(t.material):t instanceof ay&&((a=t.geometry)==null||a.dispose(),Array.isArray(t.material)?t.material.forEach(i=>this.disposeMaterial(i)):t.material&&this.disposeMaterial(t.material))});e.group.children.length>0;)e.group.remove(e.group.children[0]);e.animations.clear()}disposeMaterial(e){var t,n,a,i,o;(e instanceof dt||e instanceof Ke||e instanceof Xn)&&((t=e.map)==null||t.dispose(),"normalMap"in e&&((n=e.normalMap)==null||n.dispose()),"roughnessMap"in e&&((a=e.roughnessMap)==null||a.dispose()),"metalnessMap"in e&&((i=e.metalnessMap)==null||i.dispose()),"emissiveMap"in e&&((o=e.emissiveMap)==null||o.dispose())),e.dispose()}}class LO{createAnimationSetup(e,t,n){n!=null&&n.animationMapping&&(e.userData.animationMapping=n.animationMapping);const a=new Qu(e),i=new Map;for(const o of t)i.set(o.name.toLowerCase(),o),i.set(o.name,o);return{mixer:a,animations:i}}getIdleTimerColor(e){const a=Math.min(e/60,60)/60,i=Math.pow(a,.7),o=120*(1-i),l=80+20*i,c=60-10*i,d=`hsl(${Math.round(o)}, ${Math.round(l)}%, ${Math.round(c)}%)`;return{text:d,border:d}}formatIdleTimeShort(e){if(e<60)return`${e}s`;const t=Math.floor(e/60);if(t<60){const o=e%60;return o>0?`${t}m ${o}s`:`${t}m`}const n=Math.floor(t/60),a=t%60;return n<24?a>0?`${n}h ${a}m`:`${n}h`:`${Math.floor(n/24)}d`}}const Mj={idle:4915102,working:4890367,waiting:16752202,waiting_permission:16763904,error:16730698,orphaned:16711935,default:8947848};function jM(s){if(s.contextStats)return 100-s.contextStats.usedPercent;const e=s.contextUsed||0,t=s.contextLimit||2e5;return Math.max(0,t-e)/t*100}class OO{constructor(e){U(this,"idleTimerCanvas",null);U(this,"idleTimerCtx",null);U(this,"manaBarCanvas",null);U(this,"manaBarCtx",null);this.animConfig=e}getStatusColor(e){return Mj[e]??Mj.default}createSelectionRing(e,t=!1){const n=t?1.5:1,a=new il(.8*n,.95*n,32),i=new Ke({color:e,side:Ts,transparent:!0,opacity:0,depthTest:!1}),o=new De(a,i);return o.rotation.x=-Math.PI/2,o.position.y=.05,o.renderOrder=999,o.name="selectionRing",o}createStatusBarSprite(e,t,n,a,i=2){const o=document.createElement("canvas"),l=o.getContext("2d");o.width=4096,o.height=2560,this.drawStatusBar(l,o.width,o.height,e,t,n,a);const c=new ss(o);c.minFilter=Zu,c.magFilter=zn,c.generateMipmaps=!0,c.anisotropy=16,c.needsUpdate=!0;const d=new Xn({map:c,transparent:!0,depthTest:!1,depthWrite:!1}),m=new Un(d),p=a?.8:.5;m.position.y=i+p;const f=a?2:1.6,b=o.height/o.width;return m.scale.set(f,f*b,1),m.name="statusBar",m.renderOrder=1100,m.userData.modelHeight=i,m.userData.baseIndicatorScale=f,m.userData.aspectRatio=b,m}createNameLabelSprite(e,t,n,a,i){const o=document.createElement("canvas"),l=o.getContext("2d");o.width=4096,o.height=i?2048:1024,this.drawNameLabel(l,o.width,o.height,e,t,a,i);const c=new ss(o);c.minFilter=Zu,c.magFilter=zn,c.generateMipmaps=!0,c.anisotropy=16,c.needsUpdate=!0;const d=new Xn({map:c,transparent:!0,depthTest:!1,depthWrite:!1}),m=new Un(d),p=n?4.2:3.5;m.position.y=i?n?-1.2:-1:n?-.9:-.7;const f=o.height/o.width;return m.scale.set(p,p*f,1),m.name="nameLabelSprite",m.renderOrder=1200,m.userData.baseIndicatorScale=p,m.userData.aspectRatio=f,m}drawNameLabel(e,t,n,a,i,o,l){e.clearRect(0,0,t,n);const c=`#${i.toString(16).padStart(6,"0")}`,d=l?n*.3:n/2;let m=800;const p=300,f=o==="claude"||o==="codex",b=f?m*.42:0,x=f?m*.3:0,w=t-400-(f?b+x:0);e.font=`bold ${m}px Arial`;let k=e.measureText(a).width;for(;k>w&&m>p;)m-=40,e.font=`bold ${m}px Arial`,k=e.measureText(a).width;const S=f?m*.42:0,j=f?m*.3:0,C=S+j,N=k+C,P=t/2+C/2;if(e.textAlign="center",e.textBaseline="middle",e.shadowColor="rgba(0, 0, 0, 0.9)",e.shadowBlur=m*.12,e.shadowOffsetX=m*.04,e.shadowOffsetY=m*.04,e.strokeStyle="#000",e.lineWidth=m*.14,e.lineJoin="round",e.strokeText(a,P,d),e.shadowColor="transparent",e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0,f){const _=t/2-N/2+S/2,L=d,M=o==="codex"?"#4a9eff":"#ff9e4a";e.beginPath(),e.arc(_,L,S/2,0,Math.PI*2),e.fillStyle=M,e.fill(),e.strokeStyle="rgba(255, 255, 255, 0.9)",e.lineWidth=Math.max(4,S*.1),e.stroke()}if(e.fillStyle=c,e.fillText(a,P,d),l){const _=Math.round(m*.85),L=n*.55;let M=l;const D=t-600;let E=_;for(e.font=`italic ${E}px "Segoe UI", Arial, sans-serif`;e.measureText(M).width>D&&E>200;)E-=40,e.font=`italic ${E}px "Segoe UI", Arial, sans-serif`;e.shadowColor="rgba(0, 0, 0, 0.8)",e.shadowBlur=E*.1,e.shadowOffsetX=E*.03,e.shadowOffsetY=E*.03,e.strokeStyle="#000",e.lineWidth=E*.12,e.lineJoin="round",e.strokeText(M,t/2,L),e.shadowColor="transparent",e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0,e.fillStyle="rgba(190, 205, 225, 0.9)",e.fillText(M,t/2,L)}}drawStatusBar(e,t,n,a,i,o,l){e.clearRect(0,0,t,n);const c=t/2048;let d=80*c;l&&(e.font=`${400*c}px serif`,e.textAlign="center",e.textBaseline="top",e.fillText("👑",t/2,d),d+=440*c);const m=200*c,p=1350*c,f=(t-p)/2,b=d,x=200*c,w=f+x/2+30*c,k=b+m/2;let S;switch(i){case"working":S="#4a9eff";break;case"orphaned":S="#c060e0";break;case"error":S="#e05050";break;case"waiting":case"waiting_permission":S="#e0a030";break;default:S="#40c090"}e.beginPath(),e.arc(w,k,x/2,0,Math.PI*2),e.fillStyle=S,e.shadowColor=S,e.shadowBlur=20*c,e.fill(),e.shadowBlur=0,e.strokeStyle="rgba(0, 0, 0, 0.4)",e.lineWidth=4*c,e.stroke();const j=f+x+60*c,C=p-x-90*c,N=m-80*c,P=b+40*c,_=30*c;e.fillStyle="#0d0d14",e.beginPath(),e.roundRect(j,P,C,N,_),e.fill(),e.strokeStyle="rgba(80, 90, 110, 0.5)",e.lineWidth=4*c,e.stroke();const L=Math.max(0,Math.min(100,a))/100,M=8*c,D=Math.max(0,(C-M*2)*L);if(D>0){let I;L>.5?I="#00c896":L>.2?I="#e8a020":I="#e84040",e.fillStyle=I,e.beginPath(),e.roundRect(j+M,P+M,D,N-M*2,_-M),e.fill(),e.shadowColor=I,e.shadowBlur=12*c,e.fill(),e.shadowBlur=0}const E=`${Math.round(L*100)}%`;e.font=`bold ${180*c}px "Segoe UI", Arial, sans-serif`,e.textAlign="center",e.textBaseline="middle";const R=j+C/2,O=P+N/2;if(e.shadowColor="rgba(0, 0, 0, 0.8)",e.shadowBlur=8*c,e.shadowOffsetX=2*c,e.shadowOffsetY=2*c,e.strokeStyle="rgba(0, 0, 0, 0.9)",e.lineWidth=24*c,e.lineJoin="round",e.strokeText(E,R,O),e.shadowColor="transparent",e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0,e.fillStyle="rgba(255, 255, 255, 0.95)",e.fillText(E,R,O),d+=m+60*c,i==="idle"&&o>0){const I=Math.floor((Date.now()-o)/1e3),B=this.animConfig.formatIdleTimeShort(I),Y=this.animConfig.getIdleTimerColor(I);e.font=`bold ${140*c}px Arial`;const W=e.measureText(`⏱ ${B}`).width+140*c,K=180*c,X=(t-W)/2,H=d;e.fillStyle="rgba(0, 0, 0, 0.85)",e.beginPath(),e.roundRect(X,H,W,K,28*c),e.fill(),e.strokeStyle=Y.border,e.lineWidth=12*c,e.stroke(),e.textAlign="center",e.textBaseline="middle",e.strokeStyle="#000",e.lineWidth=14*c,e.strokeText(`⏱ ${B}`,t/2,H+K/2),e.fillStyle=Y.text,e.fillText(`⏱ ${B}`,t/2,H+K/2)}}createCombinedUISprite(e,t,n,a,i,o){const l=document.createElement("canvas"),c=l.getContext("2d");l.width=4096,l.height=2048,this.drawCombinedUI(c,l.width,l.height,e,t,n,a,i,o);const d=new ss(l);d.minFilter=Zu,d.magFilter=zn,d.generateMipmaps=!0,d.anisotropy=16,d.needsUpdate=!0;const m=new Xn({map:d,transparent:!0,depthTest:!1,depthWrite:!1}),p=new Un(m);p.position.y=o?3.2:2.2;const f=o?3:2.4,b=l.height/l.width;return p.scale.set(f,f*b,1),p.name="combinedUI",p.userData.baseIndicatorScale=f,p.userData.aspectRatio=b,p}drawCombinedUI(e,t,n,a,i,o,l,c,d){e.clearRect(0,0,t,n);const m=`#${i.toString(16).padStart(6,"0")}`,p=t/2048;let f=80*p;d&&(e.font=`${288*p}px serif`,e.textAlign="center",e.textBaseline="top",e.fillText("👑",t/2,f),f+=320*p);const b=224*p,x=t-240*p;e.font=`bold ${b}px Arial`;let w=a;if(e.measureText(w).width>x){for(;w.length>3&&e.measureText(w+"...").width>x;)w=w.slice(0,-1);w+="..."}e.textAlign="center",e.textBaseline="middle";const S=f+b/2;e.strokeStyle="#000",e.lineWidth=24*p,e.lineJoin="round",e.strokeText(w,t/2,S),e.fillStyle=m,e.fillText(w,t/2,S),f+=b+64*p;const j=200*p,C=1350*p,N=(t-C)/2,P=f,_=176*p,L=N+_/2+24*p,M=P+j/2;let D;switch(l){case"working":D="#00a8ff";break;case"orphaned":D="#e040ff";break;case"error":D="#ff3030";break;case"waiting":case"waiting_permission":D="#ffc000";break;default:D="#00e090"}e.beginPath(),e.arc(L,M,_/2,0,Math.PI*2),e.fillStyle=D,e.fill(),e.shadowColor=D,e.shadowBlur=32*p,e.fill(),e.shadowBlur=0,e.strokeStyle="#000",e.lineWidth=12*p,e.stroke();const E=N+_+64*p,R=C-_-88*p,O=j-48*p,I=P+24*p;e.fillStyle="#000",e.beginPath(),e.roundRect(E,I,R,O,24*p),e.fill(),e.strokeStyle="#5a8a8a",e.lineWidth=8*p,e.stroke();const B=Math.max(0,Math.min(100,o))/100,Y=16*p,$=Math.max(0,(R-Y*2)*B);if($>0){let H;B>.5?H="#00ff88":B>.2?H="#ffaa00":H="#ff3366",e.fillStyle=H,e.beginPath(),e.roundRect(E+Y,I+Y,$,O-Y*2,16*p),e.fill(),e.shadowColor=H,e.shadowBlur=32*p,e.fill(),e.shadowBlur=0}const W=`${Math.round(B*100)}%`;e.font=`bold ${128*p}px Arial`,e.textAlign="center",e.textBaseline="middle";const K=E+R/2,X=I+O/2;if(e.strokeStyle="#000",e.lineWidth=28*p,e.lineJoin="round",e.strokeText(W,K,X),e.fillStyle="#fff",e.shadowColor="#000",e.shadowBlur=8*p,e.fillText(W,K,X),e.shadowBlur=0,f+=j+48*p,l==="idle"&&c>0){const H=Math.floor((Date.now()-c)/1e3),se=this.animConfig.formatIdleTimeShort(H),ce=this.animConfig.getIdleTimerColor(H);e.font=`bold ${160*p}px Arial`;const V=e.measureText(`⏱ ${se}`).width+160*p,J=216*p,ie=(t-V)/2,Q=f;e.fillStyle="rgba(0, 0, 0, 0.85)",e.beginPath(),e.roundRect(ie,Q,V,J,32*p),e.fill(),e.strokeStyle=ce.border,e.lineWidth=12*p,e.stroke(),e.textAlign="center",e.textBaseline="middle",e.strokeStyle="#000",e.lineWidth=16*p,e.strokeText(`⏱ ${se}`,t/2,Q+J/2),e.fillStyle=ce.text,e.fillText(`⏱ ${se}`,t/2,Q+J/2)}}createNameLabel(e,t,n=!1){const a=document.createElement("canvas"),i=a.getContext("2d"),o=72,l=32,c=100,d=256;a.width=2048,a.height=d,i.font=`bold ${o}px Arial`;const m=i.measureText(e).width,p=512,f=m+l*2+16;a.width=Math.max(p,f),i.clearRect(0,0,a.width,a.height),i.font=`bold ${o}px Arial`;const b=m+l*2,x=(a.width-b)/2,w=(a.height-c)/2;i.fillStyle="rgba(0, 0, 0, 0.8)",i.beginPath(),i.roundRect(x,w,b,c,12),i.fill(),i.fillStyle=`#${t.toString(16).padStart(6,"0")}`,i.textAlign="center",i.textBaseline="middle",i.fillText(e,a.width/2,a.height/2);const k=new ss(a);k.minFilter=zn,k.magFilter=zn,k.needsUpdate=!0;const S=new Xn({map:k,transparent:!0,depthTest:!1}),j=new Un(S);j.position.y=n?-.2:-.3;const C=n?.75:.6,P=(n?1.5:1.2)*(a.width/512);return j.scale.set(P,C,1),j.name="nameLabel",j.renderOrder=1200,j.userData.aspectRatio=a.width/a.height,j}createManaBar(e,t,n=!1){const a=document.createElement("canvas"),i=a.getContext("2d");a.width=400,a.height=64,this.drawManaBar(i,a.width,a.height,e,t);const o=new ss(a);o.minFilter=zn,o.magFilter=zn,o.needsUpdate=!0;const l=new Xn({map:o,transparent:!0,depthTest:!1}),c=new Un(l);return c.position.y=n?3:2,c.scale.set(n?1.4:1.1,n?.22:.18,1),c.name="manaBar",c}drawManaBar(e,t,n,a,i){const o=Math.max(0,Math.min(100,a))/100;e.clearRect(0,0,t,n);const l=n/32,c=20*l,d=6*l,m=c+d+4*l,p=6*l,f=t-m-10*l,b=n-12*l,x=6*l;let w;switch(i){case"working":w="#4a9eff";break;case"orphaned":w="#ff00ff";break;case"error":w="#ff4a4a";break;case"waiting":case"waiting_permission":w="#ffcc00";break;default:w="#4aff9e"}const k=c/2+4*l,S=n/2;e.beginPath(),e.arc(k,S,c/2,0,Math.PI*2),e.fillStyle=w,e.fill(),e.shadowColor=w,e.shadowBlur=8*l,e.fill(),e.shadowBlur=0,e.strokeStyle="#000000",e.lineWidth=2*l,e.stroke(),e.fillStyle="#000000",e.beginPath(),e.roundRect(m,p,f,b,x),e.fill(),e.strokeStyle="#5a8a8a",e.lineWidth=2*l,e.stroke();const j=Math.max(0,(f-4*l)*o);if(j>0){let N,P;o>.5?(N="#00ff88",P="#00ff88"):o>.2?(N="#ffaa00",P="#ffaa00"):(N="#ff3366",P="#ff3366"),e.fillStyle=N,e.beginPath(),e.roundRect(m+2*l,p+2*l,j,b-4*l,x-2),e.fill(),e.shadowColor=P,e.shadowBlur=8*l,e.fill(),e.shadowBlur=0}const C=`${Math.round(o*100)}%`;e.font=`bold ${Math.round(24*l)}px Arial`,e.textAlign="center",e.textBaseline="middle",e.strokeStyle="#000000",e.lineWidth=4*l,e.strokeText(C,t/2,n/2),e.fillStyle="#ffffff",e.shadowColor="#ffffff",e.shadowBlur=2*l,e.fillText(C,t/2,n/2),e.shadowBlur=0}createIdleTimer(e,t,n=!1){const a=document.createElement("canvas"),i=a.getContext("2d");a.width=400,a.height=64,this.drawIdleTimer(i,a.width,a.height,e,t);const o=new ss(a);o.minFilter=zn,o.magFilter=zn,o.needsUpdate=!0;const l=new Xn({map:o,transparent:!0,depthTest:!1}),c=new Un(l);return c.position.set(0,n?3.5:2.4,0),c.scale.set(n?1.4:1.1,n?.22:.18,1),c.name="idleTimer",c}createBossCrown(){const e=document.createElement("canvas"),t=e.getContext("2d");e.width=128,e.height=128,t.clearRect(0,0,e.width,e.height),t.font="96px serif",t.textAlign="center",t.textBaseline="middle",t.fillText("👑",e.width/2,e.height/2);const n=new ss(e);n.minFilter=zn,n.magFilter=zn,n.needsUpdate=!0;const a=new Xn({map:n,transparent:!0,depthTest:!1}),i=new Un(a);return i.position.set(0,4,0),i.scale.set(.8,.8,1),i.name="bossCrown",i}drawIdleTimer(e,t,n,a,i){if(e.clearRect(0,0,t,n),a!=="idle"||i<=0)return;const o=Math.floor((Date.now()-i)/1e3),l=this.animConfig.formatIdleTimeShort(o),c=this.animConfig.getIdleTimerColor(o),d=n/80,m=24*d;e.font=`bold ${Math.round(44*d)}px Arial`;const f=e.measureText(`⏱ ${l}`).width+m*2,b=n-12*d,x=(t-f)/2,w=6*d;e.fillStyle="rgba(0, 0, 0, 0.9)",e.beginPath(),e.roundRect(x,w,f,b,10*d),e.fill(),e.strokeStyle=c.border,e.lineWidth=3*d,e.stroke(),e.textAlign="center",e.textBaseline="middle",e.strokeStyle="#000000",e.lineWidth=4*d,e.strokeText(`⏱ ${l}`,t/2,n/2),e.fillStyle=c.text,e.fillText(`⏱ ${l}`,t/2,n/2)}getIdleTimerCanvas(){return this.idleTimerCanvas||(this.idleTimerCanvas=document.createElement("canvas"),this.idleTimerCanvas.width=400,this.idleTimerCanvas.height=64,this.idleTimerCtx=this.idleTimerCanvas.getContext("2d")),{canvas:this.idleTimerCanvas,ctx:this.idleTimerCtx}}getManaBarCanvas(){return this.manaBarCanvas||(this.manaBarCanvas=document.createElement("canvas"),this.manaBarCanvas.width=400,this.manaBarCanvas.height=64,this.manaBarCtx=this.manaBarCanvas.getContext("2d")),{canvas:this.manaBarCanvas,ctx:this.manaBarCtx}}updateIdleTimer(e,t,n){const a=e.getObjectByName("idleTimer");if(!a)return;const i=a.material;if(!i.map)return;const o=i.map.image;if(!o||!(o instanceof HTMLCanvasElement))return;const l=o.getContext("2d");l&&(this.drawIdleTimer(l,o.width,o.height,t,n),i.map.needsUpdate=!0)}updateManaBar(e,t,n){const a=e.getObjectByName("manaBar");if(!a)return;const i=a.material;if(!i.map)return;const o=i.map.image;if(!o||!(o instanceof HTMLCanvasElement))return;const l=o.getContext("2d");l&&(this.drawManaBar(l,o.width,o.height,t,n),i.map.needsUpdate=!0)}updateNameLabel(e,t,n,a){var m;const i=e.getObjectByName("nameLabel");i&&((m=i.material.map)==null||m.dispose(),i.material.dispose(),e.remove(i));const o=Ka[n],l=(o==null?void 0:o.color)??16777215,c=n==="boss"||e.userData.isBoss,d=this.createNameLabelSprite(t,l,c,a);e.add(d)}updateVisuals(e,t,n,a,i){var f;const o=t.isBoss===!0||t.class==="boss",l=Math.round(jM(t)),c=e.userData;if(c._cachedStatus!==t.status||c._cachedPercent!==l||c._cachedIsBoss!==o||t.status==="idle"&&c._cachedIdleBucket!==Math.floor((Date.now()-t.lastActivity)/6e4)){c._cachedStatus=t.status,c._cachedPercent=l,c._cachedIsBoss=o,c._cachedIdleBucket=t.status==="idle"?Math.floor((Date.now()-t.lastActivity)/6e4):0;const b=e.getObjectByName("statusBar");if(b){const S=b.material;if(S.map){const j=S.map.image;if(j instanceof HTMLCanvasElement){const C=j.getContext("2d");C&&(this.drawStatusBar(C,j.width,j.height,l,t.status,t.lastActivity,o),S.map.needsUpdate=!0)}}}const x=e.getObjectByName("combinedUI");if(x){const S=x.material;if(S.map){const j=S.map.image;if(j instanceof HTMLCanvasElement){const C=j.getContext("2d");C&&(this.drawCombinedUI(C,j.width,j.height,t.name,i,l,t.status,t.lastActivity,o),S.map.needsUpdate=!0)}}}const w=!!e.getObjectByName("statusBar"),k=!!e.getObjectByName("combinedUI");!w&&!k&&(this.updateManaBar(e,l,t.status),this.updateIdleTimer(e,t.status,t.lastActivity))}const m=t.taskLabel;if(c.agentName!==t.name||c._cachedTaskLabel!==m){const b=e.getObjectByName("nameLabelSprite");if(b){if(!!c._cachedTaskLabel!==!!m){const j=b.material;(f=j.map)==null||f.dispose(),j.dispose(),e.remove(b);const C=t.isBoss===!0||t.class==="boss",N=this.createNameLabelSprite(t.name,i,C,t.provider,m);e.add(N)}else{const j=b.material;if(j.map){const C=j.map.image;if(C instanceof HTMLCanvasElement){const N=C.getContext("2d");N&&(this.drawNameLabel(N,C.width,C.height,t.name,i,t.provider,m),j.map.needsUpdate=!0)}}}c.agentName=t.name,c._cachedTaskLabel=m}const x=!!e.getObjectByName("statusBar"),w=!!e.getObjectByName("combinedUI");!x&&!w&&(this.updateNameLabel(e,t.name,t.class,t.provider),c.agentName=t.name,c._cachedTaskLabel=m)}const p=e.getObjectByName("selectionRing");if(p){const b=p.material;if(n){const x=Ka[t.class];b.color.setHex((x==null?void 0:x.color)??i),b.opacity=t.isBoss===!0||t.class==="boss"?.34:.28}else a?(b.color.setHex(16766720),b.opacity=.2):b.opacity=0}}}class IO{constructor(e){U(this,"modelLoader");U(this,"animConfig");U(this,"visualConfig");this.modelLoader=new RO(e),this.animConfig=new LO,this.visualConfig=new OO(this.animConfig)}setCustomClasses(e){this.modelLoader.setCustomClasses(e)}createAgentMesh(e){const t=new Fn;t.userData.agentId=e.id;const n=this.modelLoader.getClassConfig(e.class),a=e.isBoss===!0||e.class==="boss",{body:i,mixer:o,animations:l}=this.modelLoader.createCharacterBody(e,n.color);t.add(i);const c=this.modelLoader.calculateModelHeight(i,a),d=this.visualConfig.createSelectionRing(n.color,a);t.add(d);const m=jM(e),p=this.visualConfig.createStatusBarSprite(m,e.status,e.lastActivity,a,c);t.add(p);const f=this.visualConfig.createNameLabelSprite(e.name,n.color,a,e.provider,e.taskLabel);t.add(f),t.userData.agentName=e.name,t.userData.agentClass=e.class,t.userData.isBoss=a,t.position.set(e.position.x,e.position.y,e.position.z);const b=a?1:.75,x=a?3.5:2.5,w=new Gn(b,b,x,8),k=new Ke({visible:!1,transparent:!0,opacity:0}),S=new De(w,k);return S.position.y=x/2,S.name="clickHitbox",t.add(S),{group:t,mixer:o,animations:l,currentAction:null}}updateAgentClass(e,t){const{group:n}=e,a=n.userData.agentClass;if(a===t.class)return null;console.log(`[CharacterFactory] Agent ${t.name} class changed: ${a} -> ${t.class}`);const i=this.modelLoader.replaceAgentModel(e,t);return i&&this.visualConfig.updateNameLabel(n,t.name,t.class),i}updateVisuals(e,t,n,a=!1){const i=this.modelLoader.getClassConfig(t.class);this.visualConfig.updateVisuals(e,t,n,a,i.color)}upgradeToCharacterModel(e,t){return this.modelLoader.upgradeToCharacterModel(e,t)}disposeAgentMesh(e){this.modelLoader.disposeAgentMesh(e)}getStatusColor(e){return this.visualConfig.getStatusColor(e)}updateIdleTimer(e,t,n){this.visualConfig.updateIdleTimer(e,t,n)}updateManaBar(e,t,n){this.visualConfig.updateManaBar(e,t,n)}}const ns={STATIC:"static",IDLE:"idle",WALK:"walk",JUMP:"jump",SIT:"sit",DIE:"die",EMOTE_YES:"emote-yes",EMOTE_NO:"emote-no"},Tj={height:.5,speed:1.5};class BO{constructor(){U(this,"movements",new Map);U(this,"jumpingAgents",new Map);U(this,"animatingAgents",new Set);U(this,"jumpTime",0)}isMoving(e){return this.movements.has(e)}hasActiveMovements(){return this.movements.size>0}resolveAnimationName(e,t){var i;const n=e.group.getObjectByName("characterBody"),a=(i=n==null?void 0:n.userData)==null?void 0:i.animationMapping;if(a){const o=a[t];if(o&&e.animations.has(o))return o;if(o&&e.animations.has(o.toLowerCase()))return o.toLowerCase()}switch(t){case"idle":return ns.IDLE;case"walk":return ns.WALK;case"working":return ns.JUMP;default:return ns.IDLE}}playAnimationForState(e,t,n){const a=this.resolveAnimationName(e,t);this.playAnimation(e,a,n)}startMovement(e,t,n){const a=t.group.position.clone(),i=new gt(n.x,n.y,n.z),l=a.distanceTo(i)/EO*1e3;this.movements.delete(e),this.movements.set(e,{agentId:e,startPos:a,endPos:i,startTime:performance.now(),duration:Math.max(l,200)});const c=this.resolveAnimationName(t,"walk");this.playAnimation(t,c),this.faceDirection(t,a,i)}cancelMovement(e,t){this.movements.delete(e);const n=this.resolveAnimationName(t,"idle");this.playAnimation(t,n)}playAnimation(e,t,n){if(!e.mixer)return;const a=e.group.userData.agentId;let i=e.animations.get(t);if(i||(i=e.animations.get(t.toLowerCase())),!i){console.warn(`[MovementAnimator] Animation not found: ${t}, available:`,Array.from(e.animations.keys()));const m=this.jumpingAgents.get(a);if(this.jumpingAgents.delete(a),m!==void 0){const p=e.group.getObjectByName("characterBody");p&&(p.position.y=m)}e.currentAction&&(e.currentAction.fadeOut(.2),e.currentAction=null);return}console.log(`[MovementAnimator] Playing: ${t}`);const{loop:o=!0,fadeTime:l=.2,timeScale:c=1}=n??{},d=e.mixer.clipAction(i);if(d.setLoop(o?wP:zA,1/0),d.clampWhenFinished=!o,d.timeScale=c,e.currentAction&&e.currentAction!==d?(e.currentAction.fadeOut(l),d.reset().fadeIn(l).play()):d.reset().play(),e.currentAction=d,this.animatingAgents.add(a),t===ns.JUMP&&o){if(!this.jumpingAgents.has(a)){const m=e.group.getObjectByName("characterBody"),p=(m==null?void 0:m.position.y)??0;this.jumpingAgents.set(a,p)}}else{const m=this.jumpingAgents.get(a);if(this.jumpingAgents.delete(a),m!==void 0){const p=e.group.getObjectByName("characterBody");p&&(p.position.y=m)}}}stopAnimation(e){this.animatingAgents.delete(e),this.jumpingAgents.delete(e)}faceDirection(e,t,n){const a=new gt().subVectors(n,t).normalize();if(a.x!==0||a.z!==0){const i=e.group.getObjectByName("characterBody");if(i){const o=Math.atan2(a.x,a.z);i.rotation.y=o}}}update(e,t){var i;const n=performance.now(),a=[];this.jumpTime+=t;for(const o of this.animatingAgents){const l=e.get(o);(i=l==null?void 0:l.mixer)==null||i.update(t)}for(const[o,l]of this.jumpingAgents){const c=e.get(o);if(!c)continue;const d=c.group.getObjectByName("characterBody");if(d){const m=Math.abs(Math.sin(this.jumpTime*Tj.speed*Math.PI*2))*Tj.height;d.position.y=l+m}}for(const[o,l]of this.movements){const c=e.get(o);if(!c){a.push(o);continue}const d=n-l.startTime;let m=Math.min(d/l.duration,1);m=this.easeOutCubic(m),c.group.position.lerpVectors(l.startPos,l.endPos,m),this.smoothRotateToDirection(c,l.startPos,l.endPos,t),m>=1&&(a.push(o),c.group.position.copy(l.endPos))}for(const o of a)this.movements.delete(o);return a}smoothRotateToDirection(e,t,n,a){const i=new gt().subVectors(n,t).normalize();if(i.x===0&&i.z===0)return;const o=e.group.getObjectByName("characterBody");if(!o)return;const l=Math.atan2(i.x,i.z),c=o.rotation.y,d=l-c,m=Math.atan2(Math.sin(d),Math.cos(d)),p=10;o.rotation.y+=m*Math.min(1,p*a)}easeOutCubic(e){return 1-Math.pow(1-e,3)}get activeCount(){return this.movements.size}clear(){this.movements.clear(),this.jumpingAgents.clear(),this.animatingAgents.clear(),this.jumpTime=0}}const ls={Read:"📖",Write:"✏️",Edit:"📝",Bash:"💻",Glob:"🔍",Grep:"🔎",Task:"📋",WebFetch:"🌐",WebSearch:"🌍",TodoWrite:"✅",NotebookEdit:"📓",AskFollowupQuestion:"❓",AskUserQuestion:"❓",AttemptCompletion:"✨",ListFiles:"📂",SearchFiles:"🔎",ExecuteCommand:"⚙️",default:"⚡"},zO={Read:"tools:display.toolNames.read",Write:"tools:display.toolNames.write",Edit:"tools:display.toolNames.edit",Bash:"tools:display.toolNames.bash",Glob:"tools:display.toolNames.glob",Grep:"tools:display.toolNames.grep",Task:"tools:display.toolNames.task",WebFetch:"tools:display.toolNames.webFetch",WebSearch:"tools:display.toolNames.webSearch",TodoWrite:"tools:display.toolNames.todoWrite",NotebookEdit:"tools:display.toolNames.notebookEdit",AskFollowupQuestion:"tools:display.toolNames.askFollowupQuestion",AskUserQuestion:"tools:display.toolNames.askUserQuestion",AttemptCompletion:"tools:display.toolNames.attemptCompletion",ListFiles:"tools:display.toolNames.listFiles",SearchFiles:"tools:display.toolNames.searchFiles",ExecuteCommand:"tools:display.toolNames.executeCommand"};function CM(s,e){const t=zO[s];return t&&e(t,{defaultValue:s})||s}function Bp(s){return(typeof s=="string"?new Date(s):new Date(s)).toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1})}function NM(s,e){var t;try{const n=JSON.parse(e);switch(s){case"Read":case"Write":case"Edit":case"NotebookEdit":{const a=n.file_path||n.path||n.notebook_path;if(a)return a;break}case"Bash":{const a=n.command;if(a)return AM(a);break}case"Grep":{const a=n.pattern,i=n.path;if(a&&i)return`"${a}" in ${i}`;if(a)return`"${a}"`;break}case"Glob":{const a=n.pattern,i=n.path;if(a&&i)return`${a} in ${i}`;if(a)return a;break}case"WebFetch":{const a=n.url;if(a)return a;break}case"WebSearch":{const a=n.query;if(a)return`"${a}"`;break}case"Task":{const a=n.description,i=n.subagent_type;if(a)return i?`[${i}] ${a}`:a;if(n.prompt)return n.prompt;break}case"ExitPlanMode":case"EnterPlanMode":{const a=n.allowedPrompts;return Array.isArray(a)&&a.length>0?a.map(i=>i.prompt||i.tool||"").filter(Boolean).join(", "):s==="ExitPlanMode"&&typeof n.plan=="string"&&n.plan.trim().length>0?n.plan.trim():s==="ExitPlanMode"?"Plan ready":"Entering plan mode"}case"TodoWrite":{const a=n.todos;if(Array.isArray(a)&&a.length>0){const i=a.filter(d=>d.status==="completed").length,o=a.filter(d=>d.status==="in_progress").length,l=a.filter(d=>d.status==="pending").length,c=[];return i>0&&c.push(`${i} done`),o>0&&c.push(`${o} active`),l>0&&c.push(`${l} pending`),`${a.length} items (${c.join(", ")})`}break}case"AskUserQuestion":case"AskFollowupQuestion":{const a=n.questions||n.question;if(a){const i=Array.isArray(a)?(t=a[0])==null?void 0:t.question:a;if(i)return i}break}default:{for(const[,a]of Object.entries(n))if(typeof a=="string"&&a.length>0)return a;break}}}catch{}return null}function FO(s){if(!s.includes("curl")||!s.includes("/api/exec"))return null;const e=[],t=[/(?:-d|--data|--data-raw)\s+'((?:\\'|[^'])*)'/g,/(?:-d|--data|--data-raw)\s+"((?:\\"|[^"])*)"/g];for(const n of t){let a;for(;(a=n.exec(s))!==null;)a[1]&&e.push(a[1])}for(const n of e){const a=[n,n.replace(/\\"/g,'"'),n.replace(/\\'/g,"'"),n.replace(/\\"/g,'"').replace(/\\\\/g,"\\")];for(const i of a){const o=i.trim();if(!(!o.startsWith("{")||!o.endsWith("}")))try{const l=JSON.parse(o);if(typeof l.command=="string"&&l.command.length>0)return l.command}catch{}}}return null}function AM(s){return FO(s)||s}const Ej=/(^|[\s("'`])((?:\.{1,2}\/|~\/|\/)?[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*\.[A-Za-z0-9._-]+(?::\d+(?::\d+)?)?)/g;function $O(s){return!s||s.startsWith("-")||s.includes("://")||s.includes("*")?!1:s.includes(".")&&!s.endsWith(".")}function MM(s){if(!s)return[{text:""}];const e=[];let t=0;Ej.lastIndex=0;let n;for(;(n=Ej.exec(s))!==null;){const a=n[0],i=n[1]||"",o=n[2]||"",l=n.index;l>t&&e.push({text:s.slice(t,l)}),i&&e.push({text:i}),$O(o)?e.push({text:o,fileRef:o}):e.push({text:o}),t=l+a.length}return t<s.length&&e.push({text:s.slice(t)}),e.length>0?e:[{text:s}]}const zp="tide-file://",HO=/(^|[\s(>])((?:\.\.?\/|\/)?(?:[A-Za-z0-9._-]+\/)*[A-Za-z0-9._-]+(?:\.[A-Za-z0-9._-]+)+(?:#L\d+(?:C\d+)?)?(?::\d+(?::\d+)?)?)(?=$|[\s),.;])/g,UO=/`((?:\.\.?\/|\/)?(?:[A-Za-z0-9._-]+\/)*[A-Za-z0-9._-]+(?:\.[A-Za-z0-9._-]+)+(?:#L\d+(?:C\d+)?)?(?::\d+(?::\d+)?)?)`/g,GO=/\.(com|org|net|io|dev|app|co|me|info|biz|us|uk|de|fr|jp|cn|ru|edu|gov|mil|int|xyz|tech|online|site|store|blog|cloud|ai|gg|tv|cc|sh|fm|to|ly|gl|so|is|it|at|nl|ch|se|no|fi|dk|be|cz|pl|pt|br|mx|ar|cl|in|au|nz|za|sg|hk|tw|kr|id|ph|th|vn|my)(?:[:/\s#?]|$)/i;function _j(s){if(!s||s.includes("://")||s.startsWith("www.")||s.includes("@"))return!1;const e=s.split("/")[0];return GO.test(e)?!1:s.includes(".")&&!s.endsWith(".")}function rb(s){if(!s||!s.includes("."))return s;const e=s.split(`
44
44
  `);let t=!1;return e.map(a=>{if(a.trimStart().startsWith("```"))return t=!t,a;if(t)return a;const o=a.replace(UO,(l,c)=>{if(!_j(c))return l;const d=encodeURIComponent(c);return`[\`${c}\`](${zp}${d})`});return o.replace(HO,(l,c,d,m)=>{const p=m+c.length,f=p>0?o[p-1]:"",b=p+d.length<o.length?o[p+d.length]:"";if(f==="("&&p>1&&o[p-2]==="]"||f==="["||b==="]"||!_j(d))return l;const x=encodeURIComponent(d);return`${c}[${d}](${zp}${x})`})}).join(`
45
45
  `)}function WO(s){if(!s||!s.startsWith(zp))return null;const e=s.slice(zp.length);if(!e)return null;try{return decodeURIComponent(e)}catch{return e}}function vc(s){return s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'")?s.slice(1,-1):s}function TM(s){const e=s.trim();if(!e)return null;let t,n=e;const a=e.match(/^(\S+)\s+-lc\s+([\s\S]+)$/);if(a&&(t=`${a[1]} -lc`,n=vc(a[2].trim())),!/\brg\s+--files\b/.test(n)||!/\|\s*rg\b/.test(n))return null;const i=n.match(/\|\s*rg\b\s+(.+)$/);if(!i)return null;const o=i[1].trim();if(!o)return null;const l=o.replace(/^(?:-\S+\s+)*/,"").trim(),c=vc(l||o);return c?{shellPrefix:t,commandBody:n,searchTerm:c}:null}function EM(s){const e=s.trim();if(!e)return null;let t,n=e;const a=e.match(/^(\S+)\s+-lc\s+([\s\S]+)$/);a&&(t=`${a[1]} -lc`,n=vc(a[2].trim()));const i=/\bcurl\b[\s\S]*\/api\/notify\b/.test(n),o=/\bgdbus\b[\s\S]*org\.freedesktop\.Notifications\.Notify\b/.test(n);if(!i&&!o)return null;let l,c;const d=n.match(/-d\s+((['"])([\s\S]*?)\2)/);if(d){const m=vc(d[1]).replace(/\\"/g,'"'),p=m.match(/"title"\s*:\s*"([^"]*)"/),f=m.match(/"message"\s*:\s*"([^"]*)"/);p!=null&&p[1]&&(l=p[1]),f!=null&&f[1]&&(c=f[1])}if(!l||!c){const m=n.match(/Notifications\.Notify[\s\S]*?\s'[^']*'\s+\d+\s+'[^']*'\s+'([^']*)'\s+'([^']*)'/);!l&&(m!=null&&m[1])&&(l=m[1]),!c&&(m!=null&&m[2])&&(c=m[2])}return{shellPrefix:t,commandBody:n,title:l,message:c,viaCurl:i,viaGdbus:o}}function _M(s){const e=s.trim();if(!e)return null;let t,n=e;const a=e.match(/^(\S+)\s+-lc\s+([\s\S]+)$/);if(a&&(t=`${a[1]} -lc`,n=vc(a[2].trim())),!/\bcurl\b/.test(n)||!/PATCH/.test(n)||!/\/api\/agents\//.test(n))return null;const i=n.match(/-d\s+((['"])([\s\S]*?)\2)/);if(!i)return null;const l=vc(i[1]).replace(/\\"/g,'"').match(/"taskLabel"\s*:\s*"([^"]*)"/);return l!=null&&l[1]?{shellPrefix:t,commandBody:n,taskLabel:l[1]}:null}const rd=class rd{constructor(e){U(this,"scene");U(this,"moveOrderEffects",[]);U(this,"speechBubbles",[]);U(this,"sleepingEffects",[]);U(this,"waitingPermissionEffects",[]);U(this,"delegationEffects",[]);U(this,"subagentEffects",[]);U(this,"agentMeshes",new Map);U(this,"ringGeometry",null);U(this,"pulseGeometry",null);U(this,"chevronGeometry",null);U(this,"delegationPaperTexture",null);U(this,"sleepingBubbleTexture",null);U(this,"waitingPermissionTexture",null);U(this,"delegationSpritePool",[]);U(this,"moveOrderGroupPool",[]);U(this,"_needsUpdate",!1);U(this,"camera",null);U(this,"indicatorScale",1);this.scene=e,this.initializeCachedResources()}get needsUpdate(){return this._needsUpdate||this.moveOrderEffects.length>0||this.speechBubbles.length>0||this.sleepingEffects.length>0||this.waitingPermissionEffects.length>0||this.delegationEffects.length>0||this.subagentEffects.length>0}markDirty(){this._needsUpdate=!0}clearDirty(){this._needsUpdate=!1}initializeCachedResources(){this.ringGeometry=new il(.3,.4,32),this.pulseGeometry=new il(.1,.2,32);const e=new kP;e.moveTo(0,.15),e.lineTo(.12,.35),e.lineTo(.08,.35),e.lineTo(0,.2),e.lineTo(-.08,.35),e.lineTo(-.12,.35),e.closePath(),this.chevronGeometry=new SP(e),this.createDelegationPaperTexture(),this.createSleepingBubbleTexture(),this.createWaitingPermissionTexture(),this.initializePools()}initializePools(){for(let e=0;e<rd.POOL_SIZE;e++)if(this.delegationPaperTexture){const t=new Xn({map:this.delegationPaperTexture,transparent:!0,opacity:0,depthTest:!1}),n=new Un(t);n.scale.set(.3,.3,1),n.visible=!1,this.delegationSpritePool.push({sprite:n,inUse:!1})}for(let e=0;e<rd.POOL_SIZE;e++){const t=this.createMoveOrderGroup();t.visible=!1,this.moveOrderGroupPool.push(t)}}createMoveOrderGroup(){const e=new Fn,t=new Ke({color:4915102,side:Ts,transparent:!0,opacity:.8}),n=new De(this.ringGeometry,t);n.rotation.x=-Math.PI/2,n.name="ring",e.add(n);const a=new Ke({color:4915102,side:Ts,transparent:!0,opacity:.6}),i=new De(this.pulseGeometry,a);i.rotation.x=-Math.PI/2,i.name="pulse",e.add(i);for(let o=0;o<3;o++){const l=new Ke({color:4915102,side:Ts,transparent:!0,opacity:.9}),c=new De(this.chevronGeometry,l);c.rotation.x=-Math.PI/2,c.position.y=.5+o*.25,c.name=`chevron${o}`,e.add(c)}return e}getDelegationSprite(){for(const n of this.delegationSpritePool)if(!n.inUse)return n.inUse=!0,n.sprite.visible=!0,n.sprite.material.opacity=1,n.sprite;const e=new Xn({map:this.delegationPaperTexture,transparent:!0,opacity:1,depthTest:!1}),t=new Un(e);return t.scale.set(.3,.3,1),t}returnDelegationSprite(e){for(const t of this.delegationSpritePool)if(t.sprite===e){t.inUse=!1,t.sprite.visible=!1,this.scene.remove(e);return}this.scene.remove(e),e.material.dispose()}getMoveOrderGroup(){for(const e of this.moveOrderGroupPool)if(!e.visible)return e.visible=!0,e.traverse(t=>{if(t instanceof De){const n=t.material;n.opacity=t.name==="ring"?.8:t.name==="pulse"?.6:.9}}),e;return this.createMoveOrderGroup()}returnMoveOrderGroup(e){this.moveOrderGroupPool.includes(e)?(e.visible=!1,this.scene.remove(e)):(this.scene.remove(e),e.traverse(n=>{n instanceof De&&n.material.dispose()}))}createDelegationPaperTexture(){const e=document.createElement("canvas"),t=e.getContext("2d");e.width=64,e.height=64,t.fillStyle="#ffffff",t.strokeStyle="#ffd700",t.lineWidth=2,t.save(),t.translate(32,32),t.rotate(-.2),t.beginPath(),t.moveTo(-12,-18),t.lineTo(8,-18),t.lineTo(12,-14),t.lineTo(12,18),t.lineTo(-12,18),t.closePath(),t.fill(),t.stroke(),t.beginPath(),t.moveTo(8,-18),t.lineTo(8,-14),t.lineTo(12,-14),t.strokeStyle="#cccccc",t.stroke(),t.fillStyle="#f0f0f0",t.fill(),t.strokeStyle="#888888",t.lineWidth=1;for(let n=0;n<4;n++){const a=-8+n*6,i=n===3?10:16;t.beginPath(),t.moveTo(-8,a),t.lineTo(-8+i,a),t.stroke()}t.restore(),this.delegationPaperTexture=new ss(e),this.delegationPaperTexture.minFilter=zn,this.delegationPaperTexture.magFilter=zn}createSleepingBubbleTexture(){const e=document.createElement("canvas"),t=e.getContext("2d");e.width=128,e.height=128,t.fillStyle="rgba(40, 42, 54, 0.95)",t.strokeStyle="#bd93f9",t.lineWidth=2;const n=64,a=50,i=40;t.beginPath(),t.arc(n,a,i,0,Math.PI*2),t.fill(),t.stroke(),t.beginPath(),t.arc(30,95,10,0,Math.PI*2),t.fill(),t.stroke(),t.beginPath(),t.arc(18,115,6,0,Math.PI*2),t.fill(),t.stroke(),t.fillStyle="#8be9fd",t.font="bold 28px Arial",t.textAlign="center",t.textBaseline="middle",t.shadowColor="#8be9fd",t.shadowBlur=4,t.fillText("ZZZ",n,a),this.sleepingBubbleTexture=new ss(e),this.sleepingBubbleTexture.minFilter=zn,this.sleepingBubbleTexture.magFilter=zn}createWaitingPermissionTexture(){const e=document.createElement("canvas"),t=e.getContext("2d");e.width=128,e.height=128,t.fillStyle="rgba(40, 42, 54, 0.95)",t.strokeStyle="#ffcc00",t.lineWidth=2;const n=64,a=50,i=40;t.beginPath(),t.arc(n,a,i,0,Math.PI*2),t.fill(),t.stroke(),t.beginPath(),t.arc(30,95,10,0,Math.PI*2),t.fill(),t.stroke(),t.beginPath(),t.arc(18,115,6,0,Math.PI*2),t.fill(),t.stroke(),t.fillStyle="#ffcc00",t.font="bold 32px Arial",t.textAlign="center",t.textBaseline="middle",t.shadowColor="#ffcc00",t.shadowBlur=6,t.fillText("🔒",n,a),this.waitingPermissionTexture=new ss(e),this.waitingPermissionTexture.minFilter=zn,this.waitingPermissionTexture.magFilter=zn}setAgentMeshes(e){this.agentMeshes.clear();for(const[t,n]of e)this.agentMeshes.set(t,n.group)}updateSleepingEffect(e,t){const n=this.sleepingEffects.find(a=>a.agentId===e);t&&!n?this.createSleepingEffect(e):!t&&n&&this.removeSleepingEffect(e)}updateWaitingPermissionEffect(e,t){const n=this.waitingPermissionEffects.find(a=>a.agentId===e);t&&!n?this.createWaitingPermissionEffect(e):!t&&n&&this.removeWaitingPermissionEffect(e)}createSleepingEffect(e){const t=this.agentMeshes.get(e);if(!t||!this.sleepingBubbleTexture)return;const n=[],a=new Xn({map:this.sleepingBubbleTexture,transparent:!0,opacity:.95,depthTest:!1}),i=new Un(a);i.scale.set(.12,.12,1),i.userData.isBubble=!0,i.position.copy(t.position),i.position.y=2,i.position.x+=.15,this.scene.add(i),n.push(i),this.sleepingEffects.push({sprites:n,agentId:e,startTime:performance.now()}),this.markDirty()}removeSleepingEffect(e){const t=this.sleepingEffects.findIndex(n=>n.agentId===e);if(t!==-1){const n=this.sleepingEffects[t];for(const a of n.sprites)this.scene.remove(a),a.material.dispose();this.sleepingEffects.splice(t,1),this.markDirty()}}createWaitingPermissionEffect(e){const t=this.agentMeshes.get(e);if(!t||!this.waitingPermissionTexture)return;const n=[],a=new Xn({map:this.waitingPermissionTexture,transparent:!0,opacity:.95,depthTest:!1}),i=new Un(a);i.scale.set(.12,.12,1),i.userData.isBubble=!0,i.position.copy(t.position),i.position.y=2,i.position.x+=.15,this.scene.add(i),n.push(i),this.waitingPermissionEffects.push({sprites:n,agentId:e,startTime:performance.now()}),this.markDirty()}removeWaitingPermissionEffect(e){const t=this.waitingPermissionEffects.findIndex(n=>n.agentId===e);if(t!==-1){const n=this.waitingPermissionEffects[t];for(const a of n.sprites)this.scene.remove(a),a.material.dispose();this.waitingPermissionEffects.splice(t,1),this.markDirty()}}createDelegationEffect(e,t){const n=this.agentMeshes.get(e),a=this.agentMeshes.get(t);if(!n||!a||!this.delegationPaperTexture){console.log("[EffectsManager] Cannot create delegation effect - missing agent meshes or texture");return}const i=this.getDelegationSprite(),o=new gt(n.position.x,n.position.y+1.5,n.position.z),l=new gt(a.position.x,a.position.y+1.2,a.position.z);i.position.copy(o),this.scene.add(i),this.delegationEffects.push({sprite:i,startPosition:o.clone(),endPosition:l.clone(),startTime:performance.now(),duration:800}),this.markDirty()}createSpeechBubble(e,t,n){const a=this.agentMeshes.get(e);if(!a)return;this.removeSpeechBubble(e);const i=ls[t]||"🔧",o=this.formatToolParams(t,n),l=document.createElement("canvas"),c=l.getContext("2d");l.width=400,l.height=100;const d=o?`${i} ${t}: ${o}`:`${i} ${t}`;c.font="bold 32px Arial";const f=Math.min(c.measureText(d).width,l.width-40)+16*2,b=48,x=(l.width-f)/2,w=(l.height-b)/2,k=b/2;c.fillStyle="rgba(15, 15, 25, 0.85)",c.strokeStyle="#4a9eff",c.lineWidth=2,c.beginPath(),c.moveTo(x+k,w),c.lineTo(x+f-k,w),c.arc(x+f-k,w+k,k,-Math.PI/2,Math.PI/2),c.lineTo(x+k,w+b),c.arc(x+k,w+k,k,Math.PI/2,-Math.PI/2),c.closePath(),c.fill(),c.stroke(),c.fillStyle="#ffffff",c.font="bold 30px Arial",c.textAlign="center",c.textBaseline="middle";let S=d;const j=l.width-40;for(;c.measureText(S).width>j&&S.length>3;)S=S.slice(0,-4)+"...";c.fillText(S,l.width/2,l.height/2);const C=new ss(l);C.minFilter=zn,C.magFilter=zn,C.needsUpdate=!0;const N=new Xn({map:C,transparent:!0,opacity:0,depthTest:!1}),P=new Un(N);P.scale.set(2.4,.6,1),P.renderOrder=1e3;const _=!!a.userData._cachedTaskLabel,L=a.position.y-(_?2:1.3);P.position.copy(a.position),P.position.y=L,this.scene.add(P),this.speechBubbles.push({sprite:P,agentId:e,startTime:performance.now(),duration:4e3,baseY:L})}formatToolParams(e,t){if(!t)return"";switch(e){case"WebSearch":return t.query||"";case"WebFetch":return t.url||"";case"Read":case"Write":case"Edit":const n=t.file_path||t.path||"";return n.length>40?".../"+n.split("/").slice(-2).join("/"):n;case"Bash":const a=(t.command||"").slice(0,60);return a+(a.length>=60?"...":"");case"Grep":return`"${t.pattern||""}"`;case"Glob":return t.pattern||"";case"Task":return(t.description||"").slice(0,50);default:for(const[i,o]of Object.entries(t))if(typeof o=="string"&&o.length>0&&o.length<100)return o.slice(0,50);return""}}removeSpeechBubble(e){var n;const t=this.speechBubbles.findIndex(a=>a.agentId===e);if(t!==-1){const a=this.speechBubbles[t];this.scene.remove(a.sprite),(n=a.sprite.material.map)==null||n.dispose(),a.sprite.material.dispose(),this.speechBubbles.splice(t,1)}}createMoveOrderEffect(e){const t=this.getMoveOrderGroup();t.position.copy(e),t.position.y=.05;for(let i=0;i<3;i++){const o=t.getObjectByName(`chevron${i}`);o&&(o.position.y=.5+i*.25)}const n=t.getObjectByName("ring");n&&n.scale.setScalar(1);const a=t.getObjectByName("pulse");a&&a.scale.setScalar(1),this.scene.add(t),this.moveOrderEffects.push({group:t,startTime:performance.now(),duration:800}),this.markDirty()}setIndicatorScale(e){this.indicatorScale=e}update(){const e=performance.now();this.updateMoveOrderEffects(e),this.updateSpeechBubbles(e),this.updateSleepingEffects(),this.updateWaitingPermissionEffects(),this.updateDelegationEffects(e),this.updateSubagentEffects(e)}updateWithCamera(e){this.camera=e}calculateZoomScale(e){if(!this.camera)return this.indicatorScale;const t=this.camera.position.distanceTo(e);return Math.max(.5,Math.min(2.5,t/15))*this.indicatorScale}updateSleepingEffects(){const e=performance.now();for(const t of this.sleepingEffects){const n=this.agentMeshes.get(t.agentId);if(!n)continue;const a=e-t.startTime,i=this.calculateZoomScale(n.position);for(const o of t.sprites){o.position.x=n.position.x+.25*i,o.position.z=n.position.z;const l=.002,c=.04*i;o.position.y=2+Math.sin(a*l)*c;const d=.35*i,m=Math.sin(a*.003)*.015*i;o.scale.set(d+m,d+m,1);const p=Math.min(a/500,1);o.material.opacity=.95*p}}}updateWaitingPermissionEffects(){const e=performance.now();for(const t of this.waitingPermissionEffects){const n=this.agentMeshes.get(t.agentId);if(!n)continue;const a=e-t.startTime,i=this.calculateZoomScale(n.position);for(const o of t.sprites){o.position.x=n.position.x+.25*i,o.position.z=n.position.z;const l=.004,c=.06*i;o.position.y=2+Math.sin(a*l)*c;const d=.38*i,m=Math.sin(a*.006)*.03*i;o.scale.set(d+m,d+m,1);const p=Math.min(a/300,1),f=.85+Math.sin(a*.005)*.1;o.material.opacity=f*p}}}updateDelegationEffects(e){const t=[];for(let n=0;n<this.delegationEffects.length;n++){const a=this.delegationEffects[n],i=Math.min((e-a.startTime)/a.duration,1),o=1-(1-i)*(1-i),l=a.endPosition.x-a.startPosition.x,c=a.endPosition.y-a.startPosition.y,d=a.endPosition.z-a.startPosition.z,m=4*i*(1-i)*.8;a.sprite.position.x=a.startPosition.x+l*o,a.sprite.position.y=a.startPosition.y+c*o+m,a.sprite.position.z=a.startPosition.z+d*o,a.sprite.material.rotation=i*Math.PI*1.5,a.sprite.material.opacity=i>.8?(1-i)*5:1,i>=1&&t.push(n)}for(let n=t.length-1;n>=0;n--){const a=t[n],i=this.delegationEffects[a];this.returnDelegationSprite(i.sprite),this.delegationEffects.splice(a,1)}}updateMoveOrderEffects(e){const t=[];for(let n=0;n<this.moveOrderEffects.length;n++){const a=this.moveOrderEffects[n],i=e-a.startTime,o=Math.min(i/a.duration,1),l=1-o,c=a.group.getObjectByName("ring");c&&(c.scale.setScalar(1+o*1.5),c.material.opacity=l*.8);const d=a.group.getObjectByName("pulse");if(d){const m=(Math.sin(o*Math.PI*4)+1)/2;d.scale.setScalar(.8+m*.4),d.material.opacity=l*.6}for(let m=0;m<3;m++){const p=a.group.getObjectByName(`chevron${m}`);if(p){const f=m*.15,b=Math.max(0,Math.min((o-f)/(1-f),1));p.position.y=.5+m*.25-b*(.4+m*.15),p.material.opacity=(1-b)*.9}}o>=1&&t.push(n)}for(let n=t.length-1;n>=0;n--){const a=t[n];this.returnMoveOrderGroup(this.moveOrderEffects[a].group),this.moveOrderEffects.splice(a,1)}}updateSpeechBubbles(e){var n;const t=[];for(let a=0;a<this.speechBubbles.length;a++){const i=this.speechBubbles[a],o=e-i.startTime,l=Math.min(o/i.duration,1),c=this.agentMeshes.get(i.agentId);if(c){i.sprite.position.x=c.position.x,i.sprite.position.z=c.position.z;const b=this.calculateZoomScale(c.position);i.sprite.scale.set(2.4*b,.6*b,1)}const d=Math.min(o/200,1),m=l>.7?1-(l-.7)/.3:1;i.sprite.material.opacity=d*m;const p=c?c.position.y:0,f=c?!!c.userData._cachedTaskLabel:!1;i.sprite.position.y=p-(f?2:1.3),l>=1&&t.push(a)}for(let a=t.length-1;a>=0;a--){const i=t[a],o=this.speechBubbles[i];this.scene.remove(o.sprite),(n=o.sprite.material.map)==null||n.dispose(),o.sprite.material.dispose(),this.speechBubbles.splice(i,1)}}disposeEffect(e){this.scene.remove(e.group),e.group.traverse(t=>{t instanceof De&&t.material.dispose()})}addSubagentEffect(e,t,n,a){const i=this.agentMeshes.get(t);if(!i){console.warn(`[EffectsManager] Cannot add subagent effect: parent agent ${t} not found`);return}if(this.subagentEffects.find(S=>S.subagentId===e))return;const o=document.createElement("canvas");o.width=256,o.height=64;const l=o.getContext("2d");l.fillStyle="rgba(30, 30, 60, 0.85)";const c=12;l.beginPath(),l.moveTo(c,0),l.lineTo(o.width-c,0),l.quadraticCurveTo(o.width,0,o.width,c),l.lineTo(o.width,o.height-c),l.quadraticCurveTo(o.width,o.height,o.width-c,o.height),l.lineTo(c,o.height),l.quadraticCurveTo(0,o.height,0,o.height-c),l.lineTo(0,c),l.quadraticCurveTo(0,0,c,0),l.closePath(),l.fill(),l.strokeStyle="rgba(100, 180, 255, 0.8)",l.lineWidth=2,l.stroke(),l.fillStyle="#64b4ff",l.font="bold 28px monospace",l.fillText("⑂",8,40),l.fillStyle="#ffffff",l.font="22px sans-serif";const d=n.length>14?n.slice(0,12)+"..":n;l.fillText(d,40,38);const m=new ss(o);m.needsUpdate=!0;const p=new Xn({map:m,transparent:!0,opacity:.85,depthTest:!1}),f=new Un(p);f.scale.set(1.5,.4,1);const b=this.subagentEffects.filter(S=>S.parentAgentId===t&&!S.completed).length,x=b*Math.PI/4-Math.PI/4,w=1.5,k=i.position;f.position.set(k.x+Math.sin(x)*w,k.y+2.5+b*.5,k.z+Math.cos(x)*w),this.scene.add(f),this.subagentEffects.push({sprite:f,subagentId:e,parentAgentId:t,name:n,subagentType:a,startTime:performance.now(),completed:!1,completedAt:0}),this.markDirty(),console.log(`[EffectsManager] Added subagent effect: ${n} (${e}) near ${t}`)}completeSubagentEffect(e){const t=this.subagentEffects.find(n=>n.subagentId===e);t?(t.completed=!0,t.completedAt=performance.now(),this.markDirty(),console.log(`[EffectsManager] Marked subagent effect completed: ${t.name} (${e})`)):console.warn(`[EffectsManager] completeSubagentEffect: no effect found for subagentId=${e}`)}removeSubagentEffect(e){var n;const t=this.subagentEffects.findIndex(a=>a.subagentId===e);if(t!==-1){const a=this.subagentEffects[t];this.scene.remove(a.sprite),(n=a.sprite.material.map)==null||n.dispose(),a.sprite.material.dispose(),this.subagentEffects.splice(t,1),this.markDirty()}}updateSubagentEffects(e){var n;const t=[];for(let a=0;a<this.subagentEffects.length;a++){const i=this.subagentEffects[a],o=this.agentMeshes.get(i.parentAgentId);if(!o){t.push(a);continue}const l=this.subagentEffects.slice(0,a).filter(f=>f.parentAgentId===i.parentAgentId&&!f.completed).length,c=l*Math.PI/4-Math.PI/4,d=1.5,m=o.position;i.sprite.position.set(m.x+Math.sin(c)*d,m.y+2.5+l*.5,m.z+Math.cos(c)*d);const p=(e-i.startTime)/1e3;if(i.sprite.position.y+=Math.sin(p*1.5)*.05,i.completed&&i.completedAt>0){const f=(e-i.completedAt)/1e3;if(f>2){const b=Math.max(0,.85-(f-2)*.3);i.sprite.material.opacity=b,b<=0&&t.push(a)}}i.completed||(i.sprite.material.opacity=.75+Math.sin(p*2)*.1)}for(let a=t.length-1;a>=0;a--){const i=t[a],o=this.subagentEffects[i];this.scene.remove(o.sprite),(n=o.sprite.material.map)==null||n.dispose(),o.sprite.material.dispose(),this.subagentEffects.splice(i,1)}}removeAgentEffects(e){this.removeSleepingEffect(e),this.removeWaitingPermissionEffect(e),this.removeSpeechBubble(e);const t=this.subagentEffects.filter(n=>n.parentAgentId===e).map(n=>n.subagentId);for(const n of t)this.removeSubagentEffect(n);this.agentMeshes.delete(e)}clear(){var e,t;for(const n of this.moveOrderEffects)this.returnMoveOrderGroup(n.group);this.moveOrderEffects=[];for(const n of this.sleepingEffects)for(const a of n.sprites)this.scene.remove(a),a.material.dispose();this.sleepingEffects=[];for(const n of this.waitingPermissionEffects)for(const a of n.sprites)this.scene.remove(a),a.material.dispose();this.waitingPermissionEffects=[];for(const n of this.delegationEffects)this.returnDelegationSprite(n.sprite);this.delegationEffects=[];for(const n of this.speechBubbles)this.scene.remove(n.sprite),(e=n.sprite.material.map)==null||e.dispose(),n.sprite.material.dispose();this.speechBubbles=[];for(const n of this.subagentEffects)this.scene.remove(n.sprite),(t=n.sprite.material.map)==null||t.dispose(),n.sprite.material.dispose();this.subagentEffects=[]}dispose(){var e,t,n,a,i,o;this.clear(),(e=this.ringGeometry)==null||e.dispose(),(t=this.pulseGeometry)==null||t.dispose(),(n=this.chevronGeometry)==null||n.dispose(),this.ringGeometry=null,this.pulseGeometry=null,this.chevronGeometry=null,(a=this.delegationPaperTexture)==null||a.dispose(),(i=this.sleepingBubbleTexture)==null||i.dispose(),(o=this.waitingPermissionTexture)==null||o.dispose(),this.delegationPaperTexture=null,this.sleepingBubbleTexture=null,this.waitingPermissionTexture=null;for(const l of this.delegationSpritePool)l.sprite.material.dispose();this.delegationSpritePool=[];for(const l of this.moveOrderGroupPool)l.traverse(c=>{c instanceof De&&c.material.dispose()});this.moveOrderGroupPool=[],this.agentMeshes.clear()}};U(rd,"POOL_SIZE",10);let My=rd;class qO{constructor(){U(this,"animations",new Map)}register(e,t,n="idle"){this.animations.set(e,{state:n,time:Math.random()*Math.PI*2,basePosition:t.position.clone(),baseRotation:t.rotation.clone(),baseScale:t.scale.clone()})}unregister(e){this.animations.delete(e)}has(e){return this.animations.has(e)}setState(e,t){const n=this.animations.get(e);n&&n.state!==t&&(n.state=t,n.time=0)}updateBasePosition(e,t){const n=this.animations.get(e);n&&n.basePosition.copy(t)}update(e,t){for(const[n,a]of this.animations){const i=t.get(n);if(i)switch(a.time+=e,a.state){case"idle":this.applyIdleAnimation(i,a);break;case"working":this.applyWorkingAnimation(i,a);break;case"waiting":this.applyWaitingAnimation(i,a);break;case"error":this.applyErrorAnimation(i,a);break;case"static":this.resetToBase(i,a);break}}}applyIdleAnimation(e,t){const n=t.time,o=Math.sin(n*1.5)*.02,d=Math.sin(n*.8)*.01;e.position.set(t.basePosition.x+d,t.basePosition.y+o,t.basePosition.z)}applyWorkingAnimation(e,t){const n=t.time,o=Math.abs(Math.sin(n*6))*.25,l=.15,c=3,d=Math.sin(n*c)*l,f=Math.sin(n*3)*.22,x=Math.sin(n*c*.7)*.1,S=Math.sin(n*4)*.12;e.position.set(t.basePosition.x+d,t.basePosition.y+o,t.basePosition.z+x),e.rotation.set(t.baseRotation.x+f,t.baseRotation.y+S,t.baseRotation.z)}applyWaitingAnimation(e,t){const n=t.time,a=.02,i=1.2,o=Math.sin(n*i)*a,c=Math.sin(n*i)*.03,p=Math.sin(n*2)*.01;e.position.set(t.basePosition.x+o,t.basePosition.y+p,t.basePosition.z),e.rotation.set(t.baseRotation.x,t.baseRotation.y,t.baseRotation.z+c)}applyErrorAnimation(e,t){const n=t.time,a=.015,i=15,o=Math.sin(n*i)*a,l=Math.cos(n*i*1.3)*a*.5;e.position.set(t.basePosition.x+o,t.basePosition.y,t.basePosition.z+l)}resetToBase(e,t){e.position.copy(t.basePosition),e.rotation.copy(t.baseRotation),e.scale.copy(t.baseScale)}clear(){this.animations.clear()}}function Dj(s){const e=document.createElement("canvas"),t=e.getContext("2d"),n=s==="pokemon-stadium"?1024:512;switch(e.width=n,e.height=n,s){case"galactic":VO(t,e.width,e.height);break;case"metal":KO(t,e.width,e.height);break;case"hex":XO(t,e.width,e.height);break;case"circuit":ZO(t,e.width,e.height);break;case"pokemon-stadium":QO(t,e.width,e.height);break;default:YO(t,e.width,e.height)}return new ss(e)}function YO(s,e,t){s.fillStyle="#4a4a4a",s.fillRect(0,0,e,t);for(let n=0;n<5e3;n++){const a=Math.random()*e,i=Math.random()*t,o=60+Math.random()*40;s.fillStyle=`rgba(${o}, ${o}, ${o}, 0.3)`,s.fillRect(a,i,2,2)}s.strokeStyle="rgba(30, 30, 30, 0.4)",s.lineWidth=1;for(let n=0;n<8;n++){s.beginPath();let a=Math.random()*e,i=Math.random()*t;s.moveTo(a,i);for(let o=0;o<5;o++)a+=(Math.random()-.5)*100,i+=(Math.random()-.5)*100,s.lineTo(a,i);s.stroke()}}function VO(s,e,t){const n=s.createRadialGradient(e/2,t/2,0,e/2,t/2,e/1.5);n.addColorStop(0,"#1a0a30"),n.addColorStop(.5,"#0d0520"),n.addColorStop(1,"#050210"),s.fillStyle=n,s.fillRect(0,0,e,t);for(let a=0;a<3;a++){const i=Math.random()*e,o=Math.random()*t,l=100+Math.random()*150,c=["#ff00ff","#00ffff","#ff6600","#6600ff","#00ff66"],d=c[Math.floor(Math.random()*c.length)],m=s.createRadialGradient(i,o,0,i,o,l);m.addColorStop(0,d.replace("ff","66")+"40"),m.addColorStop(.5,d+"20"),m.addColorStop(1,"transparent"),s.fillStyle=m,s.fillRect(0,0,e,t)}for(let a=0;a<300;a++){const i=Math.random()*e,o=Math.random()*t,l=Math.random()*2,c=150+Math.random()*105;if(Math.random()>.8){const d=s.createRadialGradient(i,o,0,i,o,l*4);d.addColorStop(0,`rgba(${c}, ${c}, 255, 0.8)`),d.addColorStop(1,"transparent"),s.fillStyle=d,s.fillRect(i-l*4,o-l*4,l*8,l*8)}s.fillStyle=`rgba(${c}, ${c}, 255, 1)`,s.beginPath(),s.arc(i,o,l,0,Math.PI*2),s.fill()}s.strokeStyle="rgba(100, 50, 150, 0.15)",s.lineWidth=20,s.beginPath();for(let a=0;a<Math.PI*4;a+=.1){const i=20+a*30,o=e/2+Math.cos(a)*i,l=t/2+Math.sin(a)*i;a===0?s.moveTo(o,l):s.lineTo(o,l)}s.stroke()}function KO(s,e,t){s.fillStyle="#3a3a44",s.fillRect(0,0,e,t);for(let a=0;a<200;a++){const i=Math.random()*t,o=50+Math.random()*30;s.strokeStyle=`rgba(${o+20}, ${o+20}, ${o+30}, 0.3)`,s.lineWidth=1,s.beginPath(),s.moveTo(0,i),s.lineTo(e,i+(Math.random()-.5)*4),s.stroke()}s.strokeStyle="rgba(20, 20, 25, 0.8)",s.lineWidth=3;const n=e/4;for(let a=0;a<=e;a+=n)s.beginPath(),s.moveTo(a,0),s.lineTo(a,t),s.stroke();for(let a=0;a<=t;a+=n)s.beginPath(),s.moveTo(0,a),s.lineTo(e,a),s.stroke();s.fillStyle="#555566";for(let a=0;a<=e;a+=n)for(let i=0;i<=t;i+=n)s.beginPath(),s.arc(a,i,8,0,Math.PI*2),s.fill(),s.fillStyle="#666677",s.beginPath(),s.arc(a-2,i-2,4,0,Math.PI*2),s.fill(),s.fillStyle="#555566"}function XO(s,e,t){s.fillStyle="#1a2530",s.fillRect(0,0,e,t);const n=30,a=n*Math.sqrt(3);for(let i=-1;i<t/a+1;i++)for(let o=-1;o<e/(n*1.5)+1;o++){const l=o*n*1.5,c=i*a+(o%2===0?0:a/2),d=30+Math.random()*20;s.fillStyle=`rgb(${d}, ${d+20}, ${d+40})`,s.beginPath();for(let m=0;m<6;m++){const p=Math.PI/3*m+Math.PI/6,f=l+Math.cos(p)*(n-2),b=c+Math.sin(p)*(n-2);m===0?s.moveTo(f,b):s.lineTo(f,b)}if(s.closePath(),s.fill(),s.strokeStyle="rgba(80, 150, 200, 0.5)",s.lineWidth=2,s.stroke(),Math.random()>.85){const m=s.createRadialGradient(l,c,0,l,c,n);m.addColorStop(0,"rgba(100, 200, 255, 0.3)"),m.addColorStop(1,"transparent"),s.fillStyle=m,s.fill()}}}function ZO(s,e,t){s.fillStyle="#0a1a0f",s.fillRect(0,0,e,t),s.strokeStyle="#00ff66",s.lineWidth=2,s.shadowColor="#00ff66",s.shadowBlur=4;for(let n=20;n<t;n+=40){s.beginPath();let a=0;for(s.moveTo(a,n);a<e;){const i=20+Math.random()*60;if(a+=i,s.lineTo(a,n),Math.random()>.7&&a<e-40){const o=n+(Math.random()>.5?20:-20);s.lineTo(a,o),s.lineTo(a+20,o),a+=20}}s.stroke()}for(let n=20;n<e;n+=40)if(Math.random()>.5){s.beginPath(),s.moveTo(n,0);let a=0;for(;a<t;){const i=20+Math.random()*60;if(a+=i,s.lineTo(n,a),Math.random()>.7&&a<t-40){const o=n+(Math.random()>.5?20:-20);s.lineTo(o,a),s.lineTo(o,a+20),a+=20,s.lineTo(n,a)}}s.stroke()}s.shadowBlur=0,s.fillStyle="#111";for(let n=0;n<6;n++){const a=50+Math.random()*(e-100),i=50+Math.random()*(t-100),o=30+Math.random()*40,l=20+Math.random()*30;s.fillRect(a-o/2,i-l/2,o,l),s.fillStyle="#888";for(let c=0;c<o;c+=8)s.fillRect(a-o/2+c,i-l/2-4,4,4),s.fillRect(a-o/2+c,i+l/2,4,4);s.fillStyle="#111"}s.fillStyle="#997700";for(let n=0;n<50;n++){const a=Math.random()*e,i=Math.random()*t;s.beginPath(),s.arc(a,i,4,0,Math.PI*2),s.fill()}}function QO(s,e,t){const n=e/2,a=t/2;s.fillStyle="#2E4F2C",s.fillRect(0,0,e,t);for(let w=0;w<6e3;w++){const k=Math.random()*e,S=Math.random()*t,j=Math.random()>.5;s.fillStyle=j?"rgba(30, 50, 28, 0.3)":"rgba(55, 90, 52, 0.12)",s.fillRect(k,S,2,4)}const i=e*.05,o=30;s.strokeStyle="#ffffff",s.lineWidth=6,s.beginPath(),s.roundRect(i,i,e-i*2,t-i*2,o),s.stroke(),s.lineWidth=4,s.beginPath(),s.moveTo(i,a),s.lineTo(e-i,a),s.stroke();const l=Math.min(e,t)*.2;s.beginPath(),s.arc(n,a,l,0,Math.PI*2),s.stroke();const c=l*.6;s.fillStyle="#cc3333",s.beginPath(),s.arc(n,a,c,Math.PI,0),s.closePath(),s.fill(),s.fillStyle="#f0f0f0",s.beginPath(),s.arc(n,a,c,0,Math.PI),s.closePath(),s.fill(),s.fillStyle="#1a1a1a",s.fillRect(n-c,a-5,c*2,10),s.strokeStyle="#1a1a1a",s.lineWidth=4,s.beginPath(),s.arc(n,a,c,0,Math.PI*2),s.stroke();const d=c*.28;s.fillStyle="#f0f0f0",s.beginPath(),s.arc(n,a,d,0,Math.PI*2),s.fill(),s.strokeStyle="#1a1a1a",s.lineWidth=4,s.stroke(),s.fillStyle="#ffffff",s.beginPath(),s.arc(n,a,d*.5,0,Math.PI*2),s.fill();const m=e*.08,p=t*.05,f=l+t*.08;s.strokeStyle="#ffffff",s.lineWidth=3,s.strokeRect(n-m/2,a-f-p,m,p),s.strokeRect(n-m/2,a+f,m,p);const b=e*.05,x=i+15;s.lineWidth=3,s.beginPath(),s.moveTo(x,x+b),s.lineTo(x,x),s.lineTo(x+b,x),s.stroke(),s.beginPath(),s.moveTo(e-x-b,x),s.lineTo(e-x,x),s.lineTo(e-x,x+b),s.stroke(),s.beginPath(),s.moveTo(x,t-x-b),s.lineTo(x,t-x),s.lineTo(x+b,t-x),s.stroke(),s.beginPath(),s.moveTo(e-x-b,t-x),s.lineTo(e-x,t-x),s.lineTo(e-x,t-x-b),s.stroke()}function JO(s){const e=new Fn;e.name="galacticFloor";const t=[];eI(e);const n=tI(e);return nI(e,t),aI(e),sI(e),s.add(e),console.log("[Battlefield] Galactic group added to scene:",e),{group:e,stars:n,nebulas:t,time:0}}function eI(s){const e=document.createElement("canvas"),t=e.getContext("2d");e.width=2048,e.height=2048;const n=t.createRadialGradient(1024,1024,0,1024,1024,1024);n.addColorStop(0,"#2a1050"),n.addColorStop(.2,"#1a0a40"),n.addColorStop(.5,"#0d0525"),n.addColorStop(.8,"#060215"),n.addColorStop(1,"#020108"),t.fillStyle=n,t.fillRect(0,0,2048,2048),t.save(),t.translate(1024,1024);for(let m=0;m<3;m++){const p=m/3*Math.PI*2;t.save(),t.rotate(p);for(let f=0;f<1500;f++){const b=f/1500*800,x=b*.012,w=b*.15,k=Math.cos(x)*b+(Math.random()-.5)*w,S=Math.sin(x)*b+(Math.random()-.5)*w,j=1-b/800*.6,C=(1-b/800)*4+Math.random()*3,N=Math.floor(220*j+35),P=Math.floor(200*j+55),_=Math.floor(255);if(t.fillStyle=`rgba(${N}, ${P}, ${_}, ${j})`,t.beginPath(),t.arc(k,S,C,0,Math.PI*2),t.fill(),j>.7&&Math.random()>.5){const L=t.createRadialGradient(k,S,0,k,S,C*3);L.addColorStop(0,`rgba(${N}, ${P}, ${_}, 0.6)`),L.addColorStop(1,"transparent"),t.fillStyle=L,t.beginPath(),t.arc(k,S,C*3,0,Math.PI*2),t.fill()}}t.restore()}const a=t.createRadialGradient(0,0,0,0,0,200);a.addColorStop(0,"rgba(255, 255, 255, 1)"),a.addColorStop(.1,"rgba(255, 240, 220, 0.95)"),a.addColorStop(.3,"rgba(255, 200, 150, 0.7)"),a.addColorStop(.6,"rgba(200, 150, 255, 0.4)"),a.addColorStop(1,"transparent"),t.fillStyle=a,t.beginPath(),t.arc(0,0,200,0,Math.PI*2),t.fill(),t.restore();for(let m=0;m<1e3;m++){const p=Math.random()*2048,f=Math.random()*2048,b=.5+Math.random()*2.5,x=150+Math.random()*105,w=Math.random();let k,S,j;if(w<.6?(k=x,S=x,j=255):w<.8?(k=255,S=x,j=x*.7):(k=255,S=x*.6,j=x),t.fillStyle=`rgba(${k}, ${S}, ${j}, 1)`,t.beginPath(),t.arc(p,f,b,0,Math.PI*2),t.fill(),Math.random()>.85){const C=t.createRadialGradient(p,f,0,p,f,b*6);C.addColorStop(0,`rgba(${k}, ${S}, ${j}, 0.7)`),C.addColorStop(.5,`rgba(${k}, ${S}, ${j}, 0.2)`),C.addColorStop(1,"transparent"),t.fillStyle=C,t.beginPath(),t.arc(p,f,b*6,0,Math.PI*2),t.fill()}}const i=["#ff00ff","#00ffff","#ff6600","#6600ff"];for(let m=0;m<8;m++){const p=300+Math.random()*1448,f=300+Math.random()*1448,b=100+Math.random()*200,x=i[m%i.length],w=t.createRadialGradient(p,f,0,p,f,b);w.addColorStop(0,x+"40"),w.addColorStop(.5,x+"15"),w.addColorStop(1,"transparent"),t.fillStyle=w,t.beginPath(),t.arc(p,f,b,0,Math.PI*2),t.fill()}const o=new ss(e);o.colorSpace=ii;const l=new pr(30,30),c=new Ke({map:o,side:Ts}),d=new De(l,c);d.rotation.x=-Math.PI/2,d.position.y=.01,d.name="galaxyPlane",d.receiveShadow=!0,s.add(d),console.log("[Battlefield] Galaxy plane created:",d.position)}function tI(s){const e=new Wa,t=500,n=new Float32Array(t*3),a=new Float32Array(t*3);for(let l=0;l<t;l++){const c=Math.random()*Math.PI*2,d=Math.random()*14;n[l*3]=Math.cos(c)*d,n[l*3+1]=.05+Math.random()*.3,n[l*3+2]=Math.sin(c)*d;const m=Math.random();m<.4?(a[l*3]=.9,a[l*3+1]=.9,a[l*3+2]=1):m<.6?(a[l*3]=1,a[l*3+1]=.8,a[l*3+2]=.4):m<.8?(a[l*3]=1,a[l*3+1]=.4,a[l*3+2]=.8):(a[l*3]=.4,a[l*3+1]=1,a[l*3+2]=1)}e.setAttribute("position",new ri(n,3)),e.setAttribute("color",new ri(a,3));const i=new pm({size:.15,transparent:!0,opacity:.9,vertexColors:!0,blending:rl,depthWrite:!1}),o=new wd(e,i);return o.name="galacticStars",o.renderOrder=5,s.add(o),o}function nI(s,e){const t=[16711935,65535,16737792,6684927,65382];for(let n=0;n<4;n++){const a=document.createElement("canvas"),i=a.getContext("2d");a.width=256,a.height=256;const o=i.createRadialGradient(128,128,0,128,128,128);o.addColorStop(0,"rgba(255, 255, 255, 0.6)"),o.addColorStop(.3,"rgba(255, 255, 255, 0.3)"),o.addColorStop(.6,"rgba(255, 255, 255, 0.1)"),o.addColorStop(1,"transparent"),i.fillStyle=o,i.fillRect(0,0,256,256);const l=new ss(a),c=6+Math.random()*6,d=new pr(c,c),m=new Ke({map:l,color:t[n%t.length],transparent:!0,opacity:.25,blending:rl,depthWrite:!1,side:Ts}),p=new De(d,m);p.rotation.x=-Math.PI/2,p.position.set((Math.random()-.5)*20,.03+n*.01,(Math.random()-.5)*20),p.name=`nebula_${n}`,p.renderOrder=2+n,e.push(p),s.add(p)}}function sI(s){const e=new Wa,t=150,n=new Float32Array(t*3);for(let o=0;o<t;o++){const l=Math.random()*Math.PI*2,c=Math.random()*14;n[o*3]=Math.cos(l)*c,n[o*3+1]=.1+Math.random()*2,n[o*3+2]=Math.sin(l)*c}e.setAttribute("position",new ri(n,3));const a=new pm({size:.15,color:8947967,transparent:!0,opacity:.5,blending:rl,depthWrite:!1}),i=new wd(e,a);i.name="cosmicDust",s.add(i)}function aI(s){const e=new il(14.5,15.5,64),t=new Ke({color:4491519,transparent:!0,opacity:.6,side:Ts,blending:rl}),n=new De(e,t);n.rotation.x=-Math.PI/2,n.position.y=.02,n.name="portalRim",s.add(n);const a=new il(13.5,14.5,64),i=new Ke({color:8930559,transparent:!0,opacity:.3,side:Ts,blending:rl}),o=new De(a,i);o.rotation.x=-Math.PI/2,o.position.y=.01,o.name="portalInnerRim",s.add(o)}function Pj(s,e,t){e&&(e.group.traverse(n=>{var a,i;n instanceof De?((a=n.geometry)==null||a.dispose(),n.material instanceof hr?t(n.material):Array.isArray(n.material)&&n.material.forEach(o=>t(o))):n instanceof wd&&((i=n.geometry)==null||i.dispose(),n.material instanceof hr&&n.material.dispose())}),s.remove(e.group))}function iI(s,e){s.time+=e;const t=s.group.getObjectByName("galaxyPlane");t&&(t.rotation.z=s.time*.02),s.nebulas.forEach((o,l)=>{o.rotation.z+=e*.03*(l%2===0?1:-1),o.position.x+=Math.sin(s.time*.2+l*2)*e*.1,o.position.z+=Math.cos(s.time*.15+l*2)*e*.1,Math.abs(o.position.x)>12&&(o.position.x*=.9),Math.abs(o.position.z)>12&&(o.position.z*=.9);const c=o.material;c.opacity=.15+Math.sin(s.time*.5+l)*.1});const n=s.group.getObjectByName("portalRim");if(n){const o=n.material;o.opacity=.5+Math.sin(s.time*2)*.3}const a=s.group.getObjectByName("portalInnerRim");if(a){const o=a.material;o.opacity=.3+Math.sin(s.time*3+1)*.2}const i=s.group.getObjectByName("cosmicDust");if(i){const o=i.geometry.attributes.position.array;for(let l=0;l<o.length;l+=3)if(o[l+1]+=e*.15,o[l+1]>3){o[l+1]=.1;const c=Math.random()*Math.PI*2,d=Math.random()*14;o[l]=Math.cos(c)*d,o[l+2]=Math.sin(c)*d}i.geometry.attributes.position.needsUpdate=!0}if(s.stars){const o=s.stars.material;o.opacity=.7+Math.sin(s.time*4)*.2,s.stars.rotation.y=s.time*.01}}const Rj=new gt,Lj=new gt;function Oj(){return{phase:"dawn",sunPosition:new gt(50,10,-60),moonPosition:new gt(-40,15,-50),ambientColor:10075101,ambientIntensity:.6,hemiSkyColor:6724044,hemiGroundColor:4478310,hemiIntensity:.75,mainLightColor:12312063,mainLightIntensity:1.1,fogColor:4487082,fogDensity:.008,skyColor:3368618,starsOpacity:.2,moonOpacity:.3,sunOpacity:.9,lampIntensity:.5,windowEmissive:.3}}function Ij(){return{phase:"dusk",sunPosition:new gt(-50,8,-60),moonPosition:new gt(40,12,-50),ambientColor:7833787,ambientIntensity:.55,hemiSkyColor:4482747,hemiGroundColor:3359829,hemiIntensity:.65,mainLightColor:10075118,mainLightIntensity:.9,fogColor:2245802,fogDensity:.01,skyColor:2245802,starsOpacity:.3,moonOpacity:.4,sunOpacity:.8,lampIntensity:1.5,windowEmissive:.5}}function ob(){return{phase:"night",sunPosition:new gt(30,-20,-50),moonPosition:new gt(-30,35,-50),ambientColor:5596842,ambientIntensity:.5,hemiSkyColor:3359863,hemiGroundColor:2236996,hemiIntensity:.6,mainLightColor:13426175,mainLightIntensity:.9,fogColor:662058,fogDensity:.012,skyColor:662058,starsOpacity:.9,moonOpacity:1,sunOpacity:0,lampIntensity:2.5,windowEmissive:.8}}function lb(){return{phase:"day",sunPosition:new gt(30,50,-30),moonPosition:new gt(-30,-20,-50),ambientColor:16777215,ambientIntensity:.85,hemiSkyColor:5939433,hemiGroundColor:5596791,hemiIntensity:1,mainLightColor:16777198,mainLightIntensity:1.5,fogColor:6990048,fogDensity:.005,skyColor:4886745,starsOpacity:0,moonOpacity:0,sunOpacity:1,lampIntensity:0,windowEmissive:.1}}function qh(s,e,t,n){const a=(o,l)=>o+(l-o)*t,i=(o,l)=>{const c=o>>16&255,d=o>>8&255,m=o&255,p=l>>16&255,f=l>>8&255,b=l&255,x=Math.round(a(c,p)),w=Math.round(a(d,f)),k=Math.round(a(m,b));return x<<16|w<<8|k};return Rj.lerpVectors(s.sunPosition,e.sunPosition,t),Lj.lerpVectors(s.moonPosition,e.moonPosition,t),{phase:n,sunPosition:Rj,moonPosition:Lj,ambientColor:i(s.ambientColor,e.ambientColor),ambientIntensity:a(s.ambientIntensity,e.ambientIntensity),hemiSkyColor:i(s.hemiSkyColor,e.hemiSkyColor),hemiGroundColor:i(s.hemiGroundColor,e.hemiGroundColor),hemiIntensity:a(s.hemiIntensity,e.hemiIntensity),mainLightColor:i(s.mainLightColor,e.mainLightColor),mainLightIntensity:a(s.mainLightIntensity,e.mainLightIntensity),fogColor:i(s.fogColor,e.fogColor),fogDensity:a(s.fogDensity,e.fogDensity),skyColor:i(s.skyColor,e.skyColor),starsOpacity:a(s.starsOpacity,e.starsOpacity),moonOpacity:a(s.moonOpacity,e.moonOpacity),sunOpacity:a(s.sunOpacity,e.sunOpacity),lampIntensity:a(s.lampIntensity,e.lampIntensity),windowEmissive:a(s.windowEmissive,e.windowEmissive)}}function rI(s){if(s>=5&&s<6){const e=s-5;return qh(ob(),Oj(),e,"dawn")}else if(s>=6&&s<7){const e=s-6;return qh(Oj(),lb(),e,"dawn")}else{if(s>=7&&s<18)return lb();if(s>=18&&s<19.5){const e=(s-18)/1.5;return qh(lb(),Ij(),e,"dusk")}else if(s>=19.5&&s<21){const e=(s-19.5)/1.5;return qh(Ij(),ob(),e,"dusk")}else return ob()}}function oI(){const s=document.createElement("canvas"),e=s.getContext("2d");s.width=512,s.height=512;const t=256,n=256,a=e.createRadialGradient(t,n,50,t,n,256);a.addColorStop(0,"rgba(255, 255, 200, 1)"),a.addColorStop(.2,"rgba(255, 240, 150, 0.8)"),a.addColorStop(.4,"rgba(255, 220, 100, 0.4)"),a.addColorStop(.7,"rgba(255, 200, 80, 0.1)"),a.addColorStop(1,"rgba(255, 180, 50, 0)"),e.fillStyle=a,e.fillRect(0,0,512,512);const i=e.createRadialGradient(t,n,0,t,n,80);i.addColorStop(0,"rgba(255, 255, 255, 1)"),i.addColorStop(.5,"rgba(255, 255, 220, 1)"),i.addColorStop(1,"rgba(255, 240, 150, 0.8)"),e.fillStyle=i,e.beginPath(),e.arc(t,n,80,0,Math.PI*2),e.fill(),e.beginPath(),e.arc(t,n,60,0,Math.PI*2),e.fillStyle="#ffffee",e.fill();const o=new ss(s),l=new Xn({map:o,transparent:!0,depthWrite:!1,blending:rl}),c=new Un(l);return c.position.set(30,50,-30),c.scale.set(50,50,1),c.name="sun",c.visible=!1,c}function lI(){const s=document.createElement("canvas"),e=s.getContext("2d");s.width=512,s.height=512;const t=256,n=256,a=e.createRadialGradient(t,n,60,t,n,256);a.addColorStop(0,"rgba(200, 220, 255, 1)"),a.addColorStop(.2,"rgba(180, 200, 240, 0.8)"),a.addColorStop(.4,"rgba(150, 180, 220, 0.5)"),a.addColorStop(.7,"rgba(120, 150, 200, 0.2)"),a.addColorStop(1,"rgba(100, 130, 180, 0)"),e.fillStyle=a,e.fillRect(0,0,512,512);const i=e.createRadialGradient(t,n,0,t,n,100);i.addColorStop(0,"rgba(255, 255, 255, 1)"),i.addColorStop(.5,"rgba(230, 240, 255, 0.9)"),i.addColorStop(1,"rgba(200, 220, 255, 0.3)"),e.fillStyle=i,e.beginPath(),e.arc(t,n,100,0,Math.PI*2),e.fill(),e.beginPath(),e.arc(t,n,70,0,Math.PI*2),e.fillStyle="#e8eeff",e.fill(),e.fillStyle="rgba(180, 190, 210, 0.6)",e.beginPath(),e.arc(t-25,n-20,18,0,Math.PI*2),e.fill(),e.beginPath(),e.arc(t+25,n+15,12,0,Math.PI*2),e.fill(),e.beginPath(),e.arc(t-5,n+30,10,0,Math.PI*2),e.fill();const o=new ss(s),l=new Xn({map:o,transparent:!0,depthWrite:!1,blending:rl}),c=new Un(l);return c.position.set(-30,35,-50),c.scale.set(40,40,1),c.name="moon",c}function cI(s=1){const e=new Fn,t=new dt({color:16777215,transparent:!0,opacity:.85,roughness:1,metalness:0,depthWrite:!1}),n=new Yt(1,16,12);return[{x:0,y:0,z:0,scale:1.2},{x:-1,y:.1,z:.2,scale:1},{x:1,y:.15,z:-.1,scale:1.1},{x:-.5,y:.3,z:.4,scale:.8},{x:.6,y:.35,z:.3,scale:.9},{x:-1.5,y:-.1,z:0,scale:.7},{x:1.5,y:-.05,z:.1,scale:.75},{x:0,y:.4,z:0,scale:.7}].forEach(i=>{const o=new De(n,t);o.position.set(i.x*s,i.y*s,i.z*s),o.scale.setScalar(i.scale*s),e.add(o)}),e.userData.material=t,e}function uI(){const s=new Fn;s.name="clouds";const e=[];return[{x:-25,y:35,z:-20,scale:3.5,speed:.8},{x:15,y:40,z:-35,scale:4,speed:1},{x:-40,y:38,z:10,scale:3,speed:.9},{x:30,y:42,z:15,scale:3.8,speed:1.1},{x:0,y:36,z:-45,scale:3.2,speed:.85},{x:-15,y:44,z:30,scale:2.8,speed:1.05},{x:45,y:37,z:-10,scale:3.6,speed:.95},{x:-35,y:41,z:-30,scale:2.5,speed:1.15}].forEach((n,a)=>{const i=cI(n.scale);i.position.set(n.x,n.y,n.z),i.userData.baseX=n.x,i.userData.speed=n.speed,i.userData.index=a,s.add(i),e.push(i)}),{group:s,clouds:e,time:0}}function dI(s,e){s.time+=e,s.clouds.forEach(t=>{const n=t.userData.baseX,a=t.userData.speed,i=t.userData.index,o=60,l=.015*a,c=i*.7,d=Math.sin(s.time*l+c)*o*.5;t.position.x=n+d;const m=.3*a,p=.5;t.position.y+=Math.sin(s.time*m+c)*p*e})}function hI(s,e){s.clouds.forEach(t=>{const n=t.userData.material;n&&(n.opacity=e*.85)})}function pI(){const s=new Wa,e=300,t=new Float32Array(e*3);for(let i=0;i<e;i++){const o=Math.random()*Math.PI*2,l=Math.random()*Math.PI*.5,c=80+Math.random()*40;t[i*3]=c*Math.sin(l)*Math.cos(o),t[i*3+1]=c*Math.cos(l)+20,t[i*3+2]=c*Math.sin(l)*Math.sin(o)}s.setAttribute("position",new ri(t,3));const n=new pm({color:16777215,size:.5,transparent:!0,opacity:.8}),a=new wd(s,n);return a.name="stars",a}function mI(s){const t=s/2+5;return[{x:-t,z:-t+2,scale:1.2},{x:-t+2,z:-t,scale:1.4},{x:t,z:-t+2,scale:1.3},{x:t-2,z:-t,scale:1},{x:-t,z:t-2,scale:1.1},{x:-t+2,z:t,scale:1.5},{x:t,z:t-2,scale:1.25},{x:t-2,z:t,scale:1.35}]}function fI(s){const e=s/2,t=e+3,n=e*.5;return[{x:-t,z:-n},{x:-t,z:0},{x:-t,z:n},{x:t,z:-n},{x:t,z:0},{x:t,z:n},{x:-n,z:-t},{x:0,z:-t},{x:n,z:-t},{x:-n,z:t},{x:0,z:t},{x:n,z:t},{x:-t-5,z:n+2},{x:-t-8,z:n+5}]}function gI(s){const e=s/2+2;return[{x:-e,z:-e},{x:e,z:-e},{x:-e,z:e},{x:e,z:e}]}function Bj(s,e=_x){const t=bI(s,e),n=yI(s,e),{house:a,windowMaterials:i}=xI(s,e),{lamps:o,lampLights:l}=vI(s,e);return{trees:t,bushes:n,house:a,lamps:o,lampLights:l,windowMaterials:i}}function bI(s,e){const t=new Fn;t.name="trees_instanced";const n=mI(e),a=n.length,i=new dt({color:4863784,roughness:.9}),o=new dt({color:2972199,roughness:.8}),l=new Gn(.3,.5,3,8),c=new Yt(2,8,6),d=new Yt(1.5,8,6),m=new ur(l,i,a),p=new ur(c,o,a),f=new ur(d,o,a);m.castShadow=!0,m.receiveShadow=!0,p.castShadow=!0,f.castShadow=!0,m.name="trees_trunks",p.name="trees_foliage1",f.name="trees_foliage2";const b=new sl,x=new gt,w=new al,k=new gt;return n.forEach((S,j)=>{const C=S.scale,N=Math.random()*Math.PI*2;x.set(S.x,1.5*C,S.z),w.setFromEuler(new FA(0,N,0)),k.set(C,C,C),b.compose(x,w,k),m.setMatrixAt(j,b),x.set(S.x,4*C,S.z),k.set(C,C*.8,C),b.compose(x,w,k),p.setMatrixAt(j,b),x.set(S.x,5.5*C,S.z),k.set(C,C,C),b.compose(x,w,k),f.setMatrixAt(j,b)}),m.instanceMatrix.needsUpdate=!0,p.instanceMatrix.needsUpdate=!0,f.instanceMatrix.needsUpdate=!0,t.add(m),t.add(p),t.add(f),s.add(t),t}function yI(s,e){const t=fI(e),n=[],a=f=>{const b=Math.sin(f)*1e4;return b-Math.floor(b)};t.forEach((f,b)=>{const x=2+Math.floor(a(b*100)*2);for(let w=0;w<x;w++){const k=b*100+w,S=.6+a(k)*.4,j=(a(k+1)-.5)*.8,C=(a(k+2)-.5)*.8,N=.7+a(k+3)*.2;n.push({x:f.x+j,y:S*.7,z:f.z+C,scaleX:S,scaleY:S*N,scaleZ:S})}});const i=new dt({color:4024887,roughness:.85}),o=new Yt(1,8,6),l=new ur(o,i,n.length);l.castShadow=!0,l.receiveShadow=!0,l.name="bushes_instanced";const c=new sl,d=new gt,m=new al,p=new gt;return n.forEach((f,b)=>{d.set(f.x,f.y,f.z),m.identity(),p.set(f.scaleX,f.scaleY,f.scaleZ),c.compose(d,m,p),l.setMatrixAt(b,c)}),l.instanceMatrix.needsUpdate=!0,s.add(l),l}function xI(s,e){const t=new Fn,n=[],a=new un(6,4,5),i=new dt({color:13935988,roughness:.8}),o=new De(a,i);o.position.y=2,o.castShadow=!0,o.receiveShadow=!0,t.add(o);const l=new bc(5,3,4),c=new dt({color:9127187,roughness:.7}),d=new De(l,c);d.position.y=5.5,d.rotation.y=Math.PI/4,d.castShadow=!0,t.add(d);const m=new un(1.2,2,.1),p=new dt({color:6045747,roughness:.6}),f=new De(m,p);f.position.set(0,1,2.55),t.add(f);const b=new un(.8,.8,.1),x=new dt({color:16777130,emissive:16755268,emissiveIntensity:.5,roughness:.3});n.push(x);const w=new De(b,x);w.position.set(-1.5,2.5,2.55),t.add(w);const k=new De(b,x);k.position.set(1.5,2.5,2.55),t.add(k);const S=new un(.8,2,.8),j=new dt({color:9127187,roughness:.8}),C=new De(S,j);C.position.set(1.5,6,-1),C.castShadow=!0,t.add(C);const N=e/2;return t.position.set(-N-5,0,N-5),t.rotation.y=Math.PI/6,t.name="house",s.add(t),{house:t,windowMaterials:n}}function vI(s,e){const t=new Fn;t.name="lamps_instanced";const n=[],a=gI(e),i=a.length,o=new dt({color:3355443,roughness:.5,metalness:.5}),l=new dt({color:2236962,roughness:.4,metalness:.6}),c=new dt({color:16772778,emissive:16755268,emissiveIntensity:2,roughness:.2}),d=new Gn(.1,.15,5,8),m=new Gn(.05,.05,1,8),p=new Gn(.4,.3,.6,8),f=new Yt(.25,8,8),b=new ur(d,o,i),x=new ur(m,o,i),w=new ur(p,l,i),k=new ur(f,c,i);b.castShadow=!0,b.name="lamps_poles",x.name="lamps_arms",w.name="lamps_housings",k.name="lamps_bulbs";const S=new sl,j=new gt,C=new al,N=new gt(1,1,1);return a.forEach((P,_)=>{j.set(P.x,2.5,P.z),C.identity(),S.compose(j,C,N),b.setMatrixAt(_,S),j.set(P.x+.4,4.8,P.z),C.setFromEuler(new FA(0,0,Math.PI/2)),S.compose(j,C,N),x.setMatrixAt(_,S),j.set(P.x+.8,4.8,P.z),C.identity(),S.compose(j,C,N),w.setMatrixAt(_,S),j.set(P.x+.8,4.5,P.z),S.compose(j,C,N),k.setMatrixAt(_,S);const L=new PA(16755285,1.5,15);L.position.set(P.x,5,P.z),n.push(L),s.add(L)}),b.instanceMatrix.needsUpdate=!0,x.instanceMatrix.needsUpdate=!0,w.instanceMatrix.needsUpdate=!0,k.instanceMatrix.needsUpdate=!0,t.add(b),t.add(x),t.add(w),t.add(k),s.add(t),{lamps:t,lampLights:n}}function zj(s,e=_x){const t=e*1.5,n=new pr(t,t),a=new dt({color:2972199,roughness:.9,metalness:0}),i=new De(n,a);return i.rotation.x=-Math.PI/2,i.position.y=-.05,i.receiveShadow=!0,i.name="grass",s.add(i),i}class wI{constructor(e){U(this,"scene");U(this,"ground",null);U(this,"gridHelper",null);U(this,"sun",null);U(this,"moon",null);U(this,"stars",null);U(this,"ambientLight",null);U(this,"hemiLight",null);U(this,"mainLight",null);U(this,"fillLight",null);U(this,"lampLights",[]);U(this,"windowMaterials",[]);U(this,"trees",null);U(this,"bushes",null);U(this,"house",null);U(this,"lamps",null);U(this,"grass",null);U(this,"baseFogDensity",.01);U(this,"brightness",1);U(this,"skyColorOverride",null);U(this,"currentFloorStyle","concrete");U(this,"galacticState",null);U(this,"cloudState",null);U(this,"cloudsVisible",!0);U(this,"debugHourOverride",null);U(this,"tempColor",new Gt);U(this,"currentSize",_x);U(this,"terrainVisibility",{trees:!0,bushes:!0,house:!0,lamps:!0,grass:!0});this.scene=e}setGridVisible(e){this.gridHelper&&(this.gridHelper.visible=e)}create(){this.createGround(),this.grass=zj(this.scene,this.currentSize),this.createGrid(),this.sun=oI(),this.scene.add(this.sun),this.moon=lI(),this.scene.add(this.moon),this.stars=pI(),this.scene.add(this.stars),this.cloudState=uI(),this.scene.add(this.cloudState.group);const e=Bj(this.scene,this.currentSize);this.trees=e.trees,this.bushes=e.bushes,this.house=e.house,this.lamps=e.lamps,this.lampLights=e.lampLights,this.windowMaterials=e.windowMaterials,this.createLighting(),this.createFog(),this.updateTimeOfDay()}updateTimeOfDay(){const e=rI(this.getCurrentHour());this.applyTimeConfig(e)}getCurrentHour(){if(this.debugHourOverride!==null)return this.debugHourOverride;const e=new Date;return e.getHours()+e.getMinutes()/60}setDebugTime(e){this.debugHourOverride=e,this.updateTimeOfDay(),console.log(`[Battlefield] Time set to: ${e!==null?`${e}:00`:"real time"}`)}setTimeMode(e){const n={auto:null,day:12,night:23,dawn:6,dusk:19.5}[e]??null;this.debugHourOverride=n,this.updateTimeOfDay(),console.log(`[Battlefield] Time mode set to: ${e} (${n!==null?`${n}:00`:"real time"})`)}setTerrainConfig(e){e.battlefieldSize!==void 0&&e.battlefieldSize!==this.currentSize&&this.resizeBattlefield(e.battlefieldSize),this.terrainVisibility={trees:e.showTrees,bushes:e.showBushes,house:e.showHouse,lamps:e.showLamps,grass:e.showGrass},this.trees&&(this.trees.visible=e.showTrees),this.bushes&&(this.bushes.visible=e.showBushes),this.house&&(this.house.visible=e.showHouse),this.lamps&&(this.lamps.visible=e.showLamps),this.lampLights.forEach(t=>{t.visible=e.showLamps}),this.grass&&(this.grass.visible=e.showGrass),e.showClouds!==void 0&&(this.cloudsVisible=e.showClouds,this.cloudState&&(this.cloudState.group.visible=e.showClouds)),this.baseFogDensity=e.fogDensity*.008,e.brightness!==void 0&&(this.brightness=e.brightness),e.skyColor!==void 0&&(this.skyColorOverride=e.skyColor),this.updateTimeOfDay()}resizeBattlefield(e){this.currentSize=e,console.log(`[Battlefield] Resizing to ${e}x${e}`),this.ground&&(this.ground.geometry.dispose(),this.disposeMaterial(this.ground.material),this.scene.remove(this.ground),this.ground=null),this.createGround(),this.setFloorStyle(this.currentFloorStyle,!0),this.gridHelper&&(this.gridHelper.geometry.dispose(),this.gridHelper.material instanceof hr&&this.gridHelper.material.dispose(),this.scene.remove(this.gridHelper),this.gridHelper=null),this.createGrid(),this.grass&&(this.grass.geometry.dispose(),this.disposeMaterial(this.grass.material),this.scene.remove(this.grass)),this.grass=zj(this.scene,this.currentSize),this.grass.visible=this.terrainVisibility.grass,this.disposeTerrainElements();const t=Bj(this.scene,this.currentSize);if(this.trees=t.trees,this.bushes=t.bushes,this.house=t.house,this.lamps=t.lamps,this.lampLights=t.lampLights,this.windowMaterials=t.windowMaterials,this.trees&&(this.trees.visible=this.terrainVisibility.trees),this.bushes&&(this.bushes.visible=this.terrainVisibility.bushes),this.house&&(this.house.visible=this.terrainVisibility.house),this.lamps&&(this.lamps.visible=this.terrainVisibility.lamps),this.lampLights.forEach(n=>{n.visible=this.terrainVisibility.lamps}),this.mainLight){const n=this.currentSize*.6;this.mainLight.shadow.camera.left=-n,this.mainLight.shadow.camera.right=n,this.mainLight.shadow.camera.top=n,this.mainLight.shadow.camera.bottom=-n,this.mainLight.shadow.camera.updateProjectionMatrix()}}disposeTerrainElements(){this.trees&&(this.disposeGroup(this.trees),this.scene.remove(this.trees),this.trees=null),this.bushes&&(this.bushes.geometry.dispose(),this.bushes.material.dispose(),this.scene.remove(this.bushes),this.bushes=null),this.house&&(this.disposeGroup(this.house),this.scene.remove(this.house),this.house=null),this.lamps&&(this.disposeGroup(this.lamps),this.scene.remove(this.lamps),this.lamps=null);for(const e of this.lampLights)this.scene.remove(e),e.dispose();this.lampLights=[],this.windowMaterials=[]}setFloorStyle(e,t=!1){if(this.currentFloorStyle===e&&!t)return;const n=this.currentFloorStyle;if(this.currentFloorStyle=e,typeof window<"u"&&window.__TIDE_MEMORY_DEBUG__&&console.log(`[Battlefield] Memory: Switching floor from ${n} to ${e}`),n==="galactic"&&(Pj(this.scene,this.galacticState,this.disposeMaterial.bind(this)),this.galacticState=null,this.ground&&(this.ground.visible=!0)),this.ground){const a=this.ground.material;if(e==="galactic")console.log("[Battlefield] Creating galactic floor..."),this.ground.visible=!1,this.galacticState=JO(this.scene),console.log("[Battlefield] Galactic elements created");else{this.ground.visible=!0,a.transparent=!1,a.opacity=1,a.side=BA,a.depthWrite=!0,this.ground.renderOrder=0;const i=a.map;if(e==="none")a.map=null,a.color.setHex(2972199),a.roughness=.9,a.metalness=0,a.emissive.setHex(0),a.emissiveIntensity=0,a.needsUpdate=!0;else{const o=Dj(e);o.wrapS=Wo,o.wrapT=Wo;const l=e==="pokemon-stadium"?1:Math.round(this.currentSize/5);o.repeat.set(l,l),a.map=o,a.needsUpdate=!0}switch(i&&(i.dispose(),typeof window<"u"&&window.__TIDE_MEMORY_DEBUG__&&console.log("[Battlefield] Memory: Disposed old floor texture")),e){case"none":break;case"metal":a.color.setHex(8947865),a.roughness=.4,a.metalness=.8,a.emissive.setHex(0),a.emissiveIntensity=0;break;case"hex":a.color.setHex(4482696),a.roughness=.6,a.metalness=.4,a.emissive.setHex(1122867),a.emissiveIntensity=.2;break;case"circuit":a.color.setHex(2245683),a.roughness=.7,a.metalness=.3,a.emissive.setHex(13090),a.emissiveIntensity=.4;break;case"pokemon-stadium":a.color.setHex(11184810),a.roughness=1,a.metalness=0,a.emissive.setHex(0),a.emissiveIntensity=0;break;default:a.color.setHex(5592405),a.roughness=.8,a.metalness=.1,a.emissive.setHex(0),a.emissiveIntensity=0}}}console.log(`[Battlefield] Floor style set to: ${e}`)}updateGalacticAnimation(e){this.currentFloorStyle!=="galactic"||!this.galacticState||iI(this.galacticState,e)}updateCloudAnimation(e){!this.cloudState||!this.cloudsVisible||dI(this.cloudState,e)}disposeMaterial(e){var t;(e instanceof Ke||e instanceof dt||e instanceof Xn)&&((t=e.map)==null||t.dispose()),e.dispose()}applyTimeConfig(e){const t=this.skyColorOverride?parseInt(this.skyColorOverride.replace("#",""),16):e.skyColor;if(this.scene.background instanceof Gt?this.scene.background.setHex(t):this.scene.background=this.tempColor.setHex(t).clone(),this.scene.fog instanceof jS){const n=this.skyColorOverride?parseInt(this.skyColorOverride.replace("#",""),16):e.fogColor;this.scene.fog.color.setHex(n);const a=this.baseFogDensity>0?this.baseFogDensity/.008:0;this.scene.fog.density=e.fogDensity*a}if(this.sun&&(this.sun.position.copy(e.sunPosition),this.sun.material.opacity=e.sunOpacity,this.sun.visible=e.sunOpacity>.01),this.moon&&(this.moon.position.copy(e.moonPosition),this.moon.material.opacity=e.moonOpacity,this.moon.visible=e.moonOpacity>.01),this.stars&&(this.stars.material.opacity=e.starsOpacity,this.stars.visible=e.starsOpacity>.01),this.ambientLight&&(this.ambientLight.color.setHex(e.ambientColor),this.ambientLight.intensity=e.ambientIntensity*this.brightness),this.hemiLight&&(this.hemiLight.color.setHex(e.hemiSkyColor),this.hemiLight.groundColor.setHex(e.hemiGroundColor),this.hemiLight.intensity=e.hemiIntensity*this.brightness),this.mainLight&&(this.mainLight.color.setHex(e.mainLightColor),this.mainLight.intensity=e.mainLightIntensity*this.brightness,e.sunOpacity>e.moonOpacity?this.mainLight.position.copy(e.sunPosition):this.mainLight.position.copy(e.moonPosition)),this.lampLights.forEach(n=>{n.intensity=e.lampIntensity}),this.windowMaterials.forEach(n=>{n.emissiveIntensity=e.windowEmissive}),this.cloudState&&this.cloudsVisible){let n;switch(e.phase){case"day":n=1;break;case"dawn":case"dusk":n=.7;break;case"night":n=.2;break;default:n=1}hI(this.cloudState,n)}}getGround(){return this.ground}createGround(){const e=new pr(this.currentSize,this.currentSize),t=Dj(this.currentFloorStyle);t.wrapS=Wo,t.wrapT=Wo;const n=this.currentFloorStyle==="galactic"?1:Math.round(this.currentSize/5);t.repeat.set(n,n);const a=new dt({map:t,color:5592405,roughness:.8,metalness:.1});this.ground=new De(e,a),this.ground.rotation.x=-Math.PI/2,this.ground.receiveShadow=!0,this.ground.name="ground",this.scene.add(this.ground)}createGrid(){const e=Math.round(this.currentSize/2);this.gridHelper=new jP(this.currentSize,e,2763322,1710634),this.gridHelper.position.y=.01,this.scene.add(this.gridHelper)}createLogo(){const t=new fx().load("/assets/textures/logo-blanco.png"),n=10,a=4,i=new pr(n,a),o=new Ke({map:t,transparent:!0,opacity:.8,side:Ts,depthWrite:!1}),l=new De(i,o);l.rotation.x=-Math.PI/2,l.position.set(0,.02,0),l.name="tideLogo",this.scene.add(l)}createFog(){this.scene.fog=new jS(662058,.01),this.scene.background=new Gt(662058)}createLighting(){this.ambientLight=new xx(16777215,.6),this.scene.add(this.ambientLight),this.hemiLight=new CP(16777198,5596791,.7),this.hemiLight.position.set(0,20,0),this.scene.add(this.hemiLight),this.mainLight=new uc(16777215,1.2),this.mainLight.position.set(30,50,-30),this.mainLight.castShadow=!0,this.mainLight.shadow.mapSize.width=2048,this.mainLight.shadow.mapSize.height=2048,this.mainLight.shadow.camera.near=.5,this.mainLight.shadow.camera.far=200;const e=this.currentSize*.6;this.mainLight.shadow.camera.left=-e,this.mainLight.shadow.camera.right=e,this.mainLight.shadow.camera.top=e,this.mainLight.shadow.camera.bottom=-e,this.scene.add(this.mainLight),this.fillLight=new uc(16777215,.6),this.fillLight.position.set(-10,15,10),this.scene.add(this.fillLight);const t=new uc(11193599,.5);t.position.set(0,20,30),this.scene.add(t)}dispose(){var t,n;Pj(this.scene,this.galacticState,this.disposeMaterial.bind(this)),this.galacticState=null;const e=this.scene.getObjectByName("tideLogo");e&&((t=e.geometry)==null||t.dispose(),this.disposeMaterial(e.material),this.scene.remove(e)),this.ground&&(this.ground.geometry.dispose(),this.disposeMaterial(this.ground.material),this.scene.remove(this.ground)),this.gridHelper&&(this.gridHelper.geometry.dispose(),this.gridHelper.material instanceof hr&&this.gridHelper.material.dispose(),this.scene.remove(this.gridHelper)),this.grass&&(this.grass.geometry.dispose(),this.disposeMaterial(this.grass.material),this.scene.remove(this.grass)),this.sun&&(this.disposeMaterial(this.sun.material),this.scene.remove(this.sun)),this.moon&&(this.disposeMaterial(this.moon.material),this.scene.remove(this.moon)),this.stars&&(this.stars.geometry.dispose(),this.stars.material.dispose(),this.scene.remove(this.stars)),this.trees&&(this.disposeGroup(this.trees),this.scene.remove(this.trees),this.trees=null),this.bushes&&(this.bushes.geometry.dispose(),this.bushes.material.dispose(),this.scene.remove(this.bushes),this.bushes=null),this.house&&(this.disposeGroup(this.house),this.scene.remove(this.house),this.house=null),this.lamps&&(this.disposeGroup(this.lamps),this.scene.remove(this.lamps),this.lamps=null);for(const a of this.lampLights)this.scene.remove(a),a.dispose();this.lampLights=[],this.windowMaterials=[],this.ambientLight&&this.scene.remove(this.ambientLight),this.hemiLight&&this.scene.remove(this.hemiLight),this.mainLight&&((n=this.mainLight.shadow.map)==null||n.dispose(),this.scene.remove(this.mainLight)),this.fillLight&&this.scene.remove(this.fillLight)}disposeGroup(e){e.traverse(t=>{var n;t instanceof De&&((n=t.geometry)==null||n.dispose(),t.material instanceof hr?this.disposeMaterial(t.material):Array.isArray(t.material)&&t.material.forEach(a=>this.disposeMaterial(a)))})}}function Lt(s,e,t,n,a={},i="global"){return{id:s,name:e,description:t,key:n,modifiers:a,enabled:!0,context:i}}const cb=[Lt("toggle-commander","Toggle Commander","Open/close Commander View","k",{ctrl:!0}),Lt("toggle-commander-tab","Toggle Commander (Tab)","Open/close Commander View with Tab","Tab",{}),Lt("spawn-agent","Spawn Agent","Open new agent spawn modal","n",{alt:!0}),Lt("select-agent-1","Select Agent 1","Select first agent","1",{ctrl:!0}),Lt("select-agent-2","Select Agent 2","Select second agent","2",{ctrl:!0}),Lt("select-agent-3","Select Agent 3","Select third agent","3",{ctrl:!0}),Lt("select-agent-4","Select Agent 4","Select fourth agent","4",{ctrl:!0}),Lt("select-agent-5","Select Agent 5","Select fifth agent","5",{ctrl:!0}),Lt("select-agent-6","Select Agent 6","Select sixth agent","6",{ctrl:!0}),Lt("select-agent-7","Select Agent 7","Select seventh agent","7",{ctrl:!0}),Lt("select-agent-8","Select Agent 8","Select eighth agent","8",{ctrl:!0}),Lt("select-agent-9","Select Agent 9","Select ninth agent","9",{ctrl:!0}),Lt("delete-selected","Delete Selected","Remove selected agents","Delete",{}),Lt("delete-selected-backspace","Delete Selected (Backspace)","Remove selected agents","Backspace",{}),Lt("deselect-all","Deselect All","Clear agent selection","Escape",{}),Lt("open-terminal","Open Terminal","Open terminal for selected agent","Space",{}),Lt("dashboard-selector-toggle","Dashboard Selector","Enable dashboard card selector",",",{}),Lt("dashboard-vim-left","Dashboard Left","Move dashboard selector left","h",{}),Lt("dashboard-vim-down","Dashboard Down","Move dashboard selector down","j",{}),Lt("dashboard-vim-up","Dashboard Up","Move dashboard selector up","k",{}),Lt("dashboard-vim-right","Dashboard Right","Move dashboard selector right","l",{}),Lt("next-agent","Next Agent","Select next agent on battlefield","l",{alt:!0}),Lt("prev-agent","Previous Agent","Select previous agent on battlefield","h",{alt:!0}),Lt("next-working-agent","Next Working Agent","Select next working agent on battlefield","l",{alt:!0,shift:!0}),Lt("prev-working-agent","Previous Working Agent","Select previous working agent on battlefield","h",{alt:!0,shift:!0}),Lt("next-message","Next Message","Navigate to next message in terminal","j",{alt:!0}),Lt("prev-message","Previous Message","Navigate to previous message in terminal","k",{alt:!0}),Lt("page-down-messages","Page Down Messages","Jump down 10 messages in terminal","d",{alt:!0,shift:!0}),Lt("page-up-messages","Page Up Messages","Jump up 10 messages in terminal","u",{alt:!0}),Lt("next-agent-terminal","Next Agent (Terminal)","Switch to next agent in terminal","l",{alt:!0}),Lt("prev-agent-terminal","Previous Agent (Terminal)","Switch to previous agent in terminal","h",{alt:!0}),Lt("activate-message","Activate Message","Click on interactive element in selected message","Space",{}),Lt("toggle-file-explorer","Toggle File Explorer","Open/close file explorer","e",{alt:!0}),Lt("file-explorer-close-tab","Close File Tab","Close active file tab in explorer","w",{alt:!0}),Lt("toggle-spotlight","Toggle Spotlight","Open/close global search","p",{alt:!0}),Lt("open-database","Open Database","Open last used database query builder","d",{alt:!0}),Lt("toggle-2d-view","Cycle View Mode","Cycle between 3D, 2D, and Dashboard views","2",{alt:!0}),Lt("commander-close","Close Commander","Close Commander View","Escape",{},"commander"),Lt("commander-vim-left","Navigate Left","Move focus left (Vim H)","h",{alt:!0},"commander"),Lt("commander-vim-down","Navigate Down","Move focus down (Vim J)","j",{alt:!0},"commander"),Lt("commander-vim-up","Navigate Up","Move focus up (Vim K)","k",{alt:!0},"commander"),Lt("commander-vim-right","Navigate Right","Move focus right (Vim L)","l",{alt:!0},"commander"),Lt("commander-expand","Expand/Collapse","Toggle agent expansion","o",{alt:!0},"commander"),Lt("commander-new-agent","New Agent","Open spawn form in commander","n",{alt:!0},"commander"),Lt("commander-next-tab","Next Tab","Switch to next area tab","Tab",{},"commander"),Lt("commander-prev-tab","Previous Tab","Switch to previous area tab","Tab",{shift:!0},"commander"),Lt("toolbox-close","Close Toolbox","Close Settings panel","Escape",{},"toolbox")];function xt(s,e){if(!e||!e.enabled)return!1;const{ctrl:t,alt:n,shift:a}=e.modifiers,i=t?s.ctrlKey||s.metaKey:!s.ctrlKey&&!s.metaKey,o=n?s.altKey:!s.altKey,l=a?s.shiftKey:!s.shiftKey;let c;if(t?c=(s.ctrlKey||s.metaKey)&&o&&l:c=i&&o&&l,!c)return!1;const d=e.key;if(d.length===1&&/^[a-zA-Z]$/.test(d)){const p=`Key${d.toUpperCase()}`;return s.code===p}if(d.length===1&&/^[0-9]$/.test(d)){const p=`Digit${d}`;return s.code===p}return d==="Space"||d===" "?s.code==="Space":s.key===d}function Jo(s){const e=[];if(s.modifiers.ctrl){const n=navigator.platform.toUpperCase().indexOf("MAC")>=0;e.push(n?"⌘":"Ctrl")}if(s.modifiers.alt){const n=navigator.platform.toUpperCase().indexOf("MAC")>=0;e.push(n?"⌥":"Alt")}s.modifiers.shift&&e.push("Shift"),s.modifiers.meta&&e.push("⌘");let t=s.key;return t===" "?t="Space":t.length===1&&(t=t.toUpperCase()),e.push(t),e.join("+")}function kI(s,e,t,n){return s.filter(a=>{if(a.id===t||!a.enabled||n&&a.context!=="global"&&a.context!==n)return!1;const i=m=>m===" "||m==="Space"?"Space":m.length===1?m.toLowerCase():m,o=i(a.key),l=i(e.key);if(o!==l)return!1;const c=a.modifiers,d=e.modifiers;return(c.ctrl||!1)===(d.ctrl||!1)&&(c.alt||!1)===(d.alt||!1)&&(c.shift||!1)===(d.shift||!1)&&(c.meta||!1)===(d.meta||!1)})}class Yh{constructor(e=200){U(this,"lastClickTime",0);U(this,"lastClickId",null);U(this,"clickTimer",null);U(this,"threshold");this.threshold=e}handleClick(e){const t=performance.now(),n=t-this.lastClickTime;return this.lastClickTime>0&&this.lastClickId===e&&n<this.threshold?(this.clearTimer(),this.reset(),"double"):(this.lastClickId=e,this.lastClickTime=t,this.clearTimer(),this.clickTimer=setTimeout(()=>{this.clickTimer=null,this.lastClickId=null,this.lastClickTime=0},this.threshold),"single")}reset(){this.clearTimer(),this.lastClickId=null,this.lastClickTime=0}clearTimer(){this.clickTimer&&(clearTimeout(this.clickTimer),this.clickTimer=null)}dispose(){this.clearTimer()}}const dm=class dm{constructor(e,t,n){U(this,"canvas");U(this,"controls");U(this,"callbacks");U(this,"activePointers",new Map);U(this,"touchStartTime",0);U(this,"touchStartPos",{x:0,y:0});U(this,"isTouchDragging",!1);U(this,"isTouchPanning",!1);U(this,"touchPanStart",{x:0,y:0});U(this,"longPressTimer",null);U(this,"longPressTriggered",!1);U(this,"isPinching",!1);U(this,"lastPinchDistance",0);U(this,"twoFingerPanStart",{x:0,y:0});U(this,"lastTwoFingerAngle",0);U(this,"isThreeFingerDrag",!1);U(this,"threeFingerStart",{x:0,y:0});this.canvas=e,this.controls=t,this.callbacks=n}onTouchStart(e){for(let t=0;t<e.changedTouches.length;t++){const n=e.changedTouches[t];this.activePointers.set(n.identifier,{x:n.clientX,y:n.clientY})}this.clearLongPressTimer(),this.longPressTriggered=!1,e.touches.length===1?this.handleSingleTouchStart(e.touches[0]):e.touches.length===2?this.handleTwoTouchStart(e):e.touches.length>=3&&this.handleThreeTouchStart(e)}onTouchMove(e){for(let t=0;t<e.changedTouches.length;t++){const n=e.changedTouches[t];this.activePointers.set(n.identifier,{x:n.clientX,y:n.clientY})}e.touches.length>=3&&this.isThreeFingerDrag?this.handleThreeTouchMove(e):e.touches.length===2&&this.isPinching?this.handleTwoTouchMove(e):e.touches.length===1&&!this.isPinching&&this.handleSingleTouchMove(e.touches[0])}onTouchEnd(e){this.clearLongPressTimer();for(let t=0;t<e.changedTouches.length;t++){const n=e.changedTouches[t];this.activePointers.delete(n.identifier)}return e.touches.length===0?this.handleAllTouchesEnd(e):(e.touches.length===2?this.transitionToTwoTouches(e):e.touches.length===1&&this.transitionToOneTouch(e.touches[0]),!1)}onPointerCancel(e){this.activePointers.delete(e),this.reset()}reset(){this.isTouchPanning=!1,this.isPinching=!1,this.isThreeFingerDrag=!1,this.lastPinchDistance=0,this.isTouchDragging=!1,this.longPressTriggered=!1,this.clearLongPressTimer()}get isDragging(){return this.isTouchDragging}get wasLongPress(){return this.longPressTriggered}dispose(){this.clearLongPressTimer(),this.activePointers.clear()}reattach(e,t){this.canvas=e,this.controls=t}handleSingleTouchStart(e){this.touchStartTime=performance.now(),this.touchStartPos={x:e.clientX,y:e.clientY},this.isTouchDragging=!1,this.isTouchPanning=!1;const t=e.clientX,n=e.clientY;this.longPressTimer=setTimeout(()=>{this.longPressTriggered=!0,this.longPressTimer=null,this.callbacks.onLongPress(t,n),navigator.vibrate&&navigator.vibrate(50)},dm.LONG_PRESS_DURATION)}handleTwoTouchStart(e){e.preventDefault(),this.isPinching=!0,this.isTouchPanning=!1,this.isThreeFingerDrag=!1,this.lastPinchDistance=this.getTouchDistance(e.touches[0],e.touches[1]);const t=this.getTouchCenter(e.touches[0],e.touches[1]);this.twoFingerPanStart={x:t.x,y:t.y},this.lastTwoFingerAngle=this.getTwoFingerAngle(e.touches[0],e.touches[1])}handleThreeTouchStart(e){e.preventDefault(),this.isPinching=!1,this.isThreeFingerDrag=!0,this.controls.enableRotate=!0;const t=this.getMultiTouchCenter(e.touches);this.threeFingerStart={x:t.x,y:t.y}}handleSingleTouchMove(e){const t=e.clientX-this.touchStartPos.x,n=e.clientY-this.touchStartPos.y;if(!this.isTouchPanning&&(Math.abs(t)>lc||Math.abs(n)>lc)&&(this.clearLongPressTimer(),this.isTouchPanning=!0,this.isTouchDragging=!0,this.touchPanStart={x:e.clientX,y:e.clientY}),this.isTouchPanning){const a=e.clientX-this.touchPanStart.x,i=e.clientY-this.touchPanStart.y;this.callbacks.onPan(a,i),this.touchPanStart={x:e.clientX,y:e.clientY}}}handleTwoTouchMove(e){this.clearLongPressTimer(),e.preventDefault();const t=this.getTouchDistance(e.touches[0],e.touches[1]),n=this.getTouchCenter(e.touches[0],e.touches[1]),a=this.getTwoFingerAngle(e.touches[0],e.touches[1]);if(this.lastPinchDistance>0){const c=this.lastPinchDistance/t;this.callbacks.onPinchZoom(c,n)}this.lastPinchDistance=t;const i=n.x-this.twoFingerPanStart.x,o=n.y-this.twoFingerPanStart.y;(Math.abs(i)>1||Math.abs(o)>1)&&(this.callbacks.onOrbit(i,o),this.twoFingerPanStart={x:n.x,y:n.y});let l=a-this.lastTwoFingerAngle;l>Math.PI&&(l-=2*Math.PI),l<-Math.PI&&(l+=2*Math.PI),Math.abs(l)>.01&&(this.callbacks.onRotation(l),this.lastTwoFingerAngle=a)}handleThreeTouchMove(e){this.clearLongPressTimer(),e.preventDefault();const t=this.getMultiTouchCenter(e.touches),n=t.x-this.threeFingerStart.x,a=t.y-this.threeFingerStart.y;(Math.abs(n)>1||Math.abs(a)>1)&&(this.callbacks.onOrbit(n,a),this.threeFingerStart={x:t.x,y:t.y})}handleAllTouchesEnd(e){const t=performance.now()-this.touchStartTime,n=!this.isTouchDragging&&!this.longPressTriggered&&t<400;if(n&&e.changedTouches.length>0){const a=e.changedTouches[0];this.callbacks.onTap(a.clientX,a.clientY)}return this.reset(),n}transitionToTwoTouches(e){this.isThreeFingerDrag=!1,this.isPinching=!0,this.lastPinchDistance=this.getTouchDistance(e.touches[0],e.touches[1]);const t=this.getTouchCenter(e.touches[0],e.touches[1]);this.twoFingerPanStart={x:t.x,y:t.y}}transitionToOneTouch(e){this.isPinching=!1,this.isThreeFingerDrag=!1,this.lastPinchDistance=0,this.touchPanStart={x:e.clientX,y:e.clientY},this.touchStartPos={x:e.clientX,y:e.clientY}}clearLongPressTimer(){this.longPressTimer&&(clearTimeout(this.longPressTimer),this.longPressTimer=null)}getTouchDistance(e,t){const n=t.clientX-e.clientX,a=t.clientY-e.clientY;return Math.sqrt(n*n+a*a)}getTouchCenter(e,t){return{x:(e.clientX+t.clientX)/2,y:(e.clientY+t.clientY)/2}}getTwoFingerAngle(e,t){const n=t.clientX-e.clientX,a=t.clientY-e.clientY;return Math.atan2(a,n)}getMultiTouchCenter(e){let t=0,n=0;for(let a=0;a<e.length;a++)t+=e[a].clientX,n+=e[a].clientY;return{x:t/e.length,y:n/e.length}}};U(dm,"LONG_PRESS_DURATION",500);let Ty=dm;function SI(s){const e=Math.abs(s.deltaX),t=Math.abs(s.deltaY);return s.ctrlKey||e>1?!0:t>80&&e<1?!1:t>0&&t<=80}class jI{constructor(e,t,n){U(this,"cameraController");U(this,"callbacks");U(this,"canvas");U(this,"isGestureActive",!1);U(this,"gestureScale",1);U(this,"onGestureStart",e=>{const t=e;t.preventDefault(),z.getTrackpadConfig().enabled&&(this.isGestureActive=!0,this.gestureScale=t.scale)});U(this,"onGestureChange",e=>{const t=e;t.preventDefault();const n=z.getTrackpadConfig();if(!(!n.enabled||!this.isGestureActive)&&n.pinchToZoom&&t.scale!==this.gestureScale){const a=t.scale-this.gestureScale;this.callbacks.onZoom(a*n.sensitivity.zoom,t.clientX,t.clientY),this.gestureScale=t.scale}});U(this,"onGestureEnd",e=>{e.preventDefault(),this.isGestureActive=!1,this.gestureScale=1});this.cameraController=e,this.canvas=t,this.callbacks=n,this.setupGestureEvents()}setupGestureEvents(){"GestureEvent"in window&&(this.canvas.addEventListener("gesturestart",this.onGestureStart),this.canvas.addEventListener("gesturechange",this.onGestureChange),this.canvas.addEventListener("gestureend",this.onGestureEnd))}handleWheel(e){const t=z.getTrackpadConfig();if(!t.enabled||!SI(e))return!1;if(e.ctrlKey&&t.pinchToZoom){e.preventDefault();const n=-e.deltaY*.01*t.sensitivity.zoom;return this.callbacks.onZoom(n,e.clientX,e.clientY),!0}if(e.shiftKey&&t.shiftTwoFingerOrbit){e.preventDefault();const n=-e.deltaX*t.sensitivity.orbit,a=-e.deltaY*t.sensitivity.orbit;return this.callbacks.onOrbit(n,a),!0}if(t.twoFingerPan){e.preventDefault();const n=-e.deltaX*t.sensitivity.pan,a=-e.deltaY*t.sensitivity.pan;return this.callbacks.onPan(n,a),!0}return!1}setCameraController(e){this.cameraController=e}setCanvas(e){"GestureEvent"in window&&(this.canvas.removeEventListener("gesturestart",this.onGestureStart),this.canvas.removeEventListener("gesturechange",this.onGestureChange),this.canvas.removeEventListener("gestureend",this.onGestureEnd)),this.canvas=e,this.setupGestureEvents()}dispose(){"GestureEvent"in window&&(this.canvas.removeEventListener("gesturestart",this.onGestureStart),this.canvas.removeEventListener("gesturechange",this.onGestureChange),this.canvas.removeEventListener("gestureend",this.onGestureEnd))}}class CI{constructor(e,t){U(this,"camera");U(this,"canvas");U(this,"raycaster",new NP);U(this,"mouse",new zs);U(this,"ground",null);U(this,"agentMeshes",new Map);U(this,"agentHitboxes",[]);U(this,"resizeHandlesGetter",()=>[]);U(this,"folderIconMeshesGetter",()=>[]);this.camera=e,this.canvas=t}setReferences(e,t){this.ground=e,this.agentMeshes=t,this.agentHitboxes=[];for(const n of t.values()){const a=n.group.getObjectByName("clickHitbox");this.agentHitboxes.push(a??n.group)}}setResizeHandlesGetter(e){this.resizeHandlesGetter=e}setFolderIconMeshesGetter(e){this.folderIconMeshesGetter=e}setCanvas(e){this.canvas=e}raycastGroundFromEvent(e){if(this.updateMouseFromEvent(e),this.raycaster.setFromCamera(this.mouse,this.camera),this.ground){const a=this.raycaster.intersectObject(this.ground);if(a.length>0){const i=a[0].point;return{x:i.x,z:i.z}}}const t=new bp(new gt(0,1,0),0),n=new gt;return this.raycaster.ray.intersectPlane(t,n)?{x:n.x,z:n.z}:null}raycastGroundFromPoint(e,t){if(this.updateMouseFromPoint(e,t),this.raycaster.setFromCamera(this.mouse,this.camera),this.ground){const i=this.raycaster.intersectObject(this.ground);if(i.length>0){const o=i[0].point;return{x:o.x,z:o.z}}}const n=new bp(new gt(0,1,0),0),a=new gt;return this.raycaster.ray.intersectPlane(n,a)?{x:a.x,z:a.z}:null}checkResizeHandleClick(e){const t=this.resizeHandlesGetter();if(t.length===0)return null;this.updateMouseFromEvent(e),this.raycaster.setFromCamera(this.mouse,this.camera);const n=this.raycaster.intersectObjects(t);return n.length>0?n[0].object:null}checkFolderIconClick(e){const t=this.folderIconMeshesGetter();if(t.length===0)return null;this.updateMouseFromEvent(e),this.raycaster.setFromCamera(this.mouse,this.camera);const n=this.raycaster.intersectObjects(t);return n.length>0?n[0].object:null}findAgentAtPosition(e){if(this.updateMouseFromEvent(e),this.raycaster.setFromCamera(this.mouse,this.camera),this.agentHitboxes.length===0)return null;const t=this.raycaster.intersectObjects(this.agentHitboxes,!1);if(t.length>0){let n=t[0].object;for(;n&&!n.userData.agentId;)n=n.parent;if(n&&n.userData.agentId)return n.userData.agentId}return null}findAgentAtPoint(e,t){if(this.updateMouseFromPoint(e,t),this.raycaster.setFromCamera(this.mouse,this.camera),this.agentHitboxes.length===0)return null;const n=this.raycaster.intersectObjects(this.agentHitboxes,!1);if(n.length>0){let a=n[0].object;for(;a&&!a.userData.agentId;)a=a.parent;if(a&&a.userData.agentId)return a.userData.agentId}return null}raycastToPlane(e,t){if(this.mouse.set(e,t),this.raycaster.setFromCamera(this.mouse,this.camera),this.ground){const i=this.raycaster.intersectObject(this.ground);if(i.length>0)return i[0].point}const n=new bp(new gt(0,1,0),0),a=new gt;return this.raycaster.ray.intersectPlane(n,a)?a:null}projectToScreen(e){const t=this.canvas.getBoundingClientRect(),n=e.clone().project(this.camera);return{x:(n.x+1)/2*t.width+t.left,y:(-n.y+1)/2*t.height+t.top}}getNormalizedMouseFromEvent(e){return this.updateMouseFromEvent(e),this.mouse.clone()}getNormalizedMouseFromPoint(e,t){return this.updateMouseFromPoint(e,t),this.mouse.clone()}getAgentMeshes(){return this.agentMeshes}updateMouseFromEvent(e){const t=this.canvas.getBoundingClientRect();this.mouse.x=(e.clientX-t.left)/t.width*2-1,this.mouse.y=-((e.clientY-t.top)/t.height)*2+1}updateMouseFromPoint(e,t){const n=this.canvas.getBoundingClientRect();this.mouse.x=(e-n.left)/n.width*2-1,this.mouse.y=-((t-n.top)/n.height)*2+1}}class NI{constructor(e,t,n){U(this,"camera");U(this,"controls");U(this,"canvas");U(this,"raycastProvider",null);U(this,"goalCameraPos",null);U(this,"goalOrbitTarget",null);this.camera=e,this.controls=t,this.canvas=n}setRaycastProvider(e){this.raycastProvider=e}setControls(e){this.controls=e}setCanvas(e){this.canvas=e}handleWheelZoom(e,t=1){var C,N;e.preventDefault();const n=Math.sign(e.deltaY)*Math.min(Math.abs(e.deltaY),100)/100,a=n<0,i=.08*Math.abs(n)*t,o=((C=this.goalOrbitTarget)==null?void 0:C.clone())??this.controls.target.clone(),c=(((N=this.goalCameraPos)==null?void 0:N.clone())??this.camera.position.clone()).clone().sub(o),d=c.length(),m=this.controls.minDistance,p=this.controls.maxDistance,f=a?Math.max(m,d*(1-i)):Math.min(p,d*(1+i));if(f===d)return;let b=null;if(this.raycastProvider){const P=this.raycastProvider.getNormalizedMouseFromEvent(e);b=this.raycastProvider.raycastToPlane(P.x,P.y)}if(!b){const P=c.normalize();this.goalCameraPos=o.clone().add(P.multiplyScalar(f)),this.goalOrbitTarget=o.clone();return}const x=f/d,w=b.clone().sub(o),k=1-x,S=o.clone().add(w.multiplyScalar(k));S.y=Math.max(0,S.y);const j=c.normalize();this.goalCameraPos=S.clone().add(j.multiplyScalar(f)),this.goalOrbitTarget=S}handlePinchZoom(e,t){this.goalCameraPos=null,this.goalOrbitTarget=null;const n=this.camera.position.clone().sub(this.controls.target),a=n.length(),i=this.controls.minDistance,o=this.controls.maxDistance,l=Math.max(i,Math.min(o,a*e));if(l===a)return;const c=this.canvas.getBoundingClientRect(),d=(t.x-c.left)/c.width*2-1,m=-((t.y-c.top)/c.height)*2+1;let p=null;if(this.raycastProvider&&(p=this.raycastProvider.raycastToPlane(d,m)),!p){const S=n.normalize();this.camera.position.copy(this.controls.target).add(S.multiplyScalar(l));return}const f=l/a,b=p.clone().sub(this.controls.target),x=1-f,w=this.controls.target.clone().add(b.multiplyScalar(x));w.y=Math.max(0,w.y),this.controls.target.copy(w);const k=n.normalize();this.camera.position.copy(w).add(k.multiplyScalar(l))}handlePan(e,t){this.goalCameraPos=null,this.goalOrbitTarget=null;const n=new gt;this.camera.getWorldDirection(n);const a=new gt(-n.z,0,n.x).normalize(),i=new gt(n.x,0,n.z).normalize(),l=this.camera.position.distanceTo(this.controls.target)*.005,c=new gt;c.add(a.multiplyScalar(-e*l)),c.add(i.multiplyScalar(t*l)),this.controls.target.add(c),this.camera.position.add(c)}handleOrbit(e,t){this.goalCameraPos=null,this.goalOrbitTarget=null;const n=.005,a=-e*n,i=-t*n,o=this.camera.position.clone().sub(this.controls.target),l=new _p;l.setFromVector3(o),l.theta+=a,l.phi+=i,l.phi=Math.max(.1,Math.min(Math.PI-.1,l.phi)),o.setFromSpherical(l),this.camera.position.copy(this.controls.target).add(o),this.camera.lookAt(this.controls.target)}handleTwistRotation(e){this.goalCameraPos=null,this.goalOrbitTarget=null;const t=this.camera.position.clone().sub(this.controls.target),n=new _p;n.setFromVector3(t),n.theta+=e,n.phi=Math.max(.1,Math.min(Math.PI-.1,n.phi)),t.setFromSpherical(n),this.camera.position.copy(this.controls.target).add(t),this.camera.lookAt(this.controls.target)}updateSmoothZoom(e){if(!this.goalCameraPos||!this.goalOrbitTarget)return;const t=z.getMouseControls().sensitivity.smoothing;if(t<=0){this.camera.position.copy(this.goalCameraPos),this.controls.target.copy(this.goalOrbitTarget),this.goalCameraPos=null,this.goalOrbitTarget=null;return}const n=yx.lerp(20,3,t),a=1-Math.exp(-n*e);this.camera.position.lerp(this.goalCameraPos,a),this.controls.target.lerp(this.goalOrbitTarget,a),this.camera.position.distanceTo(this.goalCameraPos)<.005&&this.controls.target.distanceTo(this.goalOrbitTarget)<.005&&(this.camera.position.copy(this.goalCameraPos),this.controls.target.copy(this.goalOrbitTarget),this.goalCameraPos=null,this.goalOrbitTarget=null)}get isZoomAnimating(){return this.goalCameraPos!==null}}const ub={panSpeed:1,orbitSpeed:1,zoomSpeed:1,smoothing:.3,invertPanX:!1,invertPanY:!1,invertOrbitX:!1,invertOrbitY:!1},Vh={enabled:!0,pinchToZoom:!0,twoFingerPan:!0,shiftTwoFingerOrbit:!0,sensitivity:{zoom:1,pan:1,orbit:1}};function zo(s,e,t,n,a,i,o){return{id:s,name:e,description:t,button:n,modifiers:a,action:i,enabled:!0,sensitivity:o}}const db=[zo("left-click-select","Select/Click","Select agents, click on buildings/areas","left",{},"primary-action"),zo("left-drag-selection","Selection Box","Drag to select multiple agents","left",{},"selection-box"),zo("right-click-context","Context Menu / Move","Show context menu or move selected agents","right",{},"context-menu"),zo("alt-right-drag-pan","Camera Pan","Pan camera with Alt+Right-drag","right",{alt:!0},"camera-pan",1),zo("middle-drag-orbit","Camera Orbit","Orbit camera with middle-drag","middle",{},"camera-orbit",1),zo("shift-middle-drag-pan","Camera Pan (Alt)","Alternative pan with Shift+Middle-drag","middle",{shift:!0},"camera-pan",1),zo("wheel-zoom","Zoom","Zoom camera with scroll wheel","middle",{},"camera-zoom",1)],AI={0:"left",1:"middle",2:"right",3:"back",4:"forward"},MI={left:"Left Click",right:"Right Click",middle:"Middle Click",back:"Back Button",forward:"Forward Button"};function Fj(s,e){const t=[];if(s.modifiers.ctrl){const n=typeof navigator<"u"&&navigator.platform.toUpperCase().includes("MAC");t.push(n?"⌘":"Ctrl")}if(s.modifiers.alt){const n=typeof navigator<"u"&&navigator.platform.toUpperCase().includes("MAC");t.push(n?"⌥":"Alt")}return s.modifiers.shift&&t.push("Shift"),t.push(e?e(s.button):MI[s.button]),t.join("+")}function TI(s,e){const t=e.ctrl?s.ctrlKey||s.metaKey:!s.ctrlKey&&!s.metaKey,n=e.alt?s.altKey:!s.altKey,a=e.shift?s.shiftKey:!s.shiftKey;return t&&n&&a}function $j(s,e,t){return s.filter(n=>{if(n.id===t||!n.enabled||n.button!==e.button)return!1;const a=n.modifiers,i=e.modifiers;return(a.ctrl||!1)===(i.ctrl||!1)&&(a.alt||!1)===(i.alt||!1)&&(a.shift||!1)===(i.shift||!1)})}class EI{constructor(e,t){U(this,"cameraController");U(this,"callbacks");U(this,"activeDragAction",null);U(this,"activeBinding",null);U(this,"dragStartPos",{x:0,y:0});U(this,"lastDragPos",{x:0,y:0});this.cameraController=e,this.callbacks=t}setCameraController(e){this.cameraController=e}findBinding(e,t){const n=z.getMouseControls(),a=AI[t];if(!a)return null;const i=n.bindings.filter(o=>o.enabled&&o.button===a).sort((o,l)=>{const c=Object.values(o.modifiers).filter(Boolean).length;return Object.values(l.modifiers).filter(Boolean).length-c});for(const o of i)if(TI(e,o.modifiers))return o;return null}isCameraAction(e){return e==="camera-pan"||e==="camera-orbit"||e==="camera-rotate"||e==="camera-tilt"}handlePointerDown(e){const t=this.findBinding(e,e.button);return t?(this.dragStartPos={x:e.clientX,y:e.clientY},this.lastDragPos={x:e.clientX,y:e.clientY},this.isCameraAction(t.action)?(this.activeDragAction=t.action,this.activeBinding=t,!0):!1):!1}handlePointerMove(e){if(!this.activeDragAction||!this.activeBinding)return!1;const t=e.clientX-this.lastDragPos.x,n=e.clientY-this.lastDragPos.y,a=z.getMouseControls().sensitivity;switch(this.activeDragAction){case"camera-pan":{const i=(a.invertPanX?-t:t)*a.panSpeed,o=(a.invertPanY?-n:n)*a.panSpeed;this.cameraController.handlePan(i,o);break}case"camera-orbit":{const i=(a.invertOrbitX?-t:t)*a.orbitSpeed,o=(a.invertOrbitY?-n:n)*a.orbitSpeed;this.cameraController.handleOrbit(i,o);break}case"camera-rotate":this.cameraController.handleOrbit(t*a.orbitSpeed,0);break;case"camera-tilt":this.cameraController.handleOrbit(0,n*a.orbitSpeed);break;case"selection-box":this.callbacks.onSelectionBoxMove(e.clientX,e.clientY);break}return this.lastDragPos={x:e.clientX,y:e.clientY},!0}handlePointerUp(e){const t=this.activeDragAction!==null;return this.activeDragAction==="selection-box"&&this.callbacks.onSelectionBoxEnd(e.clientX,e.clientY),this.activeDragAction=null,this.activeBinding=null,t}handleWheel(e){const t=z.getMouseControls();if(!t.bindings.find(i=>i.enabled&&i.action==="camera-zoom"))return!1;const a=t.sensitivity;return this.cameraController.handleWheelZoom(e,a.zoomSpeed),!0}get isDragging(){return this.activeDragAction!==null}get currentAction(){return this.activeDragAction}cancelDrag(){this.activeDragAction=null,this.activeBinding=null}}const to=class to{constructor(e,t,n,a,i){U(this,"canvas");U(this,"camera");U(this,"controls");U(this,"selectionBox");U(this,"callbacks");U(this,"raycaster");U(this,"cameraController");U(this,"mouseControlHandler");U(this,"trackpadHandler");U(this,"touchHandler");U(this,"agentClickDetector");U(this,"agentTapDetector");U(this,"buildingClickDetector");U(this,"areaClickDetector");U(this,"isDragging",!1);U(this,"dragStart",{x:0,y:0});U(this,"dragCurrent",{x:0,y:0});U(this,"pointerDownOnCanvas",!1);U(this,"isRightDragging",!1);U(this,"rightDragStart",{x:0,y:0});U(this,"isDrawing",!1);U(this,"drawingModeChecker",()=>!1);U(this,"isResizing",!1);U(this,"resizeModeChecker",()=>!1);U(this,"areaAtPositionGetter",()=>null);U(this,"buildingAtPositionGetter",()=>null);U(this,"buildingPositionsGetter",()=>new Map);U(this,"isDraggingBuilding",!1);U(this,"draggingBuildingId",null);U(this,"buildingDragStartPos",null);U(this,"hoveredAgentId",null);U(this,"hoverTimer",null);U(this,"lastMousePos",{x:0,y:0});U(this,"lastHoverCheckTime",0);U(this,"hoveredBuildingId",null);U(this,"buildingHoverTimer",null);U(this,"onPointerDown",e=>{var n,a,i,o,l,c;if(!document.hasFocus()||document.visibilityState==="hidden")return;(a=(n=this.callbacks).onActivity)==null||a.call(n);const t=e.pointerType==="touch";if(e.button===0){this.controls.mouseButtons.LEFT=null;const d=this.raycaster.checkResizeHandleClick(e);if(d){const p=this.raycaster.raycastGroundFromEvent(e);p&&(this.isResizing=!0,t&&this.touchHandler.reset(),(o=(i=this.callbacks).onResizeStart)==null||o.call(i,d,p));return}if(this.drawingModeChecker()){const p=this.raycaster.raycastGroundFromEvent(e);p&&(this.isDrawing=!0,(c=(l=this.callbacks).onDrawStart)==null||c.call(l,p));return}const m=this.raycaster.raycastGroundFromEvent(e);if(m){const p=this.buildingAtPositionGetter(m);if(p&&!t){this.draggingBuildingId=p.id,this.buildingDragStartPos=m,this.isDraggingBuilding=!1;return}}this.isDragging=!1,this.dragStart={x:e.clientX,y:e.clientY},this.dragCurrent={x:e.clientX,y:e.clientY},this.pointerDownOnCanvas=!0}if(e.button===2){if(this.mouseControlHandler.handlePointerDown(e)){this.controls.mouseButtons.RIGHT=null;return}this.controls.mouseButtons.RIGHT=null,this.isRightDragging=!1,this.rightDragStart={x:e.clientX,y:e.clientY}}if(e.button===1&&this.mouseControlHandler.handlePointerDown(e)){this.controls.mouseButtons.MIDDLE=null;return}});U(this,"onPointerMove",e=>{var t,n,a,i,o,l,c,d;if(!document.hasFocus()||document.hidden){this.isDragging&&(this.isDragging=!1,this.selectionBox.classList.remove("active"),this.pointerDownOnCanvas=!1);return}if(e.buttons&1){if(this.isResizing){const f=this.raycaster.raycastGroundFromEvent(e);f&&((n=(t=this.callbacks).onResizeMove)==null||n.call(t,f));return}if(this.isDrawing){const f=this.raycaster.raycastGroundFromEvent(e);f&&((i=(a=this.callbacks).onDrawMove)==null||i.call(a,f));return}if(this.draggingBuildingId&&this.buildingDragStartPos){const f=this.raycaster.raycastGroundFromEvent(e);if(f){const b=f.x-this.buildingDragStartPos.x,x=f.z-this.buildingDragStartPos.z,w=Math.sqrt(b*b+x*x);!this.isDraggingBuilding&&w>.2&&(this.isDraggingBuilding=!0,(l=(o=this.callbacks).onBuildingDragStart)==null||l.call(o,this.draggingBuildingId,this.buildingDragStartPos)),this.isDraggingBuilding&&((d=(c=this.callbacks).onBuildingDragMove)==null||d.call(c,this.draggingBuildingId,f))}return}if(e.pointerType==="touch"||!this.pointerDownOnCanvas||z.getState().terminalResizing)return;const m=e.clientX-this.dragStart.x,p=e.clientY-this.dragStart.y;!this.isDragging&&(Math.abs(m)>lc||Math.abs(p)>lc)&&(this.isDragging=!0,this.selectionBox.classList.add("active")),this.isDragging&&(this.dragCurrent={x:e.clientX,y:e.clientY},this.updateSelectionBox())}if(e.buttons&2){if(this.mouseControlHandler.handlePointerMove(e))return;const m=e.clientX-this.rightDragStart.x,p=e.clientY-this.rightDragStart.y;!this.isRightDragging&&(Math.abs(m)>lc||Math.abs(p)>lc)&&(this.isRightDragging=!0)}if(!(e.buttons&4&&this.mouseControlHandler.handlePointerMove(e))&&e.buttons===0&&e.pointerType!=="touch"){const m=performance.now();m-this.lastHoverCheckTime>to.HOVER_CHECK_INTERVAL&&(this.handleHoverDetection(e),this.lastHoverCheckTime=m)}});U(this,"onPointerUp",e=>{var t,n,a,i,o,l;if(e.button===0){if(this.controls.mouseButtons.LEFT=null,e.pointerType==="touch"&&!this.isDrawing&&!this.isResizing){this.pointerDownOnCanvas=!1;return}if(this.isResizing){(n=(t=this.callbacks).onResizeEnd)==null||n.call(t),this.isResizing=!1;return}if(this.isDrawing){const c=this.raycaster.raycastGroundFromEvent(e);c&&((i=(a=this.callbacks).onDrawEnd)==null||i.call(a,c)),this.isDrawing=!1;return}if(this.draggingBuildingId){const c=this.draggingBuildingId,d=this.raycaster.raycastGroundFromEvent(e),m={x:e.clientX,y:e.clientY};this.isDraggingBuilding&&d?(l=(o=this.callbacks).onBuildingDragEnd)==null||l.call(o,c,d):this.handleBuildingClick(c,m),this.draggingBuildingId=null,this.buildingDragStartPos=null,this.isDraggingBuilding=!1;return}this.isDragging?(this.isDragging=!1,this.selectionBox.classList.remove("active"),this.selectAgentsInBox(this.dragStart,this.dragCurrent)):e.ctrlKey||this.handleSingleClick(e),this.pointerDownOnCanvas=!1}e.button===2&&(this.mouseControlHandler.handlePointerUp(e),this.controls.mouseButtons.RIGHT=null,this.isRightDragging=!1),e.button===1&&(this.mouseControlHandler.handlePointerUp(e),this.controls.mouseButtons.MIDDLE=null)});U(this,"onPointerCancel",e=>{this.touchHandler.onPointerCancel(e.pointerId)});U(this,"onPointerLeave",e=>{this.clearHoverState(),this.clearBuildingHoverState()});U(this,"onWindowBlur",()=>{this.cancelAllDragStates()});U(this,"onVisibilityChange",()=>{document.hidden&&this.cancelAllDragStates()});U(this,"onKeyDown",e=>{var f,b;const t=e.target,n=z.getState(),a=t.tagName==="INPUT"||t.tagName==="TEXTAREA"||t.isContentEditable,i=t.closest(".guake-terminal"),o=i==null?void 0:i.classList.contains("collapsed"),l=z.getShortcuts(),c=l.find(x=>x.id==="toggle-spotlight"),d=l.find(x=>x.id==="next-agent"),m=l.find(x=>x.id==="prev-agent"),p=l.find(x=>x.id==="open-terminal");if(!xt(e,c)){if(a){const x=z.getShortcuts();if((xt(e,x.find(k=>k.id==="next-agent"))||xt(e,x.find(k=>k.id==="prev-agent"))||xt(e,x.find(k=>k.id==="next-working-agent"))||xt(e,x.find(k=>k.id==="prev-working-agent")))&&o)t.blur();else if(xt(e,p)&&o)t.blur();else return}if((xt(e,d)||xt(e,m))&&!n.terminalOpen){const x=this.getOrderedAgents(n.agents);if(x.length<=1)return;const w=n.selectedAgentIds.size===1?Array.from(n.selectedAgentIds)[0]:null,k=w?x.findIndex(j=>j.id===w):-1;let S;xt(e,d)?S=k===-1?0:(k+1)%x.length:S=k===-1?x.length-1:(k-1+x.length)%x.length,e.preventDefault(),z.selectAgent(x[S].id),(b=(f=this.callbacks).onActivity)==null||b.call(f);return}if(xt(e,p)){if(i&&!o||t.tagName==="BUTTON"||t.tagName==="A")return;if(n.terminalOpen)if(i&&o)z.setTerminalOpen(!1);else return;const x=document.querySelector(".guake-terminal");if(x&&x.classList.contains("collapsed")&&n.terminalOpen&&z.setTerminalOpen(!1),n.selectedBuildingIds.size>0||n.selectedAreaId!==null)return;if(n.selectedAgentIds.size===0){const w=n.lastSelectedAgentId;w&&n.agents.has(w)&&(e.preventDefault(),z.selectAgent(w),z.setTerminalOpen(!0));return}e.preventDefault(),z.setTerminalOpen(!0)}}});U(this,"onContextMenu",e=>{var a,i;if(e.preventDefault(),e.altKey)return;if(this.controls.mouseButtons.RIGHT=null,this.isRightDragging){this.isRightDragging=!1;return}const t=z.getState(),n=this.raycaster.raycastGroundFromEvent(e);if(n){if(t.selectedAgentIds.size>0){this.callbacks.onAreaRightClick&&this.callbacks.onAreaRightClick(n);const o=Array.from(t.selectedAgentIds),l=new gt(n.x,0,n.z);this.callbacks.onMoveCommand(l,o);return}if(this.callbacks.onContextMenu){const o=this.raycaster.findAgentAtPosition(e),l=(a=this.areaAtPositionGetter)==null?void 0:a.call(this,n),c=(i=this.buildingAtPositionGetter)==null?void 0:i.call(this,n);let d;o?d={type:"agent",id:o}:c?d={type:"building",id:c.id}:l?d={type:"area",id:l.id}:d={type:"ground"},this.callbacks.onContextMenu({x:e.clientX,y:e.clientY},n,d)}}});U(this,"onWheel",e=>{var t,n;(n=(t=this.callbacks).onActivity)==null||n.call(t),!this.trackpadHandler.handleWheel(e)&&this.mouseControlHandler.handleWheel(e)});U(this,"onTouchStart",e=>{if(this.drawingModeChecker()){e.preventDefault();return}this.touchHandler.onTouchStart(e)});U(this,"onTouchMove",e=>{if(this.isDrawing||this.isResizing){e.preventDefault();return}this.touchHandler.onTouchMove(e)});U(this,"onTouchEnd",e=>{this.isDrawing||this.isResizing||this.touchHandler.onTouchEnd(e)});U(this,"handleTouchTap",(e,t)=>{var i,o,l,c,d,m;const n=this.raycaster.findAgentAtPoint(e,t);if(n){this.agentTapDetector.handleClick(n)==="double"?this.callbacks.onAgentDoubleClick(n):this.callbacks.onAgentClick(n,!1);return}const a=this.raycaster.raycastGroundFromPoint(e,t);if(a){const p=this.buildingAtPositionGetter(a);if(p){const b={x:e,y:t};this.handleBuildingClick(p.id,b);return}const f=this.areaAtPositionGetter(a);if(f){this.areaClickDetector.handleClick(f.id)==="double"?(o=(i=this.callbacks).onAreaDoubleClick)==null||o.call(i,f.id):(c=(l=this.callbacks).onAreaClick)==null||c.call(l,f.id);return}}this.agentClickDetector.reset(),this.callbacks.onGroundClick(),(m=(d=this.callbacks).onGroundClickOutsideArea)==null||m.call(d)});U(this,"handleLongPress",(e,t)=>{var c,d;const n=z.getState(),a=this.raycaster.raycastGroundFromPoint(e,t);if(!a)return;const i=this.raycaster.findAgentAtPoint(e,t);if(i){this.callbacks.onContextMenu&&this.callbacks.onContextMenu({x:e,y:t},a,{type:"agent",id:i});return}const o=(c=this.buildingAtPositionGetter)==null?void 0:c.call(this,a);if(o){this.callbacks.onContextMenu&&this.callbacks.onContextMenu({x:e,y:t},a,{type:"building",id:o.id});return}const l=(d=this.areaAtPositionGetter)==null?void 0:d.call(this,a);if(l){this.callbacks.onContextMenu&&this.callbacks.onContextMenu({x:e,y:t},a,{type:"area",id:l.id});return}if(n.selectedAgentIds.size>0){const m=Array.from(n.selectedAgentIds),p=new gt(a.x,0,a.z);this.callbacks.onMoveCommand(p,m);return}this.callbacks.onContextMenu&&this.callbacks.onContextMenu({x:e,y:t},a,{type:"ground"})});this.canvas=e,this.camera=t,this.controls=n,this.selectionBox=a,this.callbacks=i,this.raycaster=new CI(t,e),this.cameraController=new NI(t,n,e),this.cameraController.setRaycastProvider(this.raycaster),this.mouseControlHandler=new EI(this.cameraController,{onSelectionBoxStart:(o,l)=>{this.dragStart={x:o,y:l},this.dragCurrent={x:o,y:l},this.isDragging=!0,this.selectionBox.classList.add("active")},onSelectionBoxMove:(o,l)=>{this.dragCurrent={x:o,y:l},this.updateSelectionBox()},onSelectionBoxEnd:(o,l)=>{this.isDragging=!1,this.selectionBox.classList.remove("active"),this.selectAgentsInBox(this.dragStart,{x:o,y:l})}}),this.trackpadHandler=new jI(this.cameraController,e,{onPan:(o,l)=>{this.cameraController.handlePan(o,l)},onZoom:(o,l,c)=>{const d=1-o;this.cameraController.handlePinchZoom(d,{x:l,y:c})},onOrbit:(o,l)=>{this.cameraController.handleOrbit(o,l)}}),this.agentClickDetector=new Yh(300),this.agentTapDetector=new Yh(450),this.buildingClickDetector=new Yh(300),this.areaClickDetector=new Yh(300),this.touchHandler=new Ty(e,n,{onTap:this.handleTouchTap,onLongPress:this.handleLongPress,onPan:(o,l)=>this.cameraController.handlePan(o,l),onPinchZoom:(o,l)=>this.cameraController.handlePinchZoom(o,l),onOrbit:(o,l)=>this.cameraController.handleOrbit(o,l),onRotation:o=>this.cameraController.handleTwistRotation(o)}),this.setupEventListeners()}setReferences(e,t){this.raycaster.setReferences(e,t)}setDrawingModeChecker(e){this.drawingModeChecker=e}setResizeHandlers(e,t){this.raycaster.setResizeHandlesGetter(e),this.resizeModeChecker=t}setFolderIconMeshesGetter(e){this.raycaster.setFolderIconMeshesGetter(e)}setAreaAtPositionGetter(e){this.areaAtPositionGetter=e}setBuildingAtPositionGetter(e){this.buildingAtPositionGetter=e}setBuildingPositionsGetter(e){this.buildingPositionsGetter=e}raycastGround(e){return this.raycaster.raycastGroundFromEvent(e)}dispose(){this.canvas.removeEventListener("pointerdown",this.onPointerDown,!0),this.canvas.removeEventListener("pointermove",this.onPointerMove),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointercancel",this.onPointerCancel),this.canvas.removeEventListener("pointerleave",this.onPointerLeave),this.canvas.removeEventListener("contextmenu",this.onContextMenu),this.canvas.removeEventListener("wheel",this.onWheel),this.canvas.removeEventListener("touchstart",this.onTouchStart),this.canvas.removeEventListener("touchmove",this.onTouchMove),this.canvas.removeEventListener("touchend",this.onTouchEnd),this.agentClickDetector.dispose(),this.agentTapDetector.dispose(),this.buildingClickDetector.dispose(),this.areaClickDetector.dispose(),this.touchHandler.dispose(),this.trackpadHandler.dispose(),this.clearHoverTimer(),this.clearBuildingHoverTimer(),window.removeEventListener("blur",this.onWindowBlur),document.removeEventListener("visibilitychange",this.onVisibilityChange),document.removeEventListener("keydown",this.onKeyDown,!0)}reattach(e,t,n){this.dispose(),this.canvas=e,this.selectionBox=t,this.controls=n,this.raycaster.setCanvas(e),this.cameraController.setCanvas(e),this.cameraController.setControls(n),this.mouseControlHandler.setCameraController(this.cameraController),this.trackpadHandler.setCameraController(this.cameraController),this.trackpadHandler.setCanvas(e),this.touchHandler.reattach(e,n),this.setupEventListeners()}updateSmoothZoom(e){this.cameraController.updateSmoothZoom(e)}get isZoomAnimating(){return this.cameraController.isZoomAnimating}calculateFormationPositions(e,t){const n=[];if(t===1)return[{x:e.x,y:0,z:e.z}];if(t<=6){const a=Ni*Math.max(1,t/3);for(let i=0;i<t;i++){const o=i/t*Math.PI*2-Math.PI/2;n.push({x:e.x+Math.cos(o)*a,y:0,z:e.z+Math.sin(o)*a})}}else{const a=Math.ceil(Math.sqrt(t)),i=Math.ceil(t/a),o=(a-1)*Ni/2,l=(i-1)*Ni/2;for(let c=0;c<t;c++){const d=c%a,m=Math.floor(c/a);n.push({x:e.x+d*Ni-o,y:0,z:e.z+m*Ni-l})}}return n}setupEventListeners(){this.canvas.addEventListener("pointerdown",this.onPointerDown,!0),this.canvas.addEventListener("pointermove",this.onPointerMove),this.canvas.addEventListener("pointerup",this.onPointerUp),this.canvas.addEventListener("pointercancel",this.onPointerCancel),this.canvas.addEventListener("pointerleave",this.onPointerLeave),this.canvas.addEventListener("contextmenu",this.onContextMenu),this.canvas.addEventListener("wheel",this.onWheel,{passive:!1}),this.canvas.addEventListener("touchstart",this.onTouchStart,{passive:!1}),this.canvas.addEventListener("touchmove",this.onTouchMove,{passive:!1}),this.canvas.addEventListener("touchend",this.onTouchEnd,{passive:!1}),window.addEventListener("blur",this.onWindowBlur),document.addEventListener("visibilitychange",this.onVisibilityChange),document.addEventListener("keydown",this.onKeyDown,!0)}cancelAllDragStates(){this.clearHoverState(),this.clearBuildingHoverState(),this.isDragging&&(this.isDragging=!1,this.selectionBox.classList.remove("active")),this.pointerDownOnCanvas=!1}clearHoverState(){var e,t;this.clearHoverTimer(),this.hoveredAgentId!==null&&(this.hoveredAgentId=null,(t=(e=this.callbacks).onAgentHover)==null||t.call(e,null,null))}handleSingleClick(e){var i,o,l,c,d,m,p,f;const t=this.raycaster.checkFolderIconClick(e);if(t){const b=t.userData.areaId,x=t.userData.folderPath;if(b){(o=(i=this.callbacks).onFolderIconClick)==null||o.call(i,b,x);return}}const n=this.raycaster.findAgentAtPosition(e);if(n){this.agentClickDetector.handleClick(n)==="double"?this.callbacks.onAgentDoubleClick(n):this.callbacks.onAgentClick(n,e.shiftKey);return}this.agentClickDetector.reset();const a=this.raycaster.raycastGroundFromEvent(e);if(a){const b=this.areaAtPositionGetter(a);if(b){this.areaClickDetector.handleClick(b.id)==="double"?(c=(l=this.callbacks).onAreaDoubleClick)==null||c.call(l,b.id):(m=(d=this.callbacks).onAreaClick)==null||m.call(d,b.id);return}}this.areaClickDetector.reset(),e.shiftKey||(this.callbacks.onGroundClick(),(f=(p=this.callbacks).onGroundClickOutsideArea)==null||f.call(p))}handleBuildingClick(e,t){var a,i,o,l;if(this.buildingClickDetector.handleClick(e)==="double")(i=(a=this.callbacks).onBuildingDoubleClick)==null||i.call(a,e);else{const c=t||{x:window.innerWidth/2,y:window.innerHeight/2};(l=(o=this.callbacks).onBuildingClick)==null||l.call(o,e,c)}}updateSelectionBox(){const e=Math.min(this.dragStart.x,this.dragCurrent.x),t=Math.min(this.dragStart.y,this.dragCurrent.y),n=Math.abs(this.dragCurrent.x-this.dragStart.x),a=Math.abs(this.dragCurrent.y-this.dragStart.y);this.selectionBox.style.left=`${e}px`,this.selectionBox.style.top=`${t}px`,this.selectionBox.style.width=`${n}px`,this.selectionBox.style.height=`${a}px`}selectAgentsInBox(e,t){this.canvas.getBoundingClientRect();const n=Math.min(e.x,t.x),a=Math.max(e.x,t.x),i=Math.min(e.y,t.y),o=Math.max(e.y,t.y),l=[],c=[];for(const[m,p]of this.raycaster.getAgentMeshes()){const f=this.raycaster.projectToScreen(p.group.position);f.x>=n&&f.x<=a&&f.y>=i&&f.y<=o&&l.push(m)}const d=this.buildingPositionsGetter();for(const[m,p]of d){const f=this.raycaster.projectToScreen(p);f.x>=n&&f.x<=a&&f.y>=i&&f.y<=o&&c.push(m)}this.callbacks.onSelectionBox(l,c)}handleHoverDetection(e){var o,l,c,d;this.lastMousePos={x:e.clientX,y:e.clientY};const t=this.raycaster.findAgentAtPosition(e);t!==this.hoveredAgentId&&(this.clearHoverTimer(),this.hoveredAgentId!==null&&((l=(o=this.callbacks).onAgentHover)==null||l.call(o,null,null)),this.hoveredAgentId=t,t&&(this.hoverTimer=setTimeout(()=>{this.triggerHoverCallback()},to.HOVER_DELAY)));const n=this.raycaster.raycastGroundFromEvent(e),a=n?this.buildingAtPositionGetter(n):null,i=(a==null?void 0:a.id)??null;i!==this.hoveredBuildingId&&(this.clearBuildingHoverTimer(),this.hoveredBuildingId!==null&&((d=(c=this.callbacks).onBuildingHover)==null||d.call(c,null,null)),this.hoveredBuildingId=i,i&&(this.buildingHoverTimer=setTimeout(()=>{this.triggerBuildingHoverCallback()},to.BUILDING_HOVER_DELAY)))}triggerHoverCallback(){if(this.hoveredAgentId&&this.callbacks.onAgentHover){const e=this.raycaster.getAgentMeshes().get(this.hoveredAgentId);if(e){const t=this.raycaster.projectToScreen(e.group.position);this.callbacks.onAgentHover(this.hoveredAgentId,t)}}}clearHoverTimer(){this.hoverTimer&&(clearTimeout(this.hoverTimer),this.hoverTimer=null)}triggerBuildingHoverCallback(){if(this.hoveredBuildingId&&this.callbacks.onBuildingHover){const t=this.buildingPositionsGetter().get(this.hoveredBuildingId);if(t){const n=this.raycaster.projectToScreen(t);this.callbacks.onBuildingHover(this.hoveredBuildingId,n)}}}clearBuildingHoverTimer(){this.buildingHoverTimer&&(clearTimeout(this.buildingHoverTimer),this.buildingHoverTimer=null)}clearBuildingHoverState(){var e,t;this.clearBuildingHoverTimer(),this.hoveredBuildingId!==null&&(this.hoveredBuildingId=null,(t=(e=this.callbacks).onBuildingHover)==null||t.call(e,null,null))}getOrderedAgents(e){const t=Array.from(e.values()),n=new Set(t.map(b=>b.id)),i=ai(vt.AGENT_ORDER,[]).filter(b=>n.has(b)),l=t.filter(b=>!i.includes(b.id)).sort((b,x)=>(b.createdAt||0)-(x.createdAt||0)).map(b=>b.id),c=[...i,...l],d=new Map(t.map(b=>[b.id,b])),m=c.map(b=>d.get(b)).filter(b=>b!==void 0),p=new Map;for(const b of m){const x=z.getAreaForAgent(b.id),w=(x==null?void 0:x.id)||null;p.has(w)||p.set(w,{area:x?{name:x.name}:null,agents:[]}),p.get(w).agents.push(b)}const f=Array.from(p.values());return f.sort((b,x)=>{var w,k;return!b.area&&x.area?1:b.area&&!x.area?-1:!b.area&&!x.area?0:(((w=b.area)==null?void 0:w.name)||"").localeCompare(((k=x.area)==null?void 0:k.name)||"")}),f.flatMap(b=>b.agents)}};U(to,"HOVER_DELAY",400),U(to,"HOVER_CHECK_INTERVAL",50),U(to,"BUILDING_HOVER_DELAY",5e3);let Ey=to;class _I{constructor(e){U(this,"scene");U(this,"areaMeshes",new Map);U(this,"previewMesh",null);U(this,"isDrawing",!1);U(this,"drawStartPos",null);U(this,"currentTool",null);U(this,"resizeHandles",[]);U(this,"selectedAreaId",null);U(this,"isResizing",!1);U(this,"resizeHandleType",null);U(this,"resizeStartPos",null);U(this,"resizeOriginalArea",null);U(this,"areaDragAgentStartPositions",new Map);U(this,"areaDragBuildingStartPositions",new Map);U(this,"onAreaCreated",null);U(this,"onFolderIconClick",null);U(this,"folderIconMeshes",[]);U(this,"brightness",1);U(this,"logoTextures",new Map);U(this,"loadingLogoTextures",new Set);this.scene=e}setOnAreaCreated(e){this.onAreaCreated=e}setOnFolderIconClick(e){this.onFolderIconClick=e}getFolderIconMeshes(){return this.folderIconMeshes}handleFolderIconClick(e){const t=e.userData.areaId,n=e.userData.folderPath;t&&this.onFolderIconClick&&this.onFolderIconClick(t,n)}setBrightness(e){this.brightness=e;for(const[t,n]of this.areaMeshes){const a=t===this.selectedAreaId;n.traverse(i=>{if(i instanceof De&&i.name!=="resizeHandle"&&i.name!=="areaLogo"){const o=i.material,l=a?.3:.15;o.opacity=l*this.brightness}})}}setTool(e){this.currentTool=e,(!e||e==="select")&&this.cancelDrawing()}getTool(){return this.currentTool}isInDrawingMode(){return this.currentTool==="rectangle"||this.currentTool==="circle"}startDrawing(e){this.isInDrawingMode()&&(this.isDrawing=!0,this.drawStartPos=e,this.createPreview(e))}updateDrawing(e){!this.isDrawing||!this.drawStartPos||!this.previewMesh||this.updatePreview(e)}finishDrawing(e){var n;if(!this.isDrawing||!this.drawStartPos)return this.cancelDrawing(),null;const t=this.createAreaFromDraw(this.drawStartPos,e);return this.cancelDrawing(),t&&(z.addArea(t),this.renderArea(t),(n=this.onAreaCreated)==null||n.call(this,t)),t}cancelDrawing(){this.isDrawing=!1,this.drawStartPos=null,this.previewMesh&&(this.scene.remove(this.previewMesh),this.disposeGroup(this.previewMesh),this.previewMesh=null)}isCurrentlyDrawing(){return this.isDrawing}renderAllAreas(){const e=z.getState();for(const t of e.areas.values()){if(t.archived){this.areaMeshes.has(t.id)&&this.removeAreaMesh(t.id);continue}this.areaMeshes.has(t.id)||this.renderArea(t)}}renderArea(e){var o;this.removeAreaMesh(e.id);const t=new Fn;t.userData.areaId=e.id,t.userData.zIndex=e.zIndex??0;const n=new Gt(e.color),a=(e.zIndex??0)*.001;if(e.type==="rectangle"&&e.width&&e.height){const l=new pr(e.width,e.height),c=new Ke({color:n,transparent:!0,opacity:.15*this.brightness,side:Ts}),d=new De(l,c);d.rotation.x=-Math.PI/2,d.position.y=.02+a,t.add(d);const m=[new gt(-e.width/2,0,-e.height/2),new gt(e.width/2,0,-e.height/2),new gt(e.width/2,0,e.height/2),new gt(-e.width/2,0,e.height/2),new gt(-e.width/2,0,-e.height/2)],p=new Wa().setFromPoints(m),f=new qo({color:n,linewidth:2}),b=new eo(p,f);b.position.y=.03+a,t.add(b)}else if(e.type==="circle"&&e.radius){const l=new oy(e.radius,32),c=new Ke({color:n,transparent:!0,opacity:.15*this.brightness,side:Ts}),d=new De(l,c);d.rotation.x=-Math.PI/2,d.position.y=.02+a,t.add(d);const m=[];for(let x=0;x<=32;x++){const w=x/32*Math.PI*2;m.push(new gt(Math.cos(w)*e.radius,0,Math.sin(w)*e.radius))}const p=new Wa().setFromPoints(m),f=new qo({color:n,linewidth:2}),b=new eo(p,f);b.position.y=.03+a,t.add(b)}const i=this.createTextLabel(e.name,e.color);if(i.position.y=.05+a,i.name="areaLabel",t.add(i),e.directories&&e.directories.length>0){let d=0,m=0,p=3;if(e.type==="rectangle"&&e.width&&e.height)d=-e.width/2+.4,m=-e.height/2+.4,p=Math.max(1,Math.floor((e.width-.6)/.81));else if(e.type==="circle"&&e.radius){const f=e.radius*.707;d=-f+.3,m=-f+.3,p=Math.max(1,Math.floor((e.radius*1.414-.5)/.81))}e.directories.forEach((f,b)=>{var P;const x=Math.floor(b/p),w=b%p,k=((P=e.directoryGitCounts)==null?void 0:P[b])??0,S=this.createFolderIconSprite(e.color,k);S.name="folderIcon",S.userData.areaId=e.id,S.userData.folderPath=f,S.userData.isFolderIcon=!0,S.position.set(d+w*.81,.3+a,m+x*.81),t.add(S);const j=new Yt(.3,8,8),C=new Ke({visible:!1}),N=new De(j,C);N.position.copy(S.position),N.position.x+=e.center.x,N.position.z+=e.center.z,N.name="folderIconHit",N.userData.areaId=e.id,N.userData.folderPath=f,N.userData.isFolderIcon=!0,this.scene.add(N),this.folderIconMeshes.push(N)})}(o=e.logo)!=null&&o.filename&&this.addLogoToGroup(t,e,a),t.position.set(e.center.x,0,e.center.z),this.scene.add(t),this.areaMeshes.set(e.id,t)}createTextLabel(e,t){const n=document.createElement("canvas"),a=n.getContext("2d"),i=32,o=20,l=64;n.width=1024,n.height=l,a.font=`bold ${i}px Arial`;const c=a.measureText(e).width,d=256;n.width=Math.max(d,c+o*2),a.clearRect(0,0,n.width,n.height),a.font=`bold ${i}px Arial`,a.textAlign="center",a.textBaseline="middle",a.strokeStyle="#000000",a.lineWidth=4,a.strokeText(e,n.width/2,n.height/2),a.fillStyle=t,a.fillText(e,n.width/2,n.height/2);const m=new ss(n);m.needsUpdate=!0;const p=new Xn({map:m,transparent:!0,depthTest:!1}),f=new Un(p),b=.5,x=2*(n.width/256);return f.scale.set(x,b,1),f}createFolderIconSprite(e,t=0){const n=document.createElement("canvas"),a=128;n.width=a,n.height=a;const i=n.getContext("2d");i.fillStyle="rgba(0, 0, 0, 0.6)",i.beginPath(),i.arc(a/2,a/2,a*.45,0,Math.PI*2),i.fill(),i.strokeStyle=e,i.lineWidth=3,i.beginPath(),i.arc(a/2,a/2,a*.45,0,Math.PI*2),i.stroke();const o=a*.5,l=a*.35,c=(a-o)/2,d=(a-l)/2+2,m=o*.35,p=l*.22;if(i.fillStyle=e,i.beginPath(),i.moveTo(c+4,d+p),i.lineTo(c+m,d+p),i.lineTo(c+m+p,d),i.lineTo(c+4,d),i.moveTo(c,d+p),i.lineTo(c,d+l),i.lineTo(c+o,d+l),i.lineTo(c+o,d+p),i.closePath(),i.fill(),i.strokeStyle="rgba(255, 255, 255, 0.3)",i.lineWidth=1.5,i.beginPath(),i.moveTo(c+4,d+p+3),i.lineTo(c+o-4,d+p+3),i.stroke(),t>0){const w=a*.16,k=a*.78,S=a*.78;i.fillStyle="#e8943a",i.beginPath(),i.arc(k,S,w,0,Math.PI*2),i.fill(),i.strokeStyle="rgba(0, 0, 0, 0.7)",i.lineWidth=2,i.beginPath(),i.arc(k,S,w,0,Math.PI*2),i.stroke();const j=t>99?"99+":String(t),C=w*1.3;i.font=`bold ${C}px "Segoe UI", Arial, sans-serif`,i.fillStyle="#ffffff",i.textAlign="center",i.textBaseline="middle",i.fillText(j,k,S)}const f=new ss(n);f.needsUpdate=!0;const b=new Xn({map:f,transparent:!0,depthTest:!1}),x=new Un(b);return x.scale.set(.6,.6,1),x}addLogoToGroup(e,t,n){const a=t.logo,i=kd(rt(`/api/areas/logos/${a.filename}`)),o=this.logoTextures.get(a.filename);if(o){this.createLogoMesh(e,t,o,n);return}if(this.loadingLogoTextures.has(a.filename))return;this.loadingLogoTextures.add(a.filename);const l=t.id;new fx().load(i,d=>{var f;this.logoTextures.set(a.filename,d),this.loadingLogoTextures.delete(a.filename);const m=this.areaMeshes.get(l),p=z.getState().areas.get(l);if(m&&((f=p==null?void 0:p.logo)!=null&&f.filename)){const b=(p.zIndex??0)*.001;this.createLogoMesh(m,p,d,b)}},void 0,()=>{this.loadingLogoTextures.delete(a.filename)})}createLogoMesh(e,t,n,a){const i=t.logo,o=new pr(i.width,i.height),l=new Ke({map:n,transparent:!0,opacity:i.opacity??.8,side:Ts,depthWrite:!0,alphaTest:.01}),c=new De(o,l);c.rotation.x=-Math.PI/2,c.name="areaLogo",c.renderOrder=-1;const d=this.calculateLogoOffset(t,i.position,i.width,i.height);c.position.set(d.x,.04+a,d.z),e.add(c)}calculateLogoOffset(e,t,n,a){if(t==="center")return{x:0,z:0};let i=0,o=0;e.type==="rectangle"&&e.width&&e.height?(i=e.width,o=e.height):e.type==="circle"&&e.radius&&(i=e.radius*1.414,o=e.radius*1.414);const l=n/2+.2,c=a/2+.2;switch(t){case"top-left":return{x:-i/2+l,z:-o/2+c};case"top-right":return{x:i/2-l,z:-o/2+c};case"bottom-left":return{x:-i/2+l,z:o/2-c};case"bottom-right":return{x:i/2-l,z:o/2-c};default:return{x:0,z:0}}}updateAreaMesh(e){this.renderArea(e)}removeAreaMesh(e){const t=this.areaMeshes.get(e);t&&(this.scene.remove(t),this.disposeGroup(t),this.areaMeshes.delete(e)),this.folderIconMeshes=this.folderIconMeshes.filter(n=>n.userData.areaId===e?(this.scene.remove(n),n.geometry.dispose(),n.material.dispose(),!1):!0)}highlightArea(e){this.selectedAreaId=e,this.removeResizeHandles();for(const[t,n]of this.areaMeshes){const a=t===e;n.traverse(i=>{if(i instanceof De&&i.name!=="resizeHandle"&&i.name!=="areaLogo"){const o=i.material,l=a?.3:.15;o.opacity=l*this.brightness}if(i instanceof eo){const o=i.material;o.opacity=a?1:.8}})}if(e){const t=z.getState().areas.get(e);t&&this.createResizeHandles(t)}}createResizeHandles(e){const t=new Yt(.15,16,16),n=new Ke({color:16777215,transparent:!0,opacity:.9}),a=new Ke({color:16763904,transparent:!0,opacity:.9}),i=(e.zIndex??0)*.001,o=new De(t.clone(),a.clone());if(o.position.set(e.center.x,.25+i,e.center.z),o.name="resizeHandle",o.userData.handleType="move",o.userData.areaId=e.id,this.scene.add(o),this.resizeHandles.push(o),e.type==="rectangle"&&e.width&&e.height){const l=[{type:"nw",x:-e.width/2,z:-e.height/2},{type:"ne",x:e.width/2,z:-e.height/2},{type:"sw",x:-e.width/2,z:e.height/2},{type:"se",x:e.width/2,z:e.height/2}];for(const p of l){const f=new De(t.clone(),n.clone());f.position.set(e.center.x+p.x,.2+i,e.center.z+p.z),f.name="resizeHandle",f.userData.handleType=p.type,f.userData.areaId=e.id,this.scene.add(f),this.resizeHandles.push(f)}const c=new Ke({color:11197951,transparent:!0,opacity:.9}),d=new Yt(.12,16,16),m=[{type:"n",x:0,z:-e.height/2},{type:"s",x:0,z:e.height/2},{type:"e",x:e.width/2,z:0},{type:"w",x:-e.width/2,z:0}];for(const p of m){const f=new De(d.clone(),c.clone());f.position.set(e.center.x+p.x,.2+i,e.center.z+p.z),f.name="resizeHandle",f.userData.handleType=p.type,f.userData.areaId=e.id,this.scene.add(f),this.resizeHandles.push(f)}c.dispose(),d.dispose()}else if(e.type==="circle"&&e.radius){const l=new De(t.clone(),n.clone());l.position.set(e.center.x+e.radius,.2+i,e.center.z),l.name="resizeHandle",l.userData.handleType="radius",l.userData.areaId=e.id,this.scene.add(l),this.resizeHandles.push(l)}t.dispose(),n.dispose(),a.dispose()}removeResizeHandles(){for(const e of this.resizeHandles)this.scene.remove(e),e.geometry.dispose(),e.material.dispose();this.resizeHandles=[]}getResizeHandles(){return this.resizeHandles}isCurrentlyResizing(){return this.isResizing}startResize(e,t){const n=e.userData.areaId,a=e.userData.handleType,i=z.getState().areas.get(n);if(i&&(this.isResizing=!0,this.resizeHandleType=a,this.resizeStartPos=t,this.resizeOriginalArea={...i},this.areaDragAgentStartPositions.clear(),this.areaDragBuildingStartPositions.clear(),a==="move")){const o=z.getState();for(const l of o.agents.values())this.isPointInsideArea(l.position.x,l.position.z,i)&&this.areaDragAgentStartPositions.set(l.id,{...l.position});for(const l of o.buildings.values())this.isPointInsideArea(l.position.x,l.position.z,i)&&this.areaDragBuildingStartPositions.set(l.id,{...l.position})}}updateResize(e){if(!this.isResizing||!this.resizeOriginalArea||!this.resizeHandleType||!this.resizeStartPos)return;const t=this.resizeOriginalArea;let n={};if(this.resizeHandleType==="move"){const a=e.x-this.resizeStartPos.x,i=e.z-this.resizeStartPos.z;n={center:{x:t.center.x+a,z:t.center.z+i}};for(const[o,l]of this.areaDragAgentStartPositions)z.moveAgentLocal(o,{x:l.x+a,y:l.y,z:l.z+i});for(const[o,l]of this.areaDragBuildingStartPositions)z.updateBuildingLocal(o,{position:{x:l.x+a,z:l.z+i}})}else if(t.type==="rectangle"&&t.width&&t.height){const a=e.x-this.resizeStartPos.x,i=e.z-this.resizeStartPos.z,o=t.width,l=t.height,c=t.center.x,d=t.center.z,m=x=>{const w=Math.max(.5,o+x);return{width:w,cx:c+(w-o)/2}},p=x=>{const w=Math.max(.5,o-x);return{width:w,cx:c+(o-w)/2}},f=x=>{const w=Math.max(.5,l+x);return{height:w,cz:d+(w-l)/2}},b=x=>{const w=Math.max(.5,l-x);return{height:w,cz:d+(l-w)/2}};switch(this.resizeHandleType){case"se":{const x=m(a),w=f(i);n={width:x.width,height:w.height,center:{x:x.cx,z:w.cz}};break}case"sw":{const x=p(a),w=f(i);n={width:x.width,height:w.height,center:{x:x.cx,z:w.cz}};break}case"ne":{const x=m(a),w=b(i);n={width:x.width,height:w.height,center:{x:x.cx,z:w.cz}};break}case"nw":{const x=p(a),w=b(i);n={width:x.width,height:w.height,center:{x:x.cx,z:w.cz}};break}case"e":{const x=m(a);n={width:x.width,center:{x:x.cx,z:d}};break}case"w":{const x=p(a);n={width:x.width,center:{x:x.cx,z:d}};break}case"s":{const x=f(i);n={height:x.height,center:{x:c,z:x.cz}};break}case"n":{const x=b(i);n={height:x.height,center:{x:c,z:x.cz}};break}}}else if(t.type==="circle"&&this.resizeHandleType==="radius"){const a=e.x-t.center.x,i=e.z-t.center.z;n={radius:Math.max(.5,Math.sqrt(a*a+i*i))}}Object.keys(n).length>0&&z.updateArea(t.id,n)}finishResize(){if(this.resizeHandleType==="move"&&this.resizeOriginalArea&&this.resizeStartPos){const t=z.getState().areas.get(this.resizeOriginalArea.id);if(t){const n=t.center.x-this.resizeOriginalArea.center.x,a=t.center.z-this.resizeOriginalArea.center.z;if(n!==0||a!==0){for(const[i,o]of this.areaDragAgentStartPositions)z.moveAgent(i,{x:o.x+n,y:o.y,z:o.z+a});for(const[i,o]of this.areaDragBuildingStartPositions)z.moveBuilding(i,{x:o.x+n,z:o.z+a})}}}if(this.isResizing=!1,this.resizeHandleType=null,this.resizeStartPos=null,this.resizeOriginalArea=null,this.areaDragAgentStartPositions.clear(),this.areaDragBuildingStartPositions.clear(),this.selectedAreaId){this.removeResizeHandles();const e=z.getState().areas.get(this.selectedAreaId);e&&this.createResizeHandles(e)}}isPointInsideArea(e,t,n){if(n.type==="rectangle"&&n.width&&n.height){const a=n.width/2,i=n.height/2;return e>=n.center.x-a&&e<=n.center.x+a&&t>=n.center.z-i&&t<=n.center.z+i}if(n.type==="circle"&&n.radius){const a=e-n.center.x,i=t-n.center.z;return a*a+i*i<=n.radius*n.radius}return!1}getAreaAtPosition(e){const t=z.getState(),n=Array.from(t.areas.values()).filter(a=>!a.archived).sort((a,i)=>(i.zIndex??0)-(a.zIndex??0));for(const a of n)if(a.type==="rectangle"&&a.width&&a.height){const i=a.width/2,o=a.height/2;if(e.x>=a.center.x-i&&e.x<=a.center.x+i&&e.z>=a.center.z-o&&e.z<=a.center.z+o)return a}else if(a.type==="circle"&&a.radius){const i=e.x-a.center.x,o=e.z-a.center.z;if(Math.sqrt(i*i+o*o)<=a.radius)return a}return null}syncFromStore(){const e=z.getState();for(const t of this.areaMeshes.keys()){const n=e.areas.get(t);(!n||n.archived)&&this.removeAreaMesh(t)}for(const t of e.areas.values())t.archived||this.renderArea(t)}createPreview(e){this.previewMesh=new Fn,this.scene.add(this.previewMesh)}updatePreview(e){if(!this.previewMesh||!this.drawStartPos)return;for(;this.previewMesh.children.length>0;){const n=this.previewMesh.children[0];this.previewMesh.remove(n),(n instanceof De||n instanceof eo)&&(n.geometry.dispose(),n.material.dispose())}const t=new Gt("#4a9eff");if(this.currentTool==="rectangle"){const n=Math.abs(e.x-this.drawStartPos.x),a=Math.abs(e.z-this.drawStartPos.z),i=(e.x+this.drawStartPos.x)/2,o=(e.z+this.drawStartPos.z)/2;if(n>.1&&a>.1){const l=new pr(n,a),c=new Ke({color:t,transparent:!0,opacity:.2,side:Ts}),d=new De(l,c);d.rotation.x=-Math.PI/2,d.position.set(i,.02,o),this.previewMesh.add(d);const m=[new gt(this.drawStartPos.x,.03,this.drawStartPos.z),new gt(e.x,.03,this.drawStartPos.z),new gt(e.x,.03,e.z),new gt(this.drawStartPos.x,.03,e.z),new gt(this.drawStartPos.x,.03,this.drawStartPos.z)],p=new Wa().setFromPoints(m),f=new qo({color:t}),b=new eo(p,f);this.previewMesh.add(b)}}else if(this.currentTool==="circle"){const n=e.x-this.drawStartPos.x,a=e.z-this.drawStartPos.z,i=Math.sqrt(n*n+a*a);if(i>.1){const o=new oy(i,32),l=new Ke({color:t,transparent:!0,opacity:.2,side:Ts}),c=new De(o,l);c.rotation.x=-Math.PI/2,c.position.set(this.drawStartPos.x,.02,this.drawStartPos.z),this.previewMesh.add(c);const d=[];for(let b=0;b<=32;b++){const x=b/32*Math.PI*2;d.push(new gt(this.drawStartPos.x+Math.cos(x)*i,.03,this.drawStartPos.z+Math.sin(x)*i))}const m=new Wa().setFromPoints(d),p=new qo({color:t}),f=new eo(m,p);this.previewMesh.add(f)}}}createAreaFromDraw(e,t){const n=`area_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,a=z.getState().areas.size,i=z.getNextZIndex();if(this.currentTool==="rectangle"){const o=Math.abs(t.x-e.x),l=Math.abs(t.z-e.z);return o<.5||l<.5?null:{id:n,name:`Area ${a+1}`,type:"rectangle",center:{x:(e.x+t.x)/2,z:(e.z+t.z)/2},width:o,height:l,color:"#4a9eff",zIndex:i,assignedAgentIds:[],directories:[]}}else if(this.currentTool==="circle"){const o=t.x-e.x,l=t.z-e.z,c=Math.sqrt(o*o+l*l);return c<.5?null:{id:n,name:`Area ${a+1}`,type:"circle",center:{x:e.x,z:e.z},radius:c,color:"#4a9eff",zIndex:i,assignedAgentIds:[],directories:[]}}return null}disposeGroup(e){e.traverse(t=>{if(t instanceof De&&(t.geometry.dispose(),Array.isArray(t.material)?t.material.forEach(n=>n.dispose()):t.material.dispose()),t instanceof eo&&(t.geometry.dispose(),t.material.dispose()),t instanceof Un){const n=t.material;n.map&&n.map.dispose(),n.dispose()}})}dispose(){this.cancelDrawing(),this.removeResizeHandles();for(const e of this.areaMeshes.keys())this.removeAreaMesh(e);for(const e of this.folderIconMeshes)this.scene.remove(e),e.geometry.dispose(),e.material.dispose();this.folderIconMeshes=[]}}const ds={running:4915102,stopped:8947848,error:16730698,unknown:16755200,starting:4890367,stopping:16755200},Cd={desktop:{primary:7438486,secondary:4871528,accent:6534125,glow:4915102},"filing-cabinet":{primary:6869905,secondary:4766584,accent:10151604,glow:4915102},satellite:{primary:8411861,secondary:7030465,accent:12031220,glow:4890367},crystal:{primary:15557798,secondary:13975436,accent:16156595,glow:10451690},factory:{primary:15567158,secondary:14510880,accent:16166229,glow:16755200}};function Fi(s){return s.name}function pi(s){const e=document.createElement("canvas"),t=e.getContext("2d"),n=56,a=28,i=72,o=144;e.width=1024,e.height=o,t.font=`bold ${n}px Arial`;const l=t.measureText(s).width,c=256,d=l+a*2+16;e.width=Math.max(c,d),t.clearRect(0,0,e.width,e.height),t.font=`bold ${n}px Arial`;const m=l+a*2,p=(e.width-m)/2,f=(e.height-i)/2;t.fillStyle="rgba(0, 0, 0, 0.8)",t.beginPath(),t.roundRect(p,f,m,i,10),t.fill(),t.textAlign="center",t.textBaseline="middle",t.fillStyle="#ffffff",t.fillText(s,e.width/2,e.height/2);const b=new ss(e);b.minFilter=zn,b.magFilter=zn,b.needsUpdate=!0;const x=new Xn({map:b,transparent:!0,depthTest:!1}),w=new Un(x),k=.5,S=e.width/e.height;return w.scale.set(k*S,k,1),w.userData.aspectRatio=S,w}function DM(s){const e=document.createElement("canvas"),t=e.getContext("2d");e.width=64,e.height=64,t.fillStyle="#c89a5a",t.beginPath(),t.arc(32,32,28,0,Math.PI*2),t.fill(),t.strokeStyle="rgba(0, 0, 0, 0.5)",t.lineWidth=3,t.beginPath(),t.arc(32,32,28,0,Math.PI*2),t.stroke(),t.fillStyle="#ffffff",t.font="bold 28px Arial",t.textAlign="center",t.textBaseline="middle",t.fillText(s>99?"99+":String(s),32,32);const n=new ss(e);n.minFilter=zn,n.magFilter=zn;const a=new Xn({map:n,transparent:!0,depthTest:!1}),i=new Un(a);return i.scale.set(.35,.35,1),i.name="gitIndicator",i}function DI(s,e){const t=s.material;t.map&&t.map.dispose(),t.dispose();const n=DM(e);s.material=n.material}function PI(s,e){const t=s.label,n=pi(e);n.position.copy(t.position),n.name="buildingLabel",s.group.remove(t),t.material instanceof Xn&&(t.material.map&&t.material.map.dispose(),t.material.dispose()),s.group.add(n),s.label=n}function RI(s){const e=new Fn;e.userData.buildingId=s.id,e.userData.isBuilding=!0;const t=s.color?new Gt(s.color):new Gt(2763322),n=new un(1.2,2.5,.8),a=new dt({color:t,metalness:.7,roughness:.3}),i=new De(n,a);i.position.y=1.25,i.castShadow=!0,i.receiveShadow=!0,i.name="buildingBody",e.add(i);for(let C=0;C<5;C++){const N=new un(1.1,.02,.75),P=new dt({color:1710634,metalness:.5,roughness:.5}),_=new De(N,P);_.position.set(0,.5+C*.45,.03),e.add(_)}for(let C=0;C<5;C++){const N=new un(.08,.08,.05),P=new Ke({color:4915102,transparent:!0,opacity:.9}),_=new De(N,P);_.position.set(-.45,.5+C*.45,.43),_.name=`led_${C}`,e.add(_);const L=new De(N.clone(),P.clone());L.position.set(-.3,.5+C*.45,.43),L.name=`activityLed_${C}`,e.add(L)}const o=new un(1,.1,.6),l=new dt({color:1710634,metalness:.3,roughness:.7}),c=new De(o,l);c.position.set(0,2.55,0),e.add(c);const d=new Yt(.15,16,16),m=new Ke({color:ds[s.status],transparent:!0,opacity:.95}),p=new De(d,m);p.position.set(0,2.75,0),p.name="statusLight",e.add(p);const f=new Yt(.25,16,16),b=new Ke({color:ds[s.status],transparent:!0,opacity:.3}),x=new De(f,b);x.position.set(0,2.75,0),x.name="statusGlow",e.add(x);const w=new un(1.5,.1,1.1),k=new dt({color:3816010,metalness:.5,roughness:.5}),S=new De(w,k);S.position.y=.05,S.receiveShadow=!0,e.add(S);const j=pi(Fi(s));return j.position.set(0,3.2,0),j.name="buildingLabel",e.add(j),e.position.set(s.position.x,0,s.position.z),{group:e,statusLight:p,label:j}}function LI(s,e){for(let t=0;t<5;t++){const n=s.group.getObjectByName(`led_${t}`);if(n&&n.material instanceof Ke){const i=Math.sin(e*.8+t*1.2);n.material.opacity=i>.3?.6:.15}const a=s.group.getObjectByName(`activityLed_${t}`);a&&a.material instanceof Ke&&(a.material.opacity=Math.random()>.97?.5:.1)}}function OI(s,e){for(let t=0;t<5;t++){const n=s.group.getObjectByName(`activityLed_${t}`);n&&n.material instanceof Ke&&Math.random()>.95&&(n.material.opacity=n.material.opacity>.5?.2:.9)}}function II(s){const e=new Fn;e.userData.buildingId=s.id,e.userData.isBuilding=!0;const t=s.color?new Gt(s.color):new Gt(2767434),n=new Gn(.5,.7,3,8),a=new dt({color:t,metalness:.6,roughness:.4}),i=new De(n,a);i.position.y=1.5,i.castShadow=!0,i.receiveShadow=!0,i.name="buildingBody",e.add(i);for(let R=0;R<4;R++){const O=new Gn(.52-R*.03,.62-R*.03,.1,8),I=new Ke({color:4890367,transparent:!0,opacity:.7}),B=new De(O,I);B.position.y=.7+R*.6,B.name=`windowBand_${R}`,e.add(B)}const o=new Gn(.6,.5,.2,8),l=new dt({color:3816010,metalness:.7,roughness:.3}),c=new De(o,l);c.position.y=3.1,e.add(c);const d=new Gn(.15,.2,.3,6),m=new dt({color:4868698,metalness:.8,roughness:.2}),p=new De(d,m);p.position.y=3.35,e.add(p);const f=new Fn;f.position.y=3.6,f.name="antenna";const b=new un(.05,.6,.05),x=new dt({color:6974074,metalness:.9,roughness:.1}),w=new De(b,x);w.position.y=.3,f.add(w);const k=new bc(.15,.1,8);for(let R=0;R<2;R++){const O=new De(k,x);O.rotation.x=Math.PI/2,O.position.set(R===0?.2:-.2,.4,0),O.rotation.z=R===0?Math.PI/2:-Math.PI/2,f.add(O)}e.add(f);const S=new Yt(.12,16,16),j=new Ke({color:ds[s.status],transparent:!0,opacity:.95}),C=new De(S,j);C.position.set(0,4.3,0),C.name="statusLight",e.add(C);const N=new Yt(.2,16,16),P=new Ke({color:ds[s.status],transparent:!0,opacity:.3}),_=new De(N,P);_.position.set(0,4.3,0),_.name="statusGlow",e.add(_);const L=new Gn(.9,1,.15,8),M=new dt({color:3816010,metalness:.5,roughness:.5}),D=new De(L,M);D.position.y=.075,D.receiveShadow=!0,e.add(D);const E=pi(Fi(s));return E.position.set(0,4.7,0),E.name="buildingLabel",e.add(E),e.position.set(s.position.x,0,s.position.z),{group:e,statusLight:C,label:E}}function BI(s,e,t){const n=s.group.getObjectByName("antenna");n&&(n.rotation.y+=t*.3);for(let a=0;a<4;a++){const i=s.group.getObjectByName(`windowBand_${a}`);i&&i.material instanceof Ke&&(i.material.opacity=.3+Math.sin(e*.5+a*.4)*.15)}}function zI(s,e,t){const n=s.group.getObjectByName("antenna");n&&(n.rotation.y+=t*2);for(let a=0;a<4;a++){const i=s.group.getObjectByName(`windowBand_${a}`);if(i&&i.material instanceof Ke){const o=Math.sin(e*4+a*.5)*.3+.7;i.material.opacity=o}}}function FI(s){const e=new Fn;e.userData.buildingId=s.id,e.userData.isBuilding=!0;const t=s.color?new Gt(s.color):new Gt(2763338),n=new Yt(1.2,32,16,0,Math.PI*2,0,Math.PI/2),a=new dt({color:t,metalness:.4,roughness:.6,transparent:!0,opacity:.9}),i=new De(n,a);i.position.y=.15,i.castShadow=!0,i.receiveShadow=!0,i.name="buildingBody",e.add(i);const o=new Yt(.8,24,12,0,Math.PI*2,0,Math.PI/2),l=new Ke({color:4890367,transparent:!0,opacity:.3}),c=new De(o,l);c.position.y=.15,c.name="innerDome",e.add(c);const d=new dc(1,.05,8,32),m=new Ke({color:4915102,transparent:!0,opacity:.8}),p=new De(d,m);p.position.y=.6,p.rotation.x=Math.PI/2,p.name="energyRing",e.add(p);const f=new De(d.clone(),m.clone());f.position.y=.8,f.rotation.x=Math.PI/3,f.name="energyRing2",e.add(f);for(let L=0;L<4;L++){const M=new Gn(.03,.03,1.2,8),D=new Ke({color:4890367,transparent:!0,opacity:.6}),E=new De(M,D),R=L/4*Math.PI*2;E.position.set(Math.cos(R)*.5,.75,Math.sin(R)*.5),E.name=`beam_${L}`,e.add(E)}const b=new Yt(.15,16,16),x=new Ke({color:ds[s.status],transparent:!0,opacity:.95}),w=new De(b,x);w.position.set(0,1.4,0),w.name="statusLight",e.add(w);const k=new Yt(.25,16,16),S=new Ke({color:ds[s.status],transparent:!0,opacity:.3}),j=new De(k,S);j.position.set(0,1.4,0),j.name="statusGlow",e.add(j);const C=new Gn(1.4,1.5,.15,32),N=new dt({color:3816010,metalness:.6,roughness:.4}),P=new De(C,N);P.position.y=.075,P.receiveShadow=!0,e.add(P);const _=pi(Fi(s));return _.position.set(0,1.9,0),_.name="buildingLabel",e.add(_),e.position.set(s.position.x,0,s.position.z),{group:e,statusLight:w,label:_}}function $I(s,e,t){const n=s.group.getObjectByName("energyRing"),a=s.group.getObjectByName("energyRing2");n&&(n.rotation.z+=t*.2),a&&(a.rotation.z-=t*.15);const i=s.group.getObjectByName("innerDome");i&&i.material instanceof Ke&&(i.material.opacity=.15+Math.sin(e*.6)*.1);for(let o=0;o<4;o++){const l=s.group.getObjectByName(`beam_${o}`);l&&l.material instanceof Ke&&(l.material.opacity=.2+Math.sin(e*.5+o*.3)*.1)}}function HI(s,e,t){const n=s.group.getObjectByName("energyRing"),a=s.group.getObjectByName("energyRing2");n&&(n.rotation.z+=t*1.5),a&&(a.rotation.z-=t*1.2);const i=s.group.getObjectByName("innerDome");i&&i.material instanceof Ke&&(i.material.opacity=.2+Math.sin(e*2)*.15);for(let o=0;o<4;o++){const l=s.group.getObjectByName(`beam_${o}`);if(l&&l.material instanceof Ke){const c=Math.sin(e*5+o*1.5)*.3+.6;l.material.opacity=c}}}function UI(s){const e=new Fn;e.userData.buildingId=s.id,e.userData.isBuilding=!0;const t=s.color?new Gt(s.color):new Gt(3815978),n=new bc(1.3,2.5,4),a=new dt({color:t,metalness:.3,roughness:.7}),i=new De(n,a);i.position.y=1.25,i.rotation.y=Math.PI/4,i.castShadow=!0,i.receiveShadow=!0,i.name="buildingBody",e.add(i);const o=new bc(.6,1.2,4),l=new Ke({color:16755200,transparent:!0,opacity:.6}),c=new De(o,l);c.position.y=.8,c.rotation.y=Math.PI/4,c.name="pyramidCore",e.add(c);const d=[{x:.9,z:0},{x:-.9,z:0},{x:0,z:.9},{x:0,z:-.9}];for(let E=0;E<4;E++){const R=new Gn(.02,.02,2.7,8),O=new Ke({color:4915102,transparent:!0,opacity:.7}),I=new De(R,O),B=d[E];I.position.set(B.x*.5,1.25,B.z*.5);const Y=Math.atan2(1.25,.65);E<2?I.rotation.z=E===0?-Y:Y:I.rotation.x=E===2?Y:-Y,I.name=`edgeLine_${E}`,e.add(I)}const m=new Yt(.15,16,16),p=new Ke({color:16755200,transparent:!0,opacity:.9}),f=new De(m,p);f.position.y=2.7,f.name="pyramidEye",e.add(f);const b=new Yt(.25,16,16),x=new Ke({color:16755200,transparent:!0,opacity:.3}),w=new De(b,x);w.position.y=2.7,w.name="pyramidEyeGlow",e.add(w);const k=new Yt(.12,16,16),S=new Ke({color:ds[s.status],transparent:!0,opacity:.95}),j=new De(k,S);j.position.set(1.2,.3,0),j.name="statusLight",e.add(j);const C=new Yt(.2,16,16),N=new Ke({color:ds[s.status],transparent:!0,opacity:.3}),P=new De(C,N);P.position.set(1.2,.3,0),P.name="statusGlow",e.add(P);const _=new un(2.8,.15,2.8),L=new dt({color:4868666,metalness:.2,roughness:.8}),M=new De(_,L);M.position.y=.075,M.receiveShadow=!0,e.add(M);const D=pi(Fi(s));return D.position.set(0,3.2,0),D.name="buildingLabel",e.add(D),e.position.set(s.position.x,0,s.position.z),{group:e,statusLight:j,label:D}}function GI(s,e){const t=s.group.getObjectByName("pyramidEye"),n=s.group.getObjectByName("pyramidEyeGlow");t&&(t.position.y=2.7+Math.sin(e*.5)*.03,t.material instanceof Ke&&(t.material.opacity=.4+Math.sin(e*.7)*.2)),n&&(n.position.y=2.7+Math.sin(e*.5)*.03,n.material instanceof Ke&&(n.material.opacity=.15+Math.sin(e*.7)*.1));const a=s.group.getObjectByName("pyramidCore");a&&a.material instanceof Ke&&(a.material.opacity=.2+Math.sin(e*.5)*.1)}function WI(s,e){const t=s.group.getObjectByName("pyramidCore");t&&t.material instanceof Ke&&(t.material.opacity=.4+Math.sin(e*2)*.2);const n=s.group.getObjectByName("pyramidEye"),a=s.group.getObjectByName("pyramidEyeGlow");n&&n.material instanceof Ke&&(n.material.opacity=.7+Math.sin(e*3)*.3),a&&a.material instanceof Ke&&(a.material.opacity=.2+Math.sin(e*3)*.15),n&&(n.position.y=2.7+Math.sin(e*1.5)*.1),a&&(a.position.y=2.7+Math.sin(e*1.5)*.1)}function qI(s){const e=new Fn;e.userData.buildingId=s.id,e.userData.isBuilding=!0;const t=Cd.desktop,n=s.color?new Gt(s.color):new Gt(t.primary),a=new un(1.4,1,.15),i=new dt({color:n,metalness:.4,roughness:.6}),o=new De(a,i);o.position.set(0,1.4,0),o.castShadow=!0,o.name="buildingBody",e.add(o);const l=new un(1.2,.8,.02),c=new Ke({color:661032,transparent:!0,opacity:.95}),d=new De(l,c);d.position.set(0,1.4,.09),d.name="screen",e.add(d);for(let K=0;K<6;K++){const X=new un(.8-K%3*.2,.05,.01),H=new Ke({color:t.glow,transparent:!0,opacity:.9}),se=new De(X,H);se.position.set(-.1+K%2*.1,1.65-K*.1,.1),se.name=`codeLine_${K}`,e.add(se)}const m=new un(.15,.6,.15),p=new dt({color:t.secondary,metalness:.5,roughness:.5}),f=new De(m,p);f.position.set(0,.6,0),e.add(f);const b=new un(.6,.08,.4),x=new De(b,p);x.position.set(0,.25,0),e.add(x);const w=new un(1,.08,.35),k=new dt({color:t.secondary,metalness:.3,roughness:.7}),S=new De(w,k);S.position.set(0,.2,.6),S.rotation.x=-.1,e.add(S);for(let K=0;K<3;K++)for(let X=0;X<10;X++){const H=new un(.07,.03,.07),se=new dt({color:t.accent,metalness:.2,roughness:.8}),ce=new De(H,se);ce.position.set(-.38+X*.085,.25,.45+K*.1),e.add(ce)}const j=new un(.4,.9,.8),C=new dt({color:n,metalness:.4,roughness:.6}),N=new De(j,C);N.position.set(-1.1,.55,0),N.castShadow=!0,e.add(N);const P=new un(.05,.05,.02),_=new Ke({color:4915102,transparent:!0,opacity:.9}),L=new De(P,_);L.position.set(-.88,.7,.3),L.name="cpuLed",e.add(L);const M=new Yt(.1,16,16),D=new Ke({color:ds[s.status],transparent:!0,opacity:.95}),E=new De(M,D);E.position.set(.6,1.85,.1),E.name="statusLight",e.add(E);const R=new Yt(.18,16,16),O=new Ke({color:ds[s.status],transparent:!0,opacity:.3}),I=new De(R,O);I.position.set(.6,1.85,.1),I.name="statusGlow",e.add(I);const B=new un(2.6,.1,1.4),Y=new dt({color:3816010,metalness:.5,roughness:.5}),$=new De(B,Y);$.position.y=.05,$.receiveShadow=!0,e.add($);const W=pi(Fi(s));return W.position.set(0,2.3,0),W.name="buildingLabel",e.add(W),e.position.set(s.position.x,0,s.position.z),{group:e,statusLight:E,label:W}}function YI(s,e){const t=s.group.getObjectByName("buildingBody");t&&(t.rotation.y=Math.sin(e*.3)*.01);for(let n=0;n<6;n++){const a=s.group.getObjectByName(`codeLine_${n}`);a&&a.material instanceof Ke&&(a.material.opacity=.3+Math.sin(e*.4+n*.2)*.1)}}function VI(s,e){for(let n=0;n<6;n++){const a=s.group.getObjectByName(`codeLine_${n}`);if(a&&a.material instanceof Ke){const i=Math.random()>.98?.4:.8;a.material.opacity=i}}const t=s.group.getObjectByName("cpuLed");if(t&&t.material instanceof Ke){const n=Math.sin(e*6)>0?.9:.3;t.material.opacity=n}}function KI(s){const e=new Fn;e.userData.buildingId=s.id,e.userData.isBuilding=!0;const t=Cd["filing-cabinet"],n=s.color?new Gt(s.color):new Gt(t.primary),a=new un(1,2.4,.8),i=new dt({color:n,metalness:.5,roughness:.5}),o=new De(a,i);o.position.y=1.2,o.castShadow=!0,o.name="buildingBody",e.add(o);for(let S=0;S<4;S++){const j=new un(.9,.5,.05),C=new dt({color:t.secondary,metalness:.4,roughness:.6}),N=new De(j,C);N.position.set(0,.35+S*.55,.4),N.name=`drawer_${S}`,e.add(N);const P=new un(.3,.06,.05),_=new dt({color:t.accent,metalness:.7,roughness:.3}),L=new De(P,_);L.position.set(0,.35+S*.55,.47),L.name=`handle_${S}`,e.add(L);const M=new un(.4,.15,.02),D=new Ke({color:16777198}),E=new De(M,D);E.position.set(0,.45+S*.55,.44),e.add(E)}for(let S=0;S<4;S++){const j=new un(.06,.06,.02),C=new Ke({color:S%2===0?t.glow:t.accent,transparent:!0,opacity:.9}),N=new De(j,C);N.position.set(-.38,.35+S*.55,.42),N.name=`indicator_${S}`,e.add(N)}const l=new Yt(.12,16,16),c=new Ke({color:ds[s.status],transparent:!0,opacity:.95}),d=new De(l,c);d.position.set(0,2.55,0),d.name="statusLight",e.add(d);const m=new Yt(.2,16,16),p=new Ke({color:ds[s.status],transparent:!0,opacity:.3}),f=new De(m,p);f.position.set(0,2.55,0),f.name="statusGlow",e.add(f);const b=new un(1.3,.1,1.1),x=new dt({color:3816010,metalness:.5,roughness:.5}),w=new De(b,x);w.position.y=.05,w.receiveShadow=!0,e.add(w);const k=pi(Fi(s));return k.position.set(0,3,0),k.name="buildingLabel",e.add(k),e.position.set(s.position.x,0,s.position.z),{group:e,statusLight:d,label:k}}function XI(s,e){s.group.rotation.y=Math.sin(e*.5)*.005;for(let t=0;t<4;t++){const n=s.group.getObjectByName(`indicator_${t}`);n&&n.material instanceof Ke&&(n.material.opacity=.3+Math.sin(e*.6+t*.4)*.15)}}function ZI(s,e){for(let t=0;t<4;t++){const n=s.group.getObjectByName(`indicator_${t}`);if(n&&n.material instanceof Ke){const a=Math.sin(e*3+t*.8)*.3+.7;n.material.opacity=a}}for(let t=0;t<4;t++){const n=s.group.getObjectByName(`handle_${t}`);n&&(n.position.z=.47+Math.sin(e*8+t)*.005)}}function QI(s){const e=new Fn;e.userData.buildingId=s.id,e.userData.isBuilding=!0;const t=Cd.satellite,n=s.color?new Gt(s.color):new Gt(t.primary),a=new Gn(.1,.15,2,8),i=new dt({color:t.secondary,metalness:.6,roughness:.4}),o=new De(a,i);o.position.y=1,o.castShadow=!0,e.add(o);const l=new un(.3,.2,.3),c=new De(l,i);c.position.y=2.1,e.add(c);const d=new Fn;d.position.y=2.3,d.name="dishGroup";const m=new Yt(1,32,16,0,Math.PI*2,0,Math.PI/3),p=new dt({color:n,metalness:.5,roughness:.5,side:Ts}),f=new De(m,p);f.rotation.x=Math.PI/2+.3,f.name="buildingBody",d.add(f);const b=new Yt(.95,32,16,0,Math.PI*2,0,Math.PI/3),x=new dt({color:t.accent,metalness:.3,roughness:.7,side:$A}),w=new De(b,x);w.rotation.x=Math.PI/2+.3,d.add(w);const k=new Gn(.03,.03,.8,8),S=new dt({color:t.secondary,metalness:.6,roughness:.4}),j=new De(k,S);j.position.set(0,.1,.5),j.rotation.x=-.6,d.add(j);const C=new bc(.1,.2,8),N=new dt({color:t.accent,metalness:.4,roughness:.6}),P=new De(C,N);P.position.set(0,.5,.85),P.rotation.x=Math.PI/2-.6,d.add(P);const _=new Yt(.08,16,16),L=new Ke({color:t.glow,transparent:!0,opacity:.9}),M=new De(_,L);M.position.set(0,.55,.92),M.name="signal",d.add(M),e.add(d);for(let X=0;X<3;X++){const H=new il(.2+X*.15,.22+X*.15,16),se=new Ke({color:t.glow,transparent:!0,opacity:.6-X*.15,side:Ts}),ce=new De(H,se);ce.position.set(0,2.85+X*.1,.92+X*.1),ce.rotation.x=-.6,ce.name=`wave_${X}`,e.add(ce)}const D=new Yt(.1,16,16),E=new Ke({color:ds[s.status],transparent:!0,opacity:.95}),R=new De(D,E);R.position.set(0,.3,.5),R.name="statusLight",e.add(R);const O=new Yt(.18,16,16),I=new Ke({color:ds[s.status],transparent:!0,opacity:.3}),B=new De(O,I);B.position.set(0,.3,.5),B.name="statusGlow",e.add(B);const Y=new Gn(.6,.7,.15,16),$=new dt({color:t.secondary,metalness:.5,roughness:.5}),W=new De(Y,$);W.position.y=.075,W.receiveShadow=!0,e.add(W);const K=pi(Fi(s));return K.position.set(0,3.8,0),K.name="buildingLabel",e.add(K),e.position.set(s.position.x,0,s.position.z),{group:e,statusLight:R,label:K}}function JI(s,e,t){const n=s.group.getObjectByName("dishGroup");n&&(n.rotation.y+=t*.1);for(let a=0;a<3;a++){const i=s.group.getObjectByName(`wave_${a}`);i&&i.material instanceof Ke&&(i.material.opacity=.15+Math.sin(e*.5+a*.3)*.1)}}function eB(s,e,t){const n=s.group.getObjectByName("dishGroup");n&&(n.rotation.y+=t*.5);const a=s.group.getObjectByName("signal");a&&a.material instanceof Ke&&(a.material.opacity=.6+Math.sin(e*8)*.4);for(let i=0;i<3;i++){const o=s.group.getObjectByName(`wave_${i}`);if(o&&o.material instanceof Ke){const l=1+Math.sin(e*4+i)*.1;o.scale.set(l,l,1),o.material.opacity=(.5-i*.15)*(.5+Math.sin(e*4+i)*.5)}}}function tB(s){const e=new Fn;e.userData.buildingId=s.id,e.userData.isBuilding=!0;const t=Cd.crystal,n=s.color?new Gt(s.color):new Gt(t.primary),a=new CS(.8),i=new dt({color:n,metalness:.3,roughness:.2,transparent:!0,opacity:.85}),o=new De(a,i);o.position.y=1.8,o.castShadow=!0,o.name="buildingBody",e.add(o);const l=new CS(.5),c=new Ke({color:t.glow,transparent:!0,opacity:.6}),d=new De(l,c);d.position.y=1.8,d.name="crystalInner",e.add(d);for(let I=0;I<6;I++){const B=new Yt(.06,8,8),Y=new Ke({color:I%2===0?t.accent:t.glow,transparent:!0,opacity:.9}),$=new De(B,Y),W=I/6*Math.PI*2;$.position.set(Math.cos(W)*1.2,1.8+Math.sin(W*2)*.3,Math.sin(W)*1.2),$.name=`particle_${I}`,e.add($)}const m=new AP(1.3,1),p=new Ke({color:t.accent,wireframe:!0,transparent:!0,opacity:.4}),f=new De(m,p);f.position.y=1.8,f.name="energyField",e.add(f);const b=new Gn(.3,.5,.8,6),x=new dt({color:t.secondary,metalness:.5,roughness:.5}),w=new De(b,x);w.position.y=.4,e.add(w);const k=new Gn(.05,.05,.9,8),S=new Ke({color:t.glow,transparent:!0,opacity:.7}),j=new De(k,S);j.position.y=1.25,j.name="energyBeam",e.add(j);const C=new Yt(.1,16,16),N=new Ke({color:ds[s.status],transparent:!0,opacity:.95}),P=new De(C,N);P.position.set(.7,.5,0),P.name="statusLight",e.add(P);const _=new Yt(.18,16,16),L=new Ke({color:ds[s.status],transparent:!0,opacity:.3}),M=new De(_,L);M.position.set(.7,.5,0),M.name="statusGlow",e.add(M);const D=new Gn(.8,.9,.1,6),E=new dt({color:t.secondary,metalness:.6,roughness:.4}),R=new De(D,E);R.position.y=.05,R.receiveShadow=!0,e.add(R);const O=pi(Fi(s));return O.position.set(0,3,0),O.name="buildingLabel",e.add(O),e.position.set(s.position.x,0,s.position.z),{group:e,statusLight:P,label:O}}function nB(s,e,t){const n=s.group.getObjectByName("buildingBody");n&&(n.rotation.y+=t*.2,n.position.y=1.8+Math.sin(e*.8)*.05);const a=s.group.getObjectByName("crystalInner");a&&(a.rotation.y-=t*.3,a.position.y=1.8+Math.sin(e*.8)*.05,a.material instanceof Ke&&(a.material.opacity=.25+Math.sin(e*.6)*.15));const i=s.group.getObjectByName("energyField");i&&(i.rotation.y+=t*.1,i.position.y=1.8+Math.sin(e*.8)*.05,i.material instanceof Ke&&(i.material.opacity=.15+Math.sin(e*.5)*.1));for(let l=0;l<6;l++){const c=s.group.getObjectByName(`particle_${l}`);if(c){const d=l/6*Math.PI*2+e*.3;c.position.x=Math.cos(d)*1.2,c.position.z=Math.sin(d)*1.2,c.position.y=1.8+Math.sin(e*.8)*.05+Math.sin(d*2)*.2}}const o=s.group.getObjectByName("energyBeam");o&&o.material instanceof Ke&&(o.material.opacity=.2+Math.sin(e*.7)*.15)}function sB(s,e,t){const n=s.group.getObjectByName("buildingBody"),a=s.group.getObjectByName("crystalInner"),i=s.group.getObjectByName("energyField");n&&(n.rotation.y+=t*.8,n.position.y=1.8+Math.sin(e*1.5)*.1),a&&(a.rotation.y-=t*1.2,a.position.y=1.8+Math.sin(e*1.5)*.1,a.material instanceof Ke&&(a.material.opacity=.4+Math.sin(e*3)*.2)),i&&(i.rotation.y+=t*.3,i.rotation.x+=t*.2,i.position.y=1.8+Math.sin(e*1.5)*.1);for(let l=0;l<6;l++){const c=s.group.getObjectByName(`particle_${l}`);if(c){const d=l/6*Math.PI*2+e*1.5,m=1.2+Math.sin(e*2+l)*.1;c.position.x=Math.cos(d)*m,c.position.z=Math.sin(d)*m,c.position.y=1.8+Math.sin(e*1.5)*.1+Math.sin(d*2)*.3}}const o=s.group.getObjectByName("energyBeam");o&&o.material instanceof Ke&&(o.material.opacity=.4+Math.sin(e*4)*.3)}function aB(s){const e=new Fn;e.userData.buildingId=s.id,e.userData.isBuilding=!0;const t=Cd.factory,n=s.color?new Gt(s.color):new Gt(t.primary),a=new un(1.8,1.2,1.2),i=new dt({color:n,metalness:.4,roughness:.6}),o=new De(a,i);o.position.set(0,.6,0),o.castShadow=!0,o.name="buildingBody",e.add(o);const l=new un(2,.15,1.4),c=new dt({color:t.secondary,metalness:.5,roughness:.5}),d=new De(l,c);d.position.set(0,1.25,0),d.rotation.z=.05,e.add(d);const m=new Gn(.15,.18,1.2,8),p=new dt({color:t.secondary,metalness:.5,roughness:.5}),f=new De(m,p);f.position.set(.5,1.8,.3),e.add(f);const b=new dc(.17,.03,8,16),x=new De(b,p);x.position.set(.5,2.4,.3),x.rotation.x=Math.PI/2,e.add(x);for(let X=0;X<4;X++){const H=new Yt(.08+X*.03,8,8),se=new Ke({color:11184810,transparent:!0,opacity:.7-X*.12}),ce=new De(H,se);ce.position.set(.5,2.5+X*.25,.3),ce.name=`smoke_${X}`,e.add(ce)}for(let X=0;X<3;X++){const H=new un(.25,.35,.05),se=new Ke({color:t.glow,transparent:!0,opacity:.9}),ce=new De(H,se);ce.position.set(-.6+X*.5,.7,.63),ce.name=`window_${X}`,e.add(ce)}const w=new un(.4,.6,.05),k=new dt({color:t.secondary,metalness:.4,roughness:.6}),S=new De(w,k);S.position.set(.6,.35,.63),e.add(S);const j=new un(.3,.1,1.6),C=new dt({color:t.secondary,metalness:.6,roughness:.4}),N=new De(j,C);N.position.set(-1,.25,0),e.add(N);for(let X=0;X<3;X++){const H=new un(.15,.15,.15),se=new Ke({color:X%2===0?t.accent:t.glow}),ce=new De(H,se);ce.position.set(-1,.38,-.5+X*.4),ce.name=`conveyorItem_${X}`,e.add(ce)}const P=new dc(.2,.05,6,8),_=new dt({color:t.accent,metalness:.6,roughness:.4}),L=new De(P,_);L.position.set(-.8,.9,.63),L.name="gear1",e.add(L);const M=new De(P.clone(),_.clone());M.position.set(-.5,1.05,.63),M.name="gear2",e.add(M);const D=new Yt(.12,16,16),E=new Ke({color:ds[s.status],transparent:!0,opacity:.95}),R=new De(D,E);R.position.set(.85,1,.65),R.name="statusLight",e.add(R);const O=new Yt(.2,16,16),I=new Ke({color:ds[s.status],transparent:!0,opacity:.3}),B=new De(O,I);B.position.set(.85,1,.65),B.name="statusGlow",e.add(B);const Y=new un(2.4,.1,1.8),$=new dt({color:4868682,metalness:.4,roughness:.6}),W=new De(Y,$);W.position.y=.05,W.receiveShadow=!0,e.add(W);const K=pi(Fi(s));return K.position.set(0,2.9,0),K.name="buildingLabel",e.add(K),e.position.set(s.position.x,0,s.position.z),{group:e,statusLight:R,label:K}}function iB(s,e,t){const n=s.group.getObjectByName("gear1"),a=s.group.getObjectByName("gear2");n&&(n.rotation.z+=t*.3),a&&(a.rotation.z-=t*.4);for(let i=0;i<3;i++){const o=s.group.getObjectByName(`window_${i}`);o&&o.material instanceof Ke&&(o.material.opacity=.3+Math.sin(e*.4+i*.5)*.15)}for(let i=0;i<3;i++){const o=s.group.getObjectByName(`conveyorItem_${i}`);o&&(o.position.z=(o.position.z+t*.05+.5)%1.2-.5)}for(let i=0;i<4;i++){const o=s.group.getObjectByName(`smoke_${i}`);if(o){const l=2.5+i*.25,c=(e*.15+i*.3)%1.5;o.position.y=l+c,o.position.x=.5+Math.sin(e*.3+i)*.05,o.material instanceof Ke&&(o.material.opacity=Math.max(0,(.25-i*.05)*(1-c/1.5)))}}}function rB(s,e,t){for(let i=0;i<4;i++){const o=s.group.getObjectByName(`smoke_${i}`);if(o){const l=2.5+i*.25,c=(e*.5+i*.3)%1.5;o.position.y=l+c,o.position.x=.5+Math.sin(e+i)*.1,o.material instanceof Ke&&(o.material.opacity=Math.max(0,(.6-i*.12)*(1-c/1.5))),c>1.4&&(o.position.y=l)}}const n=s.group.getObjectByName("gear1"),a=s.group.getObjectByName("gear2");n&&(n.rotation.z+=t*2),a&&(a.rotation.z-=t*2.5);for(let i=0;i<3;i++){const o=s.group.getObjectByName(`conveyorItem_${i}`);o&&(o.position.z=(o.position.z+t*.3+.5)%1.2-.5)}for(let i=0;i<3;i++){const o=s.group.getObjectByName(`window_${i}`);if(o&&o.material instanceof Ke){const l=Math.random()>.99?.5:.8;o.material.opacity=l}}}function oB(s){const e=new Fn;e.userData.buildingId=s.id,e.userData.isBuilding=!0;const t=s.color?new Gt(s.color):new Gt(2763322),n=16766720,a=new Gn(1.8,2,.3,6),i=new dt({color:t,metalness:.7,roughness:.3}),o=new De(a,i);o.position.y=.15,o.receiveShadow=!0,e.add(o);const l=new Gn(1.2,1.4,.2,6),c=new dt({color:3816010,metalness:.8,roughness:.2}),d=new De(l,c);d.position.y=.4,e.add(d);const m=new Gn(.4,.6,2,6),p=new dt({color:t,metalness:.6,roughness:.4}),f=new De(m,p);f.position.y=1.5,f.castShadow=!0,f.receiveShadow=!0,f.name="buildingBody",e.add(f);const b=new Gn(.5,.4,.3,6),x=new dt({color:n,metalness:.9,roughness:.1,emissive:new Gt(n),emissiveIntensity:.3}),w=new De(b,x);w.position.y=2.65,w.name="crownBase",e.add(w);for(let $=0;$<5;$++){const W=$/5*Math.PI*2,K=new bc(.08,.4,4),X=new De(K,x);X.position.set(Math.cos(W)*.35,2.95,Math.sin(W)*.35),X.name=`crownSpike_${$}`,e.add(X)}const k=new dc(.8,.03,8,32),S=new Ke({color:n,transparent:!0,opacity:.6}),j=new De(k,S);j.position.y=1.2,j.rotation.x=Math.PI/2,j.name="holoRing1",e.add(j);const C=new dc(1.1,.02,8,32),N=new Ke({color:4915102,transparent:!0,opacity:.5}),P=new De(C,N);P.position.y=1.5,P.rotation.x=Math.PI/2,P.name="holoRing2",e.add(P);const _=new dc(1.4,.02,8,32),L=new Ke({color:4890367,transparent:!0,opacity:.4}),M=new De(_,L);M.position.y=1.8,M.rotation.x=Math.PI/2,M.name="holoRing3",e.add(M);for(let $=0;$<6;$++){const W=$/6*Math.PI*2,K=new Fn,X=new un(.3,.25,.2),H=new dt({color:3816010,metalness:.6,roughness:.4}),se=new De(X,H);se.position.y=.45,K.add(se);const ce=new pr(.25,.15),F=new Ke({color:4890367,transparent:!0,opacity:.8}),V=new De(ce,F);V.position.y=.52,V.position.z=.11,V.rotation.x=-.3,V.name=`consoleScreen_${$}`,K.add(V),K.position.set(Math.cos(W)*1.5,0,Math.sin(W)*1.5),K.rotation.y=-W+Math.PI,e.add(K)}const D=new Yt(.15,16,16),E=new Ke({color:ds[s.status],transparent:!0,opacity:.95}),R=new De(D,E);R.position.set(0,3.3,0),R.name="statusLight",e.add(R);const O=new Yt(.25,16,16),I=new Ke({color:ds[s.status],transparent:!0,opacity:.3}),B=new De(O,I);B.position.set(0,3.3,0),B.name="statusGlow",e.add(B);for(let $=0;$<6;$++){const W=$/6*Math.PI*2+Math.PI/6,K=new Gn(.06,.08,1,6),X=new dt({color:n,metalness:.8,roughness:.2,emissive:new Gt(n),emissiveIntensity:.2}),H=new De(K,X);H.position.set(Math.cos(W)*1.85,.8,Math.sin(W)*1.85),H.name=`energyPillar_${$}`,e.add(H);const se=new Yt(.08,8,8),ce=new Ke({color:n,transparent:!0,opacity:.8}),F=new De(se,ce);F.position.set(Math.cos(W)*1.85,1.35,Math.sin(W)*1.85),F.name=`pillarLight_${$}`,e.add(F)}const Y=pi(Fi(s));return Y.position.set(0,3.8,0),Y.name="buildingLabel",e.add(Y),e.position.set(s.position.x,0,s.position.z),{group:e,statusLight:R,label:Y}}function lB(s,e,t){const n=s.group.getObjectByName("holoRing1"),a=s.group.getObjectByName("holoRing2"),i=s.group.getObjectByName("holoRing3");n&&(n.rotation.z+=t*.3,n.material instanceof Ke&&(n.material.opacity=.3+Math.sin(e*.5)*.1)),a&&(a.rotation.z-=t*.2,a.material instanceof Ke&&(a.material.opacity=.25+Math.sin(e*.7+1)*.1)),i&&(i.rotation.z+=t*.1,i.material instanceof Ke&&(i.material.opacity=.2+Math.sin(e*.4+2)*.1));for(let o=0;o<6;o++){const l=s.group.getObjectByName(`pillarLight_${o}`);l&&l.material instanceof Ke&&(l.material.opacity=.4+Math.sin(e*.5+o*.5)*.2)}for(let o=0;o<6;o++){const l=s.group.getObjectByName(`consoleScreen_${o}`);l&&l.material instanceof Ke&&(l.material.opacity=.4+Math.sin(e*.3+o*.3)*.1)}}function cB(s,e,t){const n=s.group.getObjectByName("holoRing1"),a=s.group.getObjectByName("holoRing2"),i=s.group.getObjectByName("holoRing3");n&&(n.rotation.z+=t*1.5,n.rotation.x=Math.PI/2+Math.sin(e*2)*.1,n.material instanceof Ke&&(n.material.opacity=.5+Math.sin(e*3)*.2)),a&&(a.rotation.z-=t*1,a.rotation.x=Math.PI/2+Math.sin(e*1.5+1)*.15,a.material instanceof Ke&&(a.material.opacity=.4+Math.sin(e*2.5+1)*.15)),i&&(i.rotation.z+=t*.5,i.rotation.x=Math.PI/2+Math.sin(e*1+2)*.1,i.material instanceof Ke&&(i.material.opacity=.35+Math.sin(e*2+2)*.15));for(let l=0;l<6;l++){const c=s.group.getObjectByName(`pillarLight_${l}`);if(c&&c.material instanceof Ke){const d=(e*2+l*.3)%(Math.PI*2);c.material.opacity=.6+Math.sin(d)*.3}}for(let l=0;l<6;l++){const c=s.group.getObjectByName(`consoleScreen_${l}`);if(c&&c.material instanceof Ke){c.material.opacity=.7+Math.sin(e*4+l*.5)*.2;const d=(e*.1+l*.1)%1;c.material.color.setHSL(d*.2+.5,.8,.5)}}const o=s.group.getObjectByName("crownBase");o&&o.material instanceof dt&&(o.material.emissiveIntensity=.4+Math.sin(e*2)*.2)}function uB(s){switch(s.style||"server-rack"){case"tower":return II(s);case"dome":return FI(s);case"pyramid":return UI(s);case"desktop":return qI(s);case"filing-cabinet":return KI(s);case"satellite":return QI(s);case"crystal":return tB(s);case"factory":return aB(s);case"command-center":return oB(s);case"server-rack":default:return RI(s)}}function dB(s,e,t,n){switch(e.style||"server-rack"){case"server-rack":LI(s,t);break;case"desktop":YI(s,t);break;case"filing-cabinet":XI(s,t);break;case"satellite":JI(s,t,n);break;case"crystal":nB(s,t,n);break;case"factory":iB(s,t,n);break;case"tower":BI(s,t,n);break;case"dome":$I(s,t,n);break;case"pyramid":GI(s,t);break;case"command-center":lB(s,t,n);break}}function hB(s,e,t,n){const a=e.style||"server-rack",i=s.group.getObjectByName("statusGlow"),o=Math.sin(t*3)*.2+.8;switch(i&&i.material instanceof Ke&&(i.material.opacity=.3*o),a){case"server-rack":OI(s);break;case"tower":zI(s,t,n);break;case"dome":HI(s,t,n);break;case"pyramid":WI(s,t);break;case"desktop":VI(s,t);break;case"filing-cabinet":ZI(s,t);break;case"satellite":eB(s,t,n);break;case"crystal":sB(s,t,n);break;case"factory":rB(s,t,n);break;case"command-center":cB(s,t,n);break}}function pB(s,e){const t=s.group.getObjectByName("statusGlow"),n=Math.sin(e*8)*.5+.5;t&&t.material instanceof Ke&&(t.material.opacity=.5*n)}function mB(s,e){const t=s.group.getObjectByName("statusGlow"),n=Math.sin(e*2)*.5+.5;t&&t.material instanceof Ke&&(t.material.opacity=.4*n)}class fB{constructor(e){U(this,"scene");U(this,"buildingMeshes",new Map);U(this,"selectedBuildingIds",new Set);U(this,"animationTime",0);U(this,"brightness",1);U(this,"bossSubordinateLines",null);U(this,"bossSubordinateMaterial",null);U(this,"cachedBossConnections",[]);U(this,"maxLineSegments",50);U(this,"onBuildingClick",null);U(this,"onBuildingDoubleClick",null);this.scene=e}setOnBuildingClick(e){this.onBuildingClick=e}setOnBuildingDoubleClick(e){this.onBuildingDoubleClick=e}setBrightness(e){this.brightness=e;for(const t of this.buildingMeshes.values()){const n=t.group.getObjectByName("statusGlow");n&&n.material instanceof Ke&&(n.material.opacity=.3*e),t.group.traverse(a=>{if(a instanceof De&&a.material instanceof dt){const i=a.material;i.emissiveIntensity!==void 0&&(i.userData.baseEmissiveIntensity===void 0&&(i.userData.baseEmissiveIntensity=i.emissiveIntensity||1),i.emissiveIntensity=i.userData.baseEmissiveIntensity*e)}})}}addBuilding(e){this.removeBuilding(e.id);const t=uB(e);t.group.userData.style=e.style,t.group.userData.color=e.color||"";const n=e.scale||1;t.group.scale.setScalar(n),this.scene.add(t.group),this.buildingMeshes.set(e.id,t)}removeBuilding(e){const t=this.buildingMeshes.get(e);t&&(this.scene.remove(t.group),this.disposeGroup(t.group),this.buildingMeshes.delete(e))}setBuildingPosition(e,t){const n=this.buildingMeshes.get(e);n&&(n.group.position.set(t.x,0,t.z),this.updateBossLinePositions())}updateBuilding(e){var b;const t=this.buildingMeshes.get(e.id);if(!t){this.addBuilding(e);return}const n=t.group.userData.style,a=t.group.userData.color;if(n!==e.style||a!==(e.color||"")){this.removeBuilding(e.id),this.addBuilding(e);return}t.group.position.set(e.position.x,0,e.position.z);const i=e.scale||1;t.group.scale.setScalar(i);const o=ds[e.status],l=t.group.getObjectByName("statusLight");l&&l.material instanceof Ke&&l.material.color.setHex(o);const c=t.group.getObjectByName("statusGlow");c&&c.material instanceof Ke&&c.material.color.setHex(o),((b=t.label.material.map)==null?void 0:b.image)&&PI(t,e.name);const p=e.gitChangesCount||0,f=t.group.getObjectByName("gitIndicator");if(p>0){if(f)f.userData.gitCount!==p&&(DI(f,p),f.userData.gitCount=p);else{const x=DM(p),w=t.label.position;x.position.set(w.x+.6,w.y+.15,w.z),t.group.add(x),t.gitIndicator=x}t.gitIndicator&&(t.gitIndicator.userData.gitCount=p)}else if(f){t.group.remove(f);const x=f.material;x.map&&x.map.dispose(),x.dispose(),t.gitIndicator=void 0}}highlightBuilding(e){for(const t of this.selectedBuildingIds){const n=this.buildingMeshes.get(t);if(n){const a=n.group.getObjectByName("buildingBody");a&&a.material instanceof dt&&a.material.emissive.setHex(0)}}if(this.selectedBuildingIds.clear(),e){this.selectedBuildingIds.add(e);const t=this.buildingMeshes.get(e);if(t){const n=t.group.getObjectByName("buildingBody");n&&n.material instanceof dt&&n.material.emissive.setHex(2236996)}}this.updateBossConnectionLines()}highlightBuildings(e){for(const t of this.selectedBuildingIds){const n=this.buildingMeshes.get(t);if(n){const a=n.group.getObjectByName("buildingBody");a&&a.material instanceof dt&&a.material.emissive.setHex(0)}}this.selectedBuildingIds.clear();for(const t of e){this.selectedBuildingIds.add(t);const n=this.buildingMeshes.get(t);if(n){const a=n.group.getObjectByName("buildingBody");a&&a.material instanceof dt&&a.material.emissive.setHex(2236996)}}this.updateBossConnectionLines()}getBuildingMeshData(){return this.buildingMeshes}getHitboxForStyle(e){switch(e){case"desktop":return{halfWidth:2,halfDepth:2};case"filing-cabinet":return{halfWidth:1.8,halfDepth:1.2};case"factory":return{halfWidth:1.5,halfDepth:1.2};case"satellite":return{halfWidth:1.2,halfDepth:1.2};case"crystal":return{halfWidth:1.5,halfDepth:1.5};case"tower":return{halfWidth:1.2,halfDepth:1};case"dome":return{halfWidth:1.5,halfDepth:1.5};case"pyramid":return{halfWidth:1.5,halfDepth:1.5};case"command-center":return{halfWidth:2.2,halfDepth:2.2};case"server-rack":default:return{halfWidth:1.2,halfDepth:1}}}getBuildingAtPosition(e){const t=z.getState();for(const n of t.buildings.values()){const a=this.getHitboxForStyle(n.style),i=n.scale||1,o={halfWidth:a.halfWidth*i,halfDepth:a.halfDepth*i},l=Math.abs(e.x-n.position.x),c=Math.abs(e.z-n.position.z);if(l<=o.halfWidth&&c<=o.halfDepth)return n}return null}getBuildingMeshes(){return Array.from(this.buildingMeshes.values()).map(e=>e.group)}syncFromStore(){const e=z.getState();for(const t of this.buildingMeshes.keys())e.buildings.has(t)||this.removeBuilding(t);for(const t of e.buildings.values())this.buildingMeshes.has(t.id)?this.updateBuilding(t):this.addBuilding(t)}update(e){this.animationTime+=e;const t=z.getState();for(const[n,a]of this.buildingMeshes){const i=t.buildings.get(n);i&&(dB(a,i,this.animationTime,e),i.status==="running"?hB(a,i,this.animationTime,e):i.status==="starting"||i.status==="stopping"?pB(a,this.animationTime):i.status==="error"&&mB(a,this.animationTime))}}updateBossConnectionLines(){var a;const e=z.getState(),t=[],n=new Set;for(const i of this.selectedBuildingIds){const o=e.buildings.get(i);if(o&&o.type==="boss"&&o.subordinateBuildingIds){t.push(o);for(const l of o.subordinateBuildingIds)n.add(l)}if(o){for(const[,l]of e.buildings)if(l.type==="boss"&&((a=l.subordinateBuildingIds)!=null&&a.includes(o.id))&&!t.find(c=>c.id===l.id)){t.push(l);for(const c of l.subordinateBuildingIds||[])n.add(c)}}}this.cachedBossConnections=[];for(const i of t)if(!(!this.buildingMeshes.get(i.id)||!i.subordinateBuildingIds))for(const l of i.subordinateBuildingIds)this.buildingMeshes.get(l)&&this.cachedBossConnections.push({bossId:i.id,subId:l});if(this.cachedBossConnections.length>0){if(!this.bossSubordinateLines){const l=new Float32Array(this.maxLineSegments*6),c=new Wa;c.setAttribute("position",new ri(l,3)),c.setDrawRange(0,0),this.bossSubordinateMaterial=new qo({color:16766720,transparent:!0,opacity:.4}),this.bossSubordinateLines=new gx(c,this.bossSubordinateMaterial),this.bossSubordinateLines.frustumCulled=!1,this.scene.add(this.bossSubordinateLines)}const i=this.bossSubordinateLines.geometry.attributes.position,o=i.array;for(let l=0;l<this.cachedBossConnections.length&&l<this.maxLineSegments;l++){const{bossId:c,subId:d}=this.cachedBossConnections[l],m=this.buildingMeshes.get(c),p=this.buildingMeshes.get(d);if(m&&p){const f=l*6;o[f]=m.group.position.x,o[f+1]=.1,o[f+2]=m.group.position.z,o[f+3]=p.group.position.x,o[f+4]=.1,o[f+5]=p.group.position.z}}i.needsUpdate=!0,this.bossSubordinateLines.geometry.setDrawRange(0,this.cachedBossConnections.length*2),this.bossSubordinateLines.visible=!0}else this.bossSubordinateLines&&(this.bossSubordinateLines.visible=!1);for(const[i,o]of this.buildingMeshes){if(!e.buildings.get(i))continue;const c=n.has(i),d=o.group.getObjectByName("buildingBody");d&&d.material instanceof dt&&(c&&!this.selectedBuildingIds.has(i)?d.material.emissive.setHex(3351040):this.selectedBuildingIds.has(i)||d.material.emissive.setHex(0))}}updateBossLinePositions(){if(!this.bossSubordinateLines||this.cachedBossConnections.length===0)return;const e=this.bossSubordinateLines.geometry.attributes.position,t=e.array;for(let n=0;n<this.cachedBossConnections.length&&n<this.maxLineSegments;n++){const{bossId:a,subId:i}=this.cachedBossConnections[n],o=this.buildingMeshes.get(a),l=this.buildingMeshes.get(i);if(!o||!l)continue;const c=n*6;t[c]=o.group.position.x,t[c+1]=.1,t[c+2]=o.group.position.z,t[c+3]=l.group.position.x,t[c+4]=.1,t[c+5]=l.group.position.z}e.needsUpdate=!0}disposeGroup(e){e.traverse(t=>{if(t instanceof De&&(t.geometry.dispose(),Array.isArray(t.material)?t.material.forEach(n=>n.dispose()):t.material.dispose()),t instanceof Un){const n=t.material;n.map&&n.map.dispose(),n.dispose()}})}dispose(){var e;for(const t of this.buildingMeshes.keys())this.removeBuilding(t);this.bossSubordinateLines&&(this.scene.remove(this.bossSubordinateLines),this.bossSubordinateLines.geometry.dispose(),(e=this.bossSubordinateMaterial)==null||e.dispose(),this.bossSubordinateLines=null,this.bossSubordinateMaterial=null),this.cachedBossConnections=[]}}const od=class od{constructor(e,t,n,a,i,o){U(this,"scene");U(this,"characterLoader");U(this,"characterFactory");U(this,"movementAnimator");U(this,"proceduralAnimator");U(this,"effectsManager");U(this,"agentMeshes",new Map);U(this,"pendingAgents",[]);U(this,"modelsReady",!1);U(this,"characterScale",.5);U(this,"brightness",1);U(this,"idleAnimation",ns.SIT);U(this,"workingAnimation",ns.WALK);U(this,"previousAgentStatuses",new Map);U(this,"modelStyle",{saturation:1,roughness:-1,metalness:-1,emissiveBoost:0,envMapIntensity:-1,wireframe:!1,colorMode:"normal"});U(this,"onAgentMeshesChanged",null);U(this,"onProceduralCacheInvalidated",null);U(this,"onToast",null);this.scene=e,this.characterLoader=t,this.characterFactory=n,this.movementAnimator=a,this.proceduralAnimator=i,this.effectsManager=o}setOnAgentMeshesChanged(e){this.onAgentMeshesChanged=e}setOnProceduralCacheInvalidated(e){this.onProceduralCacheInvalidated=e}setOnToast(e){this.onToast=e}getAgentMeshes(){return this.agentMeshes}isModelsReady(){return this.modelsReady}setCharacterScale(e){this.characterScale=e;for(const t of this.agentMeshes.values()){const n=t.group.getObjectByName("characterBody");if(n){const a=n.userData.customModelScale??1,i=t.group.userData.isBoss===!0,o=i?1.5:1;n.scale.setScalar(a*e*o);const l=t.group.getObjectByName("statusBar");if(l){const d=new Ep().setFromObject(n).max.y,m=i?.2:.3,p=i?3:2.2;l.position.y=Math.min(Math.max(d,1)+m,p)}}}}setBrightness(e){this.brightness=e;for(const t of this.agentMeshes.values())this.applyStyleToMesh(t.group)}setModelStyle(e){Object.assign(this.modelStyle,e);for(const t of this.agentMeshes.values())this.applyStyleToMesh(t.group)}getModelStyle(){return{...this.modelStyle}}injectColorShader(e){const t=this.modelStyle.saturation,n=od.COLOR_MODE_INDEX[this.modelStyle.colorMode]??0;if(e.userData.hasColorShader)e.userData.shader&&(e.userData.shader.uniforms.uSaturation.value=t,e.userData.shader.uniforms.uColorMode.value=n);else{e.userData.hasColorShader=!0;const a=this;e.onBeforeCompile=i=>{i.uniforms.uSaturation={value:a.modelStyle.saturation},i.uniforms.uColorMode={value:od.COLOR_MODE_INDEX[a.modelStyle.colorMode]??0},i.fragmentShader=i.fragmentShader.replace("#include <common>",`#include <common>
@@ -145,7 +145,7 @@ Error generating stack: `+v.message+`
145
145
  float h = normalize(vWorldPosition + offset).y;
146
146
  gl_FragColor = vec4(mix(bottomColor, topColor, max(pow(max(h, 0.0), exponent), 0.0)), 1.0);
147
147
  }
148
- `,side:$A});a.add(new De(i,o)),a.add(new xx(16777215,1));const l=n.fromScene(a,.04).texture;t.environment=l,n.dispose(),i.dispose(),o.dispose()}createInputCallbacks(){return{onAgentClick:(e,t)=>this.inputEventHandlers.handleAgentClick(e,t),onAgentDoubleClick:e=>this.inputEventHandlers.handleAgentDoubleClick(e),onAgentHover:(e,t)=>this.inputEventHandlers.handleAgentHover(e,t),onGroundClick:()=>this.inputEventHandlers.handleGroundClick(),onMoveCommand:(e,t)=>this.inputEventHandlers.handleMoveCommand(e,t),onSelectionBox:(e,t)=>this.inputEventHandlers.handleSelectionBox(e,t),onDrawStart:e=>this.drawingManager.startDrawing(e),onDrawMove:e=>this.drawingManager.updateDrawing(e),onDrawEnd:e=>this.drawingManager.finishDrawing(e),onAreaRightClick:e=>this.inputEventHandlers.handleAreaRightClick(e),onAreaClick:e=>this.inputEventHandlers.handleAreaClick(e),onAreaDoubleClick:e=>this.inputEventHandlers.handleAreaDoubleClick(e),onResizeStart:(e,t)=>this.drawingManager.startResize(e,t),onResizeMove:e=>this.drawingManager.updateResize(e),onResizeEnd:()=>this.drawingManager.finishResize(),onGroundClickOutsideArea:()=>this.inputEventHandlers.handleGroundClickOutsideArea(),onFolderIconClick:(e,t)=>{var n;t?z.openFileExplorerForAreaFolder(e,t):z.openFileExplorerForArea(e),(n=this.onFolderIconClickCallback)==null||n.call(this,e)},onBuildingClick:(e,t)=>this.inputEventHandlers.handleBuildingClick(e,t),onBuildingDoubleClick:e=>this.inputEventHandlers.handleBuildingDoubleClick(e),onBuildingHover:(e,t)=>this.inputEventHandlers.handleBuildingHover(e,t),onBuildingDragStart:()=>{},onBuildingDragMove:(e,t)=>this.buildingManager.setBuildingPosition(e,t),onBuildingDragEnd:(e,t)=>z.updateBuildingPosition(e,t),onContextMenu:(e,t,n)=>this.callbackManager.triggerContextMenu(e,t,n),onActivity:()=>this.renderLoop.markActivity(),onToggleTerminal:()=>z.toggleTerminal()}}setupInputHandlerHelpers(){this.inputHandler.setDrawingModeChecker(()=>this.drawingManager.isInDrawingMode()),this.inputHandler.setResizeHandlers(()=>this.drawingManager.getResizeHandles(),()=>this.drawingManager.isCurrentlyResizing()),this.inputHandler.setAreaAtPositionGetter(e=>this.drawingManager.getAreaAtPosition(e)),this.inputHandler.setFolderIconMeshesGetter(()=>this.drawingManager.getFolderIconMeshes()),this.inputHandler.setBuildingAtPositionGetter(e=>{const t=this.buildingManager.getBuildingAtPosition(e);return t?{id:t.id}:null}),this.inputHandler.setBuildingPositionsGetter(()=>{const e=new Map;for(const[t,n]of this.buildingManager.getBuildingMeshData())e.set(t,n.group.position.clone());return e})}setupEventListeners(e){window.addEventListener("resize",this.onWindowResize),this.resizeObserver=new ResizeObserver(()=>this.onWindowResize()),e.parentElement&&this.resizeObserver.observe(e.parentElement),e.addEventListener("webglcontextlost",this.onContextLost),e.addEventListener("webglcontextrestored",this.onContextRestored)}updateInputHandlerReferences(){this.inputHandler.setReferences(this.battlefield.getGround(),this.agentManager.getAgentMeshes())}updateBattlefield(e,t){t-this.lastTimeUpdate>6e4&&(this.battlefield.updateTimeOfDay(),this.lastTimeUpdate=t),this.battlefield.updateGalacticAnimation(e),this.battlefield.updateCloudAnimation(e)}updateAnimations(e){const t=this.movementAnimator.update(this.agentManager.getAgentMeshes(),e);return this.effectsManager.update(),this.buildingManager.update(e),t}updateProceduralAnimations(e){if(this.proceduralBodiesDirty){this.proceduralBodiesCache.clear();for(const[t,n]of this.agentManager.getAgentMeshes())if(this.proceduralAnimator.has(t)&&n.animations.size===0){const a=n.group.getObjectByName("characterBody");a&&this.proceduralBodiesCache.set(t,a)}this.proceduralBodiesDirty=!1}this.proceduralBodiesCache.size>0&&this.proceduralAnimator.update(e,this.proceduralBodiesCache)}updateIndicatorScales(e,t,n){for(const[,a]of t){const i=e.position.distanceTo(a.group.position),o=Math.max(.5,Math.min(2.5,i/15))*n,l=a.group.userData.isBoss===!0,c=a.group.getObjectByName("statusBar"),d=a.group.getObjectByName("nameLabelSprite");if(c){const p=typeof c.userData.baseIndicatorScale=="number"?c.userData.baseIndicatorScale:l?2:1.6,f=typeof c.userData.aspectRatio=="number"?c.userData.aspectRatio:2560/4096;c.scale.set(p*o,p*f*o,1)}if(d){const p=typeof d.userData.baseIndicatorScale=="number"?d.userData.baseIndicatorScale:l?1.5:1.25,f=p>2,b=f?p:Math.max(l?1.35:1.1,Math.min(l?1.65:1.35,p)),x=typeof d.userData.aspectRatio=="number"?d.userData.aspectRatio:1024/4096,w=Math.max(.5,Math.min(2.5,i/15)),S=(f?Math.max(.8,Math.min(1.2,w)):w)*n;d.scale.set(b*S,b*x*S,1)}const m=a.group.getObjectByName("combinedUI");if(m){const p=typeof m.userData.baseIndicatorScale=="number"?m.userData.baseIndicatorScale:l?3:2.4,f=typeof m.userData.aspectRatio=="number"?m.userData.aspectRatio:1024/2048;m.scale.set(p*o,p*f*o,1)}if(!c&&!m){const p=a.group.getObjectByName("nameLabel");if(p){const x=.3*o;p.scale.set(x*(p.userData.aspectRatio||2),x,1)}const f=a.group.getObjectByName("manaBar");f&&f.scale.set(.9,.14,1);const b=a.group.getObjectByName("idleTimer");b&&b.scale.set(.9*o,.14*o,1)}}for(const[,a]of this.buildingManager.getBuildingMeshData()){const i=e.position.distanceTo(a.group.position),o=Math.max(.5,Math.min(2.5,i/15))*n,l=a.group.getObjectByName("buildingLabel");if(l){const c=.3*o;l.scale.set(c*(l.userData.aspectRatio||2),c,1)}}this.effectsManager.updateWithCamera(e)}async loadCharacterModels(){await this.agentManager.loadCharacterModels()}upgradeAgentModels(){this.agentManager.upgradeAgentModels(),this.updateInputHandlerReferences()}addAgent(e){this.agentManager.addAgent(e)}removeAgent(e){this.agentManager.removeAgent(e),this.updateInputHandlerReferences()}updateAgent(e,t=!1){this.agentManager.updateAgent(e,t)}syncAgents(e){this.agentManager.syncAgents(e)}setCustomAgentClasses(e){this.agentManager.setCustomAgentClasses(e)}refreshSelectionVisuals(){this.selectionManager.refreshSelectionVisuals()}createMoveOrderEffect(e){this.effectsManager.createMoveOrderEffect(e)}showToolBubble(e,t,n){this.effectsManager.setAgentMeshes(this.agentManager.getAgentMeshes()),this.effectsManager.createSpeechBubble(e,t,n)}showDelegationEffect(e,t){this.effectsManager.setAgentMeshes(this.agentManager.getAgentMeshes()),this.effectsManager.createDelegationEffect(e,t)}addSubagentEffect(e,t,n,a){this.effectsManager.setAgentMeshes(this.agentManager.getAgentMeshes()),this.effectsManager.addSubagentEffect(e,t,n,a)}completeSubagentEffect(e){this.effectsManager.completeSubagentEffect(e)}removeSubagentEffect(e){this.effectsManager.removeSubagentEffect(e)}focusAgent(e){this.cameraManager.focusAgent(e)}callSubordinates(e){var o;const n=z.getState().agents.get(e);if(!n||!(n.isBoss||n.class==="boss")||!((o=n.subordinateIds)!=null&&o.length))return;const a=new gt(n.position.x,n.position.y,n.position.z),i=this.inputHandler.calculateFormationPositions(a,n.subordinateIds.length);this.effectsManager.createMoveOrderEffect(a.clone()),n.subordinateIds.forEach((l,c)=>{const d=this.agentManager.getAgentMeshes().get(l);z.moveAgent(l,i[c]),d&&this.movementAnimator.startMovement(l,d,i[c])})}setDrawingTool(e){this.drawingManager.setTool(e),z.setActiveTool(e)}syncAreas(){this.drawingManager.syncFromStore()}highlightArea(e){this.drawingManager.highlightArea(e)}clearAreaSelection(){this.drawingManager.highlightArea(null)}addBuilding(e){this.buildingManager.addBuilding(e)}removeBuilding(e){this.buildingManager.removeBuilding(e)}updateBuilding(e){this.buildingManager.updateBuilding(e)}syncBuildings(){this.buildingManager.syncFromStore()}highlightBuilding(e){this.buildingManager.highlightBuilding(e)}setOnBuildingClick(e){this.callbackManager.setOnBuildingClick(e)}setOnBuildingDoubleClick(e){this.callbackManager.setOnBuildingDoubleClick(e)}setOnContextMenu(e){this.callbackManager.setOnContextMenu(e)}setOnAgentHover(e){this.callbackManager.setOnAgentHover(e)}setOnBuildingHover(e){this.callbackManager.setOnBuildingHover(e)}setOnGroundClick(e){this.callbackManager.setOnGroundClick(e)}setOnAreaDoubleClick(e){this.callbackManager.setOnAreaDoubleClick(e)}setOnFolderIconClick(e){this.onFolderIconClickCallback=e}setOnToast(e){this.agentManager.setOnToast(e)}setCharacterScale(e){this.agentManager.setCharacterScale(e),this.selectionManager.setCharacterScale(e)}setIndicatorScale(e){this.renderLoop.setIndicatorScale(e),this.effectsManager.setIndicatorScale(e)}setFpsLimit(e){this.renderLoop.setFpsLimit(e)}setPowerSaving(e){this.renderLoop.setPowerSaving(e)}setGridVisible(e){this.battlefield.setGridVisible(e)}setDebugTime(e){this.battlefield.setDebugTime(e)}setTimeMode(e){this.battlefield.setTimeMode(e)}setTerrainConfig(e){this.battlefield.setTerrainConfig(e),e.brightness!==void 0&&(this.drawingManager.setBrightness(e.brightness),this.buildingManager.setBrightness(e.brightness),this.agentManager.setBrightness(e.brightness))}setFloorStyle(e,t=!1){this.battlefield.setFloorStyle(e,t)}setIdleAnimation(e){this.agentManager.setIdleAnimation(e)}setWorkingAnimation(e){this.agentManager.setWorkingAnimation(e)}setAgentModelStyle(e){this.agentManager.setModelStyle(e)}getAgentModelStyle(){return this.agentManager.getModelStyle()}setGlobalSaturation(e){this.sceneCore.setSaturation(e)}getGlobalSaturation(){return this.sceneCore.getSaturation()}setPostProcessingEnabled(e){this.sceneCore.setPostProcessingEnabled(e)}reattach(e,t){var i,o;console.log("[SceneManager] Reattaching to new canvas (HMR)"),this.isReattaching=!0,this.renderLoop.stop(),(i=this.resizeObserver)==null||i.disconnect();const n=this.sceneCore.getCanvas();n.removeEventListener("webglcontextlost",this.onContextLost),n.removeEventListener("webglcontextrestored",this.onContextRestored),this.sceneCore.reattach(e),this.cameraManager.recreateControls(this.sceneCore.getRenderer()),this.sceneCore.updateCamera(this.cameraManager.getCamera()),e.addEventListener("webglcontextlost",this.onContextLost),e.addEventListener("webglcontextrestored",this.onContextRestored),this.inputHandler.reattach(e,t,this.cameraManager.getControls()),this.updateInputHandlerReferences(),e.parentElement&&((o=this.resizeObserver)==null||o.observe(e.parentElement)),this.onWindowResize();const a=(l=0)=>{this.isReattaching=!1,e.isConnected&&this.sceneCore.getRenderer()?(console.log("[SceneManager] Restarting animation loop after HMR reattach"),this.renderLoop.start()):l<10?(console.log(`[SceneManager] Canvas not connected, retrying... (attempt ${l+1})`),this.isReattaching=!0,requestAnimationFrame(()=>a(l+1))):console.warn("[SceneManager] Failed to restart animation loop - canvas never connected")};requestAnimationFrame(()=>a())}getMemoryDiagnostics(){var t;const e=this.sceneCore.getRenderer().info;return{threeJs:e!=null&&e.memory?{geometries:e.memory.geometries,textures:e.memory.textures,programs:((t=e.programs)==null?void 0:t.length)??0}:null,heap:nc.getUsage(),agentMeshCount:this.agentManager.getAgentMeshes().size,bossLineCount:0}}getRenderStats(){var t,n;const e=(n=(t=this.sceneCore.getRenderer())==null?void 0:t.info)==null?void 0:n.render;return e?{calls:e.calls,triangles:e.triangles,points:e.points,lines:e.lines}:null}get renderer(){return this.sceneCore.getRenderer()}logMemoryDiagnostics(){const e=this.getMemoryDiagnostics(),t=this.characterLoader.getCacheStats();console.group("%c[SceneManager Memory]","color: #ff6600; font-weight: bold"),e.threeJs&&console.log(`Three.js: ${e.threeJs.geometries} geometries, ${e.threeJs.textures} textures, ${e.threeJs.programs} programs`),e.heap&&console.log(`Heap: ${e.heap.usedMB}MB / ${e.heap.totalMB}MB (limit: ${e.heap.limitMB}MB)`),console.log(`Agent meshes: ${e.agentMeshCount}`),console.log(`CharacterLoader cache: ${t.builtInModels} built-in, ${t.customModels} custom`),t.modelNames.length>0&&console.log(` Built-in models: ${t.modelNames.join(", ")}`),t.customModelIds.length>0&&console.log(` Custom models: ${t.customModelIds.join(", ")}`),console.groupEnd()}dispose(){var n;console.log("%c[SceneManager] dispose() called - starting cleanup","color: #ff0000; font-weight: bold");const e=this.characterLoader.getCacheStats();console.log(`[SceneManager] Pre-dispose: ${e.builtInModels} built-in models, ${e.customModels} custom models`),this.renderLoop.stop(),window.removeEventListener("resize",this.onWindowResize);const t=this.sceneCore.getCanvas();t.removeEventListener("webglcontextlost",this.onContextLost),t.removeEventListener("webglcontextrestored",this.onContextRestored),(n=this.resizeObserver)==null||n.disconnect(),this.resizeObserver=null,this.inputHandler.dispose(),this.drawingManager.dispose(),this.buildingManager.dispose(),this.effectsManager.dispose(),this.agentManager.dispose(),this.selectionManager.dispose(),this.battlefield.dispose(),this.characterLoader.dispose(),this.cameraManager.dispose(),this.sceneCore.dispose(),console.log("%c[SceneManager] dispose() complete - all resources freed","color: #00ff00; font-weight: bold")}}const Fp="tide_webgl_active";typeof window<"u"&&(window.__tidePersistedScene===void 0&&(window.__tidePersistedScene=null),window.__tidePersistedCanvas===void 0&&(window.__tidePersistedCanvas=null),window.__tideWsConnected===void 0&&(window.__tideWsConnected=!1),window.__tideIsPageUnloading===void 0&&(window.__tideIsPageUnloading=!1));function xm(){return typeof window<"u"?window.__tidePersistedScene??null:null}function LM(){return typeof window<"u"?window.__tidePersistedCanvas??null:null}function YB(){return typeof window<"u"?window.__tideWsConnected??!1:!1}function hd(s){typeof window<"u"&&(window.__tidePersistedScene=s)}function td(s){typeof window<"u"&&(window.__tidePersistedCanvas=s)}function OM(s){typeof window<"u"&&(window.__tideWsConnected=s)}function VB(s){typeof window<"u"&&(window.__tideIsPageUnloading=s)}function KB(){sessionStorage.setItem(Fp,"true")}function Xh(s){VB(!0),sessionStorage.removeItem(Fp),vM(),$L(),window.__tideScene&&(window.__tideScene=null);const e=xm();e?(console.log("[App] Calling persistedScene.dispose()"),e.dispose(),hd(null)):console.log("[App] No persistedScene to dispose"),td(null),OM(!1);const t=document.getElementById("battlefield");t&&t.remove();const n=document.getElementById("app");n&&(n.innerHTML="")}function XB(){var a,i;if(window.__tideAppInitialized)return;if(window.__tideAppInitialized=!0,sessionStorage.getItem(Fp)==="true"&&console.log("[App] Detected unclean shutdown from previous session - forcing cleanup"),window.__tideScene){console.log("[App] Cleaning up stale __tideScene reference");try{(i=(a=window.__tideScene).dispose)==null||i.call(a)}catch{}window.__tideScene=null}const e=xm();if(e){console.log("[App] Cleaning up stale persistedScene");try{e.dispose()}catch{}hd(null)}const t=document.getElementById("battlefield"),n=LM();t&&t!==n&&t.remove(),sessionStorage.removeItem(Fp)}function ZB(){typeof window>"u"||(XB(),window.addEventListener("pageshow",s=>{s.persisted&&(console.log("[App] Page restored from bfcache - cleaning up"),Xh(),window.location.reload())}),window.onunload=()=>Xh(),window.onbeforeunload=s=>{Xh()},window.addEventListener("pagehide",s=>{Xh(`pagehide (persisted=${s.persisted})`)}))}ZB();const Vj={showTrees:!0,showBushes:!0,showHouse:!0,showLamps:!0,showGrass:!0,showClouds:!0,fogDensity:1,floorStyle:"metal",brightness:1,skyColor:null,battlefieldSize:50},Kj={saturation:2,roughness:.5,metalness:-1,emissiveBoost:0,envMapIntensity:1,wireframe:!1,colorMode:"normal"},Xj={idleAnimation:"sit",workingAnimation:"sprint"},QB=0;function IM(){const s={characterScale:2,indicatorScale:.7,gridVisible:!1,timeMode:"day",terrain:Vj,modelStyle:Kj,animations:Xj,fpsLimit:QB},e=ai(vt.CONFIG,null);return e?{characterScale:e.characterScale??s.characterScale,indicatorScale:e.indicatorScale??s.indicatorScale,gridVisible:e.gridVisible??s.gridVisible,timeMode:e.timeMode??s.timeMode,terrain:{...Vj,...e.terrain},modelStyle:{...Kj,...e.modelStyle},animations:{...Xj,...e.animations},fpsLimit:e.fpsLimit??s.fpsLimit}:s}function JB(s){Ei(vt.CONFIG,s)}function ez(){return typeof window>"u"?!0:window.matchMedia("(max-width: 768px)").matches}typeof window<"u"&&!window.__tideHmrRefreshListeners&&(window.__tideHmrRefreshListeners=new Set);function BM(){console.log("[Tide HMR] Manual scene refresh triggered");const s=xm();if(s){try{s.dispose()}catch(t){console.warn("[Tide HMR] Error disposing scene:",t)}hd(null)}td(null),window.__tideScene&&(window.__tideScene=null);const e=document.getElementById("battlefield");if(e){const t=e.getContext("webgl2")||e.getContext("webgl");if(t){const n=t.getExtension("WEBGL_lose_context");n&&n.loseContext()}}window.__tideHmrPendingSceneChanges=!1,window.location.reload()}typeof window<"u"&&(window.__tideHmrSceneRefresh=BM);function tz({canvasRef:s,selectionBoxRef:e,viewMode:t,sceneMountKey:n=0,showToast:a,showAgentNotification:i,toolboxModal:o,contextMenu:l,setHoveredAgentPopup:c,setBuildingPopup:d,getBuildingPopup:m,openBuildingModal:p,openPM2LogsModal:f,openBossLogsModal:b,openDatabasePanel:x,onSceneLoadingChange:w}){const k=y.useRef(null),S=y.useRef(null),j=y.useRef(null),C=y.useRef(null),N=y.useRef(null);return y.useEffect(()=>{if(t!=="3d"){w==null||w(!1);return}if(!s.current||!e.current)return;let P=!1;w==null||w(!0);const _=xm(),M=LM()===s.current;function D(){var E,R,O,I,B,Y,$,W;(E=k.current)==null||E.setOnToast(a),(R=k.current)==null||R.setOnBuildingClick((K,X)=>{z.selectBuilding(K);const H=z.getState().buildings.get(K);(H==null?void 0:H.type)==="folder"&&H.folderPath?z.openFileExplorer(H.folderPath):(H==null?void 0:H.type)==="server"||(H==null?void 0:H.type)==="boss"||(H==null?void 0:H.type)==="database"?(S.current&&clearTimeout(S.current),S.current=setTimeout(()=>{d({buildingId:K,screenPos:X,fromClick:!0}),S.current=null},150)):p(K)}),(O=k.current)==null||O.setOnContextMenu((K,X,H)=>{l.open(K,X,H)}),(I=k.current)==null||I.setOnAgentHover(()=>{}),(B=k.current)==null||B.setOnBuildingHover((K,X)=>{const H=m();if(K&&X){const se=z.getState().buildings.get(K);((se==null?void 0:se.type)==="server"||(se==null?void 0:se.type)==="boss"||(se==null?void 0:se.type)==="database")&&!(H!=null&&H.fromClick)&&d({buildingId:K,screenPos:X,fromClick:!1})}else H!=null&&H.fromClick||d(null)}),(Y=k.current)==null||Y.setOnGroundClick(()=>{d(null)}),($=k.current)==null||$.setOnAreaDoubleClick(K=>{z.selectArea(K),o.open()}),(W=k.current)==null||W.setOnBuildingDoubleClick(K=>{var H;S.current&&(clearTimeout(S.current),S.current=null),d(null);const X=z.getState().buildings.get(K);(X==null?void 0:X.type)==="server"&&((H=X.pm2)!=null&&H.enabled)?f==null||f(K):(X==null?void 0:X.type)==="boss"?b==null||b(K):(X==null?void 0:X.type)==="database"?x==null||x(K):(X==null?void 0:X.type)==="folder"&&X.folderPath?z.openFileExplorer(X.folderPath):p(K)})}if(_)try{k.current=_,M?console.log("[Tide] Reusing existing scene (StrictMode remount)"):(console.log("[Tide] Reattaching persisted scene to new canvas"),_.reattach(s.current,e.current),td(s.current));const E=z.getState();_.syncAreas(),_.syncBuildings(),E.agents.size>0&&(console.log("[Tide] Re-syncing agents from store after remount:",E.agents.size),_.syncAgents(Array.from(E.agents.values()))),D()}catch(E){console.error("[Tide] Failed to reattach persisted 3D scene:",E),w==null||w(!1)}finally{C.current=requestAnimationFrame(()=>{N.current=requestAnimationFrame(()=>{w==null||w(!1),N.current=null}),C.current=null})}else{const E=s.current,R=e.current,O=()=>{if(P){console.log("[Tide] Effect cleaned up before scene init, skipping"),w==null||w(!1);return}if(!E.isConnected||!R.isConnected){console.warn("[Tide] Canvas disconnected before initialization"),w==null||w(!1);return}(!E.clientWidth||!E.clientHeight)&&(console.log("[Tide] Canvas has no CSS dimensions, using window fallback"),E.style.width="100%",E.style.height="100%",E.offsetHeight),(!E.clientWidth||!E.clientHeight)&&(E.width=window.innerWidth,E.height=window.innerHeight),KB();try{const I=new qB(E,R);k.current=I,hd(I),td(E);const B=IM();I.setCharacterScale(B.characterScale),I.setIndicatorScale(B.indicatorScale),I.setGridVisible(B.gridVisible),I.setTimeMode(B.timeMode),I.setTerrainConfig(B.terrain),I.setFloorStyle(B.terrain.floorStyle,!0),I.setAgentModelStyle(B.modelStyle),I.setIdleAnimation(B.animations.idleAnimation),I.setWorkingAnimation(B.animations.workingAnimation),I.setFpsLimit(B.fpsLimit),I.syncAreas(),I.syncBuildings(),I.loadCharacterModels().then(()=>{console.log("[Tide] Character models ready");const Y=z.getState();Y.customAgentClasses.size>0&&(console.log("[Tide] Applying custom classes from store:",Y.customAgentClasses.size),I.setCustomAgentClasses(Y.customAgentClasses)),Y.agents.size>0&&(console.log("[Tide] Syncing agents from store:",Y.agents.size),I.syncAgents(Array.from(Y.agents.values()))),I.upgradeAgentModels()}).catch(Y=>{console.warn("[Tide] Some models failed to load, using fallback:",Y)}).finally(()=>{w==null||w(!1)}),D()}catch(I){console.error("[Tide] Failed to initialize 3D scene:",I),w==null||w(!1)}};j.current=requestAnimationFrame(O)}return gM({onAgentCreated:E=>{var R,O,I;(R=k.current)==null||R.addAgent(E),(O=k.current)==null||O.refreshSelectionVisuals(),(I=window.__spawnModalSuccess)==null||I.call(window)},onAgentUpdated:(E,R)=>{var O;(O=k.current)==null||O.updateAgent(E,R)},onAgentDeleted:E=>{var R;(R=k.current)==null||R.removeAgent(E)},onAgentsSync:E=>{var R;(R=k.current)==null||R.syncAgents(E)},onAreasSync:()=>{var R,O;(R=k.current)==null||R.syncAreas();const E=Array.from(z.getState().agents.values());(O=k.current)==null||O.syncAgents(E)},onSpawnError:()=>{var E;(E=window.__spawnModalError)==null||E.call(window)},onSpawnSuccess:()=>{var E;(E=window.__spawnModalSuccess)==null||E.call(window)},onDirectoryNotFound:E=>{var R;(R=window.__spawnModalDirNotFound)==null||R.call(window,E)},onToolUse:(E,R,O)=>{var I;(I=k.current)==null||I.showToolBubble(E,R,O)},onDelegation:(E,R)=>{var O;(O=k.current)==null||O.showDelegationEffect(E,R)},onCustomClassesSync:E=>{var R,O;(R=k.current)==null||R.setCustomAgentClasses(E),(O=k.current)==null||O.upgradeAgentModels()},onBuildingUpdated:E=>{var R;(R=k.current)==null||R.updateBuilding(E)},onSubagentStarted:E=>{var R;(R=k.current)==null||R.addSubagentEffect(E.id,E.parentAgentId,E.name,E.subagentType)},onSubagentCompleted:E=>{var I;const R=z.getSubagent(E)||z.getSubagentByToolUseId(E),O=(R==null?void 0:R.id)||E;(I=k.current)==null||I.completeSubagentEffect(O),setTimeout(()=>{var B;(B=k.current)==null||B.removeSubagentEffect(O)},3e4)}}),()=>{P=!0,j.current!==null&&(cancelAnimationFrame(j.current),j.current=null),C.current!==null&&(cancelAnimationFrame(C.current),C.current=null),N.current!==null&&(cancelAnimationFrame(N.current),N.current=null),z.getState().viewMode!=="3d"&&ez()&&k.current&&(console.log("[Tide] 3D canvas unmounted - disposing scene to free memory"),HL(),k.current.dispose(),k.current=null,hd(null),td(null))}},[t,n]),k}function nz({showToast:s,showAgentNotification:e}){const t=y.useRef(!1);y.useEffect(()=>{if(t.current||YB())return;t.current=!0,gM({onToast:s,onReconnect:()=>{z.triggerReconnect()},onAgentNotification:i=>{e(i)}}),dd(),OM(!0),PL();let n;LL(i=>{i.type==="agent_notification"&&typeof i.agentId=="string"&&hM(i.agentId)}).then(i=>{n=i});const a=()=>{console.log("[Tide] App resumed from background, reconnecting..."),setTimeout(()=>dd(),100)};return window.addEventListener("tideAppResume",a),()=>{window.removeEventListener("tideAppResume",a),n==null||n()}},[s,e])}function sz(s){y.useEffect(()=>{let e="",t="",n=new Map;const a=i=>{var c;let o=!1;const l=new Map;for(const[d,m]of i){const f=`${m.position.x.toFixed(2)},${m.position.z.toFixed(2)},${m.status},${m.class},${m.isBoss},${((c=m.subordinateIds)==null?void 0:c.length)??0}`.split("").reduce((b,x)=>(b<<5)-b+x.charCodeAt(0),0);l.set(d,f),n.get(d)!==f&&(o=!0)}return l.size!==n.size&&(o=!0),{newVersion:l,changed:o}};return z.subscribe(()=>{var f;const i=z.getState(),o=Array.from(i.selectedAgentIds).sort().join(","),l=Array.from(i.selectedBuildingIds).sort().join(","),c=o!==e,d=l!==t,{newVersion:m,changed:p}=a(i.agents);(c||d||p)&&(e=o,t=l,n=m,(f=s.current)==null||f.refreshSelectionVisuals())})},[s])}function az(s){y.useEffect(()=>{var n;(n=s.current)==null||n.syncAreas();let e=0,t=0;return z.subscribe(()=>{var l,c;const i=z.getState().areas;if(i.size!==e){e=i.size,t=Date.now(),(l=s.current)==null||l.syncAreas();return}let o=0;for(const[d,m]of i){let p=d.charCodeAt(0);p+=(m.width??0)+(m.height??0)+(m.radius??0),p+=Math.floor(m.center.x*100)+Math.floor(m.center.z*100),p+=(m.zIndex??0)*1e3;for(let f=0;f<m.name.length;f++)p+=m.name.charCodeAt(f);for(let f=0;f<m.color.length;f++)p+=m.color.charCodeAt(f);if(m.directoryGitCounts)for(const f of m.directoryGitCounts)p+=(f+1)*7;if(m.logo){p+=Math.floor((m.logo.opacity??.8)*1e3),p+=Math.floor(m.logo.width*100)+Math.floor(m.logo.height*100);for(let f=0;f<m.logo.position.length;f++)p+=m.logo.position.charCodeAt(f);if(m.logo.filename)for(let f=0;f<m.logo.filename.length;f++)p+=m.logo.filename.charCodeAt(f)}o^=p|0}o!==t&&(t=o,(c=s.current)==null||c.syncAreas())})},[s])}function iz(s){y.useEffect(()=>{var n;(n=s.current)==null||n.syncBuildings();let e=0,t=0;return z.subscribe(()=>{var l,c;const i=z.getState().buildings;if(i.size!==e){e=i.size,t=Date.now(),(l=s.current)==null||l.syncBuildings();return}let o=0;for(const[d,m]of i){o^=m.position.x*1e3+m.position.z|0,o^=(m.scale||1)*1e4|0;const p=`${m.style||""}${m.name}${m.status}${m.gitChangesCount||0}`;for(let f=0;f<p.length;f++)o=(o<<5)-o+p.charCodeAt(f)|0}o!==t&&(t=o,(c=s.current)==null||c.syncBuildings())})},[s])}function rz(s,e){y.useEffect(()=>{var t;(t=s.current)==null||t.highlightArea(e)},[s,e])}function oz(s,e){y.useEffect(()=>{var t;(t=s.current)==null||t.setPowerSaving(e)},[s,e])}function lz({sceneRef:s,spawnModal:e,commanderModal:t,explorerModal:n,spotlightModal:a,deleteConfirmModal:i,onRequestBuildingDelete:o,onOpenDatabasePanel:l,onCloseDatabasePanel:c,databasePanelOpen:d}){y.useEffect(()=>{const m=p=>{var E,R,O,I;const f=z.getShortcuts(),b=p.target,x=b.tagName==="INPUT"||b.tagName==="TEXTAREA",w=f.find(B=>B.id==="deselect-all");if(xt(p,w)){if(xy()){p.preventDefault();return}const B=z.getState();if(B.activeTool==="rectangle"||B.activeTool==="circle"){(E=s.current)==null||E.setDrawingTool(null),typeof window<"u"&&window.__tideScene2D_setDrawingTool&&window.__tideScene2D_setDrawingTool(null);return}e.isOpen?e.close():B.terminalOpen?(z.setTerminalOpen(!1),document.activeElement instanceof HTMLElement&&document.activeElement.blur()):(z.deselectAll(),(R=s.current)==null||R.refreshSelectionVisuals())}for(let B=1;B<=9;B++){const Y=f.find($=>$.id===`select-agent-${B}`);if(xt(p,Y)){p.preventDefault();const $=z.getState(),W=B-1,K=Array.from($.agents.keys());W<K.length&&(z.selectAgent(K[W]),(O=s.current)==null||O.refreshSelectionVisuals());return}}const k=f.find(B=>B.id==="spawn-agent");if(xt(p,k)){p.preventDefault(),e.open();return}const S=f.find(B=>B.id==="toggle-commander-tab");if(xt(p,S)&&!x){p.preventDefault(),t.toggle();return}const j=f.find(B=>B.id==="toggle-commander");if(xt(p,j)){p.preventDefault(),t.toggle();return}const C=f.find(B=>B.id==="toggle-file-explorer");if(xt(p,C)){p.preventDefault();const B=z.getState();if(n.isOpen||B.explorerFolderPath!==null||B.explorerAreaId!==null)n.close(),z.closeFileExplorer();else{const $=z.getLastExplorerState();if(($==null?void 0:$.type)==="folder")z.openFileExplorer($.path);else if(($==null?void 0:$.type)==="area")if(B.areas.has($.areaId))n.open($.areaId);else{const W=Array.from(B.areas.values()).filter(K=>K.directories&&K.directories.length>0);W.length>0&&n.open(W[0].id)}else{const W=Array.from(B.areas.values()).filter(K=>K.directories&&K.directories.length>0);W.length>0&&n.open(W[0].id)}}return}if(p.altKey&&!p.ctrlKey&&!p.shiftKey&&!p.metaKey&&p.code==="KeyD"){if(p.preventDefault(),p.stopPropagation(),d){c();return}const B=localStorage.getItem("tide-commander-last-database-building"),Y=z.getState();if(B){const $=Y.buildings.get(B);if(($==null?void 0:$.type)==="database"){l(B);return}}for(const[$,W]of Y.buildings)if(W.type==="database"){l($);return}return}const N=f.find(B=>B.id==="toggle-spotlight");if(xt(p,N)||p.altKey&&!p.ctrlKey&&!p.metaKey&&p.code==="KeyP"){console.log("[useKeyboardShortcuts] Spotlight shortcut matched!",{spotlightShortcut:N,altKey:p.altKey,code:p.code}),p.preventDefault(),a.toggle();return}const P=f.find(B=>B.id==="toggle-2d-view");if(xt(p,P)){p.preventDefault();const B=z.getState().viewMode,Y=B==="3d"?"2d":B==="2d"?"dashboard":"3d";z.setViewMode(Y);return}const _=f.find(B=>B.id==="next-working-agent"),L=f.find(B=>B.id==="prev-working-agent");if((xt(p,_)||xt(p,L))&&!x){const B=z.getState();if(B.terminalOpen)return;const Y=Array.from(B.agents.values());let $=Y.filter(H=>B.agentsWithUnseenOutput.has(H.id));if($.length===0&&($=Y.filter(H=>H.status==="working")),$.length===0)return;p.preventDefault();const W=B.selectedAgentIds.size===1?Array.from(B.selectedAgentIds)[0]:null,K=W?$.findIndex(H=>H.id===W):-1;let X;xt(p,_)?X=K===-1?0:(K+1)%$.length:X=K===-1?$.length-1:(K-1+$.length)%$.length,z.selectAgent($[X].id),(I=s.current)==null||I.refreshSelectionVisuals();return}const M=f.find(B=>B.id==="delete-selected"),D=f.find(B=>B.id==="delete-selected-backspace");if((xt(p,M)||xt(p,D))&&!x){const B=z.getState();if(B.selectedAgentIds.size>0){p.preventDefault(),i.open();return}if(B.selectedBuildingIds.size>0){p.preventDefault(),o();return}return}};return document.addEventListener("keydown",m,!0),()=>document.removeEventListener("keydown",m,!0)},[s,e,t,n,a,i,o,l,c,d])}function cz(){const[s,e]=y.useState(!1);return window.__tideSetBackNavModal=e,y.useEffect(()=>{if(!(window.innerWidth<=768))return;if(window.__tideBackNavSetup){window.location.hash.includes("app")||(window.location.hash="#app");return}window.__tideBackNavSetup=!0,window.location.hash.includes("app")||(window.location.hash="#app");const a=()=>{var o;window.innerWidth>768||window.location.hash.includes("app")||(window.location.hash="#app",xy()||(o=window.__tideSetBackNavModal)==null||o.call(window,!0))},i=()=>{var o;window.innerWidth>768||(window.location.hash.includes("app")||(window.location.hash="#app"),window.location.hash==="#app"&&setTimeout(()=>{window.location.hash==="#app"&&!window.location.hash.includes("app2")&&(window.history.pushState(null,"","#app2"),window.history.pushState(null,"","#app"))},50),xy()||(o=window.__tideSetBackNavModal)==null||o.call(window,!0))};window.history.pushState(null,"","#app1"),window.history.pushState(null,"","#app2"),window.history.pushState(null,"","#app"),window.addEventListener("hashchange",a),window.addEventListener("popstate",i)},[]),{showBackNavModal:s,setShowBackNavModal:e,handleLeave:()=>{e(!1);const n=window.__tideHistoryDepth??2;window.history.go(-(n+1))}}}const pb="agent-order-change";function zM(s){const e=y.useMemo(()=>new Set(s.map(c=>c.id)),[s]),[t,n]=y.useState(()=>ai(vt.AGENT_ORDER,[]));y.useEffect(()=>{const c=d=>{n(d.detail)};return window.addEventListener(pb,c),()=>{window.removeEventListener(pb,c)}},[]);const a=y.useMemo(()=>{const c=t.filter(f=>e.has(f)),d=s.filter(f=>!c.includes(f.id)).map(f=>f.id),m=[...c,...d],p=new Map(s.map(f=>[f.id,f]));return m.map(f=>p.get(f)).filter(f=>f!==void 0)},[s,t,e]),i=y.useCallback(c=>{n(c),Ei(vt.AGENT_ORDER,c),window.dispatchEvent(new CustomEvent(pb,{detail:c}))},[]),o=y.useCallback((c,d)=>{const m=a.map(f=>f.id),[p]=m.splice(c,1);m.splice(d,0,p),i(m)},[a,i]),l=y.useCallback(()=>{n([]),Ei(vt.AGENT_ORDER,[])},[]);return y.useEffect(()=>{if(e.size===0)return;const c=t.filter(d=>e.has(d));c.length!==t.length&&i(c)},[e,t,i]),{orderedAgents:a,moveAgent:o,resetOrder:l}}const Px="deivid11/tide-commander",uz=`https://api.github.com/repos/${Px}/releases/latest`,dz=`https://api.github.com/repos/${Px}/releases?per_page=3`,hz=3600*1e3,Zj="app_update_dismissed_version",Qj="0.84.1";function pz(){var m;const[s,e]=y.useState({isChecking:!1,updateAvailable:!1,updateInfo:null,recentReleases:[],error:null,currentVersion:Qj}),t=((m=Aa==null?void 0:Aa.getPlatform)==null?void 0:m.call(Aa))==="android"||!1,n=p=>p.replace(/^v/,"").split(".").map(b=>parseInt(b,10)||0),a=(p,f)=>{const b=n(p),x=n(f),w=Math.max(b.length,x.length);for(let k=0;k<w;k++){const S=b[k]||0,j=x[k]||0;if(S>j)return 1;if(S<j)return-1}return 0},i=async p=>{var b;if(Aa&&dj&&((b=Aa.isNativePlatform)==null?void 0:b.call(Aa))===!0){const x=await dj.get({url:p,headers:{Accept:"application/vnd.github.v3+json"}});return{data:x.data,status:x.status}}else{const x=await fetch(p,{headers:{Accept:"application/vnd.github.v3+json"}});return x.ok?{data:await x.json(),status:x.status}:{data:null,status:x.status}}},o=y.useCallback(async(p=!1)=>{e(f=>({...f,isChecking:!0,error:null}));try{const[f,b]=await Promise.all([i(uz),i(dz)]);if(f.status!==200)throw new Error(`GitHub API error: ${f.status}`);const x=f.data,w=x.tag_name;let k=[];b.status===200&&b.data&&(k=b.data.map(P=>({version:P.tag_name,name:P.name,publishedAt:P.published_at,releaseUrl:P.html_url})));const S=localStorage.getItem(Zj);if(!p&&S===w)return e(P=>({...P,isChecking:!1,updateAvailable:!1,recentReleases:k})),null;if(!(a(w,Qj)>0))return e(P=>({...P,isChecking:!1,updateAvailable:!1,recentReleases:k})),null;const C=x.assets.find(P=>P.name.endsWith(".apk")&&P.content_type==="application/vnd.android.package-archive"),N={version:w,name:x.name,changelog:x.body,releaseUrl:x.html_url,apkUrl:(C==null?void 0:C.browser_download_url)||null,apkSize:(C==null?void 0:C.size)||null,publishedAt:x.published_at};return e(P=>({...P,isChecking:!1,updateAvailable:!0,updateInfo:N,recentReleases:k})),N}catch(f){const b=f instanceof Error?f.message:"Failed to check for updates";return e(x=>({...x,isChecking:!1,error:b})),null}},[]),l=y.useCallback(async()=>{var p,f,b;if(!((p=s.updateInfo)!=null&&p.apkUrl)){(f=s.updateInfo)!=null&&f.releaseUrl&&window.open(s.updateInfo.releaseUrl,"_blank");return}if(!t){(b=s.updateInfo)!=null&&b.releaseUrl&&window.open(s.updateInfo.releaseUrl,"_blank");return}try{window.open(s.updateInfo.apkUrl,"_system"),e(x=>({...x,error:null}))}catch(x){const w=x instanceof Error?x.message:"Failed to open download";e(k=>({...k,error:w}))}},[s.updateInfo,t]),c=y.useCallback(()=>{s.updateInfo&&localStorage.setItem(Zj,s.updateInfo.version),e(p=>({...p,updateAvailable:!1,updateInfo:null}))},[s.updateInfo]),d=y.useCallback(()=>{var p;(p=s.updateInfo)!=null&&p.releaseUrl?window.open(s.updateInfo.releaseUrl,"_blank"):window.open(`https://github.com/${Px}/releases`,"_blank")},[s.updateInfo]);return y.useEffect(()=>{if(!t)return;const p=setTimeout(()=>{o()},5e3),f=setInterval(()=>{o()},hz);return()=>{clearTimeout(p),clearInterval(f)}},[t,o]),{...s,isAndroid:t,checkForUpdate:o,downloadAndInstall:l,dismissUpdate:c,openReleasePage:d}}function Ls(s){const e=y.useRef(null),t=y.useCallback(a=>{e.current=a.target,a.target===a.currentTarget&&a.stopPropagation()},[]),n=y.useCallback(a=>{a.target===a.currentTarget&&e.current===a.currentTarget&&(a.stopPropagation(),s()),e.current=null},[s]);return{handleMouseDown:t,handleClick:n}}const mz=3e4;function fz(){const s=y.useRef(null);y.useEffect(()=>{const e=async()=>{var o,l;const t=z.getState(),n=new Map,a=new Map;for(const[c,d]of t.buildings){const m=d.folderPath||d.cwd;m&&(a.has(m)||a.set(m,[]),a.get(m).push(c))}for(const[c,d]of a)try{const m=await bt(rt(`/api/files/git-status?path=${encodeURIComponent(c)}`));if(!m.ok)continue;const f=((o=(await m.json()).files)==null?void 0:o.length)||0;n.set(c,f);for(const b of d){const x=z.getState().buildings.get(b);x&&x.gitChangesCount!==f&&z.updateBuildingLocal(b,{gitChangesCount:f})}}catch{}const i=new Map;for(const[c,d]of t.areas)d.archived||!d.directories||d.directories.forEach((m,p)=>{m&&(i.has(m)||i.set(m,[]),i.get(m).push({areaId:c,dirIndex:p}))});if(i.size!==0)for(const[c,d]of i)try{let m;if(n.has(c))m=n.get(c);else{const f=await bt(rt(`/api/files/git-status?path=${encodeURIComponent(c)}`));if(!f.ok)continue;m=((l=(await f.json()).files)==null?void 0:l.length)||0,n.set(c,m)}const p=new Map;for(const f of d)p.has(f.areaId)||p.set(f.areaId,[]),p.get(f.areaId).push({dirIndex:f.dirIndex,count:m});for(const[f,b]of p){const x=z.getState().areas.get(f);if(!x)continue;const w=x.directoryGitCounts?[...x.directoryGitCounts]:new Array(x.directories.length).fill(0);let k=!1;for(const{dirIndex:S,count:j}of b)w[S]!==j&&(w[S]=j,k=!0);k&&z.updateAreaLocal(f,{directoryGitCounts:w})}}catch{}};return e(),s.current=setInterval(e,mz),()=>{s.current&&(clearInterval(s.current),s.current=null)}},[])}const Jj={historyLimit:500,hideCost:!0,showFPS:!1,powerSaving:!1,customAgentNames:[],experimental2DView:!1,experimentalVoiceAssistant:!1,experimentalTTS:!1,experimentalEchoPrompt:!1,externalEditorCommand:""},$p=90,mb=["simple","chat","advanced"],eC=55,tC=20,nC=85,gz=200,bz=12e4,yz=5,Ga=new Map;function xz(s){const e=Ga.get(s);e&&(Ga.delete(s),Ga.set(s,e))}function vz(){for(;Ga.size>yz;){const s=Ga.keys().next().value;if(s!==void 0)Ga.delete(s);else break}}function FM(s){Ga.delete(s)}function wz(s){return s.trim().replace(/\r\n/g,`
148
+ `,side:$A});a.add(new De(i,o)),a.add(new xx(16777215,1));const l=n.fromScene(a,.04).texture;t.environment=l,n.dispose(),i.dispose(),o.dispose()}createInputCallbacks(){return{onAgentClick:(e,t)=>this.inputEventHandlers.handleAgentClick(e,t),onAgentDoubleClick:e=>this.inputEventHandlers.handleAgentDoubleClick(e),onAgentHover:(e,t)=>this.inputEventHandlers.handleAgentHover(e,t),onGroundClick:()=>this.inputEventHandlers.handleGroundClick(),onMoveCommand:(e,t)=>this.inputEventHandlers.handleMoveCommand(e,t),onSelectionBox:(e,t)=>this.inputEventHandlers.handleSelectionBox(e,t),onDrawStart:e=>this.drawingManager.startDrawing(e),onDrawMove:e=>this.drawingManager.updateDrawing(e),onDrawEnd:e=>this.drawingManager.finishDrawing(e),onAreaRightClick:e=>this.inputEventHandlers.handleAreaRightClick(e),onAreaClick:e=>this.inputEventHandlers.handleAreaClick(e),onAreaDoubleClick:e=>this.inputEventHandlers.handleAreaDoubleClick(e),onResizeStart:(e,t)=>this.drawingManager.startResize(e,t),onResizeMove:e=>this.drawingManager.updateResize(e),onResizeEnd:()=>this.drawingManager.finishResize(),onGroundClickOutsideArea:()=>this.inputEventHandlers.handleGroundClickOutsideArea(),onFolderIconClick:(e,t)=>{var n;t?z.openFileExplorerForAreaFolder(e,t):z.openFileExplorerForArea(e),(n=this.onFolderIconClickCallback)==null||n.call(this,e)},onBuildingClick:(e,t)=>this.inputEventHandlers.handleBuildingClick(e,t),onBuildingDoubleClick:e=>this.inputEventHandlers.handleBuildingDoubleClick(e),onBuildingHover:(e,t)=>this.inputEventHandlers.handleBuildingHover(e,t),onBuildingDragStart:()=>{},onBuildingDragMove:(e,t)=>this.buildingManager.setBuildingPosition(e,t),onBuildingDragEnd:(e,t)=>z.updateBuildingPosition(e,t),onContextMenu:(e,t,n)=>this.callbackManager.triggerContextMenu(e,t,n),onActivity:()=>this.renderLoop.markActivity(),onToggleTerminal:()=>z.toggleTerminal()}}setupInputHandlerHelpers(){this.inputHandler.setDrawingModeChecker(()=>this.drawingManager.isInDrawingMode()),this.inputHandler.setResizeHandlers(()=>this.drawingManager.getResizeHandles(),()=>this.drawingManager.isCurrentlyResizing()),this.inputHandler.setAreaAtPositionGetter(e=>this.drawingManager.getAreaAtPosition(e)),this.inputHandler.setFolderIconMeshesGetter(()=>this.drawingManager.getFolderIconMeshes()),this.inputHandler.setBuildingAtPositionGetter(e=>{const t=this.buildingManager.getBuildingAtPosition(e);return t?{id:t.id}:null}),this.inputHandler.setBuildingPositionsGetter(()=>{const e=new Map;for(const[t,n]of this.buildingManager.getBuildingMeshData())e.set(t,n.group.position.clone());return e})}setupEventListeners(e){window.addEventListener("resize",this.onWindowResize),this.resizeObserver=new ResizeObserver(()=>this.onWindowResize()),e.parentElement&&this.resizeObserver.observe(e.parentElement),e.addEventListener("webglcontextlost",this.onContextLost),e.addEventListener("webglcontextrestored",this.onContextRestored)}updateInputHandlerReferences(){this.inputHandler.setReferences(this.battlefield.getGround(),this.agentManager.getAgentMeshes())}updateBattlefield(e,t){t-this.lastTimeUpdate>6e4&&(this.battlefield.updateTimeOfDay(),this.lastTimeUpdate=t),this.battlefield.updateGalacticAnimation(e),this.battlefield.updateCloudAnimation(e)}updateAnimations(e){const t=this.movementAnimator.update(this.agentManager.getAgentMeshes(),e);return this.effectsManager.update(),this.buildingManager.update(e),t}updateProceduralAnimations(e){if(this.proceduralBodiesDirty){this.proceduralBodiesCache.clear();for(const[t,n]of this.agentManager.getAgentMeshes())if(this.proceduralAnimator.has(t)&&n.animations.size===0){const a=n.group.getObjectByName("characterBody");a&&this.proceduralBodiesCache.set(t,a)}this.proceduralBodiesDirty=!1}this.proceduralBodiesCache.size>0&&this.proceduralAnimator.update(e,this.proceduralBodiesCache)}updateIndicatorScales(e,t,n){for(const[,a]of t){const i=e.position.distanceTo(a.group.position),o=Math.max(.5,Math.min(2.5,i/15))*n,l=a.group.userData.isBoss===!0,c=a.group.getObjectByName("statusBar"),d=a.group.getObjectByName("nameLabelSprite");if(c){const p=typeof c.userData.baseIndicatorScale=="number"?c.userData.baseIndicatorScale:l?2:1.6,f=typeof c.userData.aspectRatio=="number"?c.userData.aspectRatio:2560/4096;c.scale.set(p*o,p*f*o,1)}if(d){const p=typeof d.userData.baseIndicatorScale=="number"?d.userData.baseIndicatorScale:l?1.5:1.25,f=p>2,b=f?p:Math.max(l?1.35:1.1,Math.min(l?1.65:1.35,p)),x=typeof d.userData.aspectRatio=="number"?d.userData.aspectRatio:1024/4096,w=Math.max(.5,Math.min(2.5,i/15)),S=(f?Math.max(.8,Math.min(1.2,w)):w)*n;d.scale.set(b*S,b*x*S,1)}const m=a.group.getObjectByName("combinedUI");if(m){const p=typeof m.userData.baseIndicatorScale=="number"?m.userData.baseIndicatorScale:l?3:2.4,f=typeof m.userData.aspectRatio=="number"?m.userData.aspectRatio:1024/2048;m.scale.set(p*o,p*f*o,1)}if(!c&&!m){const p=a.group.getObjectByName("nameLabel");if(p){const x=.3*o;p.scale.set(x*(p.userData.aspectRatio||2),x,1)}const f=a.group.getObjectByName("manaBar");f&&f.scale.set(.9,.14,1);const b=a.group.getObjectByName("idleTimer");b&&b.scale.set(.9*o,.14*o,1)}}for(const[,a]of this.buildingManager.getBuildingMeshData()){const i=e.position.distanceTo(a.group.position),o=Math.max(.5,Math.min(2.5,i/15))*n,l=a.group.getObjectByName("buildingLabel");if(l){const c=.3*o;l.scale.set(c*(l.userData.aspectRatio||2),c,1)}}this.effectsManager.updateWithCamera(e)}async loadCharacterModels(){await this.agentManager.loadCharacterModels()}upgradeAgentModels(){this.agentManager.upgradeAgentModels(),this.updateInputHandlerReferences()}addAgent(e){this.agentManager.addAgent(e)}removeAgent(e){this.agentManager.removeAgent(e),this.updateInputHandlerReferences()}updateAgent(e,t=!1){this.agentManager.updateAgent(e,t)}syncAgents(e){this.agentManager.syncAgents(e)}setCustomAgentClasses(e){this.agentManager.setCustomAgentClasses(e)}refreshSelectionVisuals(){this.selectionManager.refreshSelectionVisuals()}createMoveOrderEffect(e){this.effectsManager.createMoveOrderEffect(e)}showToolBubble(e,t,n){this.effectsManager.setAgentMeshes(this.agentManager.getAgentMeshes()),this.effectsManager.createSpeechBubble(e,t,n)}showDelegationEffect(e,t){this.effectsManager.setAgentMeshes(this.agentManager.getAgentMeshes()),this.effectsManager.createDelegationEffect(e,t)}addSubagentEffect(e,t,n,a){this.effectsManager.setAgentMeshes(this.agentManager.getAgentMeshes()),this.effectsManager.addSubagentEffect(e,t,n,a)}completeSubagentEffect(e){this.effectsManager.completeSubagentEffect(e)}removeSubagentEffect(e){this.effectsManager.removeSubagentEffect(e)}focusAgent(e){this.cameraManager.focusAgent(e)}callSubordinates(e){var o;const n=z.getState().agents.get(e);if(!n||!(n.isBoss||n.class==="boss")||!((o=n.subordinateIds)!=null&&o.length))return;const a=new gt(n.position.x,n.position.y,n.position.z),i=this.inputHandler.calculateFormationPositions(a,n.subordinateIds.length);this.effectsManager.createMoveOrderEffect(a.clone()),n.subordinateIds.forEach((l,c)=>{const d=this.agentManager.getAgentMeshes().get(l);z.moveAgent(l,i[c]),d&&this.movementAnimator.startMovement(l,d,i[c])})}setDrawingTool(e){this.drawingManager.setTool(e),z.setActiveTool(e)}syncAreas(){this.drawingManager.syncFromStore()}highlightArea(e){this.drawingManager.highlightArea(e)}clearAreaSelection(){this.drawingManager.highlightArea(null)}addBuilding(e){this.buildingManager.addBuilding(e)}removeBuilding(e){this.buildingManager.removeBuilding(e)}updateBuilding(e){this.buildingManager.updateBuilding(e)}syncBuildings(){this.buildingManager.syncFromStore()}highlightBuilding(e){this.buildingManager.highlightBuilding(e)}setOnBuildingClick(e){this.callbackManager.setOnBuildingClick(e)}setOnBuildingDoubleClick(e){this.callbackManager.setOnBuildingDoubleClick(e)}setOnContextMenu(e){this.callbackManager.setOnContextMenu(e)}setOnAgentHover(e){this.callbackManager.setOnAgentHover(e)}setOnBuildingHover(e){this.callbackManager.setOnBuildingHover(e)}setOnGroundClick(e){this.callbackManager.setOnGroundClick(e)}setOnAreaDoubleClick(e){this.callbackManager.setOnAreaDoubleClick(e)}setOnFolderIconClick(e){this.onFolderIconClickCallback=e}setOnToast(e){this.agentManager.setOnToast(e)}setCharacterScale(e){this.agentManager.setCharacterScale(e),this.selectionManager.setCharacterScale(e)}setIndicatorScale(e){this.renderLoop.setIndicatorScale(e),this.effectsManager.setIndicatorScale(e)}setFpsLimit(e){this.renderLoop.setFpsLimit(e)}setPowerSaving(e){this.renderLoop.setPowerSaving(e)}setGridVisible(e){this.battlefield.setGridVisible(e)}setDebugTime(e){this.battlefield.setDebugTime(e)}setTimeMode(e){this.battlefield.setTimeMode(e)}setTerrainConfig(e){this.battlefield.setTerrainConfig(e),e.brightness!==void 0&&(this.drawingManager.setBrightness(e.brightness),this.buildingManager.setBrightness(e.brightness),this.agentManager.setBrightness(e.brightness))}setFloorStyle(e,t=!1){this.battlefield.setFloorStyle(e,t)}setIdleAnimation(e){this.agentManager.setIdleAnimation(e)}setWorkingAnimation(e){this.agentManager.setWorkingAnimation(e)}setAgentModelStyle(e){this.agentManager.setModelStyle(e)}getAgentModelStyle(){return this.agentManager.getModelStyle()}setGlobalSaturation(e){this.sceneCore.setSaturation(e)}getGlobalSaturation(){return this.sceneCore.getSaturation()}setPostProcessingEnabled(e){this.sceneCore.setPostProcessingEnabled(e)}reattach(e,t){var i,o;console.log("[SceneManager] Reattaching to new canvas (HMR)"),this.isReattaching=!0,this.renderLoop.stop(),(i=this.resizeObserver)==null||i.disconnect();const n=this.sceneCore.getCanvas();n.removeEventListener("webglcontextlost",this.onContextLost),n.removeEventListener("webglcontextrestored",this.onContextRestored),this.sceneCore.reattach(e),this.cameraManager.recreateControls(this.sceneCore.getRenderer()),this.sceneCore.updateCamera(this.cameraManager.getCamera()),e.addEventListener("webglcontextlost",this.onContextLost),e.addEventListener("webglcontextrestored",this.onContextRestored),this.inputHandler.reattach(e,t,this.cameraManager.getControls()),this.updateInputHandlerReferences(),e.parentElement&&((o=this.resizeObserver)==null||o.observe(e.parentElement)),this.onWindowResize();const a=(l=0)=>{this.isReattaching=!1,e.isConnected&&this.sceneCore.getRenderer()?(console.log("[SceneManager] Restarting animation loop after HMR reattach"),this.renderLoop.start()):l<10?(console.log(`[SceneManager] Canvas not connected, retrying... (attempt ${l+1})`),this.isReattaching=!0,requestAnimationFrame(()=>a(l+1))):console.warn("[SceneManager] Failed to restart animation loop - canvas never connected")};requestAnimationFrame(()=>a())}getMemoryDiagnostics(){var t;const e=this.sceneCore.getRenderer().info;return{threeJs:e!=null&&e.memory?{geometries:e.memory.geometries,textures:e.memory.textures,programs:((t=e.programs)==null?void 0:t.length)??0}:null,heap:nc.getUsage(),agentMeshCount:this.agentManager.getAgentMeshes().size,bossLineCount:0}}getRenderStats(){var t,n;const e=(n=(t=this.sceneCore.getRenderer())==null?void 0:t.info)==null?void 0:n.render;return e?{calls:e.calls,triangles:e.triangles,points:e.points,lines:e.lines}:null}get renderer(){return this.sceneCore.getRenderer()}logMemoryDiagnostics(){const e=this.getMemoryDiagnostics(),t=this.characterLoader.getCacheStats();console.group("%c[SceneManager Memory]","color: #ff6600; font-weight: bold"),e.threeJs&&console.log(`Three.js: ${e.threeJs.geometries} geometries, ${e.threeJs.textures} textures, ${e.threeJs.programs} programs`),e.heap&&console.log(`Heap: ${e.heap.usedMB}MB / ${e.heap.totalMB}MB (limit: ${e.heap.limitMB}MB)`),console.log(`Agent meshes: ${e.agentMeshCount}`),console.log(`CharacterLoader cache: ${t.builtInModels} built-in, ${t.customModels} custom`),t.modelNames.length>0&&console.log(` Built-in models: ${t.modelNames.join(", ")}`),t.customModelIds.length>0&&console.log(` Custom models: ${t.customModelIds.join(", ")}`),console.groupEnd()}dispose(){var n;console.log("%c[SceneManager] dispose() called - starting cleanup","color: #ff0000; font-weight: bold");const e=this.characterLoader.getCacheStats();console.log(`[SceneManager] Pre-dispose: ${e.builtInModels} built-in models, ${e.customModels} custom models`),this.renderLoop.stop(),window.removeEventListener("resize",this.onWindowResize);const t=this.sceneCore.getCanvas();t.removeEventListener("webglcontextlost",this.onContextLost),t.removeEventListener("webglcontextrestored",this.onContextRestored),(n=this.resizeObserver)==null||n.disconnect(),this.resizeObserver=null,this.inputHandler.dispose(),this.drawingManager.dispose(),this.buildingManager.dispose(),this.effectsManager.dispose(),this.agentManager.dispose(),this.selectionManager.dispose(),this.battlefield.dispose(),this.characterLoader.dispose(),this.cameraManager.dispose(),this.sceneCore.dispose(),console.log("%c[SceneManager] dispose() complete - all resources freed","color: #00ff00; font-weight: bold")}}const Fp="tide_webgl_active";typeof window<"u"&&(window.__tidePersistedScene===void 0&&(window.__tidePersistedScene=null),window.__tidePersistedCanvas===void 0&&(window.__tidePersistedCanvas=null),window.__tideWsConnected===void 0&&(window.__tideWsConnected=!1),window.__tideIsPageUnloading===void 0&&(window.__tideIsPageUnloading=!1));function xm(){return typeof window<"u"?window.__tidePersistedScene??null:null}function LM(){return typeof window<"u"?window.__tidePersistedCanvas??null:null}function YB(){return typeof window<"u"?window.__tideWsConnected??!1:!1}function hd(s){typeof window<"u"&&(window.__tidePersistedScene=s)}function td(s){typeof window<"u"&&(window.__tidePersistedCanvas=s)}function OM(s){typeof window<"u"&&(window.__tideWsConnected=s)}function VB(s){typeof window<"u"&&(window.__tideIsPageUnloading=s)}function KB(){sessionStorage.setItem(Fp,"true")}function Xh(s){VB(!0),sessionStorage.removeItem(Fp),vM(),$L(),window.__tideScene&&(window.__tideScene=null);const e=xm();e?(console.log("[App] Calling persistedScene.dispose()"),e.dispose(),hd(null)):console.log("[App] No persistedScene to dispose"),td(null),OM(!1);const t=document.getElementById("battlefield");t&&t.remove();const n=document.getElementById("app");n&&(n.innerHTML="")}function XB(){var a,i;if(window.__tideAppInitialized)return;if(window.__tideAppInitialized=!0,sessionStorage.getItem(Fp)==="true"&&console.log("[App] Detected unclean shutdown from previous session - forcing cleanup"),window.__tideScene){console.log("[App] Cleaning up stale __tideScene reference");try{(i=(a=window.__tideScene).dispose)==null||i.call(a)}catch{}window.__tideScene=null}const e=xm();if(e){console.log("[App] Cleaning up stale persistedScene");try{e.dispose()}catch{}hd(null)}const t=document.getElementById("battlefield"),n=LM();t&&t!==n&&t.remove(),sessionStorage.removeItem(Fp)}function ZB(){typeof window>"u"||(XB(),window.addEventListener("pageshow",s=>{s.persisted&&(console.log("[App] Page restored from bfcache - cleaning up"),Xh(),window.location.reload())}),window.onunload=()=>Xh(),window.onbeforeunload=s=>{Xh()},window.addEventListener("pagehide",s=>{Xh(`pagehide (persisted=${s.persisted})`)}))}ZB();const Vj={showTrees:!0,showBushes:!0,showHouse:!0,showLamps:!0,showGrass:!0,showClouds:!0,fogDensity:1,floorStyle:"metal",brightness:1,skyColor:null,battlefieldSize:50},Kj={saturation:2,roughness:.5,metalness:-1,emissiveBoost:0,envMapIntensity:1,wireframe:!1,colorMode:"normal"},Xj={idleAnimation:"sit",workingAnimation:"sprint"},QB=0;function IM(){const s={characterScale:2,indicatorScale:.7,gridVisible:!1,timeMode:"day",terrain:Vj,modelStyle:Kj,animations:Xj,fpsLimit:QB},e=ai(vt.CONFIG,null);return e?{characterScale:e.characterScale??s.characterScale,indicatorScale:e.indicatorScale??s.indicatorScale,gridVisible:e.gridVisible??s.gridVisible,timeMode:e.timeMode??s.timeMode,terrain:{...Vj,...e.terrain},modelStyle:{...Kj,...e.modelStyle},animations:{...Xj,...e.animations},fpsLimit:e.fpsLimit??s.fpsLimit}:s}function JB(s){Ei(vt.CONFIG,s)}function ez(){return typeof window>"u"?!0:window.matchMedia("(max-width: 768px)").matches}typeof window<"u"&&!window.__tideHmrRefreshListeners&&(window.__tideHmrRefreshListeners=new Set);function BM(){console.log("[Tide HMR] Manual scene refresh triggered");const s=xm();if(s){try{s.dispose()}catch(t){console.warn("[Tide HMR] Error disposing scene:",t)}hd(null)}td(null),window.__tideScene&&(window.__tideScene=null);const e=document.getElementById("battlefield");if(e){const t=e.getContext("webgl2")||e.getContext("webgl");if(t){const n=t.getExtension("WEBGL_lose_context");n&&n.loseContext()}}window.__tideHmrPendingSceneChanges=!1,window.location.reload()}typeof window<"u"&&(window.__tideHmrSceneRefresh=BM);function tz({canvasRef:s,selectionBoxRef:e,viewMode:t,sceneMountKey:n=0,showToast:a,showAgentNotification:i,toolboxModal:o,contextMenu:l,setHoveredAgentPopup:c,setBuildingPopup:d,getBuildingPopup:m,openBuildingModal:p,openPM2LogsModal:f,openBossLogsModal:b,openDatabasePanel:x,onSceneLoadingChange:w}){const k=y.useRef(null),S=y.useRef(null),j=y.useRef(null),C=y.useRef(null),N=y.useRef(null);return y.useEffect(()=>{if(t!=="3d"){w==null||w(!1);return}if(!s.current||!e.current)return;let P=!1;w==null||w(!0);const _=xm(),M=LM()===s.current;function D(){var E,R,O,I,B,Y,$,W;(E=k.current)==null||E.setOnToast(a),(R=k.current)==null||R.setOnBuildingClick((K,X)=>{z.selectBuilding(K);const H=z.getState().buildings.get(K);(H==null?void 0:H.type)==="folder"&&H.folderPath?z.openFileExplorer(H.folderPath):(H==null?void 0:H.type)==="server"||(H==null?void 0:H.type)==="boss"||(H==null?void 0:H.type)==="database"?(S.current&&clearTimeout(S.current),S.current=setTimeout(()=>{d({buildingId:K,screenPos:X,fromClick:!0}),S.current=null},150)):p(K)}),(O=k.current)==null||O.setOnContextMenu((K,X,H)=>{l.open(K,X,H)}),(I=k.current)==null||I.setOnAgentHover(()=>{}),(B=k.current)==null||B.setOnBuildingHover((K,X)=>{const H=m();if(K&&X){const se=z.getState().buildings.get(K);((se==null?void 0:se.type)==="server"||(se==null?void 0:se.type)==="boss"||(se==null?void 0:se.type)==="database")&&!(H!=null&&H.fromClick)&&d({buildingId:K,screenPos:X,fromClick:!1})}else H!=null&&H.fromClick||d(null)}),(Y=k.current)==null||Y.setOnGroundClick(()=>{d(null)}),($=k.current)==null||$.setOnAreaDoubleClick(K=>{z.selectArea(K),o.open()}),(W=k.current)==null||W.setOnBuildingDoubleClick(K=>{var H;S.current&&(clearTimeout(S.current),S.current=null),d(null);const X=z.getState().buildings.get(K);(X==null?void 0:X.type)==="server"&&((H=X.pm2)!=null&&H.enabled)?f==null||f(K):(X==null?void 0:X.type)==="boss"?b==null||b(K):(X==null?void 0:X.type)==="database"?x==null||x(K):(X==null?void 0:X.type)==="folder"&&X.folderPath?z.openFileExplorer(X.folderPath):p(K)})}if(_)try{k.current=_,M?console.log("[Tide] Reusing existing scene (StrictMode remount)"):(console.log("[Tide] Reattaching persisted scene to new canvas"),_.reattach(s.current,e.current),td(s.current));const E=z.getState();_.syncAreas(),_.syncBuildings(),E.agents.size>0&&(console.log("[Tide] Re-syncing agents from store after remount:",E.agents.size),_.syncAgents(Array.from(E.agents.values()))),D()}catch(E){console.error("[Tide] Failed to reattach persisted 3D scene:",E),w==null||w(!1)}finally{C.current=requestAnimationFrame(()=>{N.current=requestAnimationFrame(()=>{w==null||w(!1),N.current=null}),C.current=null})}else{const E=s.current,R=e.current,O=()=>{if(P){console.log("[Tide] Effect cleaned up before scene init, skipping"),w==null||w(!1);return}if(!E.isConnected||!R.isConnected){console.warn("[Tide] Canvas disconnected before initialization"),w==null||w(!1);return}(!E.clientWidth||!E.clientHeight)&&(console.log("[Tide] Canvas has no CSS dimensions, using window fallback"),E.style.width="100%",E.style.height="100%",E.offsetHeight),(!E.clientWidth||!E.clientHeight)&&(E.width=window.innerWidth,E.height=window.innerHeight),KB();try{const I=new qB(E,R);k.current=I,hd(I),td(E);const B=IM();I.setCharacterScale(B.characterScale),I.setIndicatorScale(B.indicatorScale),I.setGridVisible(B.gridVisible),I.setTimeMode(B.timeMode),I.setTerrainConfig(B.terrain),I.setFloorStyle(B.terrain.floorStyle,!0),I.setAgentModelStyle(B.modelStyle),I.setIdleAnimation(B.animations.idleAnimation),I.setWorkingAnimation(B.animations.workingAnimation),I.setFpsLimit(B.fpsLimit),I.syncAreas(),I.syncBuildings(),I.loadCharacterModels().then(()=>{console.log("[Tide] Character models ready");const Y=z.getState();Y.customAgentClasses.size>0&&(console.log("[Tide] Applying custom classes from store:",Y.customAgentClasses.size),I.setCustomAgentClasses(Y.customAgentClasses)),Y.agents.size>0&&(console.log("[Tide] Syncing agents from store:",Y.agents.size),I.syncAgents(Array.from(Y.agents.values()))),I.upgradeAgentModels()}).catch(Y=>{console.warn("[Tide] Some models failed to load, using fallback:",Y)}).finally(()=>{w==null||w(!1)}),D()}catch(I){console.error("[Tide] Failed to initialize 3D scene:",I),w==null||w(!1)}};j.current=requestAnimationFrame(O)}return gM({onAgentCreated:E=>{var R,O,I;(R=k.current)==null||R.addAgent(E),(O=k.current)==null||O.refreshSelectionVisuals(),(I=window.__spawnModalSuccess)==null||I.call(window)},onAgentUpdated:(E,R)=>{var O;(O=k.current)==null||O.updateAgent(E,R)},onAgentDeleted:E=>{var R;(R=k.current)==null||R.removeAgent(E)},onAgentsSync:E=>{var R;(R=k.current)==null||R.syncAgents(E)},onAreasSync:()=>{var R,O;(R=k.current)==null||R.syncAreas();const E=Array.from(z.getState().agents.values());(O=k.current)==null||O.syncAgents(E)},onSpawnError:()=>{var E;(E=window.__spawnModalError)==null||E.call(window)},onSpawnSuccess:()=>{var E;(E=window.__spawnModalSuccess)==null||E.call(window)},onDirectoryNotFound:E=>{var R;(R=window.__spawnModalDirNotFound)==null||R.call(window,E)},onToolUse:(E,R,O)=>{var I;(I=k.current)==null||I.showToolBubble(E,R,O)},onDelegation:(E,R)=>{var O;(O=k.current)==null||O.showDelegationEffect(E,R)},onCustomClassesSync:E=>{var R,O;(R=k.current)==null||R.setCustomAgentClasses(E),(O=k.current)==null||O.upgradeAgentModels()},onBuildingUpdated:E=>{var R;(R=k.current)==null||R.updateBuilding(E)},onSubagentStarted:E=>{var R;(R=k.current)==null||R.addSubagentEffect(E.id,E.parentAgentId,E.name,E.subagentType)},onSubagentCompleted:E=>{var I;const R=z.getSubagent(E)||z.getSubagentByToolUseId(E),O=(R==null?void 0:R.id)||E;(I=k.current)==null||I.completeSubagentEffect(O),setTimeout(()=>{var B;(B=k.current)==null||B.removeSubagentEffect(O)},3e4)}}),()=>{P=!0,j.current!==null&&(cancelAnimationFrame(j.current),j.current=null),C.current!==null&&(cancelAnimationFrame(C.current),C.current=null),N.current!==null&&(cancelAnimationFrame(N.current),N.current=null),z.getState().viewMode!=="3d"&&ez()&&k.current&&(console.log("[Tide] 3D canvas unmounted - disposing scene to free memory"),HL(),k.current.dispose(),k.current=null,hd(null),td(null))}},[t,n]),k}function nz({showToast:s,showAgentNotification:e}){const t=y.useRef(!1);y.useEffect(()=>{if(t.current||YB())return;t.current=!0,gM({onToast:s,onReconnect:()=>{z.triggerReconnect()},onAgentNotification:i=>{e(i)}}),dd(),OM(!0),PL();let n;LL(i=>{i.type==="agent_notification"&&typeof i.agentId=="string"&&hM(i.agentId)}).then(i=>{n=i});const a=()=>{console.log("[Tide] App resumed from background, reconnecting..."),setTimeout(()=>dd(),100)};return window.addEventListener("tideAppResume",a),()=>{window.removeEventListener("tideAppResume",a),n==null||n()}},[s,e])}function sz(s){y.useEffect(()=>{let e="",t="",n=new Map;const a=i=>{var c;let o=!1;const l=new Map;for(const[d,m]of i){const f=`${m.position.x.toFixed(2)},${m.position.z.toFixed(2)},${m.status},${m.class},${m.isBoss},${((c=m.subordinateIds)==null?void 0:c.length)??0}`.split("").reduce((b,x)=>(b<<5)-b+x.charCodeAt(0),0);l.set(d,f),n.get(d)!==f&&(o=!0)}return l.size!==n.size&&(o=!0),{newVersion:l,changed:o}};return z.subscribe(()=>{var f;const i=z.getState(),o=Array.from(i.selectedAgentIds).sort().join(","),l=Array.from(i.selectedBuildingIds).sort().join(","),c=o!==e,d=l!==t,{newVersion:m,changed:p}=a(i.agents);(c||d||p)&&(e=o,t=l,n=m,(f=s.current)==null||f.refreshSelectionVisuals())})},[s])}function az(s){y.useEffect(()=>{var n;(n=s.current)==null||n.syncAreas();let e=0,t=0;return z.subscribe(()=>{var l,c;const i=z.getState().areas;if(i.size!==e){e=i.size,t=Date.now(),(l=s.current)==null||l.syncAreas();return}let o=0;for(const[d,m]of i){let p=d.charCodeAt(0);p+=(m.width??0)+(m.height??0)+(m.radius??0),p+=Math.floor(m.center.x*100)+Math.floor(m.center.z*100),p+=(m.zIndex??0)*1e3;for(let f=0;f<m.name.length;f++)p+=m.name.charCodeAt(f);for(let f=0;f<m.color.length;f++)p+=m.color.charCodeAt(f);if(m.directoryGitCounts)for(const f of m.directoryGitCounts)p+=(f+1)*7;if(m.logo){p+=Math.floor((m.logo.opacity??.8)*1e3),p+=Math.floor(m.logo.width*100)+Math.floor(m.logo.height*100);for(let f=0;f<m.logo.position.length;f++)p+=m.logo.position.charCodeAt(f);if(m.logo.filename)for(let f=0;f<m.logo.filename.length;f++)p+=m.logo.filename.charCodeAt(f)}o^=p|0}o!==t&&(t=o,(c=s.current)==null||c.syncAreas())})},[s])}function iz(s){y.useEffect(()=>{var n;(n=s.current)==null||n.syncBuildings();let e=0,t=0;return z.subscribe(()=>{var l,c;const i=z.getState().buildings;if(i.size!==e){e=i.size,t=Date.now(),(l=s.current)==null||l.syncBuildings();return}let o=0;for(const[d,m]of i){o^=m.position.x*1e3+m.position.z|0,o^=(m.scale||1)*1e4|0;const p=`${m.style||""}${m.name}${m.status}${m.gitChangesCount||0}`;for(let f=0;f<p.length;f++)o=(o<<5)-o+p.charCodeAt(f)|0}o!==t&&(t=o,(c=s.current)==null||c.syncBuildings())})},[s])}function rz(s,e){y.useEffect(()=>{var t;(t=s.current)==null||t.highlightArea(e)},[s,e])}function oz(s,e){y.useEffect(()=>{var t;(t=s.current)==null||t.setPowerSaving(e)},[s,e])}function lz({sceneRef:s,spawnModal:e,commanderModal:t,explorerModal:n,spotlightModal:a,deleteConfirmModal:i,onRequestBuildingDelete:o,onOpenDatabasePanel:l,onCloseDatabasePanel:c,databasePanelOpen:d}){y.useEffect(()=>{const m=p=>{var E,R,O,I;const f=z.getShortcuts(),b=p.target,x=b.tagName==="INPUT"||b.tagName==="TEXTAREA",w=f.find(B=>B.id==="deselect-all");if(xt(p,w)){if(xy()){p.preventDefault();return}const B=z.getState();if(B.activeTool==="rectangle"||B.activeTool==="circle"){(E=s.current)==null||E.setDrawingTool(null),typeof window<"u"&&window.__tideScene2D_setDrawingTool&&window.__tideScene2D_setDrawingTool(null);return}e.isOpen?e.close():B.terminalOpen?(z.setTerminalOpen(!1),document.activeElement instanceof HTMLElement&&document.activeElement.blur()):(z.deselectAll(),(R=s.current)==null||R.refreshSelectionVisuals())}for(let B=1;B<=9;B++){const Y=f.find($=>$.id===`select-agent-${B}`);if(xt(p,Y)){p.preventDefault();const $=z.getState(),W=B-1,K=Array.from($.agents.keys());W<K.length&&(z.selectAgent(K[W]),(O=s.current)==null||O.refreshSelectionVisuals());return}}const k=f.find(B=>B.id==="spawn-agent");if(xt(p,k)){p.preventDefault(),e.open();return}const S=f.find(B=>B.id==="toggle-commander-tab");if(xt(p,S)&&!x){p.preventDefault(),t.toggle();return}const j=f.find(B=>B.id==="toggle-commander");if(xt(p,j)){p.preventDefault(),t.toggle();return}const C=f.find(B=>B.id==="toggle-file-explorer");if(xt(p,C)){p.preventDefault();const B=z.getState();if(n.isOpen||B.explorerFolderPath!==null||B.explorerAreaId!==null)n.close(),z.closeFileExplorer();else{const $=z.getLastExplorerState();if(($==null?void 0:$.type)==="folder")z.openFileExplorer($.path);else if(($==null?void 0:$.type)==="area")if(B.areas.has($.areaId))n.open($.areaId);else{const W=Array.from(B.areas.values()).filter(K=>K.directories&&K.directories.length>0);W.length>0&&n.open(W[0].id)}else{const W=Array.from(B.areas.values()).filter(K=>K.directories&&K.directories.length>0);W.length>0&&n.open(W[0].id)}}return}if(p.altKey&&!p.ctrlKey&&!p.shiftKey&&!p.metaKey&&p.code==="KeyD"){if(p.preventDefault(),p.stopPropagation(),d){c();return}const B=localStorage.getItem("tide-commander-last-database-building"),Y=z.getState();if(B){const $=Y.buildings.get(B);if(($==null?void 0:$.type)==="database"){l(B);return}}for(const[$,W]of Y.buildings)if(W.type==="database"){l($);return}return}const N=f.find(B=>B.id==="toggle-spotlight");if(xt(p,N)||p.altKey&&!p.ctrlKey&&!p.metaKey&&p.code==="KeyP"){console.log("[useKeyboardShortcuts] Spotlight shortcut matched!",{spotlightShortcut:N,altKey:p.altKey,code:p.code}),p.preventDefault(),a.toggle();return}const P=f.find(B=>B.id==="toggle-2d-view");if(xt(p,P)){p.preventDefault();const B=z.getState().viewMode,Y=B==="3d"?"2d":B==="2d"?"dashboard":"3d";z.setViewMode(Y);return}const _=f.find(B=>B.id==="next-working-agent"),L=f.find(B=>B.id==="prev-working-agent");if((xt(p,_)||xt(p,L))&&!x){const B=z.getState();if(B.terminalOpen)return;const Y=Array.from(B.agents.values());let $=Y.filter(H=>B.agentsWithUnseenOutput.has(H.id));if($.length===0&&($=Y.filter(H=>H.status==="working")),$.length===0)return;p.preventDefault();const W=B.selectedAgentIds.size===1?Array.from(B.selectedAgentIds)[0]:null,K=W?$.findIndex(H=>H.id===W):-1;let X;xt(p,_)?X=K===-1?0:(K+1)%$.length:X=K===-1?$.length-1:(K-1+$.length)%$.length,z.selectAgent($[X].id),(I=s.current)==null||I.refreshSelectionVisuals();return}const M=f.find(B=>B.id==="delete-selected"),D=f.find(B=>B.id==="delete-selected-backspace");if((xt(p,M)||xt(p,D))&&!x){const B=z.getState();if(B.selectedAgentIds.size>0){p.preventDefault(),i.open();return}if(B.selectedBuildingIds.size>0){p.preventDefault(),o();return}return}};return document.addEventListener("keydown",m,!0),()=>document.removeEventListener("keydown",m,!0)},[s,e,t,n,a,i,o,l,c,d])}function cz(){const[s,e]=y.useState(!1);return window.__tideSetBackNavModal=e,y.useEffect(()=>{if(!(window.innerWidth<=768))return;if(window.__tideBackNavSetup){window.location.hash.includes("app")||(window.location.hash="#app");return}window.__tideBackNavSetup=!0,window.location.hash.includes("app")||(window.location.hash="#app");const a=()=>{var o;window.innerWidth>768||window.location.hash.includes("app")||(window.location.hash="#app",xy()||(o=window.__tideSetBackNavModal)==null||o.call(window,!0))},i=()=>{var o;window.innerWidth>768||(window.location.hash.includes("app")||(window.location.hash="#app"),window.location.hash==="#app"&&setTimeout(()=>{window.location.hash==="#app"&&!window.location.hash.includes("app2")&&(window.history.pushState(null,"","#app2"),window.history.pushState(null,"","#app"))},50),xy()||(o=window.__tideSetBackNavModal)==null||o.call(window,!0))};window.history.pushState(null,"","#app1"),window.history.pushState(null,"","#app2"),window.history.pushState(null,"","#app"),window.addEventListener("hashchange",a),window.addEventListener("popstate",i)},[]),{showBackNavModal:s,setShowBackNavModal:e,handleLeave:()=>{e(!1);const n=window.__tideHistoryDepth??2;window.history.go(-(n+1))}}}const pb="agent-order-change";function zM(s){const e=y.useMemo(()=>new Set(s.map(c=>c.id)),[s]),[t,n]=y.useState(()=>ai(vt.AGENT_ORDER,[]));y.useEffect(()=>{const c=d=>{n(d.detail)};return window.addEventListener(pb,c),()=>{window.removeEventListener(pb,c)}},[]);const a=y.useMemo(()=>{const c=t.filter(f=>e.has(f)),d=s.filter(f=>!c.includes(f.id)).map(f=>f.id),m=[...c,...d],p=new Map(s.map(f=>[f.id,f]));return m.map(f=>p.get(f)).filter(f=>f!==void 0)},[s,t,e]),i=y.useCallback(c=>{n(c),Ei(vt.AGENT_ORDER,c),window.dispatchEvent(new CustomEvent(pb,{detail:c}))},[]),o=y.useCallback((c,d)=>{const m=a.map(f=>f.id),[p]=m.splice(c,1);m.splice(d,0,p),i(m)},[a,i]),l=y.useCallback(()=>{n([]),Ei(vt.AGENT_ORDER,[])},[]);return y.useEffect(()=>{if(e.size===0)return;const c=t.filter(d=>e.has(d));c.length!==t.length&&i(c)},[e,t,i]),{orderedAgents:a,moveAgent:o,resetOrder:l}}const Px="deivid11/tide-commander",uz=`https://api.github.com/repos/${Px}/releases/latest`,dz=`https://api.github.com/repos/${Px}/releases?per_page=3`,hz=3600*1e3,Zj="app_update_dismissed_version",Qj="0.84.2";function pz(){var m;const[s,e]=y.useState({isChecking:!1,updateAvailable:!1,updateInfo:null,recentReleases:[],error:null,currentVersion:Qj}),t=((m=Aa==null?void 0:Aa.getPlatform)==null?void 0:m.call(Aa))==="android"||!1,n=p=>p.replace(/^v/,"").split(".").map(b=>parseInt(b,10)||0),a=(p,f)=>{const b=n(p),x=n(f),w=Math.max(b.length,x.length);for(let k=0;k<w;k++){const S=b[k]||0,j=x[k]||0;if(S>j)return 1;if(S<j)return-1}return 0},i=async p=>{var b;if(Aa&&dj&&((b=Aa.isNativePlatform)==null?void 0:b.call(Aa))===!0){const x=await dj.get({url:p,headers:{Accept:"application/vnd.github.v3+json"}});return{data:x.data,status:x.status}}else{const x=await fetch(p,{headers:{Accept:"application/vnd.github.v3+json"}});return x.ok?{data:await x.json(),status:x.status}:{data:null,status:x.status}}},o=y.useCallback(async(p=!1)=>{e(f=>({...f,isChecking:!0,error:null}));try{const[f,b]=await Promise.all([i(uz),i(dz)]);if(f.status!==200)throw new Error(`GitHub API error: ${f.status}`);const x=f.data,w=x.tag_name;let k=[];b.status===200&&b.data&&(k=b.data.map(P=>({version:P.tag_name,name:P.name,publishedAt:P.published_at,releaseUrl:P.html_url})));const S=localStorage.getItem(Zj);if(!p&&S===w)return e(P=>({...P,isChecking:!1,updateAvailable:!1,recentReleases:k})),null;if(!(a(w,Qj)>0))return e(P=>({...P,isChecking:!1,updateAvailable:!1,recentReleases:k})),null;const C=x.assets.find(P=>P.name.endsWith(".apk")&&P.content_type==="application/vnd.android.package-archive"),N={version:w,name:x.name,changelog:x.body,releaseUrl:x.html_url,apkUrl:(C==null?void 0:C.browser_download_url)||null,apkSize:(C==null?void 0:C.size)||null,publishedAt:x.published_at};return e(P=>({...P,isChecking:!1,updateAvailable:!0,updateInfo:N,recentReleases:k})),N}catch(f){const b=f instanceof Error?f.message:"Failed to check for updates";return e(x=>({...x,isChecking:!1,error:b})),null}},[]),l=y.useCallback(async()=>{var p,f,b;if(!((p=s.updateInfo)!=null&&p.apkUrl)){(f=s.updateInfo)!=null&&f.releaseUrl&&window.open(s.updateInfo.releaseUrl,"_blank");return}if(!t){(b=s.updateInfo)!=null&&b.releaseUrl&&window.open(s.updateInfo.releaseUrl,"_blank");return}try{window.open(s.updateInfo.apkUrl,"_system"),e(x=>({...x,error:null}))}catch(x){const w=x instanceof Error?x.message:"Failed to open download";e(k=>({...k,error:w}))}},[s.updateInfo,t]),c=y.useCallback(()=>{s.updateInfo&&localStorage.setItem(Zj,s.updateInfo.version),e(p=>({...p,updateAvailable:!1,updateInfo:null}))},[s.updateInfo]),d=y.useCallback(()=>{var p;(p=s.updateInfo)!=null&&p.releaseUrl?window.open(s.updateInfo.releaseUrl,"_blank"):window.open(`https://github.com/${Px}/releases`,"_blank")},[s.updateInfo]);return y.useEffect(()=>{if(!t)return;const p=setTimeout(()=>{o()},5e3),f=setInterval(()=>{o()},hz);return()=>{clearTimeout(p),clearInterval(f)}},[t,o]),{...s,isAndroid:t,checkForUpdate:o,downloadAndInstall:l,dismissUpdate:c,openReleasePage:d}}function Ls(s){const e=y.useRef(null),t=y.useCallback(a=>{e.current=a.target,a.target===a.currentTarget&&a.stopPropagation()},[]),n=y.useCallback(a=>{a.target===a.currentTarget&&e.current===a.currentTarget&&(a.stopPropagation(),s()),e.current=null},[s]);return{handleMouseDown:t,handleClick:n}}const mz=3e4;function fz(){const s=y.useRef(null);y.useEffect(()=>{const e=async()=>{var o,l;const t=z.getState(),n=new Map,a=new Map;for(const[c,d]of t.buildings){const m=d.folderPath||d.cwd;m&&(a.has(m)||a.set(m,[]),a.get(m).push(c))}for(const[c,d]of a)try{const m=await bt(rt(`/api/files/git-status?path=${encodeURIComponent(c)}`));if(!m.ok)continue;const f=((o=(await m.json()).files)==null?void 0:o.length)||0;n.set(c,f);for(const b of d){const x=z.getState().buildings.get(b);x&&x.gitChangesCount!==f&&z.updateBuildingLocal(b,{gitChangesCount:f})}}catch{}const i=new Map;for(const[c,d]of t.areas)d.archived||!d.directories||d.directories.forEach((m,p)=>{m&&(i.has(m)||i.set(m,[]),i.get(m).push({areaId:c,dirIndex:p}))});if(i.size!==0)for(const[c,d]of i)try{let m;if(n.has(c))m=n.get(c);else{const f=await bt(rt(`/api/files/git-status?path=${encodeURIComponent(c)}`));if(!f.ok)continue;m=((l=(await f.json()).files)==null?void 0:l.length)||0,n.set(c,m)}const p=new Map;for(const f of d)p.has(f.areaId)||p.set(f.areaId,[]),p.get(f.areaId).push({dirIndex:f.dirIndex,count:m});for(const[f,b]of p){const x=z.getState().areas.get(f);if(!x)continue;const w=x.directoryGitCounts?[...x.directoryGitCounts]:new Array(x.directories.length).fill(0);let k=!1;for(const{dirIndex:S,count:j}of b)w[S]!==j&&(w[S]=j,k=!0);k&&z.updateAreaLocal(f,{directoryGitCounts:w})}}catch{}};return e(),s.current=setInterval(e,mz),()=>{s.current&&(clearInterval(s.current),s.current=null)}},[])}const Jj={historyLimit:500,hideCost:!0,showFPS:!1,powerSaving:!1,customAgentNames:[],experimental2DView:!1,experimentalVoiceAssistant:!1,experimentalTTS:!1,experimentalEchoPrompt:!1,externalEditorCommand:""},$p=90,mb=["simple","chat","advanced"],eC=55,tC=20,nC=85,gz=200,bz=12e4,yz=5,Ga=new Map;function xz(s){const e=Ga.get(s);e&&(Ga.delete(s),Ga.set(s,e))}function vz(){for(;Ga.size>yz;){const s=Ga.keys().next().value;if(s!==void 0)Ga.delete(s);else break}}function FM(s){Ga.delete(s)}function wz(s){return s.trim().replace(/\r\n/g,`
149
149
  `)}function Py(s,e){return`${s}:${wz(e)}`}function sC(s,e,t,n){if(s.uuid&&e.has(s.uuid))return!1;const a=s.isUserPrompt?"user":"assistant",i=Py(a,s.text),o=s.timestamp||0,l=t.get(i);return l!==void 0&&Math.abs(o-l)<=bz?!1:o>n}function $M({selectedAgentId:s,hasSessionId:e,reconnectCount:t,historyRefreshTrigger:n,lastPrompts:a,outputScrollRef:i}){const[o,l]=y.useState([]),[c,d]=y.useState(!1),[m,p]=y.useState(!1),[f,b]=y.useState(0),[x,w]=y.useState(!1),[k,S]=y.useState(!1),[j,C]=y.useState(0),N=y.useRef(!0),P=y.useRef(0),_=y.useRef(0),L=y.useRef(!1),M=y.useRef(!1),D=y.useRef(null),E=y.useRef(!1),R=y.useRef(null),O=y.useRef(null);y.useEffect(()=>(N.current=!0,()=>{N.current=!1}),[]),y.useEffect(()=>{if(!s||!e){l([]),_.current=0,S(!1),M.current=!1,C(0),d(!1),p(!1),b(V=>V+1),E.current=!1,R.current=null;return}const $=`${s}:${t}:${n}`;if(R.current===$)return;const W=D.current!==null&&D.current!==s,K=t>0,X=W||K,H=!W&&!E.current&&e;D.current=s,E.current=e,R.current=$;let se;if(K){const V=z.getOutputs(s);V.length>0&&(se=V.map(J=>({...J})))}O.current&&(clearTimeout(O.current),O.current=null),K&&Ga.delete(s),P.current+=1;const ce=P.current;p(!0);const F=Ga.get(s);F?(xz(s),l(F.messages),_.current=F.messages.length,S(F.hasMore),M.current=F.hasMore,C(F.totalCount)):(l([]),_.current=0,S(!1),M.current=!1,C(0)),H||(O.current=setTimeout(()=>{d(!0)},150)),bt(rt(`/api/agents/${s}/history?limit=${$p}&offset=0`)).then(V=>{if(!V.ok)throw new Error(`HTTP ${V.status}: ${V.statusText}`);return V.json()}).then(V=>{if(ce!==P.current)return;const J=Array.isArray(V.messages)?V.messages:[];l(J),_.current=J.length;const ie=V.hasMore||!1;if(S(ie),M.current=ie,C(V.totalCount||0),Ga.set(s,{messages:J,hasMore:ie,totalCount:V.totalCount||0}),vz(),se&&se.length>0){const Q=J.length>0?Math.max(...J.map(ue=>ue.timestamp?new Date(ue.timestamp).getTime():0)):0,Z=new Set(J.map(ue=>ue.uuid).filter(ue=>typeof ue=="string"&&ue.length>0)),G=new Map;for(const ue of J){if(ue.type!=="user"&&ue.type!=="assistant")continue;const be=Py(ue.type,ue.content),ve=ue.timestamp?new Date(ue.timestamp).getTime():0,ge=G.get(be)??0;ve>ge&&G.set(be,ve)}const re=se.filter(ue=>sC(ue,Z,G,Q));z.clearOutputs(s);for(const ue of re)z.addOutput(s,ue)}else if(J.length>0){const Q=Math.max(...J.map(be=>be.timestamp?new Date(be.timestamp).getTime():0)),Z=new Set(J.map(be=>be.uuid).filter(be=>typeof be=="string"&&be.length>0)),G=new Map;for(const be of J){if(be.type!=="user"&&be.type!=="assistant")continue;const ve=Py(be.type,be.content),ge=be.timestamp?new Date(be.timestamp).getTime():0,_e=G.get(ve)??0;ge>_e&&G.set(ve,ge)}const re=z.getOutputs(s),ue=re.filter(be=>{const ve=sC(be,Z,G,Q);return ve||console.warn(`[HISTORY-DEDUP] Removing live output: uuid=${be.uuid||"none"} ts=${be.timestamp} lastHistTs=${Q} text="${be.text.slice(0,80)}"`),ve});if(re.length!==ue.length){console.warn(`[HISTORY-DEDUP] Cleared ${re.length-ue.length}/${re.length} overlapping outputs for agent ${s}`),z.clearOutputs(s);for(const be of ue)z.addOutput(s,be)}}if(!a.get(s)){for(let Q=J.length-1;Q>=0;Q--)if(J[Q].type==="user"){z.setLastPrompt(s,J[Q].content);break}}}).catch(V=>{if(console.error("Failed to load history:",V),l([]),_.current=0,S(!1),M.current=!1,C(0),X&&se&&se.length>0){z.clearOutputs(s);for(const J of se)z.addOutput(s,J)}}).finally(()=>{N.current&&ce===P.current&&(O.current&&(clearTimeout(O.current),O.current=null),d(!1),p(!1),b(V=>V+1))})},[s,e,t,n]);const I=y.useCallback(async()=>{if(!s||L.current||!M.current)return;const $=i.current;if(!$){console.warn("loadMoreHistory: outputScrollRef not connected");return}const W=$.scrollHeight-$.scrollTop;L.current=!0,w(!0);const K=_.current;try{const H=await(await bt(rt(`/api/agents/${s}/history?limit=${$p}&offset=${K}`))).json();if(H.messages&&H.messages.length>0){if(!N.current)return;l(ce=>{const F=[...H.messages,...ce];return _.current=F.length,F});const se=H.hasMore||!1;M.current=se,S(se),requestAnimationFrame(()=>{requestAnimationFrame(()=>{N.current&&(i.current&&(i.current.scrollTop=i.current.scrollHeight-W),L.current=!1,w(!1))})})}else{if(!N.current)return;L.current=!1,w(!1)}}catch(X){if(console.error("Failed to load more history:",X),!N.current)return;L.current=!1,w(!1)}},[s,i]),B=y.useCallback($=>{if(!i.current||$.current)return;const{scrollTop:W}=i.current;!L.current&&M.current&&W<gz&&I()},[I,i]),Y=y.useCallback(()=>{l([]),_.current=0,s&&Ga.delete(s)},[s]);return{history:o,loadingHistory:c,fetchingHistory:m,historyLoadVersion:f,loadingMore:x,hasMore:k,totalCount:j,isMountedRef:N,loadMoreHistory:I,handleScroll:B,clearHistory:Y,hasCachedHistory:y.useCallback($=>Ga.has($),[])}}function _u(...s){}function kz(s,e,t,n,a){return{setAgents(i){const o=new Map;for(const c of i)o.set(c.id,c),(c.class==="boss"||c.isBoss)&&_u("[Store.setAgents] Boss agent:",c.name,"subordinateIds:",c.subordinateIds);const l=i.find(c=>c.status==="working");e(c=>{c.agents=o,l&&c.selectedAgentIds.size===0&&(c.selectedAgentIds=new Set([l.id]),c.terminalOpen=!0)}),t()},addAgent(i){e(o=>{const l=new Map(o.agents);l.set(i.id,i),o.agents=l}),t()},updateAgent(i){var m;const l=s().agents.get(i.id),c=(l==null?void 0:l.status)!==i.status;c&&_u(`[Store] Agent ${i.name} status update: ${l==null?void 0:l.status} → ${i.status}`);let d=!1;e(p=>{const f=new Map(p.agents);f.set(i.id,i),p.agents=f,c&&(l==null?void 0:l.status)==="working"&&i.status==="idle"&&(p.terminalOpen&&p.selectedAgentIds.has(i.id)||(p.agentsWithUnseenOutput=new Set(p.agentsWithUnseenOutput),p.agentsWithUnseenOutput.add(i.id),_u(`[Store] Agent ${i.name} completed work - marked as unseen`),d=!0))}),d&&a&&a(),t(),c&&_u(`[Store] Agent ${i.name} status now in store: ${(m=s().agents.get(i.id))==null?void 0:m.status}`)},updateAgentContextStats(i,o){const c=s().agents.get(i);c&&(e(d=>{const m=new Map(d.agents);m.set(i,{...c,contextStats:o,contextUsed:o.totalTokens,contextLimit:o.contextWindow}),d.agents=m}),t())},updateAgentContext(i,o,l){const d=s().agents.get(i);if(d){const m=Math.max(1,l||2e5),p=Math.max(0,Math.min(100,Number((o/m*100).toFixed(1))));e(f=>{const b=new Map(f.agents),x=d.contextStats?{...d.contextStats,totalTokens:o,contextWindow:m,usedPercent:p,lastUpdated:Date.now()}:void 0;b.set(i,{...d,contextUsed:o,contextLimit:m,contextStats:x}),f.agents=b}),t()}},removeAgent(i){const o=s().agentsWithUnseenOutput.has(i);e(l=>{const c=new Map(l.agents);c.delete(i),l.agents=c;const d=new Set(l.selectedAgentIds);d.delete(i),l.selectedAgentIds=d,l.agentOutputs.delete(i),l.lastPrompts.delete(i),l.agentsWithUnseenOutput.has(i)&&(l.agentsWithUnseenOutput=new Set(l.agentsWithUnseenOutput),l.agentsWithUnseenOutput.delete(i)),l.delegationHistories.delete(i),l.lastDelegationReceived.delete(i),l.agentTaskProgress.delete(i),l.supervisor.narratives.delete(i),l.supervisor.agentHistories.delete(i),l.supervisor.historyFetchedForAgents.delete(i),l.subagents.delete(i)}),FM(i),o&&a&&a(),t()},selectAgent(i){let o=!1;e(l=>{l.selectedAgentIds=new Set(i?[i]:[]),i&&(l.lastSelectedAgentId=i,l.agentsWithUnseenOutput.has(i)&&(l.agentsWithUnseenOutput=new Set(l.agentsWithUnseenOutput),l.agentsWithUnseenOutput.delete(i),o=!0)),l.currentSnapshot=null}),o&&a&&a(),t()},addToSelection(i){let o=!1;e(l=>{const c=new Set(l.selectedAgentIds);c.has(i)?c.delete(i):(c.add(i),l.agentsWithUnseenOutput.has(i)&&(l.agentsWithUnseenOutput=new Set(l.agentsWithUnseenOutput),l.agentsWithUnseenOutput.delete(i),o=!0)),l.selectedAgentIds=c}),o&&a&&a(),t()},selectMultiple(i){e(o=>{o.selectedAgentIds=new Set(i)}),t()},deselectAll(){e(i=>{i.selectedAgentIds=new Set}),t()},spawnAgent(i,o,l,c,d,m,p,f,b,x,w,k,S){_u("[Store] spawnAgent called with:",{name:i,agentClass:o,cwd:l,position:c,sessionId:d,useChrome:m,permissionMode:p,initialSkillIds:f,provider:b,codexConfig:x,codexModel:w,model:k,customInstructions:S?`${S.length} chars`:void 0});const j=c?{x:c.x,y:0,z:c.z}:void 0,C={type:"spawn_agent",payload:{name:i,class:o,cwd:l,position:j,sessionId:d,useChrome:m,permissionMode:p,initialSkillIds:f,provider:b,codexConfig:x,codexModel:w,model:k,customInstructions:S}},N=n();if(!N){console.error("[Store] sendMessage is not defined! WebSocket may not be connected");return}N(C)},createDirectoryAndSpawn(i,o,l){var c;(c=n())==null||c({type:"create_directory",payload:{path:i,name:o,class:l}})},sendCommand(i,o){var l;e(c=>{c.lastPrompts.set(i,{text:o,timestamp:Date.now()})}),t(),(l=n())==null||l({type:"send_command",payload:{agentId:i,command:o}})},refreshAgentContext(i){var o;(o=n())==null||o({type:"request_context_stats",payload:{agentId:i}})},moveAgentLocal(i,o){const c=s().agents.get(i);c&&(e(d=>{const m={...c,position:o},p=new Map(d.agents);p.set(i,m),d.agents=p}),t())},moveAgent(i,o){var d;const c=s().agents.get(i);c&&(e(m=>{const p={...c,position:o},f=new Map(m.agents);f.set(i,p),m.agents=f}),t()),(d=n())==null||d({type:"move_agent",payload:{agentId:i,position:o}})},killAgent(i){var o;(o=n())==null||o({type:"kill_agent",payload:{agentId:i}})},stopAgent(i){var o;(o=n())==null||o({type:"stop_agent",payload:{agentId:i}})},clearContext(i){var o;(o=n())==null||o({type:"clear_context",payload:{agentId:i}}),e(l=>{const c=l.agents.get(i);if(c){const p={...c,status:"idle",currentTask:void 0,taskLabel:void 0,currentTool:void 0,lastAssignedTask:void 0,lastAssignedTaskTime:void 0,sessionId:void 0,tokensUsed:0,contextUsed:0,contextStats:void 0},f=new Map(l.agents);f.set(i,p),l.agents=f}const d=new Map(l.agentOutputs);d.delete(i),l.agentOutputs=d;const m=new Map(l.lastPrompts);m.delete(i),l.lastPrompts=m}),t()},collapseContext(i){var o;(o=n())==null||o({type:"collapse_context",payload:{agentId:i}})},removeAgentFromServer(i){var o;(o=n())==null||o({type:"remove_agent",payload:{agentId:i}})},renameAgent(i,o){var d;const c=s().agents.get(i);c&&(e(m=>{const p={...c,name:o},f=new Map(m.agents);f.set(i,p),m.agents=f}),t()),(d=n())==null||d({type:"rename_agent",payload:{agentId:i,name:o}})},updateAgentProperties(i,o){var d;const c=s().agents.get(i);c&&(e(m=>{const p={...c};o.class!==void 0&&(p.class=o.class),o.permissionMode!==void 0&&(p.permissionMode=o.permissionMode),o.model!==void 0&&(p.model=o.model),o.provider!==void 0&&(p.provider=o.provider),o.codexConfig!==void 0&&(p.codexConfig=o.codexConfig),o.codexModel!==void 0&&(p.codexModel=o.codexModel),o.useChrome!==void 0&&(p.useChrome=o.useChrome),o.cwd!==void 0&&(p.cwd=o.cwd);const f=new Map(m.agents);f.set(i,p),m.agents=f}),t()),(d=n())==null||d({type:"update_agent_properties",payload:{agentId:i,updates:o}})},getTotalTokens(){let i=0;for(const o of s().agents.values())i+=o.tokensUsed;return i},getSelectedAgents(){const i=s(),o=[];for(const l of i.selectedAgentIds){const c=i.agents.get(l);c&&o.push(c)}return o},addActivity(i){e(o=>{o.activities.unshift(i),o.activities.length>100&&o.activities.pop()}),t()},addToolExecution(i,o,l){const d=s().agents.get(i);e(m=>{m.toolExecutions.unshift({agentId:i,agentName:(d==null?void 0:d.name)||"Unknown",toolName:o,toolInput:l,timestamp:Date.now()}),m.toolExecutions.length>200&&m.toolExecutions.pop()}),t()},addFileChange(i,o,l){const d=s().agents.get(i);e(m=>{m.fileChanges.unshift({agentId:i,agentName:(d==null?void 0:d.name)||"Unknown",action:o,filePath:l,timestamp:Date.now()}),m.fileChanges.length>200&&m.fileChanges.pop()}),t()},async loadToolHistory(){try{const o=await(await bt(rt("/api/agents/tool-history?limit=100"))).json();e(l=>{o.toolExecutions&&(l.toolExecutions=o.toolExecutions),o.fileChanges&&(l.fileChanges=o.fileChanges)}),t()}catch(i){console.error("[Store] Failed to load tool history:",i)}}}}const aC=200,Sz=1024*1024,iC=64*1024,rC=`
150
150
 
151
151
  [output truncated]`;function pd(s){return s.length*2}function jz(s,e){if(pd(s)<=e)return s;const t=pd(rC),n=Math.max(0,e-t),a=Math.floor(n/2);return`${s.slice(0,a)}${rC}`}function oC(s){return pd(s.text)<=iC?s:{...s,text:jz(s.text,iC)}}function lC(s){let e=s;e.length>aC&&(e=e.slice(-aC));let t=e.reduce((n,a)=>n+pd(a.text),0);for(;e.length>1&&t>Sz;)t-=pd(e[0].text),e=e.slice(1);return e}function Cz(s,e,t,n){return{addOutput(a,i){const o=n();e(l=>{const c=l.agentOutputs.get(a)||[],d=oC(i);if(d.uuid&&c.some(b=>b.uuid===d.uuid))return;const m=lC([...c,d]);ud.info(`Store: ${c.length} -> ${m.length}`,{agentId:a,text:d.text.slice(0,60),isStreaming:d.isStreaming,listeners:o},"store:addOutput");const p=new Map(l.agentOutputs);p.set(a,m),l.agentOutputs=p}),t()},clearOutputs(a){e(i=>{const o=new Map(i.agentOutputs);o.delete(a),i.agentOutputs=o}),t()},getOutputs(a){return s().agentOutputs.get(a)||[]},addUserPromptToOutput(a,i){this.addOutput(a,{text:i,isStreaming:!1,timestamp:Date.now(),isUserPrompt:!0})},getLastPrompt(a){return s().lastPrompts.get(a)},setLastPrompt(a,i){e(o=>{o.lastPrompts.set(a,{text:i,timestamp:Date.now()})}),t()},preserveOutputs(){const a=s(),i=new Map;for(const[o,l]of a.agentOutputs)i.set(o,l.map(c=>({...c})));return i},mergeOutputsWithHistory(a,i,o){let l=[...i,...o].map(oC);return l.sort((c,d)=>c.timestamp-d.timestamp),l=lC(l),e(c=>{const d=new Map(c.agentOutputs);d.set(a,l),c.agentOutputs=d}),t(),l}}}function Nz(s,e,t,n){return{setSupervisorReport(a){e(i=>{i.supervisor.lastReport=a,i.supervisor.lastReportTime=a.timestamp;const o=new Map(i.supervisor.agentHistories);for(const l of a.agentSummaries){const c=o.get(l.agentId)||[],d={id:`${a.id}-${l.agentId}`,timestamp:a.timestamp,reportId:a.id,analysis:l};if(!c.some(m=>m.reportId===a.id)){const m=[d,...c];m.length>50&&m.pop(),o.set(l.agentId,m)}}i.supervisor.agentHistories=o,i.supervisor.generatingReport=!1}),t()},addNarrative(a,i){e(o=>{const l=o.supervisor.narratives.get(a)||[];l.unshift(i),l.length>50&&l.pop();const c=new Map(o.supervisor.narratives);c.set(a,l),o.supervisor.narratives=c}),t()},getNarratives(a){return s().supervisor.narratives.get(a)||[]},setSupervisorStatus(a){e(i=>{i.supervisor.enabled=a.enabled,a.autoReportOnComplete!==void 0&&(i.supervisor.autoReportOnComplete=a.autoReportOnComplete),i.supervisor.lastReportTime=a.lastReportTime,i.supervisor.nextReportTime=a.nextReportTime}),t()},setSupervisorConfig(a){var i;(i=n())==null||i({type:"set_supervisor_config",payload:a})},requestSupervisorReport(){var a;e(i=>{i.supervisor.generatingReport=!0}),t(),(a=n())==null||a({type:"request_supervisor_report",payload:{}})},requestAgentSupervisorHistory(a){var i;e(o=>{o.supervisor.loadingHistoryForAgent=a}),t(),(i=n())==null||i({type:"request_agent_supervisor_history",payload:{agentId:a}})},setAgentSupervisorHistory(a){e(i=>{const o=new Map(i.supervisor.agentHistories);o.set(a.agentId,a.entries),i.supervisor.agentHistories=o,i.supervisor.historyFetchedForAgents.add(a.agentId),i.supervisor.loadingHistoryForAgent===a.agentId&&(i.supervisor.loadingHistoryForAgent=null)}),t()},getAgentSupervisorHistory(a){return s().supervisor.agentHistories.get(a)||[]},addAgentAnalysis(a,i){e(o=>{const l=new Map(o.supervisor.agentHistories),c=l.get(a)||[],d={id:`single-${Date.now()}-${a}`,timestamp:Date.now(),reportId:`single-${Date.now()}`,analysis:i};if(!c.some(p=>Math.abs(p.timestamp-d.timestamp)<5e3&&p.analysis.statusDescription===i.statusDescription)){const p=[d,...c];p.length>50&&p.pop(),l.set(a,p),o.supervisor.agentHistories=l}}),t()},isLoadingHistoryForAgent(a){return s().supervisor.loadingHistoryForAgent===a},hasHistoryBeenFetched(a){return s().supervisor.historyFetchedForAgents.has(a)},setGlobalUsage(a){console.log("[Supervisor] setGlobalUsage called with:",a),e(i=>{i.supervisor.globalUsage=a,i.supervisor.refreshingUsage=!1}),t()},requestGlobalUsage(){console.log("[Supervisor] requestGlobalUsage called"),e(i=>{i.supervisor.refreshingUsage=!0}),t();const a=n();console.log("[Supervisor] sendMessage function:",a?"available":"null"),a?(console.log("[Supervisor] Sending request_global_usage message"),a({type:"request_global_usage",payload:{}})):console.warn("[Supervisor] Cannot send request_global_usage - no sendMessage function")},getGlobalUsage(){return s().supervisor.globalUsage}}}function Az(s,e,t,n){const a=()=>{var l;const o=Array.from(s().areas.values());(l=n())==null||l({type:"sync_areas",payload:o})},i=()=>{e(o=>{o.areas=new Map(o.areas)})};return{setActiveTool(o){e(l=>{l.activeTool=o,o!=="select"&&(l.selectedAreaId=null)}),t()},selectArea(o){e(l=>{l.selectedAreaId=o}),t()},addArea(o){if(o.zIndex===void 0||o.zIndex===null){const l=Array.from(s().areas.values()),c=l.length===0?-1:Math.max(...l.map(d=>d.zIndex??0));o.zIndex=c+1}e(l=>{l.areas.set(o.id,o)}),i(),a(),t()},updateArea(o,l){s().areas.get(o)&&(e(m=>{Object.assign(m.areas.get(o),l)}),i(),a(),t())},updateAreaLocal(o,l){s().areas.get(o)&&(e(m=>{Object.assign(m.areas.get(o),l)}),i(),t())},deleteArea(o){e(l=>{l.areas.delete(o),l.selectedAreaId===o&&(l.selectedAreaId=null)}),i(),a(),t()},assignAgentToArea(o,l){const d=s().areas.get(l);d&&!d.assignedAgentIds.includes(o)&&(e(m=>{for(const p of m.areas.values()){const f=p.assignedAgentIds.indexOf(o);f!==-1&&p.assignedAgentIds.splice(f,1)}m.areas.get(l).assignedAgentIds.push(o)}),i(),a(),t())},unassignAgentFromArea(o,l){const d=s().areas.get(l);if(d){const m=d.assignedAgentIds.indexOf(o);m!==-1&&(e(p=>{p.areas.get(l).assignedAgentIds.splice(m,1)}),i(),a(),t())}},addDirectoryToArea(o,l){const d=s().areas.get(o);d&&!d.directories.includes(l)&&(e(m=>{m.areas.get(o).directories.push(l)}),i(),a(),t())},removeDirectoryFromArea(o,l){const d=s().areas.get(o);if(d){const m=d.directories.indexOf(l);m!==-1&&(e(p=>{p.areas.get(o).directories.splice(m,1)}),i(),a(),t())}},getAreaDirectories(o){const l=s().areas.get(o);return(l==null?void 0:l.directories)||[]},isPositionInArea(o,l){if(l.type==="rectangle"&&l.width&&l.height){const c=l.width/2,d=l.height/2;return o.x>=l.center.x-c&&o.x<=l.center.x+c&&o.z>=l.center.z-d&&o.z<=l.center.z+d}else if(l.type==="circle"&&l.radius){const c=o.x-l.center.x,d=o.z-l.center.z;return c*c+d*d<=l.radius*l.radius}return!1},getAreaForAgent(o){const l=s(),c=l.agents.get(o);if(!c)return null;for(const d of l.areas.values())if(this.isPositionInArea({x:c.position.x,z:c.position.z},d))return d;return null},setAreasFromServer(o){e(l=>{const c=new Map;for(let d=0;d<o.length;d++){const m=o[d];m.directories||(m.directories=[]),(m.zIndex===void 0||m.zIndex===null)&&(m.zIndex=d),m.archived===void 0&&(m.archived=!1),c.set(m.id,m)}l.areas=c}),t()},getAreasInZOrder(){return Array.from(s().areas.values()).sort((l,c)=>(l.zIndex??0)-(c.zIndex??0))},getNextZIndex(){const o=Array.from(s().areas.values());return o.length===0?0:Math.max(...o.map(c=>c.zIndex??0))+1},bringAreaToFront(o){const l=s(),c=l.areas.get(o);if(!c)return;const d=Array.from(l.areas.values()),m=d.length===0?-1:Math.max(...d.map(x=>x.zIndex??0)),p=m+1,f=c.zIndex??0,b=d.filter(x=>(x.zIndex??0)===m);f===m&&b.length===1||(e(x=>{x.areas.get(o).zIndex=p}),i(),a(),t())},sendAreaToBack(o){const l=s(),c=l.areas.get(o);if(!c)return;const d=Array.from(l.areas.values()),m=Math.min(...d.map(b=>b.zIndex??0)),p=c.zIndex??0,f=d.filter(b=>(b.zIndex??0)===m);p===m&&f.length===1||(e(b=>{for(const x of b.areas.values())x.id!==o&&(x.zIndex=(x.zIndex??0)+1);b.areas.get(o).zIndex=0}),i(),a(),t())},setAreaZIndex(o,l){s().areas.get(o)&&(e(m=>{m.areas.get(o).zIndex=l}),i(),a(),t())},archiveArea(o,l){const d=s().areas.get(o);if(!(!d||d.archived)){if(l)for(const m of d.assignedAgentIds)l(m);e(m=>{const p=m.areas.get(o);p.archived=!0,p.archivedAt=Date.now(),p.originalCenter={...p.center},m.selectedAreaId===o&&(m.selectedAreaId=null)}),i(),a(),t()}},restoreArchivedArea(o,l){const c=s(),d=c.areas.get(o);if(!d||!d.archived)return;const m=d.center,p=l||d.originalCenter||d.center,f=p.x-m.x,b=p.z-m.z,x=Array.from(c.areas.values()),k=(x.length===0?-1:Math.max(...x.map(S=>S.zIndex??0)))+1;e(S=>{const j=S.areas.get(o);if(j.archived=!1,j.archivedAt=void 0,j.center=p,j.zIndex=k,f!==0||b!==0)for(const C of j.assignedAgentIds){const N=S.agents.get(C);N&&(N.position={x:N.position.x+f,y:N.position.y,z:N.position.z+b})}}),i(),a(),t()},getArchivedAreas(){return Array.from(s().areas.values()).filter(o=>o.archived===!0)},getVisibleAreas(){return Array.from(s().areas.values()).filter(o=>!o.archived)},isAgentInArchivedArea(o){const l=s();for(const c of l.areas.values())if(c.archived&&c.assignedAgentIds.includes(o))return!0;return!1}}}function Mz(s,e,t,n){const a=()=>{var l;const o=Array.from(s().buildings.values());(l=n())==null||l({type:"sync_buildings",payload:o})},i={selectBuilding(o){e(l=>{l.selectedBuildingIds.clear(),o&&l.selectedBuildingIds.add(o)}),t()},selectMultipleBuildings(o){e(l=>{l.selectedBuildingIds.clear();for(const c of o)l.selectedBuildingIds.add(c)}),t()},toggleBuildingSelection(o){e(l=>{l.selectedBuildingIds.has(o)?l.selectedBuildingIds.delete(o):l.selectedBuildingIds.add(o)}),t()},isBuildingSelected(o){return s().selectedBuildingIds.has(o)},getSelectedBuildingIds(){return Array.from(s().selectedBuildingIds)},deleteSelectedBuildings(){var l,c,d;const o=s();for(const m of o.selectedBuildingIds){const p=o.buildings.get(m);((l=p==null?void 0:p.pm2)!=null&&l.enabled||(c=p==null?void 0:p.docker)!=null&&c.enabled)&&((d=n())==null||d({type:"building_command",payload:{buildingId:m,command:"delete"}}))}e(m=>{const p=new Map(m.buildings);for(const f of m.selectedBuildingIds)p.delete(f);m.buildings=p,m.selectedBuildingIds.clear()}),a(),t()},addBuilding(o){e(l=>{const c=new Map(l.buildings);c.set(o.id,o),l.buildings=c}),a(),t()},updateBuilding(o,l){const d=s().buildings.get(o);d&&(e(m=>{const p=new Map(m.buildings);p.set(o,{...d,...l}),m.buildings=p}),a(),t())},updateBuildingLocal(o,l){const d=s().buildings.get(o);d&&(e(m=>{const p=new Map(m.buildings);p.set(o,{...d,...l}),m.buildings=p}),t())},deleteBuilding(o){var d,m,p;const c=s().buildings.get(o);((d=c==null?void 0:c.pm2)!=null&&d.enabled||(m=c==null?void 0:c.docker)!=null&&m.enabled)&&((p=n())==null||p({type:"building_command",payload:{buildingId:o,command:"delete"}})),e(f=>{const b=new Map(f.buildings);b.delete(o),f.buildings=b,f.selectedBuildingIds.delete(o)}),a(),t()},moveBuilding(o,l){const d=s().buildings.get(o);d&&(e(m=>{const p=new Map(m.buildings);p.set(o,{...d,position:l}),m.buildings=p}),a(),t())},updateBuildingPosition(o,l){i.moveBuilding(o,l)},createBuilding(o){const l={...o,id:`building_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,status:"stopped",createdAt:Date.now()};i.addBuilding(l)},sendBuildingCommand(o,l){var c;(c=n())==null||c({type:"building_command",payload:{buildingId:o,command:l}})},addBuildingLogs(o,l){e(c=>{const m=[...c.buildingLogs.get(o)||[],l];m.length>500&&m.splice(0,m.length-500);const p=new Map(c.buildingLogs);p.set(o,m),c.buildingLogs=p}),t()},getBuildingLogs(o){return s().buildingLogs.get(o)||[]},clearBuildingLogs(o){e(l=>{const c=new Map(l.buildingLogs);c.delete(o),l.buildingLogs=c}),t()},setBuildingsFromServer(o){e(l=>{const c=new Map;for(const d of o)c.set(d.id,d);l.buildings=c}),t()},updateBuildingFromServer(o){e(l=>{const c=new Map(l.buildings);c.set(o.id,o),l.buildings=c}),t()},removeBuildingFromServer(o){e(l=>{const c=new Map(l.buildings);c.delete(o),l.buildings=c,l.selectedBuildingIds.delete(o)}),t()},startLogStreaming(o,l=100){var d,m,p;const c=s().buildings.get(o);e(f=>{const b=new Map(f.streamingBuildingLogs);b.set(o,""),f.streamingBuildingLogs=b}),(d=c==null?void 0:c.docker)!=null&&d.enabled?(m=n())==null||m({type:"docker_logs_start",payload:{buildingId:o,lines:l}}):(p=n())==null||p({type:"pm2_logs_start",payload:{buildingId:o,lines:l}})},stopLogStreaming(o){var c,d,m;const l=s().buildings.get(o);(c=l==null?void 0:l.docker)!=null&&c.enabled?(d=n())==null||d({type:"docker_logs_stop",payload:{buildingId:o}}):(m=n())==null||m({type:"pm2_logs_stop",payload:{buildingId:o}})},appendStreamingLogChunk(o,l){e(c=>{const d=c.streamingBuildingLogs.get(o)||"",m=500*1024;let p=d+l;if(p.length>m){const b=p.indexOf(`
@@ -232,7 +232,7 @@ ${oe}`:ke=oe}z.sendCommand(t,ke),i(""),l(!1),k(new Map),m([]),S(),window.innerWi
232
232
  `),children:["⑂",w.length]}),x.length>0&&w.length===0&&r.jsxs("span",{className:"aop-subagent-count",title:c("terminal:overview.subagentsCompleted",{count:x.length}),style:{opacity:.5},children:["⑂",x.length]})]}),f&&r.jsxs("div",{className:`aop-last-message ${f.isUserPrompt?"user":"assistant"}`,title:f.text.split(`
233
233
  `)[0],children:[r.jsx("span",{className:"lm-prefix",children:f.isUserPrompt?"▶":"◀"}),r.jsx("span",{className:"lm-text",children:$1(f.text,80)}),r.jsx("span",{className:"lm-time",children:Bp(f.timestamp)})]}),t&&r.jsxs("div",{className:"aop-agent-body",children:[x.length>0&&r.jsxs("div",{className:"aop-subagents",children:[r.jsx("div",{className:"aop-section-label",children:c("terminal:overview.subagents",{count:x.length})}),x.map(k=>r.jsxs("div",{className:`aop-subagent-item ${k.status}`,children:[r.jsx("span",{className:"sub-icon",children:k.status==="completed"?"✅":k.status==="failed"?"❌":k.status==="unknown"?"⬜":"⑂"}),r.jsx("span",{className:"sub-name",children:k.name}),r.jsx("span",{className:"sub-type",children:k.type}),k.description&&r.jsx("span",{className:"sub-desc",title:k.description,children:$1(k.description,50)})]},k.id))]}),p.length>0&&r.jsxs("div",{className:"aop-tool-timeline",children:[r.jsx("div",{className:"aop-section-label",children:c("terminal:overview.recentActivity")}),p.map((k,S)=>{var C,N;const j=k.toolInput&&(k.toolInput.file_path||((C=k.toolInput.command)==null?void 0:C.slice(0,40))||k.toolInput.pattern||k.toolInput.description||((N=k.toolInput.prompt)==null?void 0:N.slice(0,50)))||"";return r.jsxs("div",{className:"aop-timeline-entry",children:[r.jsx("span",{className:"tl-time",children:Bp(k.timestamp)}),r.jsx("span",{className:"tl-icon",children:ls[k.toolName]||ls.default}),r.jsx("span",{className:"tl-tool",children:k.toolName}),j&&r.jsx("span",{className:"tl-param",children:j})]},`${k.timestamp}-${S}`)})]}),n.length===0&&a.length===0&&r.jsx("div",{className:"aop-no-activity",children:c("terminal:overview.noToolActivity")})]})]})}function XH({progress:s,defaultExpanded:e=!1,onAgentClick:t}){const[n,a]=y.useState(null),i=y.useRef(s.status),o=n!==null?!n:s.status==="working"||s.status==="completed"||s.status==="failed";y.useEffect(()=>{i.current!==s.status&&(i.current==="working"&&(s.status==="completed"||s.status==="failed")&&a(!1),i.current=s.status)},[s.status]);const l={working:"#4a9eff",completed:"#22c55e",failed:"#ef4444"},c={working:"⚙️",completed:"✅",failed:"❌"},{t:d}=$e(["tools"]),m={working:d("tools:progress.workingOn"),completed:d("tools:progress.taskFinished"),failed:d("tools:progress.taskFailed")},p=s.taskDescription.length>80?s.taskDescription.slice(0,80)+"...":s.taskDescription,f=()=>{const x=s.completedAt||Date.now(),w=Math.floor((x-s.startedAt)/1e3);if(w<60)return`${w}s`;const k=Math.floor(w/60),S=w%60;return`${k}m ${S}s`},b=()=>{a(o)};return r.jsxs("div",{className:`agent-progress-indicator status-${s.status} ${o?"expanded":"collapsed"}`,children:[r.jsxs("div",{className:"agent-progress-header",onClick:b,children:[r.jsx("span",{className:"agent-progress-status-icon",style:{color:l[s.status]},children:c[s.status]}),r.jsx("span",{className:"agent-progress-agent-name",onClick:x=>{t&&(x.stopPropagation(),t(s.agentId))},children:s.agentName}),r.jsx("span",{className:"agent-progress-status-text",style:{color:l[s.status]},children:m[s.status]}),r.jsx("span",{className:"agent-progress-elapsed",children:f()}),r.jsx("span",{className:"agent-progress-toggle",children:o?"▼":"▶"})]}),!o&&r.jsx("div",{className:"agent-progress-task-preview",children:p}),o&&r.jsxs("div",{className:"agent-progress-expanded",children:[r.jsx("div",{className:"agent-progress-task-full",children:s.taskDescription}),s.output.length>0&&r.jsx("div",{className:"agent-progress-output-section",children:r.jsx(ZH,{output:s.output,agentId:s.agentId,maxHeight:200})})]})]})}function ZH({output:s,agentId:e,maxHeight:t=200}){const n=y.useRef(null),a=y.useMemo(()=>s.map((o,l)=>({text:o,isStreaming:!1,timestamp:Date.now()-(s.length-l)*100})),[s]),i=cv({outputs:a,viewMode:"simple"});return y.useEffect(()=>{n.current&&(n.current.scrollTop=n.current.scrollHeight)},[i]),i.length===0?null:r.jsx("div",{ref:n,className:"agent-progress-output",style:{maxHeight:`${t}px`},children:i.map((o,l)=>r.jsx(bv,{output:o,agentId:e},`progress-${l}`))})}const QH={id:"dracula",name:"Dracula",description:"Vampire purple with fangs pink",colors:{bgPrimary:"#282a36",bgSecondary:"#21222c",bgTertiary:"#343746",borderColor:"#44475a",textPrimary:"#f8f8f2",textSecondary:"#bfbfbf",textMuted:"#6272a4",accentBlue:"#8be9fd",accentGreen:"#50fa7b",accentOrange:"#ffb86c",accentRed:"#ff5555",accentPurple:"#bd93f9",accentCyan:"#8be9fd",accentClaude:"#50fa7b",accentClaudeLight:"#69ff94",accentPink:"#ff79c6",accentYellow:"#f1fa8c",msgUserBg:"rgba(189, 147, 249, 0.12)",msgUserBorder:"#bd93f9",msgUserText:"#bd93f9",msgAssistantBg:"rgba(255, 121, 198, 0.12)",msgAssistantBorder:"#ff79c6",msgAssistantText:"#ff79c6",toolUseBg:"rgba(255, 184, 108, 0.08)",toolUseBorder:"#ffb86c",toolUseText:"#ffb86c",toolUseName:"#8be9fd",toolResultBg:"rgba(80, 250, 123, 0.08)",toolResultBorder:"#50fa7b",toolResultText:"#50fa7b",outputLineBg:"rgba(189, 147, 249, 0.04)",contextBarBg:"rgba(189, 147, 249, 0.25)",contextBarFill:"#bd93f9"}},RE={id:"muted",name:"Muted",description:"Foggy dawn through frosted glass",colors:{bgPrimary:"#16181c",bgSecondary:"#1c1f24",bgTertiary:"#24282e",borderColor:"#33393f",textPrimary:"#c8ccd4",textSecondary:"#9099a4",textMuted:"#5c6670",accentBlue:"#7aa8c8",accentGreen:"#8ab898",accentOrange:"#c8a878",accentRed:"#c88888",accentPurple:"#a898b8",accentCyan:"#88b8c0",accentClaude:"#8ab898",accentClaudeLight:"#9ac8a8",accentPink:"#b898a8",accentYellow:"#c8c098",msgUserBg:"rgba(138, 184, 152, 0.06)",msgUserBorder:"rgba(138, 184, 152, 0.3)",msgUserText:"#8ab898",msgAssistantBg:"rgba(168, 152, 184, 0.06)",msgAssistantBorder:"rgba(168, 152, 184, 0.3)",msgAssistantText:"#a898b8",toolUseBg:"rgba(200, 168, 120, 0.05)",toolUseBorder:"rgba(200, 168, 120, 0.3)",toolUseText:"#c8a878",toolUseName:"#88b8c0",toolResultBg:"rgba(136, 184, 192, 0.05)",toolResultBorder:"rgba(136, 184, 192, 0.3)",toolResultText:"#88b8c0",outputLineBg:"rgba(144, 153, 164, 0.03)",contextBarBg:"rgba(168, 152, 184, 0.2)",contextBarFill:"#a898b8"}},JH={id:"muted-red",name:"Rosewood",description:"Aged wine by candlelight",colors:{bgPrimary:"#1a1014",bgSecondary:"#221418",bgTertiary:"#2c1c20",borderColor:"#482830",textPrimary:"#f0e4e8",textSecondary:"#c8b0b8",textMuted:"#8c6878",accentBlue:"#8898c8",accentGreen:"#78a890",accentOrange:"#d8a068",accentRed:"#c85868",accentPurple:"#a878a0",accentCyan:"#88a8b0",accentClaude:"#78a890",accentClaudeLight:"#88b8a0",accentPink:"#d88898",accentYellow:"#d8c088",msgUserBg:"rgba(216, 136, 152, 0.10)",msgUserBorder:"#d88898",msgUserText:"#d88898",msgAssistantBg:"rgba(200, 88, 104, 0.10)",msgAssistantBorder:"#c85868",msgAssistantText:"#c85868",toolUseBg:"rgba(216, 160, 104, 0.08)",toolUseBorder:"#d8a068",toolUseText:"#d8a068",toolUseName:"#d8c088",toolResultBg:"rgba(168, 120, 160, 0.08)",toolResultBorder:"#a878a0",toolResultText:"#a878a0",outputLineBg:"rgba(200, 88, 104, 0.03)",contextBarBg:"rgba(216, 136, 152, 0.25)",contextBarFill:"#d88898"}},eU={id:"nord",name:"Nord",description:"Polar night with aurora",colors:{bgPrimary:"#2e3440",bgSecondary:"#3b4252",bgTertiary:"#434c5e",borderColor:"#4c566a",textPrimary:"#eceff4",textSecondary:"#d8dee9",textMuted:"#7b88a1",accentBlue:"#81a1c1",accentGreen:"#a3be8c",accentOrange:"#d08770",accentRed:"#bf616a",accentPurple:"#b48ead",accentCyan:"#88c0d0",accentClaude:"#a3be8c",accentClaudeLight:"#b3ce9c",accentPink:"#b48ead",accentYellow:"#ebcb8b",msgUserBg:"rgba(136, 192, 208, 0.10)",msgUserBorder:"#88c0d0",msgUserText:"#88c0d0",msgAssistantBg:"rgba(163, 190, 140, 0.10)",msgAssistantBorder:"#a3be8c",msgAssistantText:"#a3be8c",toolUseBg:"rgba(208, 135, 112, 0.08)",toolUseBorder:"#d08770",toolUseText:"#d08770",toolUseName:"#ebcb8b",toolResultBg:"rgba(180, 142, 173, 0.08)",toolResultBorder:"#b48ead",toolResultText:"#b48ead",outputLineBg:"rgba(67, 76, 94, 0.3)",contextBarBg:"rgba(129, 161, 193, 0.25)",contextBarFill:"#81a1c1"}},tU={id:"solarized-dark",name:"Solarized",description:"Precision-engineered contrast",colors:{bgPrimary:"#002b36",bgSecondary:"#073642",bgTertiary:"#094652",borderColor:"#586e75",textPrimary:"#93a1a1",textSecondary:"#839496",textMuted:"#657b83",accentBlue:"#268bd2",accentGreen:"#859900",accentOrange:"#cb4b16",accentRed:"#dc322f",accentPurple:"#6c71c4",accentCyan:"#2aa198",accentClaude:"#859900",accentClaudeLight:"#95a910",accentPink:"#d33682",accentYellow:"#b58900",msgUserBg:"rgba(42, 161, 152, 0.12)",msgUserBorder:"#2aa198",msgUserText:"#2aa198",msgAssistantBg:"rgba(133, 153, 0, 0.12)",msgAssistantBorder:"#859900",msgAssistantText:"#859900",toolUseBg:"rgba(203, 75, 22, 0.10)",toolUseBorder:"#cb4b16",toolUseText:"#cb4b16",toolUseName:"#b58900",toolResultBg:"rgba(108, 113, 196, 0.10)",toolResultBorder:"#6c71c4",toolResultText:"#6c71c4",outputLineBg:"rgba(7, 54, 66, 0.5)",contextBarBg:"rgba(38, 139, 210, 0.25)",contextBarFill:"#268bd2"}},nU={id:"monokai",name:"Monokai",description:"Neon jungle on warm charcoal",colors:{bgPrimary:"#272822",bgSecondary:"#1e1f1a",bgTertiary:"#3e3d32",borderColor:"#49483e",textPrimary:"#f8f8f2",textSecondary:"#cfcfc2",textMuted:"#75715e",accentBlue:"#66d9ef",accentGreen:"#a6e22e",accentOrange:"#fd971f",accentRed:"#f92672",accentPurple:"#ae81ff",accentCyan:"#66d9ef",accentClaude:"#a6e22e",accentClaudeLight:"#b6f23e",accentPink:"#f92672",accentYellow:"#e6db74",msgUserBg:"rgba(249, 38, 114, 0.10)",msgUserBorder:"#f92672",msgUserText:"#f92672",msgAssistantBg:"rgba(166, 226, 46, 0.10)",msgAssistantBorder:"#a6e22e",msgAssistantText:"#a6e22e",toolUseBg:"rgba(253, 151, 31, 0.08)",toolUseBorder:"#fd971f",toolUseText:"#fd971f",toolUseName:"#66d9ef",toolResultBg:"rgba(174, 129, 255, 0.08)",toolResultBorder:"#ae81ff",toolResultText:"#ae81ff",outputLineBg:"rgba(62, 61, 50, 0.3)",contextBarBg:"rgba(249, 38, 114, 0.25)",contextBarFill:"#f92672"}},sU={id:"gruvbox",name:"Gruvbox",description:"Retro coffee shop warmth",colors:{bgPrimary:"#282828",bgSecondary:"#1d2021",bgTertiary:"#3c3836",borderColor:"#504945",textPrimary:"#ebdbb2",textSecondary:"#d5c4a1",textMuted:"#928374",accentBlue:"#83a598",accentGreen:"#b8bb26",accentOrange:"#fe8019",accentRed:"#fb4934",accentPurple:"#d3869b",accentCyan:"#8ec07c",accentClaude:"#b8bb26",accentClaudeLight:"#c8cb36",accentPink:"#d3869b",accentYellow:"#fabd2f",msgUserBg:"rgba(254, 128, 25, 0.10)",msgUserBorder:"#fe8019",msgUserText:"#fe8019",msgAssistantBg:"rgba(142, 192, 124, 0.10)",msgAssistantBorder:"#8ec07c",msgAssistantText:"#8ec07c",toolUseBg:"rgba(250, 189, 47, 0.08)",toolUseBorder:"#fabd2f",toolUseText:"#fabd2f",toolUseName:"#83a598",toolResultBg:"rgba(211, 134, 155, 0.08)",toolResultBorder:"#d3869b",toolResultText:"#d3869b",outputLineBg:"rgba(60, 56, 54, 0.4)",contextBarBg:"rgba(254, 128, 25, 0.25)",contextBarFill:"#fe8019"}},aU={id:"atom",name:"Atom",description:"Deep space exploration",colors:{bgPrimary:"#0c1014",bgSecondary:"#121820",bgTertiary:"#1a222c",borderColor:"#283040",textPrimary:"#d8e0f0",textSecondary:"#9ca8c0",textMuted:"#5a6880",accentBlue:"#5dade2",accentGreen:"#58d68d",accentOrange:"#f0b060",accentRed:"#ec7063",accentPurple:"#af7ac5",accentCyan:"#48c9b0",accentClaude:"#58d68d",accentClaudeLight:"#68e69d",accentPink:"#f1948a",accentYellow:"#f7dc6f",msgUserBg:"rgba(93, 173, 226, 0.10)",msgUserBorder:"#5dade2",msgUserText:"#5dade2",msgAssistantBg:"rgba(88, 214, 141, 0.10)",msgAssistantBorder:"#58d68d",msgAssistantText:"#58d68d",toolUseBg:"rgba(240, 176, 96, 0.08)",toolUseBorder:"#f0b060",toolUseText:"#f0b060",toolUseName:"#48c9b0",toolResultBg:"rgba(175, 122, 197, 0.08)",toolResultBorder:"#af7ac5",toolResultText:"#af7ac5",outputLineBg:"rgba(26, 34, 44, 0.5)",contextBarBg:"rgba(175, 122, 197, 0.25)",contextBarFill:"#af7ac5"}},iU={id:"cyberpunk",name:"Cyberpunk",description:"Neon noir dystopia",colors:{bgPrimary:"#030308",bgSecondary:"#08080f",bgTertiary:"#101018",borderColor:"#181828",textPrimary:"#e8e8ff",textSecondary:"#a0a0c8",textMuted:"#5050a0",accentBlue:"#00f0ff",accentGreen:"#00ff9f",accentOrange:"#ff6600",accentRed:"#ff003c",accentPurple:"#bf00ff",accentCyan:"#00f0ff",accentClaude:"#00ff9f",accentClaudeLight:"#50ffbf",accentPink:"#ff00aa",accentYellow:"#fff000",msgUserBg:"rgba(255, 0, 170, 0.12)",msgUserBorder:"#ff00aa",msgUserText:"#ff00aa",msgAssistantBg:"rgba(0, 255, 159, 0.10)",msgAssistantBorder:"#00ff9f",msgAssistantText:"#00ff9f",toolUseBg:"rgba(191, 0, 255, 0.10)",toolUseBorder:"#bf00ff",toolUseText:"#bf00ff",toolUseName:"#00f0ff",toolResultBg:"rgba(0, 240, 255, 0.08)",toolResultBorder:"#00f0ff",toolResultText:"#00f0ff",outputLineBg:"rgba(191, 0, 255, 0.03)",contextBarBg:"rgba(255, 0, 170, 0.30)",contextBarFill:"#ff00aa"}},rU={id:"synthwave",name:"Synthwave",description:"Sunset over chrome horizon",colors:{bgPrimary:"#241b30",bgSecondary:"#1a1424",bgTertiary:"#2e2540",borderColor:"#4a3860",textPrimary:"#f8e8f8",textSecondary:"#c8a8d0",textMuted:"#7860a0",accentBlue:"#2de2e6",accentGreen:"#0abdc6",accentOrange:"#ff9e64",accentRed:"#ff3864",accentPurple:"#9d4edd",accentCyan:"#2de2e6",accentClaude:"#0abdc6",accentClaudeLight:"#2ad0d8",accentPink:"#f706cf",accentYellow:"#fede5d",msgUserBg:"rgba(247, 6, 207, 0.12)",msgUserBorder:"#f706cf",msgUserText:"#f706cf",msgAssistantBg:"rgba(45, 226, 230, 0.10)",msgAssistantBorder:"#2de2e6",msgAssistantText:"#2de2e6",toolUseBg:"rgba(255, 158, 100, 0.10)",toolUseBorder:"#ff9e64",toolUseText:"#ff9e64",toolUseName:"#fede5d",toolResultBg:"rgba(157, 78, 221, 0.10)",toolResultBorder:"#9d4edd",toolResultText:"#9d4edd",outputLineBg:"rgba(157, 78, 221, 0.05)",contextBarBg:"rgba(247, 6, 207, 0.25)",contextBarFill:"#f706cf"}},oU={id:"abyss",name:"Abyss",description:"Deep black, vivid accents",colors:{bgPrimary:"#080a0c",bgSecondary:"#0c0e12",bgTertiary:"#12161a",borderColor:"#1c2028",textPrimary:"#a8b0b8",textSecondary:"#889098",textMuted:"#505860",accentBlue:"#4da8da",accentGreen:"#50c878",accentOrange:"#e89050",accentRed:"#e85050",accentPurple:"#a070d8",accentCyan:"#50d0d0",accentClaude:"#50c878",accentClaudeLight:"#68e090",accentPink:"#e070a0",accentYellow:"#e8d050",msgUserBg:"#0b0b0b",msgUserBorder:"transparent",msgUserText:"#98a0a8",msgAssistantBg:"#1B1C25",msgAssistantBorder:"transparent",msgAssistantText:"#98a0a8",toolUseBg:"#1B1C25",toolUseBorder:"#e89050",toolUseText:"#98a0a8",toolUseName:"#e89050",toolResultBg:"#1B1C25",toolResultBorder:"#a070d8",toolResultText:"#98a0a8",outputLineBg:"#0a0c10",contextBarBg:"rgba(80, 88, 96, 0.3)",contextBarFill:"#606870"}},lU={id:"catppuccin",name:"Catppuccin",description:"Cozy pastel mocha cafe",colors:{bgPrimary:"#1e1e2e",bgSecondary:"#181825",bgTertiary:"#313244",borderColor:"#45475a",textPrimary:"#cdd6f4",textSecondary:"#bac2de",textMuted:"#6c7086",accentBlue:"#89b4fa",accentGreen:"#a6e3a1",accentOrange:"#fab387",accentRed:"#f38ba8",accentPurple:"#cba6f7",accentCyan:"#94e2d5",accentClaude:"#a6e3a1",accentClaudeLight:"#b6f3b1",accentPink:"#f5c2e7",accentYellow:"#f9e2af",msgUserBg:"rgba(180, 190, 254, 0.10)",msgUserBorder:"#b4befe",msgUserText:"#b4befe",msgAssistantBg:"rgba(148, 226, 213, 0.10)",msgAssistantBorder:"#94e2d5",msgAssistantText:"#94e2d5",toolUseBg:"rgba(250, 179, 135, 0.08)",toolUseBorder:"#fab387",toolUseText:"#fab387",toolUseName:"#f9e2af",toolResultBg:"rgba(203, 166, 247, 0.08)",toolResultBorder:"#cba6f7",toolResultText:"#cba6f7",outputLineBg:"rgba(49, 50, 68, 0.4)",contextBarBg:"rgba(245, 194, 231, 0.25)",contextBarFill:"#f5c2e7"}},cU={id:"github-dark",name:"GitHub Dark",description:"Developer professional minimal",colors:{bgPrimary:"#0d1117",bgSecondary:"#161b22",bgTertiary:"#21262d",borderColor:"#30363d",textPrimary:"#c9d1d9",textSecondary:"#8b949e",textMuted:"#484f58",accentBlue:"#58a6ff",accentGreen:"#3fb950",accentOrange:"#d29922",accentRed:"#f85149",accentPurple:"#a371f7",accentCyan:"#79c0ff",accentClaude:"#3fb950",accentClaudeLight:"#56d364",accentPink:"#f778ba",accentYellow:"#e3b341",msgUserBg:"rgba(88, 166, 255, 0.08)",msgUserBorder:"#58a6ff",msgUserText:"#58a6ff",msgAssistantBg:"rgba(63, 185, 80, 0.08)",msgAssistantBorder:"#3fb950",msgAssistantText:"#3fb950",toolUseBg:"rgba(210, 153, 34, 0.08)",toolUseBorder:"#d29922",toolUseText:"#d29922",toolUseName:"#79c0ff",toolResultBg:"rgba(163, 113, 247, 0.08)",toolResultBorder:"#a371f7",toolResultText:"#a371f7",outputLineBg:"rgba(33, 38, 45, 0.5)",contextBarBg:"rgba(88, 166, 255, 0.25)",contextBarFill:"#58a6ff"}},uU={id:"one-dark",name:"One Dark",description:"Moonlit late night coding",colors:{bgPrimary:"#282c34",bgSecondary:"#21252b",bgTertiary:"#2c323c",borderColor:"#3e4451",textPrimary:"#abb2bf",textSecondary:"#828997",textMuted:"#5c6370",accentBlue:"#61afef",accentGreen:"#98c379",accentOrange:"#d19a66",accentRed:"#e06c75",accentPurple:"#c678dd",accentCyan:"#56b6c2",accentClaude:"#98c379",accentClaudeLight:"#a8d389",accentPink:"#e06c75",accentYellow:"#e5c07b",msgUserBg:"rgba(86, 182, 194, 0.10)",msgUserBorder:"#56b6c2",msgUserText:"#56b6c2",msgAssistantBg:"rgba(152, 195, 121, 0.10)",msgAssistantBorder:"#98c379",msgAssistantText:"#98c379",toolUseBg:"rgba(209, 154, 102, 0.08)",toolUseBorder:"#d19a66",toolUseText:"#d19a66",toolUseName:"#e5c07b",toolResultBg:"rgba(198, 120, 221, 0.08)",toolResultBorder:"#c678dd",toolResultText:"#c678dd",outputLineBg:"rgba(44, 50, 60, 0.5)",contextBarBg:"rgba(97, 175, 239, 0.25)",contextBarFill:"#61afef"}},dU={id:"classic",name:"Classic",description:"Original transparent style",colors:{bgPrimary:"#0d0d14",bgSecondary:"#14141e",bgTertiary:"#1c1c28",borderColor:"#2a2a3a",textPrimary:"#d0d0d8",textSecondary:"#8a8a98",textMuted:"#5a6a8a",accentBlue:"#5a8fd4",accentGreen:"#50fa7b",accentOrange:"#c89a5a",accentRed:"#c85a5a",accentPurple:"#9a80c0",accentCyan:"#8be9fd",accentClaude:"#50fa7b",accentClaudeLight:"#69ff94",accentPink:"#c87a9a",accentYellow:"#c8c87a",msgUserBg:"rgba(139, 233, 253, 0.12)",msgUserBorder:"transparent",msgUserText:"#8be9fd",msgAssistantBg:"rgba(80, 250, 123, 0.12)",msgAssistantBorder:"transparent",msgAssistantText:"#50fa7b",toolUseBg:"rgba(255, 184, 108, 0.05)",toolUseBorder:"transparent",toolUseText:"#8be9fd",toolUseName:"#ffb86c",toolResultBg:"rgba(80, 250, 123, 0.06)",toolResultBorder:"transparent",toolResultText:"#50fa7b",outputLineBg:"transparent",contextBarBg:"rgba(106, 154, 120, 0.25)",contextBarFill:"#6a9a78"}},Na=[dU,oU,QH,RE,JH,eU,tU,nU,sU,aU,iU,rU,lU,cU,uU];function id(s){return Na.find(e=>e.id===s)||RE}const hU="classic";function Xp(s){const e=document.documentElement,{colors:t}=s;e.style.setProperty("--bg-primary",t.bgPrimary),e.style.setProperty("--bg-secondary",t.bgSecondary),e.style.setProperty("--bg-tertiary",t.bgTertiary),e.style.setProperty("--border-color",t.borderColor),e.style.setProperty("--text-primary",t.textPrimary),e.style.setProperty("--text-secondary",t.textSecondary),e.style.setProperty("--text-muted",t.textMuted),e.style.setProperty("--accent-blue",t.accentBlue),e.style.setProperty("--accent-green",t.accentGreen),e.style.setProperty("--accent-orange",t.accentOrange),e.style.setProperty("--accent-red",t.accentRed),e.style.setProperty("--accent-purple",t.accentPurple),e.style.setProperty("--accent-cyan",t.accentCyan),e.style.setProperty("--accent-claude",t.accentClaude),e.style.setProperty("--accent-claude-light",t.accentClaudeLight),e.style.setProperty("--accent-pink",t.accentPink),e.style.setProperty("--accent-yellow",t.accentYellow),e.style.setProperty("--msg-user-bg",t.msgUserBg),e.style.setProperty("--msg-user-border",t.msgUserBorder),e.style.setProperty("--msg-user-text",t.msgUserText),e.style.setProperty("--msg-assistant-bg",t.msgAssistantBg),e.style.setProperty("--msg-assistant-border",t.msgAssistantBorder),e.style.setProperty("--msg-assistant-text",t.msgAssistantText),e.style.setProperty("--tool-use-bg",t.toolUseBg),e.style.setProperty("--tool-use-border",t.toolUseBorder),e.style.setProperty("--tool-use-text",t.toolUseText),e.style.setProperty("--tool-use-name",t.toolUseName),e.style.setProperty("--tool-result-bg",t.toolResultBg),e.style.setProperty("--tool-result-border",t.toolResultBorder),e.style.setProperty("--tool-result-text",t.toolResultText),e.style.setProperty("--output-line-bg",t.outputLineBg),e.style.setProperty("--context-bar-bg",t.contextBarBg),e.style.setProperty("--context-bar-fill",t.contextBarFill);try{localStorage.setItem("tide-theme",s.id)}catch{}}function yv(){try{const s=localStorage.getItem("tide-theme");if(s&&Na.some(e=>e.id===s))return s}catch{}return hU}function pU(){const s=yv(),e=id(s);Xp(e)}const mU=y.memo(function(){const{t:e}=$e(["terminal"]),[t,n]=y.useState(!1),[a,i]=y.useState(()=>yv()),[o,l]=y.useState(-1),c=y.useRef(null),d=y.useRef(null),m=Na.findIndex(w=>w.id===a);y.useEffect(()=>{if(!t)return;const w=k=>{c.current&&!c.current.contains(k.target)&&n(!1)};return document.addEventListener("mousedown",w),()=>document.removeEventListener("mousedown",w)},[t]),y.useEffect(()=>{t&&l(m)},[t,m]);const p=w=>{const k=w==="next"?(m+1)%Na.length:(m-1+Na.length)%Na.length,S=Na[k],j=id(S.id);Xp(j),i(S.id)},f=w=>{t||(w.key==="ArrowUp"||w.key==="ArrowLeft"?(w.preventDefault(),p("prev")):w.key==="ArrowDown"||w.key==="ArrowRight"?(w.preventDefault(),p("next")):(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),n(!0)))};y.useEffect(()=>{if(!t)return;const w=k=>{var S,j;k.key==="Escape"?(n(!1),(S=d.current)==null||S.focus()):k.key==="ArrowDown"?(k.preventDefault(),l(C=>(C+1)%Na.length)):k.key==="ArrowUp"?(k.preventDefault(),l(C=>(C-1+Na.length)%Na.length)):k.key==="Enter"&&o>=0&&(k.preventDefault(),b(Na[o].id),(j=d.current)==null||j.focus())};return document.addEventListener("keydown",w),()=>document.removeEventListener("keydown",w)},[t,o]);const b=w=>{const k=id(w);Xp(k),i(w),n(!1)},x=id(a);return r.jsxs("div",{className:"theme-selector",ref:c,children:[r.jsxs("button",{ref:d,className:"theme-selector-trigger",onClick:()=>n(!t),onKeyDown:f,title:e("terminal:themeSelector.themeTitle",{name:x.name}),children:[r.jsx("span",{className:"theme-selector-icon",children:"🎨"}),r.jsx("span",{className:"theme-selector-name",children:x.name}),r.jsx("span",{className:"theme-selector-arrow",children:t?"▲":"▼"})]}),t&&r.jsxs("div",{className:"theme-selector-dropdown",onMouseDown:w=>w.stopPropagation(),onClick:w=>w.stopPropagation(),children:[r.jsx("div",{className:"theme-selector-header",children:e("terminal:themeSelector.selectTheme")}),r.jsx("div",{className:"theme-selector-list",children:Na.map((w,k)=>r.jsxs("button",{className:`theme-selector-option ${w.id===a?"active":""} ${k===o?"highlighted":""}`,onClick:S=>{S.stopPropagation(),b(w.id)},onMouseDown:S=>S.stopPropagation(),onMouseEnter:()=>l(k),children:[r.jsx("span",{className:"theme-option-preview",style:{background:`linear-gradient(135deg, ${w.colors.bgPrimary} 0%, ${w.colors.bgSecondary} 50%, ${w.colors.accentPurple} 100%)`}}),r.jsxs("span",{className:"theme-option-info",children:[r.jsx("span",{className:"theme-option-name",children:w.name}),r.jsx("span",{className:"theme-option-desc",children:w.description})]}),w.id===a&&r.jsx("span",{className:"theme-option-check",children:"✓"})]},w.id))})]})]})}),H1=1e4,fU=3e4,gU=12e4;function Ob(s){const e=dv(s);return hv(e.userMessage).userMessage.trim().replace(/\r\n/g,`
234
234
  `)}function sp(s){return s.trim().replace(/\r\n/g,`
235
- `)}function bU(s){return s.startsWith("Using tool:")||s.startsWith("Tool input:")||s.startsWith("Tool result:")||s.startsWith("Bash output:")||s.startsWith("Session started:")||s.startsWith("[thinking]")||s.startsWith("Tokens:")||s.startsWith("Cost:")||s.startsWith("Context (estimated from Codex turn usage):")||s.startsWith("🔄 [System]")||s.startsWith("📋 [System]")||s.startsWith("[System]")}const yU=y.memo(function({onSaveSnapshot:e}={}){var et,ct,Qt,On,rn;const{t}=$e(["terminal","common"]),n=fi(),a=wm(),i=WM(),o=Bx(),l=Hx(),c=ZM(),d=qM(),m=Fx(),p=$x(),f=mF(),b=!!f,x=y.useMemo(()=>f?{id:f.agentId,name:f.agentName,class:f.agentClass,status:"idle",provider:"claude",position:{x:0,y:0,z:0},cwd:f.cwd,permissionMode:"interactive",tokensUsed:0,contextUsed:0,contextLimit:2e5,taskCount:0,createdAt:f.createdAt,lastActivity:f.createdAt}:null,[f]),w=Array.from(a),S=w.length===1?w[0]:null,C=(Lx(S)||null)??(b?x:null),N=S??(b?(f==null?void 0:f.agentId)??null:null),P=!!(C!=null&&C.sessionId)&&!b,_=mo(),L=y.useMemo(()=>{if(!N)return null;for(const We of _.values())if(We.assignedAgentIds.includes(N)&&We.directories.length>0)return We;return null},[N,_]),{terminalHeight:M,terminalRef:D,handleResizeStart:E}=Y9(),R=q9(),O=Ox(N),I=y.useMemo(()=>b&&f?f.outputs.map(We=>({text:We.text||"",timestamp:We.timestamp,isStreaming:!1,isUserPrompt:!1})):O,[b,f,O]),B=y.useRef(null),Y=y.useRef(null),$=y.useRef(null),[W,K]=y.useState(()=>{const We=la(vt.VIEW_MODE);return We==="simple"||We==="chat"||We==="advanced"?We:la(vt.ADVANCED_VIEW)==="true"?"advanced":"simple"}),[X,H]=y.useState(null),[se,ce]=y.useState(null),[F,V]=y.useState(null),[J,ie]=y.useState(null),[Q,Z]=y.useState(!1);En("guake-image-modal",X!==null,()=>H(null)),En("guake-bash-modal",se!==null,()=>ce(null)),En("guake-response-modal",J!==null,()=>ie(null)),En("guake-context-confirm",F!==null,()=>V(null)),En("guake-agent-info",Q,()=>Z(!1));const[G,re]=y.useState(!1),[ue,be]=y.useState(()=>Ms.isEnabled()),ve=vF(),ge=y.useCallback(We=>z.setOverviewPanelOpen(We),[]),[_e,Le]=y.useState(!1),[ke,ne]=y.useState(null),de=y.useRef(null),le=y.useRef(null),[oe,he]=y.useState(!1),[Ce,xe]=y.useState(!1),[Ze,ye]=y.useState(!1),[Se,qe]=y.useState(!1),ee=y.useRef(0),me=i&&C!==null,pe=$M({selectedAgentId:N,hasSessionId:P,reconnectCount:l,historyRefreshTrigger:c,lastPrompts:o,outputScrollRef:B}),Oe=K9({selectedAgentId:N,isOpen:me}),Je=V9({agents:n,selectedAgentId:N,isOpen:me,loadingHistory:pe.fetchingHistory,hasModalOpen:!!(X||se||J||m||p),outputRef:B}),Fe=hE({selectedAgentId:S}),kt=qz(),Ee=y.useMemo(()=>b||!N?[]:Array.from(kt.values()).filter(We=>We.agentId===N&&We.status==="pending"),[b,N,kt]),Ye=(C==null?void 0:C.class)==="boss"||(C==null?void 0:C.isBoss),tt=iF(!b&&Ye?N:null),it=rF(b?null:N),ft=xF(b?null:N);y.useEffect(()=>{G&&!ue&&(be(!0),Ms.setEnabled(!0))},[G,ue]),y.useEffect(()=>{me||Z(!1)},[me]),y.useEffect(()=>{const We=C==null?void 0:C.status;if(de.current==="working"&&We==="idle"){le.current&&clearTimeout(le.current);const Ct=N?o.get(N):void 0;ne(Ct!=null&&Ct.timestamp?Date.now()-Ct.timestamp:null),Le(!0),le.current=setTimeout(()=>{Le(!1),ne(null),le.current=null},4e3)}else We==="working"&&(le.current&&(clearTimeout(le.current),le.current=null),Le(!1),ne(null));return de.current=We||null,()=>{le.current&&clearTimeout(le.current)}},[C==null?void 0:C.status]);const ut=y.useMemo(()=>{const{history:We}=pe,ot=new Map;for(const Et of We)Et.type==="tool_result"&&Et.toolUseId&&ot.set(Et.toolUseId,Et.content);return(Et=>Et.map(_t=>{if(_t.type==="tool_use"&&_t.toolName==="Bash"&&_t.toolUseId){const zt=ot.get(_t.toolUseId);let Pt;try{Pt=(_t.toolInput||(_t.content?JSON.parse(_t.content):{})).command}catch{}return{..._t,_bashOutput:zt,_bashCommand:Pt}}return _t}))(We)},[pe.history,W]),ae=pE({outputs:I,viewMode:W}),Ne=y.useMemo(()=>{const We=[],ot=new Set,Ct=new Set;let Et=null,_t=0;for(const zt of ut){if(zt.type==="assistant"){const is=zt.uuid?`uuid:${zt.uuid}:${sp(zt.content)}`:`sig:${zt.timestamp}:${sp(zt.content)}`;if(ot.has(is))continue;ot.add(is),We.push(zt);continue}if(zt.type!=="user"){We.push(zt);continue}const Pt=Ob(zt.content),Xt=zt.uuid?`uuid:${zt.uuid}:${Pt}`:null;if(Xt&&Ct.has(Xt))continue;const Wt=zt.timestamp?new Date(zt.timestamp).getTime():0;Et===Pt&&Math.abs(Wt-_t)<=H1||(We.push(zt),Xt&&Ct.add(Xt),Et=Pt,_t=Wt)}return We},[ut]),Ge=y.useMemo(()=>{const We=new Map,ot=new Set,Ct=new Map;for(const Pt of Ne){const Xt=Pt.timestamp?new Date(Pt.timestamp).getTime():0;if(Pt.type==="user"){const pa=Ob(Pt.content),ma=We.get(pa)??0;Xt>ma&&We.set(pa,Xt);continue}if(Pt.type!=="assistant")continue;Pt.uuid&&ot.add(Pt.uuid);const Wt=sp(Pt.content),is=Ct.get(Wt)??0;Xt>is&&Ct.set(Wt,Xt)}const Et=[];let _t=null,zt=0;for(const Pt of ae){if(!Pt.isUserPrompt){if(!Pt.isStreaming&&!bU(Pt.text)){if(Pt.uuid&&ot.has(Pt.uuid))continue;const pa=sp(Pt.text),ma=Pt.timestamp||0,bi=Ct.get(pa);if(bi&&Math.abs(ma-bi)<=gU)continue}Et.push(Pt);continue}const Xt=Ob(Pt.text),Wt=Pt.timestamp||0,is=We.get(Xt);is&&Wt>=is&&Wt-is<=fU||_t===Xt&&Math.abs(Wt-zt)<=H1||(Et.push(Pt),_t=Xt,zt=Wt)}return Et},[ae,Ne]),at=Ne.length+Ge.length,ht=Q9({totalMessages:at,isOpen:me,hasModalOpen:!!(X||se||J||m),scrollContainerRef:B,selectedAgentId:N,inputRef:Y,textareaRef:$,useTextarea:Fe.useTextarea});y.useEffect(()=>{if(!(!(se!=null&&se.isLive)||!se.command)){for(const We of Ge)if(We._bashCommand===se.command&&We._bashOutput){ce({command:se.command,output:We._bashOutput,isLive:!1});return}}},[se,Ge]);const $t=y.useCallback((We,ot)=>{H({url:We,name:ot})},[]),Vt=y.useCallback((We,ot)=>{const Ct=Td(We,C==null?void 0:C.cwd),Et=Ct.line?{...ot||{},targetLine:Ct.line}:ot;z.setFileViewerPath(Ct.path,Et,C==null?void 0:C.cwd)},[C==null?void 0:C.cwd]),jt=y.useCallback((We,ot)=>{ce({command:We,output:ot,isLive:ot==="Running..."})},[]),It=y.useCallback(We=>{ie(We)},[]),At=y.useCallback(()=>{Z(We=>!We)},[]),[Bt,Ln]=y.useState(!0),fn=y.useRef(!1),hs=y.useRef(!1),Qn=y.useCallback(()=>{hs.current||(fn.current=!0,Ln(!1))},[]),Kn=y.useCallback(()=>xe(!1),[]);y.useEffect(()=>{Ln(!0),fn.current=!1,hs.current=!0;const We=setTimeout(()=>{hs.current=!1},3e3);return()=>clearTimeout(We)},[N]);const vs=y.useRef(pe.handleScroll);vs.current=pe.handleScroll;const Dn=y.useCallback(()=>{if(!B.current||R.keyboardScrollLockRef.current)return;const{scrollTop:We,scrollHeight:ot,clientHeight:Ct}=B.current,Et=ot-We-Ct<150;hs.current||(fn.current=!Et,Et&&Ln(!0)),vs.current(R.keyboardScrollLockRef)},[B,R.keyboardScrollLockRef]),Yn=O.length>0&&((ct=(et=O[O.length-1])==null?void 0:et.text)==null?void 0:ct.length)||0;y.useEffect(()=>{R.keyboardScrollLockRef.current||fn.current||requestAnimationFrame(()=>{if(B.current){const{scrollTop:We,scrollHeight:ot,clientHeight:Ct}=B.current;ot-We-Ct<150&&(B.current.scrollTop=ot)}})},[O.length,Yn,R.keyboardScrollLockRef,B]);const ps=y.useRef(null);y.useLayoutEffect(()=>{const We=ps.current;We!==null&&We!==S?(he(!1),S&&pe.hasCachedHistory(S)||ye(!0),z.getState().currentSnapshot&&z.setCurrentSnapshot(null)):S||he(!1),ps.current=S},[S]),y.useEffect(()=>{if(!Ze||pe.fetchingHistory)return;const We=requestAnimationFrame(()=>{B.current&&(B.current.scrollTop=B.current.scrollHeight),ye(!1)});return()=>cancelAnimationFrame(We)},[Ze,pe.fetchingHistory,pe.historyLoadVersion]);const ms=y.useRef(!1);y.useEffect(()=>{me&&S&&z.clearUnseenForAgent(S)},[me,S]),y.useEffect(()=>{ms.current=!0,xe(!0)},[N,l]),y.useEffect(()=>{pe.fetchingHistory&&(ms.current=!0,xe(!0))},[pe.fetchingHistory]),y.useEffect(()=>{if(!Ce||!me||pe.fetchingHistory)return;const We=B.current;if(!We)return;let ot=null;const Ct=performance.now();let Et=0,_t=-1;const zt=()=>{const{scrollTop:Xt,scrollHeight:Wt,clientHeight:is}=We;return Wt-Xt-is<=2},Pt=()=>{const Xt=performance.now(),Wt=We.scrollHeight,is=Math.abs(Wt-_t)<=1,pa=zt();if(is&&pa?Et+=1:Et=0,_t=Wt,Et>=3){xe(!1),ot=null;return}if(Xt-Ct>8e3){xe(!1),ot=null;return}ot=requestAnimationFrame(Pt)};return ot=requestAnimationFrame(Pt),()=>{ot!==null&&cancelAnimationFrame(ot)}},[Ce,me,pe.fetchingHistory,pe.historyLoadVersion]);const Za=y.useRef(!1);y.useEffect(()=>{Za.current&&!Ce&&ms.current&&(ms.current=!1,he(!0)),Za.current=Ce},[Ce]),y.useEffect(()=>{if(!me||!ms.current||Ce||pe.fetchingHistory)return;const We=requestAnimationFrame(()=>{ms.current&&(ms.current=!1,he(!0))});return()=>cancelAnimationFrame(We)},[pe.historyLoadVersion,me,Ce,pe.fetchingHistory]),y.useEffect(()=>{const We=ot=>{if(ot.key==="`"&&!ot.ctrlKey&&!ot.altKey&&C){const Ct=ot.target;Ct.tagName!=="INPUT"&&Ct.tagName!=="TEXTAREA"&&(ot.preventDefault(),z.toggleTerminal())}};return document.addEventListener("keydown",We),()=>document.removeEventListener("keydown",We)},[C]),y.useEffect(()=>{const We=ot=>{ot.key==="Escape"&&(m?(ot.stopImmediatePropagation(),z.clearFileViewerPath()):p?(ot.stopImmediatePropagation(),z.closeContextModal()):J?(ot.stopImmediatePropagation(),ie(null)):se?(ot.stopImmediatePropagation(),ce(null)):X?(ot.stopImmediatePropagation(),H(null)):Oe.searchMode&&(ot.stopImmediatePropagation(),Oe.closeSearch()))};return document.addEventListener("keydown",We,!0),()=>document.removeEventListener("keydown",We,!0)},[X,se,J,Oe,m,p]);const da=y.useRef(me),Is=y.useRef(!1);y.useEffect(()=>{da.current=me},[me]),y.useEffect(()=>{if(window.innerWidth<=768)return;const ot=_t=>{var Wt;if(!(_t instanceof Element))return!1;const zt=(Wt=D.current)==null?void 0:Wt.contains(_t),Pt=_t.closest(".agent-bar"),Xt=!!_t.closest(".modal-overlay, .modal, .image-modal-overlay, .image-modal, .bash-modal-overlay, .bash-modal, .agent-info-modal-overlay, .agent-info-modal, .agent-response-modal, .pasted-text-modal-overlay, .pasted-text-modal, .file-viewer-overlay, .file-viewer-modal, .context-view-modal, .guake-context-confirm-overlay, .guake-context-confirm-modal");return!!zt||!!Pt||Xt},Ct=_t=>{if(!da.current){Is.current=!1;return}Is.current=!ot(_t.target)},Et=_t=>{Is.current&&(ot(_t.target)||z.setTerminalOpen(!1),Is.current=!1)};return document.addEventListener("mousedown",Ct,!0),document.addEventListener("mouseup",Et,!0),()=>{document.removeEventListener("mousedown",Ct,!0),document.removeEventListener("mouseup",Et,!0)}},[]),y.useEffect(()=>{const We=()=>{document.hidden&&R.cleanup()};return document.addEventListener("visibilitychange",We),()=>document.removeEventListener("visibilitychange",We)},[R]),y.useEffect(()=>()=>R.cleanup(),[N,R]);const Jn=typeof window<"u"&&window.innerWidth<=768;if(!C)return Jn&&d==="terminal"&&a.size===0?r.jsx("div",{ref:D,className:"guake-terminal open",style:{"--terminal-height":`${M}%`},children:r.jsx("div",{className:"guake-content",children:r.jsx("div",{className:"guake-output",style:{display:"flex",alignItems:"center",justifyContent:"center",color:"#6272a4"},children:r.jsxs("div",{style:{textAlign:"center"},children:[r.jsx("div",{style:{fontSize:"48px",marginBottom:"16px"},children:"👆"}),r.jsx("div",{style:{fontSize:"16px"},children:t("terminal:empty.tapAgent")}),r.jsx("div",{style:{fontSize:"14px",marginTop:"8px",opacity:.7},children:t("terminal:empty.switchTo3D")})]})})})}):Jn&&d==="terminal"&&a.size>0?r.jsx("div",{ref:D,className:"guake-terminal open",style:{"--terminal-height":`${M}%`},children:r.jsx("div",{className:"guake-content",children:r.jsx("div",{className:"guake-output",style:{display:"flex",alignItems:"center",justifyContent:"center",color:"#6272a4"},children:r.jsxs("div",{className:"guake-empty loading",children:[t("terminal:empty.loadingTerminal"),r.jsxs("span",{className:"loading-dots",children:[r.jsx("span",{}),r.jsx("span",{}),r.jsx("span",{})]})]})})})}):null;if(!N)return null;const ha=We=>{We.preventDefault(),We.stopPropagation(),ee.current++,We.dataTransfer.types.includes("Files")&&qe(!0)},pt=We=>{We.preventDefault(),We.stopPropagation()},Kt=We=>{We.preventDefault(),We.stopPropagation(),ee.current--,ee.current===0&&qe(!1)},Ae=async We=>{We.preventDefault(),We.stopPropagation(),ee.current=0,qe(!1);const ot=We.dataTransfer.files;if(ot.length)for(const Ct of ot){const Et=await Fe.uploadFile(Ct);Et&&Fe.setAttachedFiles(_t=>[..._t,Et])}};return r.jsxs("div",{ref:D,className:`guake-terminal ${me?"open":"collapsed"} ${G&&me?"with-debug-panel":""} ${ve&&me?"with-overview-panel":""} ${Se?"drag-over":""}`,style:{"--terminal-height":`${M}%`},onDragEnter:ha,onDragOver:pt,onDragLeave:Kt,onDrop:Ae,children:[r.jsxs("div",{className:"guake-drop-overlay",children:[r.jsx("div",{className:"drop-border"}),r.jsx("span",{className:"drop-icon",children:"📎"}),r.jsx("span",{className:"drop-label",children:t("terminal:input.dropToAttach")})]}),!b&&G&&me&&N&&r.jsx(GH,{agentId:N,onClose:()=>re(!1)}),!b&&ve&&me&&N&&r.jsx(VH,{activeAgentId:N,onClose:()=>ge(!1),onSelectAgent:We=>{z.selectAgent(We)}}),r.jsxs("div",{className:"guake-content",children:[r.jsx(lH,{selectedAgent:C,selectedAgentId:N,sortedAgents:Je.sortedAgents,swipeOffset:Je.swipeOffset,viewMode:W,setViewMode:K,searchMode:Oe.searchMode,toggleSearch:Oe.toggleSearch,closeSearch:Oe.closeSearch,debugPanelOpen:G,setDebugPanelOpen:re,debuggerEnabled:ue,setDebuggerEnabled:be,overviewPanelOpen:ve,setOverviewPanelOpen:ge,agentInfoOpen:Q,onToggleAgentInfo:At,outputsLength:Ne.length+Ge.length,setContextConfirm:V,headerRef:Je.headerRef,onSaveSnapshot:b?void 0:e,isSnapshotView:b}),Oe.searchMode&&r.jsx(cH,{searchInputRef:Oe.searchInputRef,searchQuery:Oe.searchQuery,setSearchQuery:Oe.setSearchQuery,handleSearch:Oe.handleSearch,closeSearch:Oe.closeSearch,searchLoading:Oe.searchLoading,searchResultsCount:Oe.searchResults.length}),r.jsxs("div",{className:`guake-swipe-container ${Je.swipeAnimationClass}`,style:Je.swipeOffset!==0?{transform:`translateX(${Je.swipeOffset*40}%)`}:void 0,children:[Je.sortedAgents.length>1&&Je.swipeOffset!==0&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:`swipe-indicator left ${Je.swipeOffset>.3?"visible":""}`,children:[r.jsx("span",{className:"indicator-icon",children:"←"}),r.jsx("span",{className:"indicator-name",children:(Qt=Je.prevAgent)==null?void 0:Qt.name})]}),r.jsxs("div",{className:`swipe-indicator right ${Je.swipeOffset<-.3?"visible":""}`,children:[r.jsx("span",{className:"indicator-name",children:(On=Je.nextAgent)==null?void 0:On.name}),r.jsx("span",{className:"indicator-icon",children:"→"})]})]}),Je.sortedAgents.length>1&&Je.sortedAgents.length<=8&&Je.swipeOffset!==0&&r.jsx("div",{className:`swipe-dots ${Math.abs(Je.swipeOffset)>.1?"visible":""}`,children:Je.sortedAgents.map((We,ot)=>r.jsx("div",{className:`swipe-dot ${ot===Je.currentAgentIndex?"active":""}`},We.id))}),r.jsx("div",{className:"guake-output",ref:B,onScroll:Dn,children:Oe.searchMode&&Oe.searchResults.length>0?r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"guake-search-header",children:t("terminal:header.searchResultsTitle")}),Oe.searchResults.map((We,ot)=>r.jsx(gv,{message:We,agentId:N,highlight:Oe.searchQuery,onImageClick:$t,onFileClick:Vt,onBashClick:jt,onViewMarkdown:It},`s-${ot}`))]}):r.jsxs("div",{className:`guake-history-content ${oe?"fade-in":""}`,children:[Ze&&r.jsxs("div",{className:"guake-empty loading",children:[t("terminal:empty.loadingConversation"),r.jsxs("span",{className:"loading-dots",children:[r.jsx("span",{}),r.jsx("span",{}),r.jsx("span",{})]})]}),!Ze&&pe.loadingHistory&&pe.history.length===0&&O.length===0&&r.jsxs("div",{className:"guake-empty loading",children:[t("terminal:empty.loadingConversation"),r.jsxs("span",{className:"loading-dots",children:[r.jsx("span",{}),r.jsx("span",{}),r.jsx("span",{})]})]}),!Ze&&!pe.loadingHistory&&pe.history.length===0&&I.length===0&&C.status!=="working"&&r.jsx("div",{className:"guake-empty",children:t("terminal:empty.noOutput")}),!Ze&&pe.hasMore&&!Oe.searchMode&&r.jsx("div",{className:"guake-load-more",children:pe.loadingMore?r.jsx("span",{children:t("terminal:empty.loadingOlder")}):r.jsx("button",{onClick:pe.loadMoreHistory,children:t("terminal:empty.loadMore",{count:pe.totalCount-pe.history.length})})}),!Ze&&r.jsx(PE,{historyMessages:Ne,liveOutputs:Ge,agentId:N,execTasks:it,subagents:ft,viewMode:W,selectedMessageIndex:ht.selectedIndex,isMessageSelected:ht.isSelected,onImageClick:$t,onFileClick:Vt,onBashClick:jt,onViewMarkdown:It,scrollContainerRef:B,onScrollTopReached:pe.loadMoreHistory,isLoadingMore:pe.loadingMore,hasMore:pe.hasMore,shouldAutoScroll:Bt,onUserScroll:Qn,pinToBottom:Ce,onPinCancel:Kn,isLoadingHistory:pe.fetchingHistory},N),!Ze&&Ye&&tt.size>0&&r.jsxs("div",{className:"agent-progress-container",children:[r.jsxs("div",{className:"agent-progress-container-header",children:[r.jsx("span",{className:"progress-crown",children:"👑"}),r.jsx("span",{children:t("terminal:empty.subordinateProgress")}),r.jsx("span",{className:"progress-count",children:t("terminal:empty.activeCount",{count:tt.size})})]}),Array.from(tt.values()).map(We=>r.jsx(XH,{progress:We,defaultExpanded:We.status==="working",onAgentClick:z.selectAgent},We.agentId))]})]})})]}),r.jsx(gH,{selectedAgent:C,selectedAgentId:N,isOpen:me,command:Fe.command,setCommand:Fe.setCommand,forceTextarea:Fe.forceTextarea,setForceTextarea:Fe.setForceTextarea,useTextarea:Fe.useTextarea,attachedFiles:Fe.attachedFiles,setAttachedFiles:Fe.setAttachedFiles,removeAttachedFile:Fe.removeAttachedFile,uploadFile:Fe.uploadFile,pastedTexts:Fe.pastedTexts,expandPastedTexts:Fe.expandPastedTexts,incrementPastedCount:Fe.incrementPastedCount,setPastedTexts:Fe.setPastedTexts,resetPastedCount:Fe.resetPastedCount,handleInputFocus:R.handleInputFocus,handleInputBlur:R.handleInputBlur,pendingPermissions:Ee,showCompletion:_e,completionElapsed:ke,onImageClick:$t,inputRef:Y,textareaRef:$,isSnapshotView:b,onClearHistory:pe.clearHistory}),r.jsxs("div",{className:"guake-agent-status-bar",children:[!b&&(C==null?void 0:C.isDetached)&&r.jsx(Yp,{content:r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"tide-tooltip__title",children:["🔄 ",t("terminal:empty.reattachingSessionTitle")]}),r.jsxs("div",{className:"tide-tooltip__text",children:[t("terminal:empty.reattachingSessionDesc"),r.jsx("br",{}),r.jsx("br",{}),r.jsxs("strong",{children:[t("common:labels.status"),":"]})," ",t("terminal:empty.reattachingSessionStatus")]})]}),position:"top",className:"tide-tooltip--detached",children:r.jsxs("span",{className:"guake-detached-badge",title:t("terminal:empty.reattachingBadge"),children:[r.jsx("span",{className:"guake-detached-spinner",children:"🔄"})," ",t("terminal:empty.reattaching")]})}),(C==null?void 0:C.cwd)&&r.jsxs("span",{className:"guake-agent-cwd",children:["📁 ",C.cwd.split("/").filter(Boolean).slice(-2).join("/")||C.cwd]}),L&&L.directories.map(We=>r.jsxs("span",{className:"guake-agent-area-dir",title:We,onClick:()=>z.openFileExplorerForAreaFolder(L.id,We),children:["📂 ",We.split("/").filter(Boolean).pop()||We]},We)),!b&&C&&(()=>{const We=C.contextStats,ot=!!We,Ct=We?We.totalTokens:C.contextUsed||0,Et=We?We.contextWindow:C.contextLimit||2e5,_t=We?We.usedPercent:Math.round(Ct/Et*100),zt=Math.round(100-_t),Pt=_t>=80?"#ff4a4a":_t>=60?"#ff9e4a":_t>=40?"#ffd700":"#4aff9e",Xt=(Ct/1e3).toFixed(1),Wt=(Et/1e3).toFixed(1);return r.jsxs("span",{className:"guake-agent-context",onClick:()=>z.setContextModalAgentId(N),title:t(ot?"terminal:context.clickToViewStats":"terminal:context.clickToFetchStats"),children:[r.jsx("span",{className:"context-icon",children:"📊"}),r.jsxs("span",{className:"context-label",children:[t("terminal:agentInfo.context"),":"]}),r.jsx("span",{className:"context-bar-mini",children:r.jsx("span",{className:"context-bar-mini-fill",style:{width:`${Math.min(100,_t)}%`,backgroundColor:Pt}})}),r.jsxs("span",{className:"context-tokens",style:{color:Pt},children:[Xt,"k/",Wt,"k"]}),r.jsxs("span",{className:"context-free",children:["(",t("terminal:context.percentFree",{percent:zt}),")"]}),!ot&&r.jsx("span",{className:"context-warning",title:t("terminal:context.clickToFetchStats"),children:"⚠️"})]})})(),r.jsx(mU,{})]})]}),me&&r.jsx("div",{className:"guake-resize-handle",onMouseDown:E,title:t("common:rightPanel.dragToResize")}),r.jsxs("div",{className:"guake-handle",onClick:()=>{me&&z.toggleTerminal()},onDoubleClick:()=>{me||z.toggleTerminal()},style:{top:me?`min(${M}%, calc(100vh - 72px))`:"0"},children:[r.jsx("span",{className:"guake-handle-icon",children:me?"▲":"▼"}),r.jsx("span",{className:"guake-handle-text",children:C.name})]}),X&&r.jsx(kE,{url:X.url,name:X.name,onClose:()=>H(null)}),se&&r.jsx(SE,{state:se,onClose:()=>ce(null)}),F&&r.jsx(xH,{action:F,selectedAgentId:N,subordinateCount:((rn=C==null?void 0:C.subordinateIds)==null?void 0:rn.length)||0,onClose:()=>V(null),onClearHistory:pe.clearHistory}),r.jsx(vH,{}),r.jsx(wH,{}),r.jsx(kH,{agent:C,isOpen:Q,onClose:()=>Z(!1)}),!b&&r.jsx(jE,{agent:C,content:J,onClose:()=>ie(null)})]})});function xU(s){return s.trim().replace(/^v/i,"")}function U1(s){const t=xU(s).match(/^(\d+(?:\.\d+)*)(?:-([0-9A-Za-z.-]+))?/);if(!t)return null;const n=t[1].split(".").map(i=>Number.parseInt(i,10));if(n.some(Number.isNaN))return null;const a=t[2]?t[2].split("."):[];return{core:n,prerelease:a}}function vU(s,e){if(s.length===0&&e.length===0)return 0;if(s.length===0)return 1;if(e.length===0)return-1;const t=Math.max(s.length,e.length);for(let n=0;n<t;n+=1){const a=s[n],i=e[n];if(a===void 0)return-1;if(i===void 0)return 1;const o=/^\d+$/.test(a)?Number.parseInt(a,10):null,l=/^\d+$/.test(i)?Number.parseInt(i,10):null;if(o!==null&&l!==null){if(o>l)return 1;if(o<l)return-1;continue}if(o!==null)return-1;if(l!==null)return 1;const c=a.localeCompare(i);if(c!==0)return c>0?1:-1}return 0}function wU(s,e){const t=U1(s),n=U1(e);if(!t||!n)return null;const a=Math.max(t.core.length,n.core.length);for(let i=0;i<a;i+=1){const o=t.core[i]??0,l=n.core[i]??0;if(o>l)return 1;if(o<l)return-1}return vU(t.prerelease,n.prerelease)}function kU(s,e){const t=wU(s,e);return t===null?"unknown":t<0?"behind":t>0?"ahead":"equal"}async function SU(s,e={}){const{timeoutMs:t=5e3,fetchImpl:n=fetch}=e;try{const a=new AbortController,i=setTimeout(()=>a.abort(),t),o=Date.now(),l=await n(`https://registry.npmjs.org/${encodeURIComponent(s)}/latest?t=${o}`,{signal:a.signal,headers:{Accept:"application/json"}});if(clearTimeout(i),!l.ok)return null;const c=await l.json();return typeof c.version=="string"?c.version:null}catch{return null}}async function jU(s,e,t={}){const n=await SU(s,t);return n?{currentVersion:e,latestVersion:n,relation:kU(e,n)}:{currentVersion:e,latestVersion:null,relation:"unknown"}}const CU="tide-commander",Ib="0.84.1";function NU(){const[s,e]=y.useState({currentVersion:Ib,latestVersion:null,relation:"unknown",isChecking:!1}),t=y.useCallback(async()=>{e(a=>({...a,isChecking:!0}));const n=await jU(CU,Ib);e({currentVersion:Ib,latestVersion:n.latestVersion,relation:n.relation,isChecking:!1})},[]);return y.useEffect(()=>{t()},[t]),{...s,refresh:t}}const AU=y.memo(function({agent:e,currentIndex:t,agentIndex:n,isTouchInput:a,isTouchDragEnabled:i,isSelected:o,hasUnseenOutput:l,isDragging:c,isDragOver:d,customClasses:m,onDragStart:p,onDragEnd:f,onDragOver:b,onDragEnter:x,onDragLeave:w,onDrop:k,onAgentClick:S,onAgentDoubleClick:j,onTouchStart:C,onTouchMove:N,onTouchEnd:P,onTouchCancel:_,onHoverEnter:L,onHoverLeave:M,onItemRef:D}){const E=y.useMemo(()=>go(e.class,m),[e.class,m]),R=!a||i,O=y.useCallback(I=>{D(e.id,I)},[e.id,D]);return r.jsxs("div",{ref:O,className:`agent-bar-item ${o?"selected":""} ${e.status} ${e.isBoss?"is-boss":""} ${c?"dragging":""} ${d?"drag-over":""} ${i?"touch-drag-enabled":""}`,draggable:R,onDragStart:I=>p(I,e),onDragEnd:f,onDragOver:I=>b(I,n),onDragEnter:I=>x(I,n),onDragLeave:w,onDrop:I=>k(I,n),onTouchStart:I=>C(I,e.id),onTouchMove:N,onTouchEnd:P,onTouchCancel:_,onClick:I=>S(e,I),onDoubleClick:()=>j(e),onMouseEnter:()=>L(e),onMouseLeave:M,title:a?`${e.name} (${t+1}) - Long press to reorder`:`${e.name} (${t+1}) - Drag to reorder within group`,children:[r.jsxs("div",{className:"agent-bar-avatar",children:[r.jsx("span",{className:"agent-bar-icon",children:E.icon}),r.jsx("span",{className:"agent-bar-status",style:{backgroundColor:wx(e.status)}}),l&&r.jsx("span",{className:"agent-bar-notification-badge",title:"New output available - click to view"}),e.status==="idle"&&e.lastActivity>0&&r.jsx("span",{className:"agent-bar-idle-clock",style:{color:fm(e.lastActivity)},title:gm(e.lastActivity),children:"⏱"})]}),r.jsxs("span",{className:"agent-bar-hotkey",title:`Ctrl+${t+1}`,children:["^",t+1]})]})}),MU=y.memo(function({onFocusAgent:e,onSpawnClick:t,onSpawnBossClick:n,onNewBuildingClick:a,onNewAreaClick:i}){const{t:o}=$e(["common"]),l=fi(),c=mo(),d=wm(),m=zz(),p=Bx(),f=fo(),b=gi(),x=Ux(),[w,k]=y.useState(!1);bM("AgentBar");const S=y.useRef(null),j=y.useRef(null),C=y.useRef(null),N=y.useRef(new Map);y.useEffect(()=>{{k(!1);return}},[f.experimental2DView]),y.useEffect(()=>{const Ee=j.current;if(!Ee)return;const Ye=tt=>{Ee.scrollWidth<=Ee.clientWidth||(tt.preventDefault(),Ee.scrollLeft+=tt.deltaY)};return Ee.addEventListener("wheel",Ye,{passive:!1}),()=>Ee.removeEventListener("wheel",Ye)},[]);const[P,_]=y.useState(null),[L,M]=y.useState(new Map),[D,E]=y.useState(null),[R,O]=y.useState(null),I=y.useRef(0),[B,Y]=y.useState(null),$=y.useRef(null),W=y.useRef(null),K=y.useRef(null),X=y.useRef(null),H=350,se=8,ce=y.useMemo(()=>typeof window>"u"?!1:"ontouchstart"in window||window.matchMedia("(pointer: coarse)").matches,[]),F=y.useMemo(()=>Array.from(l.values()).filter(Ee=>!z.isAgentInArchivedArea(Ee.id)).sort((Ee,Ye)=>(Ee.createdAt||0)-(Ye.createdAt||0)),[l,c]),{orderedAgents:V,moveAgent:J}=zM(F),ie=V,Q=y.useMemo(()=>{const Ee=new Map;for(const Ye of ie)Ee.set(Ye.id,z.getAreaForAgent(Ye.id));return Ee},[ie,c]),Z=y.useMemo(()=>{const Ee=new Map;for(const tt of ie){const it=Q.get(tt.id)||null,ft=(it==null?void 0:it.id)||null;Ee.has(ft)||Ee.set(ft,{area:it,agents:[]}),Ee.get(ft).agents.push(tt)}const Ye=Array.from(Ee.values());return Ye.sort((tt,it)=>{var ft,ut;return!tt.area&&it.area?1:tt.area&&!it.area?-1:!tt.area&&!it.area?0:(((ft=tt.area)==null?void 0:ft.name)||"").localeCompare(((ut=it.area)==null?void 0:ut.name)||"")}),Ye},[ie,Q]),G=y.useRef(e);G.current=e;const re=y.useRef(D);re.current=D;const ue=y.useRef(ie);ue.current=ie;const be=y.useRef(Q);be.current=Q;const ve=y.useRef(J);ve.current=J,y.useEffect(()=>{const Ee=new Map(L);let Ye=!1;for(const tt of ie){const it=L.get(tt.id);tt.currentTool?(!it||it.tool!==tt.currentTool)&&(Ee.set(tt.id,{tool:tt.currentTool,key:Date.now()}),Ye=!0):it&&setTimeout(()=>{M(ft=>{const ut=new Map(ft);return ut.delete(tt.id),ut})},1500)}Ye&&M(Ee)},[ie.map(Ee=>Ee.currentTool).join(",")]),y.useEffect(()=>{const Ee=m;if(!Ee)return;const Ye=N.current.get(Ee),tt=j.current;Ye&&tt&&requestAnimationFrame(()=>{const it=Ye.getBoundingClientRect(),ft=tt.getBoundingClientRect(),ae=it.left-ft.left+tt.scrollLeft+it.width/2,Ne=tt.clientWidth;tt.scrollTo({left:ae-Ne/2,behavior:"smooth"})})},[m]);const ge=y.useCallback((Ee,Ye)=>{if(K.current===Ee.id){K.current=null,Ye.preventDefault(),Ye.stopPropagation();return}z.setLastSelectionViaDirectClick(!0),Ye.shiftKey?z.addToSelection(Ee.id):z.selectAgent(Ee.id),z.setTerminalOpen(!0)},[]),_e=y.useCallback(Ee=>{var Ye;(Ye=G.current)==null||Ye.call(G,Ee.id),z.setTerminalOpen(!0)},[]),Le=y.useCallback(()=>_(null),[]),ke=y.useCallback((Ee,Ye)=>{Ye?N.current.set(Ee,Ye):N.current.delete(Ee)},[]),ne=y.useCallback((Ee,Ye)=>{E(Ye),Y(Ye.id),Ee.dataTransfer.effectAllowed="move",Ee.dataTransfer.setData("text/plain",Ye.id),requestAnimationFrame(()=>{Ee.target.classList.add("dragging")})},[]),de=y.useCallback(Ee=>{E(null),O(null),Y(null),I.current=0,Ee.target.classList.remove("dragging")},[]),le=y.useCallback((Ee,Ye)=>{Ee.preventDefault();const tt=re.current;if(tt){const it=be.current.get(tt.id),ft=ue.current[Ye],ut=ft?be.current.get(ft.id):null,ae=(it==null?void 0:it.id)??null,Ne=(ut==null?void 0:ut.id)??null;Ee.dataTransfer.dropEffect=ae===Ne?"move":"none"}else Ee.dataTransfer.dropEffect="move"},[]),oe=y.useCallback((Ee,Ye)=>{Ee.preventDefault(),I.current++;const tt=re.current;if(tt){const it=be.current.get(tt.id),ft=ue.current[Ye],ut=ft?be.current.get(ft.id):null,ae=(it==null?void 0:it.id)??null,Ne=(ut==null?void 0:ut.id)??null;O(ae===Ne?Ye:null)}else O(Ye)},[]),he=y.useCallback(Ee=>{I.current--,I.current===0&&O(null)},[]),Ce=y.useCallback((Ee,Ye)=>{Ee.preventDefault();const tt=re.current;if(!tt)return;const it=ue.current,ft=be.current,ut=it.findIndex(ae=>ae.id===tt.id);if(ut!==-1&&ut!==Ye){const ae=ft.get(tt.id),Ne=it[Ye],Ge=Ne?ft.get(Ne.id):null,at=(ae==null?void 0:ae.id)??null,ht=(Ge==null?void 0:Ge.id)??null;at===ht&&ve.current(ut,Ye)}E(null),O(null),Y(null),I.current=0},[]),xe=y.useCallback(()=>{$.current&&(clearTimeout($.current),$.current=null)},[]),Ze=y.useCallback(()=>{X.current&&(clearTimeout(X.current),X.current=null)},[]),ye=y.useCallback((Ee,Ye)=>{if(!ce||Ee.touches.length!==1)return;xe(),Ze(),Y(null);const tt=Ee.touches[0];W.current={agentId:Ye,x:tt.clientX,y:tt.clientY},$.current=setTimeout(()=>{Y(Ye),K.current=Ye,$.current=null},H)},[xe,Ze,ce]),Se=y.useCallback(Ee=>{if(!ce||Ee.touches.length!==1)return;const Ye=W.current;if(!Ye||!$.current)return;const tt=Ee.touches[0],it=tt.clientX-Ye.x,ft=tt.clientY-Ye.y;Math.sqrt(it*it+ft*ft)>se&&(xe(),W.current=null)},[xe,ce]),qe=y.useCallback(()=>{xe(),W.current=null,re.current||Y(null),Ze(),X.current=setTimeout(()=>{K.current=null,X.current=null},450)},[xe,Ze]);y.useEffect(()=>()=>{xe(),Ze()},[xe,Ze]);const ee=Ee=>{const Ye=`common:status.${Ee}`;return o(Ye,{defaultValue:o("common:status.unknown")})},{currentVersion:me,latestVersion:pe,relation:Oe,isChecking:Je}=NU(),Fe=me;let kt=0;return r.jsxs("div",{className:"agent-bar",ref:S,children:[r.jsxs("div",{className:"agent-bar-scroll",ref:j,children:[r.jsxs("div",{className:"agent-bar-version",title:pe?`Tide Commander v${Fe} (npm: v${pe})`:`Tide Commander v${Fe}`,children:[r.jsxs("span",{children:["v",Fe]}),Oe==="behind"&&pe?r.jsxs("span",{className:"agent-bar-version-badge agent-bar-version-badge-behind",title:`Behind npm latest v${pe}`,children:["npm v",pe]}):Oe==="ahead"&&pe?r.jsxs("span",{className:"agent-bar-version-badge agent-bar-version-badge-ahead",title:`Ahead of npm latest v${pe}`,children:["npm v",pe]}):null,Oe==="behind"?r.jsx("a",{href:"https://github.com/deivid11/tide-commander/releases",target:"_blank",rel:"noopener noreferrer",className:"agent-bar-version-status agent-bar-version-status-behind",title:o("common:agentBar.behindNpmTooltip",{defaultValue:"Current version is behind npm latest"}),children:o("common:agentBar.behindNpm",{defaultValue:"(behind npm)"})}):Oe==="ahead"?r.jsx("span",{className:"agent-bar-version-status agent-bar-version-status-ahead",title:o("common:agentBar.aheadNpmTooltip",{defaultValue:"Current version is newer than npm latest"}),children:o("common:agentBar.aheadNpm",{defaultValue:"(ahead of npm)"})}):Oe==="equal"?r.jsx("a",{href:"https://github.com/deivid11/tide-commander/releases",target:"_blank",rel:"noopener noreferrer",className:"agent-bar-version-status",children:o("common:agentBar.updated")}):Je?r.jsx("span",{className:"agent-bar-version-status",children:o("common:agentBar.checkingNpm",{defaultValue:"(checking npm)"})}):r.jsx("span",{className:"agent-bar-version-status",children:o("common:agentBar.unknownNpm",{defaultValue:"(npm unknown)"})}),w&&r.jsx("button",{className:"agent-bar-hmr-refresh",onClick:BM,title:"Refresh 3D Scene (HMR changes pending)",children:"↻"})]}),r.jsxs("div",{className:"agent-bar-list",ref:C,children:[r.jsxs("button",{className:"agent-bar-spawn-btn",onClick:t,title:o("common:agentBar.spawnNewAgent"),children:[r.jsx("span",{className:"agent-bar-spawn-icon",children:"+"}),r.jsx("span",{className:"agent-bar-spawn-label",children:o("common:agentBar.newAgent")})]}),r.jsxs("button",{className:"agent-bar-spawn-btn agent-bar-boss-btn",onClick:n,title:o("common:agentBar.spawnBoss"),children:[r.jsx("span",{className:"agent-bar-spawn-icon",children:"👑"}),r.jsx("span",{className:"agent-bar-spawn-label",children:o("common:agentBar.newBoss")})]}),r.jsxs("button",{className:"agent-bar-spawn-btn agent-bar-building-btn",onClick:a,title:o("common:agentBar.addNewBuilding"),children:[r.jsx("span",{className:"agent-bar-spawn-icon",children:"🏢"}),r.jsx("span",{className:"agent-bar-spawn-label",children:o("common:agentBar.newBuilding")})]}),r.jsxs("button",{className:"agent-bar-spawn-btn agent-bar-area-btn",onClick:i,title:o("common:agentBar.drawNewArea"),children:[r.jsx("span",{className:"agent-bar-spawn-icon",children:"🔲"}),r.jsx("span",{className:"agent-bar-spawn-label",children:o("common:agentBar.newArea")})]}),Z.map(Ee=>{var it,ft,ut,ae,Ne;const Ye=Ee.agents,tt=!Ee.area;return r.jsxs("div",{className:`agent-bar-group ${tt?"unassigned":""}`,style:{borderColor:((it=Ee.area)==null?void 0:it.color)||void 0,background:Ee.area?`${Ee.area.color}15`:void 0},children:[r.jsx("div",{className:"agent-bar-area-label",children:r.jsx("span",{className:"agent-bar-area-name",style:{color:((ft=Ee.area)==null?void 0:ft.color)||"#888"},children:((ut=Ee.area)==null?void 0:ut.name)||o("common:agentBar.unassigned")})}),((ae=Ee.area)==null?void 0:ae.directories)&&Ee.area.directories.length>0&&r.jsx("div",{className:"agent-bar-folders",children:Ee.area.directories.map((Ge,at)=>r.jsxs("div",{className:"agent-bar-folder-item",onClick:ht=>{ht.stopPropagation(),z.openFileExplorer(Ge)},children:[r.jsx("span",{className:"agent-bar-folder-icon",children:"📁"}),r.jsxs("div",{className:"agent-bar-folder-tooltip",children:[r.jsx("div",{className:"agent-bar-folder-tooltip-path",children:Ge}),r.jsx("div",{className:"agent-bar-folder-tooltip-hint",children:o("common:agentBar.clickToOpen")})]})]},at))}),Ye.map(Ge=>{const at=kt++,ht=ie.findIndex($t=>$t.id===Ge.id);return r.jsx(AU,{agent:Ge,currentIndex:at,agentIndex:ht,isTouchInput:ce,isTouchDragEnabled:B===Ge.id,isSelected:d.has(Ge.id),hasUnseenOutput:x.has(Ge.id),isDragging:(D==null?void 0:D.id)===Ge.id,isDragOver:R===ht,customClasses:b,onDragStart:ne,onDragEnd:de,onDragOver:le,onDragEnter:oe,onDragLeave:he,onDrop:Ce,onAgentClick:ge,onAgentDoubleClick:_e,onTouchStart:ye,onTouchMove:Se,onTouchEnd:qe,onTouchCancel:qe,onHoverEnter:_,onHoverLeave:Le,onItemRef:ke},Ge.id)})]},((Ne=Ee.area)==null?void 0:Ne.id)||"unassigned")})]})]}),Array.from(L.entries()).map(([Ee,Ye])=>{const tt=N.current.get(Ee);if(!tt)return null;const it=tt.getBoundingClientRect(),ft=ls[Ye.tool]||ls.default;return r.jsxs("div",{className:"agent-bar-tool-bubble",title:Ye.tool,style:{position:"fixed",left:it.left+it.width/2,bottom:window.innerHeight-it.top+8},children:[r.jsx("span",{className:"agent-bar-tool-icon",children:ft}),r.jsx("span",{className:"agent-bar-tool-name",children:Ye.tool})]},`tool-${Ee}-${Ye.key}`)}),P&&(()=>{const Ee=z.getAreaForAgent(P.id),Ye=p.get(P.id),tt=go(P.class,b),it=z.getAgentSupervisorHistory(P.id),ft=it.length>0?it[it.length-1]:void 0,ut=Date.now()-(P.createdAt||Date.now()),ae=Math.floor(ut/6e4),Ne=Math.floor(ae/60),Ge=Ne>0?`${Ne}h ${ae%60}m`:`${ae}m`,at=It=>It>=1e6?`${(It/1e6).toFixed(1)}M`:It>=1e3?`${(It/1e3).toFixed(1)}K`:It.toString(),ht=P.contextLimit>0?Math.round(P.contextUsed/P.contextLimit*100):0,$t=It=>{switch(It){case"on_track":return"#4aff9e";case"completed":return"#4a9eff";case"stalled":return"#ff9e4a";case"blocked":return"#ff4a4a";case"idle":return"#888888";default:return"#888888"}},Vt=N.current.get(P.id),jt={};if(Vt){const It=Vt.getBoundingClientRect();jt.position="fixed",jt.left=It.left+It.width/2,jt.bottom=window.innerHeight-It.top+12}return r.jsxs("div",{className:"agent-bar-tooltip",style:jt,children:[r.jsxs("div",{className:"agent-bar-tooltip-header",children:[r.jsx("span",{className:"agent-bar-tooltip-icon",children:tt.icon}),r.jsxs("span",{className:"agent-bar-tooltip-name",children:[r.jsx("img",{src:P.provider==="codex"?"/assets/codex.png":"/assets/claude.png",alt:P.provider,className:"agent-bar-provider-icon",title:P.provider==="codex"?"Codex Agent":"Claude Agent"}),P.name]}),r.jsx("span",{className:"agent-bar-tooltip-status",style:{color:wx(P.status)},children:ee(P.status)})]}),r.jsxs("div",{className:"agent-bar-tooltip-info",children:[r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[o("common:labels.class"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value",children:[P.class," — ",tt.description]})]}),Ee&&r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[o("common:agentPopup.area"),":"]}),r.jsx("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-area",style:{color:Ee.color},children:Ee.name})]}),r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[o("common:agentPopup.directory"),":"]}),r.jsx("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-path",children:P.cwd})]}),r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[o("common:labels.uptime"),":"]}),r.jsx("span",{className:"agent-bar-tooltip-value",children:Ge})]}),r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[o("common:labels.tokens"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value",children:[at(P.tokensUsed)," ",o("common:agentPopup.used")]})]}),r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[o("common:labels.context"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value",style:{color:ht>80?"#ff4a4a":ht>60?"#ff9e4a":void 0},children:[at(P.contextUsed)," / ",at(P.contextLimit)," (",ht,"%)"]})]}),P.currentTool&&r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[o("common:agentPopup.tool"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-tool",children:[ls[P.currentTool]||ls.default," ",P.currentTool]})]}),P.taskLabel&&r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsx("span",{className:"agent-bar-tooltip-label",children:"📋 Task:"}),r.jsx("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-tool",children:P.taskLabel})]}),P.currentTask&&r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[o("common:labels.task"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value",children:[P.currentTask.substring(0,150),P.currentTask.length>150?"...":""]})]}),P.lastAssignedTask&&!P.currentTask&&r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[o("common:agentPopup.assignedTask"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-query",children:[P.lastAssignedTask.substring(0,200),P.lastAssignedTask.length>200?"...":""]})]}),Ye&&r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[o("common:agentPopup.lastQuery"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-query",children:[Ye.text.substring(0,300),Ye.text.length>300?"...":""]})]}),ft&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"agent-bar-tooltip-divider"}),r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[o("common:agentPopup.supervisor"),":"]}),r.jsx("span",{className:"agent-bar-tooltip-value",style:{color:$t(ft.analysis.progress)},children:ft.analysis.progress.replace("_"," ")})]}),r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[o("common:labels.status"),":"]}),r.jsx("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-supervisor",children:ft.analysis.statusDescription})]}),ft.analysis.recentWorkSummary&&r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[o("common:labels.summary"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-supervisor",children:[ft.analysis.recentWorkSummary.substring(0,300),ft.analysis.recentWorkSummary.length>300?"...":""]})]}),ft.analysis.concerns&&ft.analysis.concerns.length>0&&r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[o("common:labels.concerns"),":"]}),r.jsx("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-concerns",children:ft.analysis.concerns.join("; ")})]})]})]})]})})()]})});function TU({activeTool:s,onExit:e}){const{t}=$e(["notifications","terminal"]);if(!s||s==="select")return null;const n=t(s==="rectangle"?"notifications:drawing.rectangleTool":"notifications:drawing.circleTool"),a=s==="rectangle"?"▭":"○";return r.jsxs("div",{className:"drawing-mode-indicator",children:[r.jsxs("div",{className:"drawing-mode-content",children:[r.jsx("span",{className:"drawing-mode-icon",children:a}),r.jsxs("div",{className:"drawing-mode-text",children:[r.jsxs("span",{className:"drawing-mode-title",children:[t("terminal:drawingMode.drawingArea"),": ",n]}),r.jsxs("span",{className:"drawing-mode-hint",children:[t("terminal:drawingMode.clickAndDrag")," • ",t("terminal:drawingMode.pressEscape")]})]})]}),r.jsx("button",{className:"drawing-mode-exit",onClick:e,title:t("terminal:drawingMode.exitDrawingMode"),children:"✕"})]})}const EU={idle:"common:status.idle",working:"common:status.working",waiting:"common:status.waiting",error:"common:status.error",offline:"common:status.offline"},Bb=s=>s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(1)}K`:s.toString(),_U=s=>{switch(s){case"on_track":return"#4aff9e";case"completed":return"#4a9eff";case"stalled":return"#ff9e4a";case"blocked":return"#ff4a4a";case"idle":return"#888888";default:return"#888888"}},DU=y.memo(function({agent:e,screenPos:t,onClose:n}){const{t:a}=$e(["common"]),i=gi(),o=z.getAreaForAgent(e.id),l=z.getState().lastPrompts.get(e.id),c=go(e.class,i),d=z.getAgentSupervisorHistory(e.id),m=d.length>0?d[d.length-1]:void 0,p=Date.now()-(e.createdAt||Date.now()),f=Math.floor(p/6e4),b=Math.floor(f/60),x=b>0?`${b}h ${f%60}m`:`${f}m`,w=e.contextLimit>0?Math.round(e.contextUsed/e.contextLimit*100):0,k=y.useMemo(()=>{let C=t.x-150,N=t.y-320-10;return typeof window<"u"&&(C<10?C=10:C+300>window.innerWidth-10&&(C=window.innerWidth-300-10),N<10&&(N=t.y+10)),{position:"fixed",left:C,top:N,zIndex:1e4,maxWidth:300,maxHeight:320,fontSize:"0.85em"}},[t.x,t.y]);return r.jsxs("div",{className:"agent-hover-popup",style:k,onMouseLeave:n,children:[r.jsxs("div",{className:"agent-bar-tooltip-header",children:[r.jsx("span",{className:"agent-bar-tooltip-icon",children:c.icon}),r.jsx("span",{className:"agent-bar-tooltip-name",children:e.name}),r.jsx("span",{className:"agent-bar-tooltip-status",style:{color:wx(e.status)},children:a(EU[e.status]||"common:status.unknown")})]}),r.jsxs("div",{className:"agent-bar-tooltip-info",children:[r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:labels.class"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value",children:[e.class," — ",c.description]})]}),o&&r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:agentPopup.area"),":"]}),r.jsx("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-area",style:{color:o.color},children:o.name})]}),r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:agentPopup.directory"),":"]}),r.jsx("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-path",children:e.cwd})]}),r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:labels.uptime"),":"]}),r.jsx("span",{className:"agent-bar-tooltip-value",children:x})]}),r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:labels.tokens"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value",children:[Bb(e.tokensUsed)," ",a("common:agentPopup.used")]})]}),r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:labels.context"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value",style:{color:w>80?"#ff4a4a":w>60?"#ff9e4a":void 0},children:[Bb(e.contextUsed)," / ",Bb(e.contextLimit)," (",w,"%)"]})]}),e.currentTool&&r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:agentPopup.tool"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-tool",children:[ls[e.currentTool]||ls.default," ",e.currentTool]})]}),e.currentTask&&r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:labels.task"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value",children:[e.currentTask.substring(0,150),e.currentTask.length>150?"...":""]})]}),e.lastAssignedTask&&!e.currentTask&&r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:agentPopup.assignedTask"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-query",children:[e.lastAssignedTask.substring(0,200),e.lastAssignedTask.length>200?"...":""]})]}),l&&r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:agentPopup.lastQuery"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-query",children:[l.text.substring(0,300),l.text.length>300?"...":""]})]}),m&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"agent-bar-tooltip-divider"}),r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:agentPopup.supervisor"),":"]}),r.jsx("span",{className:"agent-bar-tooltip-value",style:{color:_U(m.analysis.progress)},children:m.analysis.progress.replace("_"," ")})]}),r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:labels.status"),":"]}),r.jsx("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-supervisor",children:m.analysis.statusDescription})]}),m.analysis.recentWorkSummary&&r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:labels.summary"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-supervisor",children:[m.analysis.recentWorkSummary.substring(0,300),m.analysis.recentWorkSummary.length>300?"...":""]})]}),m.analysis.concerns&&m.analysis.concerns.length>0&&r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:labels.concerns"),":"]}),r.jsx("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-concerns",children:m.analysis.concerns.join("; ")})]})]})]})]})});function G1(s){if(s===0)return"0 B";const e=1024,t=["B","KB","MB","GB"],n=Math.floor(Math.log(s)/Math.log(e));return parseFloat((s/Math.pow(e,n)).toFixed(1))+" "+t[n]}function W1(s){const t=Date.now()-s,n=Math.floor(t/(1e3*60*60)),a=Math.floor(t%(1e3*60*60)/(1e3*60));return n>0?`${n}h ${a}m`:`${a}m`}const q1={30:"#1a1a1a",31:"#e74c3c",32:"#2ecc71",33:"#f39c12",34:"#3498db",35:"#9b59b6",36:"#00bcd4",37:"#ecf0f1",90:"#7f8c8d",91:"#ff6b6b",92:"#4ade80",93:"#fbbf24",94:"#60a5fa",95:"#c084fc",96:"#22d3ee",97:"#ffffff"};function PU(s){const e=[],t=/\x1B\[([0-9;]*)m/g;let n=0,a=null,i;for(;(i=t.exec(s))!==null;){if(i.index>n){const l=s.slice(n,i.index);a?e.push(r.jsx("span",{style:{color:a},children:l},e.length)):e.push(l)}const o=i[1].split(";").map(Number);for(const l of o)l===0||l===39?a=null:q1[l]&&(a=q1[l]);n=t.lastIndex}if(n<s.length){const o=s.slice(n);a?e.push(r.jsx("span",{style:{color:a},children:o},e.length)):e.push(o)}return e.length>0?e:[s]}const RU=y.memo(function({building:e,screenPos:t,onClose:n,onOpenSettings:a,onOpenLogsModal:i,onOpenUrlInModal:o}){var $,W,K,X,H,se,ce,F,V,J,ie,Q,Z,G,re,ue,be,ve,ge,_e;const{t:l}=$e(["terminal","common"]),[c,d]=y.useState(!1),[m,p]=y.useState(null),[f,b]=y.useState(!1),x=y.useRef(null),w=y.useRef(m);w.current=m;const{buildingLogs:k}=qn(),S=z.getBuildingLogs(e.id),j=($=e.pm2)==null?void 0:$.enabled,C=(W=e.docker)==null?void 0:W.enabled,N=y.useRef(null),P=y.useRef(null),_=y.useCallback(Le=>{Le.preventDefault();const ke=w.current?w.current.x:0,ne=w.current?w.current.y:0;x.current={mouseX:Le.clientX,mouseY:Le.clientY,popupX:ke,popupY:ne},b(!0),N.current=de=>{if(!x.current)return;const le=de.clientX-x.current.mouseX,oe=de.clientY-x.current.mouseY;p({x:x.current.popupX+le,y:x.current.popupY+oe})},P.current=()=>{b(!1),x.current=null,N.current&&document.removeEventListener("mousemove",N.current),P.current&&document.removeEventListener("mouseup",P.current)},document.addEventListener("mousemove",N.current),document.addEventListener("mouseup",P.current)},[]);y.useEffect(()=>()=>{N.current&&document.removeEventListener("mousemove",N.current),P.current&&document.removeEventListener("mouseup",P.current)},[]);const L=Le=>{if(Le==="logs"){if((j||C)&&i){i();return}z.sendBuildingCommand(e.id,Le),d(!0)}else z.sendBuildingCommand(e.id,Le)},M=(Le,ke)=>{if(Le){const ne=`http://localhost:${Le}`;ke&&o?o(ne):window.open(ne,"_blank")}},D=((K=e.pm2Status)==null?void 0:K.ports)||[],E=((H=(X=e.dockerStatus)==null?void 0:X.ports)==null?void 0:H.map(Le=>Le.host))||[],R=j?D:C?E:[],O=j?!!((se=e.pm2)!=null&&se.script):C?!!((ce=e.docker)!=null&&ce.image)||((F=e.docker)==null?void 0:F.mode)==="compose"||((V=e.docker)==null?void 0:V.mode)==="existing":!!((J=e.commands)!=null&&J.start),I=j?!!((ie=e.pm2)!=null&&ie.script):C?!0:!!((Q=e.commands)!=null&&Q.stop),B=j?!!((Z=e.pm2)!=null&&Z.script):C?!0:!!((G=e.commands)!=null&&G.restart),Y=y.useMemo(()=>{const ke=c?400:250;let ne=t.x+20,de=t.y-80;return typeof window<"u"&&!m&&(t.x+20+280>window.innerWidth&&(ne=t.x-280-20),t.y-80<0?de=10:t.y-80+ke>window.innerHeight&&(de=window.innerHeight-ke-10)),{position:"fixed",left:ne+((m==null?void 0:m.x)||0),top:de+((m==null?void 0:m.y)||0),zIndex:1e3,cursor:f?"grabbing":void 0}},[t.x,t.y,c,m,f]);return r.jsxs("div",{className:"building-action-popup",style:Y,onClick:Le=>Le.stopPropagation(),children:[r.jsxs("div",{className:`building-popup-header ${f?"dragging":""}`,onMouseDown:_,children:[r.jsx("span",{className:"building-popup-name",children:e.name}),R.length>0&&r.jsx("span",{className:"building-popup-ports",children:R.map(Le=>r.jsxs("a",{href:`http://localhost:${Le}`,className:"building-popup-port-link",onClick:ke=>{ke.preventDefault(),ke.stopPropagation(),M(Le,ke.altKey)},onMouseDown:ke=>ke.stopPropagation(),title:`Open http://localhost:${Le} (Alt+Click for modal)`,children:[":",Le]},Le))}),r.jsx("span",{className:"building-popup-status",style:{backgroundColor:co[e.status]},children:e.status}),r.jsx("button",{className:"building-popup-close",onClick:n,children:"x"})]}),j&&e.pm2Status&&r.jsxs("div",{className:"building-popup-metrics",children:[r.jsxs("span",{className:"metric",children:[r.jsx("span",{className:"label",children:"PID"}),r.jsx("span",{className:"value",children:e.pm2Status.pid||"-"})]}),r.jsxs("span",{className:"metric",children:[r.jsx("span",{className:"label",children:"CPU"}),r.jsxs("span",{className:"value",children:[((re=e.pm2Status.cpu)==null?void 0:re.toFixed(1))||"0","%"]})]}),r.jsxs("span",{className:"metric",children:[r.jsx("span",{className:"label",children:"MEM"}),r.jsx("span",{className:"value",children:G1(e.pm2Status.memory||0)})]}),e.pm2Status.restarts!==void 0&&e.pm2Status.restarts>0&&r.jsxs("span",{className:"metric",children:[r.jsx("span",{className:"label",children:"RST"}),r.jsx("span",{className:"value",children:e.pm2Status.restarts})]}),e.pm2Status.uptime&&r.jsxs("span",{className:"metric",children:[r.jsx("span",{className:"label",children:"UP"}),r.jsx("span",{className:"value",children:W1(e.pm2Status.uptime)})]})]}),C&&e.dockerStatus&&r.jsxs("div",{className:"building-popup-metrics",children:[r.jsxs("span",{className:"metric",children:[r.jsx("span",{className:"label",children:"ID"}),r.jsx("span",{className:"value",children:e.dockerStatus.containerId||"-"})]}),e.dockerStatus.cpu!==void 0&&r.jsxs("span",{className:"metric",children:[r.jsx("span",{className:"label",children:"CPU"}),r.jsxs("span",{className:"value",children:[e.dockerStatus.cpu.toFixed(1),"%"]})]}),e.dockerStatus.memory!==void 0&&r.jsxs("span",{className:"metric",children:[r.jsx("span",{className:"label",children:"MEM"}),r.jsx("span",{className:"value",children:G1(e.dockerStatus.memory)})]}),e.dockerStatus.health&&e.dockerStatus.health!=="none"&&r.jsxs("span",{className:"metric",children:[r.jsx("span",{className:"label",children:"HEALTH"}),r.jsx("span",{className:"value",style:{color:e.dockerStatus.health==="healthy"?"#4ade80":e.dockerStatus.health==="unhealthy"?"#f87171":"#fbbf24"},children:e.dockerStatus.health==="healthy"?"✓":e.dockerStatus.health==="unhealthy"?"✗":"..."})]}),e.dockerStatus.startedAt&&r.jsxs("span",{className:"metric",children:[r.jsx("span",{className:"label",children:"UP"}),r.jsx("span",{className:"value",children:W1(e.dockerStatus.startedAt)})]})]}),C&&((ue=e.dockerStatus)==null?void 0:ue.services)&&e.dockerStatus.services.length>0&&r.jsx("div",{className:"building-popup-services",children:e.dockerStatus.services.map((Le,ke)=>r.jsxs("span",{className:"service-item",title:`${Le.name}: ${Le.status}`,children:[r.jsx("span",{className:"service-indicator",style:{backgroundColor:Le.status==="running"?"#4ade80":"#f87171"}}),r.jsx("span",{className:"service-name",children:Le.name})]},ke))}),(e.lastError||j&&((be=e.pm2Status)==null?void 0:be.status)==="errored"||C&&((ve=e.dockerStatus)==null?void 0:ve.status)==="dead")&&r.jsxs("div",{className:"building-popup-error",children:[e.lastError||l("terminal:building.processFailedToStart"),j&&((ge=e.pm2Status)==null?void 0:ge.restarts)&&e.pm2Status.restarts>5&&r.jsxs("span",{className:"error-hint",children:[" - ",l("terminal:building.checkLogsOrConfig")]}),C&&((_e=e.dockerStatus)==null?void 0:_e.health)==="unhealthy"&&r.jsxs("span",{className:"error-hint",children:[" - ",l("terminal:building.healthCheckFailing")]})]}),r.jsxs("div",{className:"building-popup-actions",children:[r.jsxs("button",{className:"action-btn start",onClick:()=>L("start"),disabled:!O||e.status==="running"||e.status==="starting",title:l(O?"terminal:buildingAction.start":"terminal:buildingAction.noStartCommand"),children:[r.jsx("span",{className:"icon",children:"▶"}),l("terminal:buildingAction.start")]}),r.jsxs("button",{className:"action-btn stop",onClick:()=>L("stop"),disabled:!I||e.status==="stopped"||e.status==="stopping",title:l(I?"terminal:buildingAction.stop":"terminal:buildingAction.noStopCommand"),children:[r.jsx("span",{className:"icon",children:"■"}),l("terminal:buildingAction.stop")]}),r.jsxs("button",{className:"action-btn restart",onClick:()=>L("restart"),disabled:!B,title:l(B?"terminal:buildingAction.restart":"terminal:buildingAction.noRestartCommand"),children:[r.jsx("span",{className:"icon",children:"↺"}),l("terminal:buildingAction.restart")]}),r.jsxs("button",{className:"action-btn logs",onClick:()=>L("logs"),title:l("terminal:buildingAction.viewLogs"),children:[r.jsx("span",{className:"icon",children:"📄"}),l("terminal:logs.title")]}),R.length===1&&r.jsxs("button",{className:"action-btn open-url",onClick:Le=>M(R[0],Le.altKey),title:`Open http://localhost:${R[0]} (Alt+Click for modal)`,children:[r.jsx("span",{className:"icon",children:"🔗"}),l("terminal:buildingAction.openInBrowser")]}),R.length>1&&r.jsxs("div",{className:"action-btn-group",children:[r.jsxs("span",{className:"action-btn-label",children:[l("terminal:buildingAction.openInBrowser"),":"]}),R.map(Le=>r.jsxs("button",{className:"action-btn open-url port-btn",onClick:ke=>M(Le,ke.altKey),title:`Open http://localhost:${Le} (Alt+Click for modal)`,children:[":",Le]},Le))]})]}),c&&S.length>0&&r.jsxs("div",{className:"building-popup-logs",children:[r.jsxs("div",{className:"logs-header",children:[r.jsx("span",{children:l("terminal:logs.title")}),r.jsx("button",{onClick:()=>z.clearBuildingLogs(e.id),children:l("terminal:logs.clear")})]}),r.jsx("div",{className:"logs-content",children:S.slice(-50).map((Le,ke)=>r.jsx("pre",{children:PU(Le)},ke))})]}),r.jsx("button",{className:"building-popup-settings",onClick:a,children:l("terminal:buildingAction.fullSettings")})]})});function LU(s){if(s===0)return"0 B";const e=1024,t=["B","KB","MB","GB"],n=Math.floor(Math.log(s)/Math.log(e));return parseFloat((s/Math.pow(e,n)).toFixed(1))+" "+t[n]}function OU(s){const t=Date.now()-s,n=Math.floor(t/(1e3*60*60)),a=Math.floor(t%(1e3*60*60)/(1e3*60));return n>0?`${n}h ${a}m`:`${a}m`}const IU=y.memo(function({building:e,screenPos:t,onClose:n,onOpenSettings:a,onOpenLogsModal:i,onOpenUrlInModal:o}){const{t:l}=$e(["terminal","common"]),[c,d]=y.useState(null),[m,p]=y.useState(!1),f=y.useRef(null),b=y.useRef(c);b.current=c;const{buildings:x}=qn(),k=(e.subordinateBuildingIds||[]).map(D=>x.get(D)).filter(D=>D!==void 0),S=y.useRef(null),j=y.useRef(null),C=y.useCallback(D=>{D.preventDefault();const E=b.current?b.current.x:0,R=b.current?b.current.y:0;f.current={mouseX:D.clientX,mouseY:D.clientY,popupX:E,popupY:R},p(!0),S.current=O=>{if(!f.current)return;const I=O.clientX-f.current.mouseX,B=O.clientY-f.current.mouseY;d({x:f.current.popupX+I,y:f.current.popupY+B})},j.current=()=>{p(!1),f.current=null,S.current&&document.removeEventListener("mousemove",S.current),j.current&&document.removeEventListener("mouseup",j.current)},document.addEventListener("mousemove",S.current),document.addEventListener("mouseup",j.current)},[]);y.useEffect(()=>()=>{S.current&&document.removeEventListener("mousemove",S.current),j.current&&document.removeEventListener("mouseup",j.current)},[]);const N=D=>{z.sendBossBuildingCommand(e.id,D)},P=k.reduce((D,E)=>(D[E.status]=(D[E.status]||0)+1,D),{}),_=k.some(D=>{var E;return(E=D.pm2)==null?void 0:E.enabled}),L=(D,E)=>{const R=`http://localhost:${D}`;E&&o?o(R):window.open(R,"_blank")},M=y.useMemo(()=>{let R=t.x+20,O=t.y-80;return typeof window<"u"&&!c&&(t.x+20+340>window.innerWidth&&(R=t.x-340-20),t.y-80<0?O=10:t.y-80+350>window.innerHeight&&(O=window.innerHeight-350-10)),{position:"fixed",left:R+((c==null?void 0:c.x)||0),top:O+((c==null?void 0:c.y)||0),zIndex:1e3,cursor:m?"grabbing":void 0}},[t.x,t.y,c,m]);return r.jsxs("div",{className:"building-action-popup boss-building-popup",style:M,onClick:D=>D.stopPropagation(),children:[r.jsxs("div",{className:`building-popup-header boss-header ${m?"dragging":""}`,onMouseDown:C,children:[r.jsx("span",{className:"boss-icon",children:"👑"}),r.jsx("span",{className:"building-popup-name",children:e.name}),r.jsx("span",{className:"subordinate-count",children:l("terminal:building.unitsCount",{count:k.length})}),r.jsx("button",{className:"building-popup-close",onClick:n,children:"x"})]}),r.jsxs("div",{className:"boss-status-overview",children:[Object.entries(P).map(([D,E])=>r.jsxs("span",{className:"status-badge",style:{backgroundColor:co[D]||"#666"},children:[E," ",D]},D)),k.length===0&&r.jsx("span",{className:"no-subordinates",children:l("terminal:building.noSubordinates")})]}),k.length>0&&r.jsx("div",{className:"subordinate-list",children:k.map(D=>{var E,R,O;return r.jsxs("div",{className:"subordinate-item",children:[r.jsx("span",{className:"sub-status-dot",style:{backgroundColor:co[D.status]}}),r.jsx("span",{className:"sub-name",children:D.name}),((E=D.pm2Status)==null?void 0:E.ports)&&D.pm2Status.ports.length>0&&r.jsx("span",{className:"sub-port",children:D.pm2Status.ports.map(I=>r.jsxs("a",{href:`http://localhost:${I}`,className:"building-popup-port-link",onClick:B=>{B.preventDefault(),B.stopPropagation(),L(I,B.altKey)},title:`Open http://localhost:${I} (Alt+Click for modal)`,children:[":",I]},I))}),D.pm2Status&&r.jsxs("span",{className:"sub-metrics",children:[(R=D.pm2Status.cpu)==null?void 0:R.toFixed(0),"% | ",LU(D.pm2Status.memory||0)]}),((O=D.pm2Status)==null?void 0:O.uptime)&&r.jsx("span",{className:"sub-uptime",children:OU(D.pm2Status.uptime)})]},D.id)})}),r.jsxs("div",{className:"building-popup-actions boss-actions",children:[r.jsxs("button",{className:"action-btn start",onClick:()=>N("start_all"),disabled:k.length===0,title:l("terminal:building.startAllSubs"),children:[r.jsx("span",{className:"icon",children:"▶"}),l("terminal:building.startAll")]}),r.jsxs("button",{className:"action-btn stop",onClick:()=>N("stop_all"),disabled:k.length===0,title:l("terminal:building.stopAllSubs"),children:[r.jsx("span",{className:"icon",children:"■"}),l("terminal:building.stopAll")]}),r.jsxs("button",{className:"action-btn restart",onClick:()=>N("restart_all"),disabled:k.length===0,title:l("terminal:building.restartAllSubs"),children:[r.jsx("span",{className:"icon",children:"↺"}),l("terminal:building.restartAll")]}),_&&r.jsxs("button",{className:"action-btn logs",onClick:i,title:l("terminal:building.viewUnifiedLogs"),children:[r.jsx("span",{className:"icon",children:"📄"}),l("terminal:building.logs")]})]}),r.jsx("button",{className:"building-popup-settings",onClick:a,children:l("terminal:building.fullSettings")})]})}),BU=y.memo(function({building:e,screenPos:t,onClose:n,onOpenSettings:a,onOpenDatabasePanel:i}){var P;const{t:o}=$e(["terminal","common"]),[l,c]=y.useState(null),[d,m]=y.useState(!1),p=y.useRef(null),f=y.useRef(l);f.current=l;const b=Sm(e.id),x=((P=e.database)==null?void 0:P.connections)??[],w=y.useRef(null),k=y.useRef(null),S=y.useCallback(_=>{_.preventDefault();const L=f.current?f.current.x:0,M=f.current?f.current.y:0;p.current={mouseX:_.clientX,mouseY:_.clientY,popupX:L,popupY:M},m(!0),w.current=D=>{if(!p.current)return;const E=D.clientX-p.current.mouseX,R=D.clientY-p.current.mouseY;c({x:p.current.popupX+E,y:p.current.popupY+R})},k.current=()=>{m(!1),p.current=null,w.current&&document.removeEventListener("mousemove",w.current),k.current&&document.removeEventListener("mouseup",k.current)},document.addEventListener("mousemove",w.current),document.addEventListener("mouseup",k.current)},[]);y.useEffect(()=>()=>{w.current&&document.removeEventListener("mousemove",w.current),k.current&&document.removeEventListener("mouseup",k.current)},[]);const j=_=>{z.testDatabaseConnection(e.id,_)},C=_=>b.connectionStatus.get(_),N=y.useMemo(()=>{let M=t.x+20,D=t.y-80;return typeof window<"u"&&!l&&(t.x+20+320>window.innerWidth&&(M=t.x-320-20),t.y-80<0?D=10:t.y-80+300>window.innerHeight&&(D=window.innerHeight-300-10)),{position:"fixed",left:M+((l==null?void 0:l.x)||0),top:D+((l==null?void 0:l.y)||0),zIndex:1e3,cursor:d?"grabbing":void 0}},[t.x,t.y,l,d]);return r.jsxs("div",{className:"building-action-popup database-building-popup",style:N,onClick:_=>_.stopPropagation(),children:[r.jsxs("div",{className:`building-popup-header database-header ${d?"dragging":""}`,onMouseDown:S,children:[r.jsx("span",{className:"database-icon",children:"🗄️"}),r.jsx("span",{className:"building-popup-name",children:e.name}),r.jsx("span",{className:"connection-count",children:o("terminal:building.connCount",{count:x.length})}),r.jsx("button",{className:"building-popup-close",onClick:n,children:"x"})]}),x.length>0?r.jsx("div",{className:"database-connection-list",children:x.map(_=>{const L=C(_.id);return r.jsxs("div",{className:"database-connection-item",children:[r.jsx("span",{className:"conn-engine",children:_.engine==="mysql"?"🐬":"🐘"}),r.jsx("span",{className:"conn-name",children:_.name}),r.jsxs("span",{className:"conn-host",children:[_.host,":",_.port]}),L&&r.jsx("span",{className:`conn-status ${L.connected?"connected":"disconnected"}`,children:L.connected?"●":"○"}),r.jsx("button",{className:"conn-test-btn",onClick:()=>j(_.id),title:o("terminal:building.testConnection"),children:"↻"})]},_.id)})}):r.jsxs("div",{className:"database-no-connections",children:[r.jsx("p",{children:o("terminal:building.noConnections")}),r.jsx("p",{className:"hint",children:o("terminal:building.clickSettingsToAdd")})]}),r.jsxs("div",{className:"building-popup-actions database-actions",children:[r.jsxs("button",{className:"action-btn query",onClick:i,disabled:x.length===0,title:o("terminal:building.openDbExplorer"),children:[r.jsx("span",{className:"icon",children:"⌨"}),o("terminal:building.query")]}),r.jsxs("button",{className:"action-btn test-all",onClick:()=>x.forEach(_=>j(_.id)),disabled:x.length===0,title:o("terminal:building.testAllConnections"),children:[r.jsx("span",{className:"icon",children:"↻"}),o("terminal:building.testAll")]})]}),r.jsx("button",{className:"building-popup-settings",onClick:a,children:o("common:buttons.settings")})]})}),zU=({building:s,connections:e,activeConnectionId:t,activeDatabase:n,collapsed:a,onToggleCollapse:i,onConnectionChange:o,onDatabaseChange:l,onInsertTable:c,onSelectTableQuery:d})=>{const{t:m}=$e(["terminal"]),p=Sm(s.id),[f,b]=y.useState(new Set),[x,w]=y.useState(""),[k,S]=y.useState(!1),[j,C]=y.useState(null),N=y.useRef(null),P=y.useRef(null),_=t?p.databases.get(t)??[]:[],L=t&&n?`${t}:${n}`:"",M=L?p.tables.get(L)??[]:[],D=t?p.connectionStatus.get(t):void 0,E=y.useMemo(()=>{if(!x.trim())return _;const I=x.toLowerCase();return _.filter(B=>B.toLowerCase().includes(I))},[_,x]);y.useEffect(()=>{const I=B=>{P.current&&!P.current.contains(B.target)&&S(!1)};return k&&document.addEventListener("mousedown",I),()=>document.removeEventListener("mousedown",I)},[k]),y.useEffect(()=>{t&&!D&&z.testDatabaseConnection(s.id,t)},[s.id,t,D]),y.useEffect(()=>{t&&(D!=null&&D.connected)&&_.length===0&&z.listDatabases(s.id,t)},[s.id,t,D==null?void 0:D.connected,_.length]),y.useEffect(()=>{t&&n&&M.length===0&&z.listTables(s.id,t,n)},[s.id,t,n,M.length]),y.useEffect(()=>{C(null)},[t,n]);const R=y.useCallback(I=>{b(B=>{const Y=new Set(B);if(Y.has(I))Y.delete(I);else if(Y.add(I),t&&n){const $=`${t}:${n}:${I}`;p.tableSchemas.has($)||z.getTableSchema(s.id,t,n,I)}return Y})},[s.id,t,n,p.tableSchemas]),O=I=>{if(!t||!n)return null;const B=`${t}:${n}:${I}`;return p.tableSchemas.get(B)};return a?r.jsx("div",{className:"database-sidebar database-sidebar--collapsed",children:r.jsx("button",{className:"database-sidebar__toggle",onClick:i,title:m("terminal:database.expandSidebar"),children:"»"})}):r.jsxs("div",{className:"database-sidebar",children:[r.jsxs("div",{className:"database-sidebar__header",children:[r.jsx("span",{children:m("terminal:database.explorer")}),r.jsx("button",{className:"database-sidebar__toggle",onClick:i,title:m("terminal:database.collapseSidebar"),children:"«"})]}),r.jsxs("div",{className:"database-sidebar__section",children:[r.jsx("div",{className:"database-sidebar__section-title",children:m("terminal:database.connection")}),r.jsx("select",{className:"database-sidebar__select",value:t||"",onChange:I=>o(I.target.value),children:e.length===0?r.jsx("option",{value:"",children:m("terminal:database.noConnections")}):e.map(I=>r.jsxs("option",{value:I.id,children:[I.engine==="mysql"?"🐬":"🐘"," ",I.name]},I.id))}),D&&r.jsx("div",{className:`database-sidebar__status ${D.connected?"database-sidebar__status--connected":"database-sidebar__status--error"}`,children:D.connected?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"database-sidebar__status-icon",children:"✓"}),m("terminal:database.connected"),D.serverVersion&&r.jsxs("span",{className:"database-sidebar__version",children:["(",D.serverVersion,")"]})]}):r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"database-sidebar__status-icon",children:"✗"}),D.error||m("terminal:database.disconnected")]})})]}),_.length>0&&r.jsxs("div",{className:"database-sidebar__section",children:[r.jsx("div",{className:"database-sidebar__section-title",children:m("terminal:database.databaseTitle")}),r.jsxs("div",{className:"database-sidebar__searchable-select",ref:P,children:[r.jsx("input",{ref:N,className:"database-sidebar__search-input",type:"text",value:k?x:n||"",placeholder:m("terminal:database.selectDatabase"),onChange:I=>{w(I.target.value),k||S(!0)},onFocus:()=>{S(!0),w("")},onKeyDown:I=>{var B,Y;I.key==="Escape"?(S(!1),w(""),(B=N.current)==null||B.blur()):I.key==="Enter"&&E.length===1&&(l(E[0]),S(!1),w(""),(Y=N.current)==null||Y.blur())}}),k&&r.jsx("div",{className:"database-sidebar__dropdown",children:E.length===0?r.jsx("div",{className:"database-sidebar__dropdown-empty",children:"No matches"}):E.map(I=>r.jsx("div",{className:`database-sidebar__dropdown-item ${I===n?"database-sidebar__dropdown-item--active":""}`,onMouseDown:B=>{B.preventDefault(),l(I),S(!1),w("")},children:I},I))})]})]}),M.length>0&&r.jsxs("div",{className:"database-sidebar__section database-sidebar__section--tables",children:[r.jsx("div",{className:"database-sidebar__section-title",children:m("terminal:database.tablesCount",{count:M.length})}),r.jsx("div",{className:"database-sidebar__tables",children:M.map(I=>{const B=f.has(I.name),Y=B?O(I.name):null;return r.jsxs("div",{className:"database-sidebar__table",children:[r.jsxs("div",{className:"database-sidebar__table-header",children:[r.jsx("button",{className:"database-sidebar__table-expand",onClick:()=>R(I.name),title:B?"Collapse table schema":"Expand table schema",children:B?"▼":"▶"}),r.jsx("span",{className:"database-sidebar__table-icon",children:I.type==="view"?"👁":"📋"}),r.jsx("span",{className:`database-sidebar__table-name ${j===I.name?"database-sidebar__table-name--selected":""}`,onClick:()=>C(I.name),onDoubleClick:()=>{C(I.name),d(I.name)},children:I.name}),r.jsx("button",{className:"database-sidebar__table-insert",onClick:$=>{$.stopPropagation(),c(I.name)},title:m("terminal:database.insertTableName"),children:"+"})]}),B&&Y&&r.jsx("div",{className:"database-sidebar__table-columns",children:Y.columns.map($=>r.jsxs("div",{className:"database-sidebar__column",onClick:()=>c($.name),title:`${$.type}${$.nullable?" NULL":" NOT NULL"}${$.primaryKey?" PK":""}`,children:[r.jsx("span",{className:"database-sidebar__column-icon",children:$.primaryKey?"🔑":""}),r.jsx("span",{className:"database-sidebar__column-name",children:$.name}),r.jsx("span",{className:"database-sidebar__column-type",children:$.type})]},$.name))})]},I.name)})})]})]})};function xv(s){const e=[];let t=!1,n=!1,a=!1,i=!1,o=0;for(let c=0;c<s.length;c++){const d=s[c],m=s[c+1];if(a){d===`
235
+ `)}function bU(s){return s.startsWith("Using tool:")||s.startsWith("Tool input:")||s.startsWith("Tool result:")||s.startsWith("Bash output:")||s.startsWith("Session started:")||s.startsWith("[thinking]")||s.startsWith("Tokens:")||s.startsWith("Cost:")||s.startsWith("Context (estimated from Codex turn usage):")||s.startsWith("🔄 [System]")||s.startsWith("📋 [System]")||s.startsWith("[System]")}const yU=y.memo(function({onSaveSnapshot:e}={}){var et,ct,Qt,On,rn;const{t}=$e(["terminal","common"]),n=fi(),a=wm(),i=WM(),o=Bx(),l=Hx(),c=ZM(),d=qM(),m=Fx(),p=$x(),f=mF(),b=!!f,x=y.useMemo(()=>f?{id:f.agentId,name:f.agentName,class:f.agentClass,status:"idle",provider:"claude",position:{x:0,y:0,z:0},cwd:f.cwd,permissionMode:"interactive",tokensUsed:0,contextUsed:0,contextLimit:2e5,taskCount:0,createdAt:f.createdAt,lastActivity:f.createdAt}:null,[f]),w=Array.from(a),S=w.length===1?w[0]:null,C=(Lx(S)||null)??(b?x:null),N=S??(b?(f==null?void 0:f.agentId)??null:null),P=!!(C!=null&&C.sessionId)&&!b,_=mo(),L=y.useMemo(()=>{if(!N)return null;for(const We of _.values())if(We.assignedAgentIds.includes(N)&&We.directories.length>0)return We;return null},[N,_]),{terminalHeight:M,terminalRef:D,handleResizeStart:E}=Y9(),R=q9(),O=Ox(N),I=y.useMemo(()=>b&&f?f.outputs.map(We=>({text:We.text||"",timestamp:We.timestamp,isStreaming:!1,isUserPrompt:!1})):O,[b,f,O]),B=y.useRef(null),Y=y.useRef(null),$=y.useRef(null),[W,K]=y.useState(()=>{const We=la(vt.VIEW_MODE);return We==="simple"||We==="chat"||We==="advanced"?We:la(vt.ADVANCED_VIEW)==="true"?"advanced":"simple"}),[X,H]=y.useState(null),[se,ce]=y.useState(null),[F,V]=y.useState(null),[J,ie]=y.useState(null),[Q,Z]=y.useState(!1);En("guake-image-modal",X!==null,()=>H(null)),En("guake-bash-modal",se!==null,()=>ce(null)),En("guake-response-modal",J!==null,()=>ie(null)),En("guake-context-confirm",F!==null,()=>V(null)),En("guake-agent-info",Q,()=>Z(!1));const[G,re]=y.useState(!1),[ue,be]=y.useState(()=>Ms.isEnabled()),ve=vF(),ge=y.useCallback(We=>z.setOverviewPanelOpen(We),[]),[_e,Le]=y.useState(!1),[ke,ne]=y.useState(null),de=y.useRef(null),le=y.useRef(null),[oe,he]=y.useState(!1),[Ce,xe]=y.useState(!1),[Ze,ye]=y.useState(!1),[Se,qe]=y.useState(!1),ee=y.useRef(0),me=i&&C!==null,pe=$M({selectedAgentId:N,hasSessionId:P,reconnectCount:l,historyRefreshTrigger:c,lastPrompts:o,outputScrollRef:B}),Oe=K9({selectedAgentId:N,isOpen:me}),Je=V9({agents:n,selectedAgentId:N,isOpen:me,loadingHistory:pe.fetchingHistory,hasModalOpen:!!(X||se||J||m||p),outputRef:B}),Fe=hE({selectedAgentId:S}),kt=qz(),Ee=y.useMemo(()=>b||!N?[]:Array.from(kt.values()).filter(We=>We.agentId===N&&We.status==="pending"),[b,N,kt]),Ye=(C==null?void 0:C.class)==="boss"||(C==null?void 0:C.isBoss),tt=iF(!b&&Ye?N:null),it=rF(b?null:N),ft=xF(b?null:N);y.useEffect(()=>{G&&!ue&&(be(!0),Ms.setEnabled(!0))},[G,ue]),y.useEffect(()=>{me||Z(!1)},[me]),y.useEffect(()=>{const We=C==null?void 0:C.status;if(de.current==="working"&&We==="idle"){le.current&&clearTimeout(le.current);const Ct=N?o.get(N):void 0;ne(Ct!=null&&Ct.timestamp?Date.now()-Ct.timestamp:null),Le(!0),le.current=setTimeout(()=>{Le(!1),ne(null),le.current=null},4e3)}else We==="working"&&(le.current&&(clearTimeout(le.current),le.current=null),Le(!1),ne(null));return de.current=We||null,()=>{le.current&&clearTimeout(le.current)}},[C==null?void 0:C.status]);const ut=y.useMemo(()=>{const{history:We}=pe,ot=new Map;for(const Et of We)Et.type==="tool_result"&&Et.toolUseId&&ot.set(Et.toolUseId,Et.content);return(Et=>Et.map(_t=>{if(_t.type==="tool_use"&&_t.toolName==="Bash"&&_t.toolUseId){const zt=ot.get(_t.toolUseId);let Pt;try{Pt=(_t.toolInput||(_t.content?JSON.parse(_t.content):{})).command}catch{}return{..._t,_bashOutput:zt,_bashCommand:Pt}}return _t}))(We)},[pe.history,W]),ae=pE({outputs:I,viewMode:W}),Ne=y.useMemo(()=>{const We=[],ot=new Set,Ct=new Set;let Et=null,_t=0;for(const zt of ut){if(zt.type==="assistant"){const is=zt.uuid?`uuid:${zt.uuid}:${sp(zt.content)}`:`sig:${zt.timestamp}:${sp(zt.content)}`;if(ot.has(is))continue;ot.add(is),We.push(zt);continue}if(zt.type!=="user"){We.push(zt);continue}const Pt=Ob(zt.content),Xt=zt.uuid?`uuid:${zt.uuid}:${Pt}`:null;if(Xt&&Ct.has(Xt))continue;const Wt=zt.timestamp?new Date(zt.timestamp).getTime():0;Et===Pt&&Math.abs(Wt-_t)<=H1||(We.push(zt),Xt&&Ct.add(Xt),Et=Pt,_t=Wt)}return We},[ut]),Ge=y.useMemo(()=>{const We=new Map,ot=new Set,Ct=new Map;for(const Pt of Ne){const Xt=Pt.timestamp?new Date(Pt.timestamp).getTime():0;if(Pt.type==="user"){const pa=Ob(Pt.content),ma=We.get(pa)??0;Xt>ma&&We.set(pa,Xt);continue}if(Pt.type!=="assistant")continue;Pt.uuid&&ot.add(Pt.uuid);const Wt=sp(Pt.content),is=Ct.get(Wt)??0;Xt>is&&Ct.set(Wt,Xt)}const Et=[];let _t=null,zt=0;for(const Pt of ae){if(!Pt.isUserPrompt){if(!Pt.isStreaming&&!bU(Pt.text)){if(Pt.uuid&&ot.has(Pt.uuid))continue;const pa=sp(Pt.text),ma=Pt.timestamp||0,bi=Ct.get(pa);if(bi&&Math.abs(ma-bi)<=gU)continue}Et.push(Pt);continue}const Xt=Ob(Pt.text),Wt=Pt.timestamp||0,is=We.get(Xt);is&&Wt>=is&&Wt-is<=fU||_t===Xt&&Math.abs(Wt-zt)<=H1||(Et.push(Pt),_t=Xt,zt=Wt)}return Et},[ae,Ne]),at=Ne.length+Ge.length,ht=Q9({totalMessages:at,isOpen:me,hasModalOpen:!!(X||se||J||m),scrollContainerRef:B,selectedAgentId:N,inputRef:Y,textareaRef:$,useTextarea:Fe.useTextarea});y.useEffect(()=>{if(!(!(se!=null&&se.isLive)||!se.command)){for(const We of Ge)if(We._bashCommand===se.command&&We._bashOutput){ce({command:se.command,output:We._bashOutput,isLive:!1});return}}},[se,Ge]);const $t=y.useCallback((We,ot)=>{H({url:We,name:ot})},[]),Vt=y.useCallback((We,ot)=>{const Ct=Td(We,C==null?void 0:C.cwd),Et=Ct.line?{...ot||{},targetLine:Ct.line}:ot;z.setFileViewerPath(Ct.path,Et,C==null?void 0:C.cwd)},[C==null?void 0:C.cwd]),jt=y.useCallback((We,ot)=>{ce({command:We,output:ot,isLive:ot==="Running..."})},[]),It=y.useCallback(We=>{ie(We)},[]),At=y.useCallback(()=>{Z(We=>!We)},[]),[Bt,Ln]=y.useState(!0),fn=y.useRef(!1),hs=y.useRef(!1),Qn=y.useCallback(()=>{hs.current||(fn.current=!0,Ln(!1))},[]),Kn=y.useCallback(()=>xe(!1),[]);y.useEffect(()=>{Ln(!0),fn.current=!1,hs.current=!0;const We=setTimeout(()=>{hs.current=!1},3e3);return()=>clearTimeout(We)},[N]);const vs=y.useRef(pe.handleScroll);vs.current=pe.handleScroll;const Dn=y.useCallback(()=>{if(!B.current||R.keyboardScrollLockRef.current)return;const{scrollTop:We,scrollHeight:ot,clientHeight:Ct}=B.current,Et=ot-We-Ct<150;hs.current||(fn.current=!Et,Et&&Ln(!0)),vs.current(R.keyboardScrollLockRef)},[B,R.keyboardScrollLockRef]),Yn=O.length>0&&((ct=(et=O[O.length-1])==null?void 0:et.text)==null?void 0:ct.length)||0;y.useEffect(()=>{R.keyboardScrollLockRef.current||fn.current||requestAnimationFrame(()=>{if(B.current){const{scrollTop:We,scrollHeight:ot,clientHeight:Ct}=B.current;ot-We-Ct<150&&(B.current.scrollTop=ot)}})},[O.length,Yn,R.keyboardScrollLockRef,B]);const ps=y.useRef(null);y.useLayoutEffect(()=>{const We=ps.current;We!==null&&We!==S?(he(!1),S&&pe.hasCachedHistory(S)||ye(!0),z.getState().currentSnapshot&&z.setCurrentSnapshot(null)):S||he(!1),ps.current=S},[S]),y.useEffect(()=>{if(!Ze||pe.fetchingHistory)return;const We=requestAnimationFrame(()=>{B.current&&(B.current.scrollTop=B.current.scrollHeight),ye(!1)});return()=>cancelAnimationFrame(We)},[Ze,pe.fetchingHistory,pe.historyLoadVersion]);const ms=y.useRef(!1);y.useEffect(()=>{me&&S&&z.clearUnseenForAgent(S)},[me,S]),y.useEffect(()=>{ms.current=!0,xe(!0)},[N,l]),y.useEffect(()=>{pe.fetchingHistory&&(ms.current=!0,xe(!0))},[pe.fetchingHistory]),y.useEffect(()=>{if(!Ce||!me||pe.fetchingHistory)return;const We=B.current;if(!We)return;let ot=null;const Ct=performance.now();let Et=0,_t=-1;const zt=()=>{const{scrollTop:Xt,scrollHeight:Wt,clientHeight:is}=We;return Wt-Xt-is<=2},Pt=()=>{const Xt=performance.now(),Wt=We.scrollHeight,is=Math.abs(Wt-_t)<=1,pa=zt();if(is&&pa?Et+=1:Et=0,_t=Wt,Et>=3){xe(!1),ot=null;return}if(Xt-Ct>8e3){xe(!1),ot=null;return}ot=requestAnimationFrame(Pt)};return ot=requestAnimationFrame(Pt),()=>{ot!==null&&cancelAnimationFrame(ot)}},[Ce,me,pe.fetchingHistory,pe.historyLoadVersion]);const Za=y.useRef(!1);y.useEffect(()=>{Za.current&&!Ce&&ms.current&&(ms.current=!1,he(!0)),Za.current=Ce},[Ce]),y.useEffect(()=>{if(!me||!ms.current||Ce||pe.fetchingHistory)return;const We=requestAnimationFrame(()=>{ms.current&&(ms.current=!1,he(!0))});return()=>cancelAnimationFrame(We)},[pe.historyLoadVersion,me,Ce,pe.fetchingHistory]),y.useEffect(()=>{const We=ot=>{if(ot.key==="`"&&!ot.ctrlKey&&!ot.altKey&&C){const Ct=ot.target;Ct.tagName!=="INPUT"&&Ct.tagName!=="TEXTAREA"&&(ot.preventDefault(),z.toggleTerminal())}};return document.addEventListener("keydown",We),()=>document.removeEventListener("keydown",We)},[C]),y.useEffect(()=>{const We=ot=>{ot.key==="Escape"&&(m?(ot.stopImmediatePropagation(),z.clearFileViewerPath()):p?(ot.stopImmediatePropagation(),z.closeContextModal()):J?(ot.stopImmediatePropagation(),ie(null)):se?(ot.stopImmediatePropagation(),ce(null)):X?(ot.stopImmediatePropagation(),H(null)):Oe.searchMode&&(ot.stopImmediatePropagation(),Oe.closeSearch()))};return document.addEventListener("keydown",We,!0),()=>document.removeEventListener("keydown",We,!0)},[X,se,J,Oe,m,p]);const da=y.useRef(me),Is=y.useRef(!1);y.useEffect(()=>{da.current=me},[me]),y.useEffect(()=>{if(window.innerWidth<=768)return;const ot=_t=>{var Wt;if(!(_t instanceof Element))return!1;const zt=(Wt=D.current)==null?void 0:Wt.contains(_t),Pt=_t.closest(".agent-bar"),Xt=!!_t.closest(".modal-overlay, .modal, .image-modal-overlay, .image-modal, .bash-modal-overlay, .bash-modal, .agent-info-modal-overlay, .agent-info-modal, .agent-response-modal, .pasted-text-modal-overlay, .pasted-text-modal, .file-viewer-overlay, .file-viewer-modal, .context-view-modal, .guake-context-confirm-overlay, .guake-context-confirm-modal");return!!zt||!!Pt||Xt},Ct=_t=>{if(!da.current){Is.current=!1;return}Is.current=!ot(_t.target)},Et=_t=>{Is.current&&(ot(_t.target)||z.setTerminalOpen(!1),Is.current=!1)};return document.addEventListener("mousedown",Ct,!0),document.addEventListener("mouseup",Et,!0),()=>{document.removeEventListener("mousedown",Ct,!0),document.removeEventListener("mouseup",Et,!0)}},[]),y.useEffect(()=>{const We=()=>{document.hidden&&R.cleanup()};return document.addEventListener("visibilitychange",We),()=>document.removeEventListener("visibilitychange",We)},[R]),y.useEffect(()=>()=>R.cleanup(),[N,R]);const Jn=typeof window<"u"&&window.innerWidth<=768;if(!C)return Jn&&d==="terminal"&&a.size===0?r.jsx("div",{ref:D,className:"guake-terminal open",style:{"--terminal-height":`${M}%`},children:r.jsx("div",{className:"guake-content",children:r.jsx("div",{className:"guake-output",style:{display:"flex",alignItems:"center",justifyContent:"center",color:"#6272a4"},children:r.jsxs("div",{style:{textAlign:"center"},children:[r.jsx("div",{style:{fontSize:"48px",marginBottom:"16px"},children:"👆"}),r.jsx("div",{style:{fontSize:"16px"},children:t("terminal:empty.tapAgent")}),r.jsx("div",{style:{fontSize:"14px",marginTop:"8px",opacity:.7},children:t("terminal:empty.switchTo3D")})]})})})}):Jn&&d==="terminal"&&a.size>0?r.jsx("div",{ref:D,className:"guake-terminal open",style:{"--terminal-height":`${M}%`},children:r.jsx("div",{className:"guake-content",children:r.jsx("div",{className:"guake-output",style:{display:"flex",alignItems:"center",justifyContent:"center",color:"#6272a4"},children:r.jsxs("div",{className:"guake-empty loading",children:[t("terminal:empty.loadingTerminal"),r.jsxs("span",{className:"loading-dots",children:[r.jsx("span",{}),r.jsx("span",{}),r.jsx("span",{})]})]})})})}):null;if(!N)return null;const ha=We=>{We.preventDefault(),We.stopPropagation(),ee.current++,We.dataTransfer.types.includes("Files")&&qe(!0)},pt=We=>{We.preventDefault(),We.stopPropagation()},Kt=We=>{We.preventDefault(),We.stopPropagation(),ee.current--,ee.current===0&&qe(!1)},Ae=async We=>{We.preventDefault(),We.stopPropagation(),ee.current=0,qe(!1);const ot=We.dataTransfer.files;if(ot.length)for(const Ct of ot){const Et=await Fe.uploadFile(Ct);Et&&Fe.setAttachedFiles(_t=>[..._t,Et])}};return r.jsxs("div",{ref:D,className:`guake-terminal ${me?"open":"collapsed"} ${G&&me?"with-debug-panel":""} ${ve&&me?"with-overview-panel":""} ${Se?"drag-over":""}`,style:{"--terminal-height":`${M}%`},onDragEnter:ha,onDragOver:pt,onDragLeave:Kt,onDrop:Ae,children:[r.jsxs("div",{className:"guake-drop-overlay",children:[r.jsx("div",{className:"drop-border"}),r.jsx("span",{className:"drop-icon",children:"📎"}),r.jsx("span",{className:"drop-label",children:t("terminal:input.dropToAttach")})]}),!b&&G&&me&&N&&r.jsx(GH,{agentId:N,onClose:()=>re(!1)}),!b&&ve&&me&&N&&r.jsx(VH,{activeAgentId:N,onClose:()=>ge(!1),onSelectAgent:We=>{z.selectAgent(We)}}),r.jsxs("div",{className:"guake-content",children:[r.jsx(lH,{selectedAgent:C,selectedAgentId:N,sortedAgents:Je.sortedAgents,swipeOffset:Je.swipeOffset,viewMode:W,setViewMode:K,searchMode:Oe.searchMode,toggleSearch:Oe.toggleSearch,closeSearch:Oe.closeSearch,debugPanelOpen:G,setDebugPanelOpen:re,debuggerEnabled:ue,setDebuggerEnabled:be,overviewPanelOpen:ve,setOverviewPanelOpen:ge,agentInfoOpen:Q,onToggleAgentInfo:At,outputsLength:Ne.length+Ge.length,setContextConfirm:V,headerRef:Je.headerRef,onSaveSnapshot:b?void 0:e,isSnapshotView:b}),Oe.searchMode&&r.jsx(cH,{searchInputRef:Oe.searchInputRef,searchQuery:Oe.searchQuery,setSearchQuery:Oe.setSearchQuery,handleSearch:Oe.handleSearch,closeSearch:Oe.closeSearch,searchLoading:Oe.searchLoading,searchResultsCount:Oe.searchResults.length}),r.jsxs("div",{className:`guake-swipe-container ${Je.swipeAnimationClass}`,style:Je.swipeOffset!==0?{transform:`translateX(${Je.swipeOffset*40}%)`}:void 0,children:[Je.sortedAgents.length>1&&Je.swipeOffset!==0&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:`swipe-indicator left ${Je.swipeOffset>.3?"visible":""}`,children:[r.jsx("span",{className:"indicator-icon",children:"←"}),r.jsx("span",{className:"indicator-name",children:(Qt=Je.prevAgent)==null?void 0:Qt.name})]}),r.jsxs("div",{className:`swipe-indicator right ${Je.swipeOffset<-.3?"visible":""}`,children:[r.jsx("span",{className:"indicator-name",children:(On=Je.nextAgent)==null?void 0:On.name}),r.jsx("span",{className:"indicator-icon",children:"→"})]})]}),Je.sortedAgents.length>1&&Je.sortedAgents.length<=8&&Je.swipeOffset!==0&&r.jsx("div",{className:`swipe-dots ${Math.abs(Je.swipeOffset)>.1?"visible":""}`,children:Je.sortedAgents.map((We,ot)=>r.jsx("div",{className:`swipe-dot ${ot===Je.currentAgentIndex?"active":""}`},We.id))}),r.jsx("div",{className:"guake-output",ref:B,onScroll:Dn,children:Oe.searchMode&&Oe.searchResults.length>0?r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"guake-search-header",children:t("terminal:header.searchResultsTitle")}),Oe.searchResults.map((We,ot)=>r.jsx(gv,{message:We,agentId:N,highlight:Oe.searchQuery,onImageClick:$t,onFileClick:Vt,onBashClick:jt,onViewMarkdown:It},`s-${ot}`))]}):r.jsxs("div",{className:`guake-history-content ${oe?"fade-in":""}`,children:[Ze&&r.jsxs("div",{className:"guake-empty loading",children:[t("terminal:empty.loadingConversation"),r.jsxs("span",{className:"loading-dots",children:[r.jsx("span",{}),r.jsx("span",{}),r.jsx("span",{})]})]}),!Ze&&pe.loadingHistory&&pe.history.length===0&&O.length===0&&r.jsxs("div",{className:"guake-empty loading",children:[t("terminal:empty.loadingConversation"),r.jsxs("span",{className:"loading-dots",children:[r.jsx("span",{}),r.jsx("span",{}),r.jsx("span",{})]})]}),!Ze&&!pe.loadingHistory&&pe.history.length===0&&I.length===0&&C.status!=="working"&&r.jsx("div",{className:"guake-empty",children:t("terminal:empty.noOutput")}),!Ze&&pe.hasMore&&!Oe.searchMode&&r.jsx("div",{className:"guake-load-more",children:pe.loadingMore?r.jsx("span",{children:t("terminal:empty.loadingOlder")}):r.jsx("button",{onClick:pe.loadMoreHistory,children:t("terminal:empty.loadMore",{count:pe.totalCount-pe.history.length})})}),!Ze&&r.jsx(PE,{historyMessages:Ne,liveOutputs:Ge,agentId:N,execTasks:it,subagents:ft,viewMode:W,selectedMessageIndex:ht.selectedIndex,isMessageSelected:ht.isSelected,onImageClick:$t,onFileClick:Vt,onBashClick:jt,onViewMarkdown:It,scrollContainerRef:B,onScrollTopReached:pe.loadMoreHistory,isLoadingMore:pe.loadingMore,hasMore:pe.hasMore,shouldAutoScroll:Bt,onUserScroll:Qn,pinToBottom:Ce,onPinCancel:Kn,isLoadingHistory:pe.fetchingHistory},N),!Ze&&Ye&&tt.size>0&&r.jsxs("div",{className:"agent-progress-container",children:[r.jsxs("div",{className:"agent-progress-container-header",children:[r.jsx("span",{className:"progress-crown",children:"👑"}),r.jsx("span",{children:t("terminal:empty.subordinateProgress")}),r.jsx("span",{className:"progress-count",children:t("terminal:empty.activeCount",{count:tt.size})})]}),Array.from(tt.values()).map(We=>r.jsx(XH,{progress:We,defaultExpanded:We.status==="working",onAgentClick:z.selectAgent},We.agentId))]})]})})]}),r.jsx(gH,{selectedAgent:C,selectedAgentId:N,isOpen:me,command:Fe.command,setCommand:Fe.setCommand,forceTextarea:Fe.forceTextarea,setForceTextarea:Fe.setForceTextarea,useTextarea:Fe.useTextarea,attachedFiles:Fe.attachedFiles,setAttachedFiles:Fe.setAttachedFiles,removeAttachedFile:Fe.removeAttachedFile,uploadFile:Fe.uploadFile,pastedTexts:Fe.pastedTexts,expandPastedTexts:Fe.expandPastedTexts,incrementPastedCount:Fe.incrementPastedCount,setPastedTexts:Fe.setPastedTexts,resetPastedCount:Fe.resetPastedCount,handleInputFocus:R.handleInputFocus,handleInputBlur:R.handleInputBlur,pendingPermissions:Ee,showCompletion:_e,completionElapsed:ke,onImageClick:$t,inputRef:Y,textareaRef:$,isSnapshotView:b,onClearHistory:pe.clearHistory}),r.jsxs("div",{className:"guake-agent-status-bar",children:[!b&&(C==null?void 0:C.isDetached)&&r.jsx(Yp,{content:r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"tide-tooltip__title",children:["🔄 ",t("terminal:empty.reattachingSessionTitle")]}),r.jsxs("div",{className:"tide-tooltip__text",children:[t("terminal:empty.reattachingSessionDesc"),r.jsx("br",{}),r.jsx("br",{}),r.jsxs("strong",{children:[t("common:labels.status"),":"]})," ",t("terminal:empty.reattachingSessionStatus")]})]}),position:"top",className:"tide-tooltip--detached",children:r.jsxs("span",{className:"guake-detached-badge",title:t("terminal:empty.reattachingBadge"),children:[r.jsx("span",{className:"guake-detached-spinner",children:"🔄"})," ",t("terminal:empty.reattaching")]})}),(C==null?void 0:C.cwd)&&r.jsxs("span",{className:"guake-agent-cwd",children:["📁 ",C.cwd.split("/").filter(Boolean).slice(-2).join("/")||C.cwd]}),L&&L.directories.map(We=>r.jsxs("span",{className:"guake-agent-area-dir",title:We,onClick:()=>z.openFileExplorerForAreaFolder(L.id,We),children:["📂 ",We.split("/").filter(Boolean).pop()||We]},We)),!b&&C&&(()=>{const We=C.contextStats,ot=!!We,Ct=We?We.totalTokens:C.contextUsed||0,Et=We?We.contextWindow:C.contextLimit||2e5,_t=We?We.usedPercent:Math.round(Ct/Et*100),zt=Math.round(100-_t),Pt=_t>=80?"#ff4a4a":_t>=60?"#ff9e4a":_t>=40?"#ffd700":"#4aff9e",Xt=(Ct/1e3).toFixed(1),Wt=(Et/1e3).toFixed(1);return r.jsxs("span",{className:"guake-agent-context",onClick:()=>z.setContextModalAgentId(N),title:t(ot?"terminal:context.clickToViewStats":"terminal:context.clickToFetchStats"),children:[r.jsx("span",{className:"context-icon",children:"📊"}),r.jsxs("span",{className:"context-label",children:[t("terminal:agentInfo.context"),":"]}),r.jsx("span",{className:"context-bar-mini",children:r.jsx("span",{className:"context-bar-mini-fill",style:{width:`${Math.min(100,_t)}%`,backgroundColor:Pt}})}),r.jsxs("span",{className:"context-tokens",style:{color:Pt},children:[Xt,"k/",Wt,"k"]}),r.jsxs("span",{className:"context-free",children:["(",t("terminal:context.percentFree",{percent:zt}),")"]}),!ot&&r.jsx("span",{className:"context-warning",title:t("terminal:context.clickToFetchStats"),children:"⚠️"})]})})(),r.jsx(mU,{})]})]}),me&&r.jsx("div",{className:"guake-resize-handle",onMouseDown:E,title:t("common:rightPanel.dragToResize")}),r.jsxs("div",{className:"guake-handle",onClick:()=>{me&&z.toggleTerminal()},onDoubleClick:()=>{me||z.toggleTerminal()},style:{top:me?`min(${M}%, calc(100vh - 72px))`:"0"},children:[r.jsx("span",{className:"guake-handle-icon",children:me?"▲":"▼"}),r.jsx("span",{className:"guake-handle-text",children:C.name})]}),X&&r.jsx(kE,{url:X.url,name:X.name,onClose:()=>H(null)}),se&&r.jsx(SE,{state:se,onClose:()=>ce(null)}),F&&r.jsx(xH,{action:F,selectedAgentId:N,subordinateCount:((rn=C==null?void 0:C.subordinateIds)==null?void 0:rn.length)||0,onClose:()=>V(null),onClearHistory:pe.clearHistory}),r.jsx(vH,{}),r.jsx(wH,{}),r.jsx(kH,{agent:C,isOpen:Q,onClose:()=>Z(!1)}),!b&&r.jsx(jE,{agent:C,content:J,onClose:()=>ie(null)})]})});function xU(s){return s.trim().replace(/^v/i,"")}function U1(s){const t=xU(s).match(/^(\d+(?:\.\d+)*)(?:-([0-9A-Za-z.-]+))?/);if(!t)return null;const n=t[1].split(".").map(i=>Number.parseInt(i,10));if(n.some(Number.isNaN))return null;const a=t[2]?t[2].split("."):[];return{core:n,prerelease:a}}function vU(s,e){if(s.length===0&&e.length===0)return 0;if(s.length===0)return 1;if(e.length===0)return-1;const t=Math.max(s.length,e.length);for(let n=0;n<t;n+=1){const a=s[n],i=e[n];if(a===void 0)return-1;if(i===void 0)return 1;const o=/^\d+$/.test(a)?Number.parseInt(a,10):null,l=/^\d+$/.test(i)?Number.parseInt(i,10):null;if(o!==null&&l!==null){if(o>l)return 1;if(o<l)return-1;continue}if(o!==null)return-1;if(l!==null)return 1;const c=a.localeCompare(i);if(c!==0)return c>0?1:-1}return 0}function wU(s,e){const t=U1(s),n=U1(e);if(!t||!n)return null;const a=Math.max(t.core.length,n.core.length);for(let i=0;i<a;i+=1){const o=t.core[i]??0,l=n.core[i]??0;if(o>l)return 1;if(o<l)return-1}return vU(t.prerelease,n.prerelease)}function kU(s,e){const t=wU(s,e);return t===null?"unknown":t<0?"behind":t>0?"ahead":"equal"}async function SU(s,e={}){const{timeoutMs:t=5e3,fetchImpl:n=fetch}=e;try{const a=new AbortController,i=setTimeout(()=>a.abort(),t),o=Date.now(),l=await n(`https://registry.npmjs.org/${encodeURIComponent(s)}/latest?t=${o}`,{signal:a.signal,headers:{Accept:"application/json"}});if(clearTimeout(i),!l.ok)return null;const c=await l.json();return typeof c.version=="string"?c.version:null}catch{return null}}async function jU(s,e,t={}){const n=await SU(s,t);return n?{currentVersion:e,latestVersion:n,relation:kU(e,n)}:{currentVersion:e,latestVersion:null,relation:"unknown"}}const CU="tide-commander",Ib="0.84.2";function NU(){const[s,e]=y.useState({currentVersion:Ib,latestVersion:null,relation:"unknown",isChecking:!1}),t=y.useCallback(async()=>{e(a=>({...a,isChecking:!0}));const n=await jU(CU,Ib);e({currentVersion:Ib,latestVersion:n.latestVersion,relation:n.relation,isChecking:!1})},[]);return y.useEffect(()=>{t()},[t]),{...s,refresh:t}}const AU=y.memo(function({agent:e,currentIndex:t,agentIndex:n,isTouchInput:a,isTouchDragEnabled:i,isSelected:o,hasUnseenOutput:l,isDragging:c,isDragOver:d,customClasses:m,onDragStart:p,onDragEnd:f,onDragOver:b,onDragEnter:x,onDragLeave:w,onDrop:k,onAgentClick:S,onAgentDoubleClick:j,onTouchStart:C,onTouchMove:N,onTouchEnd:P,onTouchCancel:_,onHoverEnter:L,onHoverLeave:M,onItemRef:D}){const E=y.useMemo(()=>go(e.class,m),[e.class,m]),R=!a||i,O=y.useCallback(I=>{D(e.id,I)},[e.id,D]);return r.jsxs("div",{ref:O,className:`agent-bar-item ${o?"selected":""} ${e.status} ${e.isBoss?"is-boss":""} ${c?"dragging":""} ${d?"drag-over":""} ${i?"touch-drag-enabled":""}`,draggable:R,onDragStart:I=>p(I,e),onDragEnd:f,onDragOver:I=>b(I,n),onDragEnter:I=>x(I,n),onDragLeave:w,onDrop:I=>k(I,n),onTouchStart:I=>C(I,e.id),onTouchMove:N,onTouchEnd:P,onTouchCancel:_,onClick:I=>S(e,I),onDoubleClick:()=>j(e),onMouseEnter:()=>L(e),onMouseLeave:M,title:a?`${e.name} (${t+1}) - Long press to reorder`:`${e.name} (${t+1}) - Drag to reorder within group`,children:[r.jsxs("div",{className:"agent-bar-avatar",children:[r.jsx("span",{className:"agent-bar-icon",children:E.icon}),r.jsx("span",{className:"agent-bar-status",style:{backgroundColor:wx(e.status)}}),l&&r.jsx("span",{className:"agent-bar-notification-badge",title:"New output available - click to view"}),e.status==="idle"&&e.lastActivity>0&&r.jsx("span",{className:"agent-bar-idle-clock",style:{color:fm(e.lastActivity)},title:gm(e.lastActivity),children:"⏱"})]}),r.jsxs("span",{className:"agent-bar-hotkey",title:`Ctrl+${t+1}`,children:["^",t+1]})]})}),MU=y.memo(function({onFocusAgent:e,onSpawnClick:t,onSpawnBossClick:n,onNewBuildingClick:a,onNewAreaClick:i}){const{t:o}=$e(["common"]),l=fi(),c=mo(),d=wm(),m=zz(),p=Bx(),f=fo(),b=gi(),x=Ux(),[w,k]=y.useState(!1);bM("AgentBar");const S=y.useRef(null),j=y.useRef(null),C=y.useRef(null),N=y.useRef(new Map);y.useEffect(()=>{{k(!1);return}},[f.experimental2DView]),y.useEffect(()=>{const Ee=j.current;if(!Ee)return;const Ye=tt=>{Ee.scrollWidth<=Ee.clientWidth||(tt.preventDefault(),Ee.scrollLeft+=tt.deltaY)};return Ee.addEventListener("wheel",Ye,{passive:!1}),()=>Ee.removeEventListener("wheel",Ye)},[]);const[P,_]=y.useState(null),[L,M]=y.useState(new Map),[D,E]=y.useState(null),[R,O]=y.useState(null),I=y.useRef(0),[B,Y]=y.useState(null),$=y.useRef(null),W=y.useRef(null),K=y.useRef(null),X=y.useRef(null),H=350,se=8,ce=y.useMemo(()=>typeof window>"u"?!1:"ontouchstart"in window||window.matchMedia("(pointer: coarse)").matches,[]),F=y.useMemo(()=>Array.from(l.values()).filter(Ee=>!z.isAgentInArchivedArea(Ee.id)).sort((Ee,Ye)=>(Ee.createdAt||0)-(Ye.createdAt||0)),[l,c]),{orderedAgents:V,moveAgent:J}=zM(F),ie=V,Q=y.useMemo(()=>{const Ee=new Map;for(const Ye of ie)Ee.set(Ye.id,z.getAreaForAgent(Ye.id));return Ee},[ie,c]),Z=y.useMemo(()=>{const Ee=new Map;for(const tt of ie){const it=Q.get(tt.id)||null,ft=(it==null?void 0:it.id)||null;Ee.has(ft)||Ee.set(ft,{area:it,agents:[]}),Ee.get(ft).agents.push(tt)}const Ye=Array.from(Ee.values());return Ye.sort((tt,it)=>{var ft,ut;return!tt.area&&it.area?1:tt.area&&!it.area?-1:!tt.area&&!it.area?0:(((ft=tt.area)==null?void 0:ft.name)||"").localeCompare(((ut=it.area)==null?void 0:ut.name)||"")}),Ye},[ie,Q]),G=y.useRef(e);G.current=e;const re=y.useRef(D);re.current=D;const ue=y.useRef(ie);ue.current=ie;const be=y.useRef(Q);be.current=Q;const ve=y.useRef(J);ve.current=J,y.useEffect(()=>{const Ee=new Map(L);let Ye=!1;for(const tt of ie){const it=L.get(tt.id);tt.currentTool?(!it||it.tool!==tt.currentTool)&&(Ee.set(tt.id,{tool:tt.currentTool,key:Date.now()}),Ye=!0):it&&setTimeout(()=>{M(ft=>{const ut=new Map(ft);return ut.delete(tt.id),ut})},1500)}Ye&&M(Ee)},[ie.map(Ee=>Ee.currentTool).join(",")]),y.useEffect(()=>{const Ee=m;if(!Ee)return;const Ye=N.current.get(Ee),tt=j.current;Ye&&tt&&requestAnimationFrame(()=>{const it=Ye.getBoundingClientRect(),ft=tt.getBoundingClientRect(),ae=it.left-ft.left+tt.scrollLeft+it.width/2,Ne=tt.clientWidth;tt.scrollTo({left:ae-Ne/2,behavior:"smooth"})})},[m]);const ge=y.useCallback((Ee,Ye)=>{if(K.current===Ee.id){K.current=null,Ye.preventDefault(),Ye.stopPropagation();return}z.setLastSelectionViaDirectClick(!0),Ye.shiftKey?z.addToSelection(Ee.id):z.selectAgent(Ee.id),z.setTerminalOpen(!0)},[]),_e=y.useCallback(Ee=>{var Ye;(Ye=G.current)==null||Ye.call(G,Ee.id),z.setTerminalOpen(!0)},[]),Le=y.useCallback(()=>_(null),[]),ke=y.useCallback((Ee,Ye)=>{Ye?N.current.set(Ee,Ye):N.current.delete(Ee)},[]),ne=y.useCallback((Ee,Ye)=>{E(Ye),Y(Ye.id),Ee.dataTransfer.effectAllowed="move",Ee.dataTransfer.setData("text/plain",Ye.id),requestAnimationFrame(()=>{Ee.target.classList.add("dragging")})},[]),de=y.useCallback(Ee=>{E(null),O(null),Y(null),I.current=0,Ee.target.classList.remove("dragging")},[]),le=y.useCallback((Ee,Ye)=>{Ee.preventDefault();const tt=re.current;if(tt){const it=be.current.get(tt.id),ft=ue.current[Ye],ut=ft?be.current.get(ft.id):null,ae=(it==null?void 0:it.id)??null,Ne=(ut==null?void 0:ut.id)??null;Ee.dataTransfer.dropEffect=ae===Ne?"move":"none"}else Ee.dataTransfer.dropEffect="move"},[]),oe=y.useCallback((Ee,Ye)=>{Ee.preventDefault(),I.current++;const tt=re.current;if(tt){const it=be.current.get(tt.id),ft=ue.current[Ye],ut=ft?be.current.get(ft.id):null,ae=(it==null?void 0:it.id)??null,Ne=(ut==null?void 0:ut.id)??null;O(ae===Ne?Ye:null)}else O(Ye)},[]),he=y.useCallback(Ee=>{I.current--,I.current===0&&O(null)},[]),Ce=y.useCallback((Ee,Ye)=>{Ee.preventDefault();const tt=re.current;if(!tt)return;const it=ue.current,ft=be.current,ut=it.findIndex(ae=>ae.id===tt.id);if(ut!==-1&&ut!==Ye){const ae=ft.get(tt.id),Ne=it[Ye],Ge=Ne?ft.get(Ne.id):null,at=(ae==null?void 0:ae.id)??null,ht=(Ge==null?void 0:Ge.id)??null;at===ht&&ve.current(ut,Ye)}E(null),O(null),Y(null),I.current=0},[]),xe=y.useCallback(()=>{$.current&&(clearTimeout($.current),$.current=null)},[]),Ze=y.useCallback(()=>{X.current&&(clearTimeout(X.current),X.current=null)},[]),ye=y.useCallback((Ee,Ye)=>{if(!ce||Ee.touches.length!==1)return;xe(),Ze(),Y(null);const tt=Ee.touches[0];W.current={agentId:Ye,x:tt.clientX,y:tt.clientY},$.current=setTimeout(()=>{Y(Ye),K.current=Ye,$.current=null},H)},[xe,Ze,ce]),Se=y.useCallback(Ee=>{if(!ce||Ee.touches.length!==1)return;const Ye=W.current;if(!Ye||!$.current)return;const tt=Ee.touches[0],it=tt.clientX-Ye.x,ft=tt.clientY-Ye.y;Math.sqrt(it*it+ft*ft)>se&&(xe(),W.current=null)},[xe,ce]),qe=y.useCallback(()=>{xe(),W.current=null,re.current||Y(null),Ze(),X.current=setTimeout(()=>{K.current=null,X.current=null},450)},[xe,Ze]);y.useEffect(()=>()=>{xe(),Ze()},[xe,Ze]);const ee=Ee=>{const Ye=`common:status.${Ee}`;return o(Ye,{defaultValue:o("common:status.unknown")})},{currentVersion:me,latestVersion:pe,relation:Oe,isChecking:Je}=NU(),Fe=me;let kt=0;return r.jsxs("div",{className:"agent-bar",ref:S,children:[r.jsxs("div",{className:"agent-bar-scroll",ref:j,children:[r.jsxs("div",{className:"agent-bar-version",title:pe?`Tide Commander v${Fe} (npm: v${pe})`:`Tide Commander v${Fe}`,children:[r.jsxs("span",{children:["v",Fe]}),Oe==="behind"&&pe?r.jsxs("span",{className:"agent-bar-version-badge agent-bar-version-badge-behind",title:`Behind npm latest v${pe}`,children:["npm v",pe]}):Oe==="ahead"&&pe?r.jsxs("span",{className:"agent-bar-version-badge agent-bar-version-badge-ahead",title:`Ahead of npm latest v${pe}`,children:["npm v",pe]}):null,Oe==="behind"?r.jsx("a",{href:"https://github.com/deivid11/tide-commander/releases",target:"_blank",rel:"noopener noreferrer",className:"agent-bar-version-status agent-bar-version-status-behind",title:o("common:agentBar.behindNpmTooltip",{defaultValue:"Current version is behind npm latest"}),children:o("common:agentBar.behindNpm",{defaultValue:"(behind npm)"})}):Oe==="ahead"?r.jsx("span",{className:"agent-bar-version-status agent-bar-version-status-ahead",title:o("common:agentBar.aheadNpmTooltip",{defaultValue:"Current version is newer than npm latest"}),children:o("common:agentBar.aheadNpm",{defaultValue:"(ahead of npm)"})}):Oe==="equal"?r.jsx("a",{href:"https://github.com/deivid11/tide-commander/releases",target:"_blank",rel:"noopener noreferrer",className:"agent-bar-version-status",children:o("common:agentBar.updated")}):Je?r.jsx("span",{className:"agent-bar-version-status",children:o("common:agentBar.checkingNpm",{defaultValue:"(checking npm)"})}):r.jsx("span",{className:"agent-bar-version-status",children:o("common:agentBar.unknownNpm",{defaultValue:"(npm unknown)"})}),w&&r.jsx("button",{className:"agent-bar-hmr-refresh",onClick:BM,title:"Refresh 3D Scene (HMR changes pending)",children:"↻"})]}),r.jsxs("div",{className:"agent-bar-list",ref:C,children:[r.jsxs("button",{className:"agent-bar-spawn-btn",onClick:t,title:o("common:agentBar.spawnNewAgent"),children:[r.jsx("span",{className:"agent-bar-spawn-icon",children:"+"}),r.jsx("span",{className:"agent-bar-spawn-label",children:o("common:agentBar.newAgent")})]}),r.jsxs("button",{className:"agent-bar-spawn-btn agent-bar-boss-btn",onClick:n,title:o("common:agentBar.spawnBoss"),children:[r.jsx("span",{className:"agent-bar-spawn-icon",children:"👑"}),r.jsx("span",{className:"agent-bar-spawn-label",children:o("common:agentBar.newBoss")})]}),r.jsxs("button",{className:"agent-bar-spawn-btn agent-bar-building-btn",onClick:a,title:o("common:agentBar.addNewBuilding"),children:[r.jsx("span",{className:"agent-bar-spawn-icon",children:"🏢"}),r.jsx("span",{className:"agent-bar-spawn-label",children:o("common:agentBar.newBuilding")})]}),r.jsxs("button",{className:"agent-bar-spawn-btn agent-bar-area-btn",onClick:i,title:o("common:agentBar.drawNewArea"),children:[r.jsx("span",{className:"agent-bar-spawn-icon",children:"🔲"}),r.jsx("span",{className:"agent-bar-spawn-label",children:o("common:agentBar.newArea")})]}),Z.map(Ee=>{var it,ft,ut,ae,Ne;const Ye=Ee.agents,tt=!Ee.area;return r.jsxs("div",{className:`agent-bar-group ${tt?"unassigned":""}`,style:{borderColor:((it=Ee.area)==null?void 0:it.color)||void 0,background:Ee.area?`${Ee.area.color}15`:void 0},children:[r.jsx("div",{className:"agent-bar-area-label",children:r.jsx("span",{className:"agent-bar-area-name",style:{color:((ft=Ee.area)==null?void 0:ft.color)||"#888"},children:((ut=Ee.area)==null?void 0:ut.name)||o("common:agentBar.unassigned")})}),((ae=Ee.area)==null?void 0:ae.directories)&&Ee.area.directories.length>0&&r.jsx("div",{className:"agent-bar-folders",children:Ee.area.directories.map((Ge,at)=>r.jsxs("div",{className:"agent-bar-folder-item",onClick:ht=>{ht.stopPropagation(),z.openFileExplorer(Ge)},children:[r.jsx("span",{className:"agent-bar-folder-icon",children:"📁"}),r.jsxs("div",{className:"agent-bar-folder-tooltip",children:[r.jsx("div",{className:"agent-bar-folder-tooltip-path",children:Ge}),r.jsx("div",{className:"agent-bar-folder-tooltip-hint",children:o("common:agentBar.clickToOpen")})]})]},at))}),Ye.map(Ge=>{const at=kt++,ht=ie.findIndex($t=>$t.id===Ge.id);return r.jsx(AU,{agent:Ge,currentIndex:at,agentIndex:ht,isTouchInput:ce,isTouchDragEnabled:B===Ge.id,isSelected:d.has(Ge.id),hasUnseenOutput:x.has(Ge.id),isDragging:(D==null?void 0:D.id)===Ge.id,isDragOver:R===ht,customClasses:b,onDragStart:ne,onDragEnd:de,onDragOver:le,onDragEnter:oe,onDragLeave:he,onDrop:Ce,onAgentClick:ge,onAgentDoubleClick:_e,onTouchStart:ye,onTouchMove:Se,onTouchEnd:qe,onTouchCancel:qe,onHoverEnter:_,onHoverLeave:Le,onItemRef:ke},Ge.id)})]},((Ne=Ee.area)==null?void 0:Ne.id)||"unassigned")})]})]}),Array.from(L.entries()).map(([Ee,Ye])=>{const tt=N.current.get(Ee);if(!tt)return null;const it=tt.getBoundingClientRect(),ft=ls[Ye.tool]||ls.default;return r.jsxs("div",{className:"agent-bar-tool-bubble",title:Ye.tool,style:{position:"fixed",left:it.left+it.width/2,bottom:window.innerHeight-it.top+8},children:[r.jsx("span",{className:"agent-bar-tool-icon",children:ft}),r.jsx("span",{className:"agent-bar-tool-name",children:Ye.tool})]},`tool-${Ee}-${Ye.key}`)}),P&&(()=>{const Ee=z.getAreaForAgent(P.id),Ye=p.get(P.id),tt=go(P.class,b),it=z.getAgentSupervisorHistory(P.id),ft=it.length>0?it[it.length-1]:void 0,ut=Date.now()-(P.createdAt||Date.now()),ae=Math.floor(ut/6e4),Ne=Math.floor(ae/60),Ge=Ne>0?`${Ne}h ${ae%60}m`:`${ae}m`,at=It=>It>=1e6?`${(It/1e6).toFixed(1)}M`:It>=1e3?`${(It/1e3).toFixed(1)}K`:It.toString(),ht=P.contextLimit>0?Math.round(P.contextUsed/P.contextLimit*100):0,$t=It=>{switch(It){case"on_track":return"#4aff9e";case"completed":return"#4a9eff";case"stalled":return"#ff9e4a";case"blocked":return"#ff4a4a";case"idle":return"#888888";default:return"#888888"}},Vt=N.current.get(P.id),jt={};if(Vt){const It=Vt.getBoundingClientRect();jt.position="fixed",jt.left=It.left+It.width/2,jt.bottom=window.innerHeight-It.top+12}return r.jsxs("div",{className:"agent-bar-tooltip",style:jt,children:[r.jsxs("div",{className:"agent-bar-tooltip-header",children:[r.jsx("span",{className:"agent-bar-tooltip-icon",children:tt.icon}),r.jsxs("span",{className:"agent-bar-tooltip-name",children:[r.jsx("img",{src:P.provider==="codex"?"/assets/codex.png":"/assets/claude.png",alt:P.provider,className:"agent-bar-provider-icon",title:P.provider==="codex"?"Codex Agent":"Claude Agent"}),P.name]}),r.jsx("span",{className:"agent-bar-tooltip-status",style:{color:wx(P.status)},children:ee(P.status)})]}),r.jsxs("div",{className:"agent-bar-tooltip-info",children:[r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[o("common:labels.class"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value",children:[P.class," — ",tt.description]})]}),Ee&&r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[o("common:agentPopup.area"),":"]}),r.jsx("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-area",style:{color:Ee.color},children:Ee.name})]}),r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[o("common:agentPopup.directory"),":"]}),r.jsx("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-path",children:P.cwd})]}),r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[o("common:labels.uptime"),":"]}),r.jsx("span",{className:"agent-bar-tooltip-value",children:Ge})]}),r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[o("common:labels.tokens"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value",children:[at(P.tokensUsed)," ",o("common:agentPopup.used")]})]}),r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[o("common:labels.context"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value",style:{color:ht>80?"#ff4a4a":ht>60?"#ff9e4a":void 0},children:[at(P.contextUsed)," / ",at(P.contextLimit)," (",ht,"%)"]})]}),P.currentTool&&r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[o("common:agentPopup.tool"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-tool",children:[ls[P.currentTool]||ls.default," ",P.currentTool]})]}),P.taskLabel&&r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsx("span",{className:"agent-bar-tooltip-label",children:"📋 Task:"}),r.jsx("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-tool",children:P.taskLabel})]}),P.currentTask&&r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[o("common:labels.task"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value",children:[P.currentTask.substring(0,150),P.currentTask.length>150?"...":""]})]}),P.lastAssignedTask&&!P.currentTask&&r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[o("common:agentPopup.assignedTask"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-query",children:[P.lastAssignedTask.substring(0,200),P.lastAssignedTask.length>200?"...":""]})]}),Ye&&r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[o("common:agentPopup.lastQuery"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-query",children:[Ye.text.substring(0,300),Ye.text.length>300?"...":""]})]}),ft&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"agent-bar-tooltip-divider"}),r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[o("common:agentPopup.supervisor"),":"]}),r.jsx("span",{className:"agent-bar-tooltip-value",style:{color:$t(ft.analysis.progress)},children:ft.analysis.progress.replace("_"," ")})]}),r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[o("common:labels.status"),":"]}),r.jsx("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-supervisor",children:ft.analysis.statusDescription})]}),ft.analysis.recentWorkSummary&&r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[o("common:labels.summary"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-supervisor",children:[ft.analysis.recentWorkSummary.substring(0,300),ft.analysis.recentWorkSummary.length>300?"...":""]})]}),ft.analysis.concerns&&ft.analysis.concerns.length>0&&r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[o("common:labels.concerns"),":"]}),r.jsx("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-concerns",children:ft.analysis.concerns.join("; ")})]})]})]})]})})()]})});function TU({activeTool:s,onExit:e}){const{t}=$e(["notifications","terminal"]);if(!s||s==="select")return null;const n=t(s==="rectangle"?"notifications:drawing.rectangleTool":"notifications:drawing.circleTool"),a=s==="rectangle"?"▭":"○";return r.jsxs("div",{className:"drawing-mode-indicator",children:[r.jsxs("div",{className:"drawing-mode-content",children:[r.jsx("span",{className:"drawing-mode-icon",children:a}),r.jsxs("div",{className:"drawing-mode-text",children:[r.jsxs("span",{className:"drawing-mode-title",children:[t("terminal:drawingMode.drawingArea"),": ",n]}),r.jsxs("span",{className:"drawing-mode-hint",children:[t("terminal:drawingMode.clickAndDrag")," • ",t("terminal:drawingMode.pressEscape")]})]})]}),r.jsx("button",{className:"drawing-mode-exit",onClick:e,title:t("terminal:drawingMode.exitDrawingMode"),children:"✕"})]})}const EU={idle:"common:status.idle",working:"common:status.working",waiting:"common:status.waiting",error:"common:status.error",offline:"common:status.offline"},Bb=s=>s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(1)}K`:s.toString(),_U=s=>{switch(s){case"on_track":return"#4aff9e";case"completed":return"#4a9eff";case"stalled":return"#ff9e4a";case"blocked":return"#ff4a4a";case"idle":return"#888888";default:return"#888888"}},DU=y.memo(function({agent:e,screenPos:t,onClose:n}){const{t:a}=$e(["common"]),i=gi(),o=z.getAreaForAgent(e.id),l=z.getState().lastPrompts.get(e.id),c=go(e.class,i),d=z.getAgentSupervisorHistory(e.id),m=d.length>0?d[d.length-1]:void 0,p=Date.now()-(e.createdAt||Date.now()),f=Math.floor(p/6e4),b=Math.floor(f/60),x=b>0?`${b}h ${f%60}m`:`${f}m`,w=e.contextLimit>0?Math.round(e.contextUsed/e.contextLimit*100):0,k=y.useMemo(()=>{let C=t.x-150,N=t.y-320-10;return typeof window<"u"&&(C<10?C=10:C+300>window.innerWidth-10&&(C=window.innerWidth-300-10),N<10&&(N=t.y+10)),{position:"fixed",left:C,top:N,zIndex:1e4,maxWidth:300,maxHeight:320,fontSize:"0.85em"}},[t.x,t.y]);return r.jsxs("div",{className:"agent-hover-popup",style:k,onMouseLeave:n,children:[r.jsxs("div",{className:"agent-bar-tooltip-header",children:[r.jsx("span",{className:"agent-bar-tooltip-icon",children:c.icon}),r.jsx("span",{className:"agent-bar-tooltip-name",children:e.name}),r.jsx("span",{className:"agent-bar-tooltip-status",style:{color:wx(e.status)},children:a(EU[e.status]||"common:status.unknown")})]}),r.jsxs("div",{className:"agent-bar-tooltip-info",children:[r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:labels.class"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value",children:[e.class," — ",c.description]})]}),o&&r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:agentPopup.area"),":"]}),r.jsx("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-area",style:{color:o.color},children:o.name})]}),r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:agentPopup.directory"),":"]}),r.jsx("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-path",children:e.cwd})]}),r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:labels.uptime"),":"]}),r.jsx("span",{className:"agent-bar-tooltip-value",children:x})]}),r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:labels.tokens"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value",children:[Bb(e.tokensUsed)," ",a("common:agentPopup.used")]})]}),r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:labels.context"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value",style:{color:w>80?"#ff4a4a":w>60?"#ff9e4a":void 0},children:[Bb(e.contextUsed)," / ",Bb(e.contextLimit)," (",w,"%)"]})]}),e.currentTool&&r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:agentPopup.tool"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-tool",children:[ls[e.currentTool]||ls.default," ",e.currentTool]})]}),e.currentTask&&r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:labels.task"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value",children:[e.currentTask.substring(0,150),e.currentTask.length>150?"...":""]})]}),e.lastAssignedTask&&!e.currentTask&&r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:agentPopup.assignedTask"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-query",children:[e.lastAssignedTask.substring(0,200),e.lastAssignedTask.length>200?"...":""]})]}),l&&r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:agentPopup.lastQuery"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-query",children:[l.text.substring(0,300),l.text.length>300?"...":""]})]}),m&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"agent-bar-tooltip-divider"}),r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:agentPopup.supervisor"),":"]}),r.jsx("span",{className:"agent-bar-tooltip-value",style:{color:_U(m.analysis.progress)},children:m.analysis.progress.replace("_"," ")})]}),r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:labels.status"),":"]}),r.jsx("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-supervisor",children:m.analysis.statusDescription})]}),m.analysis.recentWorkSummary&&r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:labels.summary"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-supervisor",children:[m.analysis.recentWorkSummary.substring(0,300),m.analysis.recentWorkSummary.length>300?"...":""]})]}),m.analysis.concerns&&m.analysis.concerns.length>0&&r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:labels.concerns"),":"]}),r.jsx("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-concerns",children:m.analysis.concerns.join("; ")})]})]})]})]})});function G1(s){if(s===0)return"0 B";const e=1024,t=["B","KB","MB","GB"],n=Math.floor(Math.log(s)/Math.log(e));return parseFloat((s/Math.pow(e,n)).toFixed(1))+" "+t[n]}function W1(s){const t=Date.now()-s,n=Math.floor(t/(1e3*60*60)),a=Math.floor(t%(1e3*60*60)/(1e3*60));return n>0?`${n}h ${a}m`:`${a}m`}const q1={30:"#1a1a1a",31:"#e74c3c",32:"#2ecc71",33:"#f39c12",34:"#3498db",35:"#9b59b6",36:"#00bcd4",37:"#ecf0f1",90:"#7f8c8d",91:"#ff6b6b",92:"#4ade80",93:"#fbbf24",94:"#60a5fa",95:"#c084fc",96:"#22d3ee",97:"#ffffff"};function PU(s){const e=[],t=/\x1B\[([0-9;]*)m/g;let n=0,a=null,i;for(;(i=t.exec(s))!==null;){if(i.index>n){const l=s.slice(n,i.index);a?e.push(r.jsx("span",{style:{color:a},children:l},e.length)):e.push(l)}const o=i[1].split(";").map(Number);for(const l of o)l===0||l===39?a=null:q1[l]&&(a=q1[l]);n=t.lastIndex}if(n<s.length){const o=s.slice(n);a?e.push(r.jsx("span",{style:{color:a},children:o},e.length)):e.push(o)}return e.length>0?e:[s]}const RU=y.memo(function({building:e,screenPos:t,onClose:n,onOpenSettings:a,onOpenLogsModal:i,onOpenUrlInModal:o}){var $,W,K,X,H,se,ce,F,V,J,ie,Q,Z,G,re,ue,be,ve,ge,_e;const{t:l}=$e(["terminal","common"]),[c,d]=y.useState(!1),[m,p]=y.useState(null),[f,b]=y.useState(!1),x=y.useRef(null),w=y.useRef(m);w.current=m;const{buildingLogs:k}=qn(),S=z.getBuildingLogs(e.id),j=($=e.pm2)==null?void 0:$.enabled,C=(W=e.docker)==null?void 0:W.enabled,N=y.useRef(null),P=y.useRef(null),_=y.useCallback(Le=>{Le.preventDefault();const ke=w.current?w.current.x:0,ne=w.current?w.current.y:0;x.current={mouseX:Le.clientX,mouseY:Le.clientY,popupX:ke,popupY:ne},b(!0),N.current=de=>{if(!x.current)return;const le=de.clientX-x.current.mouseX,oe=de.clientY-x.current.mouseY;p({x:x.current.popupX+le,y:x.current.popupY+oe})},P.current=()=>{b(!1),x.current=null,N.current&&document.removeEventListener("mousemove",N.current),P.current&&document.removeEventListener("mouseup",P.current)},document.addEventListener("mousemove",N.current),document.addEventListener("mouseup",P.current)},[]);y.useEffect(()=>()=>{N.current&&document.removeEventListener("mousemove",N.current),P.current&&document.removeEventListener("mouseup",P.current)},[]);const L=Le=>{if(Le==="logs"){if((j||C)&&i){i();return}z.sendBuildingCommand(e.id,Le),d(!0)}else z.sendBuildingCommand(e.id,Le)},M=(Le,ke)=>{if(Le){const ne=`http://localhost:${Le}`;ke&&o?o(ne):window.open(ne,"_blank")}},D=((K=e.pm2Status)==null?void 0:K.ports)||[],E=((H=(X=e.dockerStatus)==null?void 0:X.ports)==null?void 0:H.map(Le=>Le.host))||[],R=j?D:C?E:[],O=j?!!((se=e.pm2)!=null&&se.script):C?!!((ce=e.docker)!=null&&ce.image)||((F=e.docker)==null?void 0:F.mode)==="compose"||((V=e.docker)==null?void 0:V.mode)==="existing":!!((J=e.commands)!=null&&J.start),I=j?!!((ie=e.pm2)!=null&&ie.script):C?!0:!!((Q=e.commands)!=null&&Q.stop),B=j?!!((Z=e.pm2)!=null&&Z.script):C?!0:!!((G=e.commands)!=null&&G.restart),Y=y.useMemo(()=>{const ke=c?400:250;let ne=t.x+20,de=t.y-80;return typeof window<"u"&&!m&&(t.x+20+280>window.innerWidth&&(ne=t.x-280-20),t.y-80<0?de=10:t.y-80+ke>window.innerHeight&&(de=window.innerHeight-ke-10)),{position:"fixed",left:ne+((m==null?void 0:m.x)||0),top:de+((m==null?void 0:m.y)||0),zIndex:1e3,cursor:f?"grabbing":void 0}},[t.x,t.y,c,m,f]);return r.jsxs("div",{className:"building-action-popup",style:Y,onClick:Le=>Le.stopPropagation(),children:[r.jsxs("div",{className:`building-popup-header ${f?"dragging":""}`,onMouseDown:_,children:[r.jsx("span",{className:"building-popup-name",children:e.name}),R.length>0&&r.jsx("span",{className:"building-popup-ports",children:R.map(Le=>r.jsxs("a",{href:`http://localhost:${Le}`,className:"building-popup-port-link",onClick:ke=>{ke.preventDefault(),ke.stopPropagation(),M(Le,ke.altKey)},onMouseDown:ke=>ke.stopPropagation(),title:`Open http://localhost:${Le} (Alt+Click for modal)`,children:[":",Le]},Le))}),r.jsx("span",{className:"building-popup-status",style:{backgroundColor:co[e.status]},children:e.status}),r.jsx("button",{className:"building-popup-close",onClick:n,children:"x"})]}),j&&e.pm2Status&&r.jsxs("div",{className:"building-popup-metrics",children:[r.jsxs("span",{className:"metric",children:[r.jsx("span",{className:"label",children:"PID"}),r.jsx("span",{className:"value",children:e.pm2Status.pid||"-"})]}),r.jsxs("span",{className:"metric",children:[r.jsx("span",{className:"label",children:"CPU"}),r.jsxs("span",{className:"value",children:[((re=e.pm2Status.cpu)==null?void 0:re.toFixed(1))||"0","%"]})]}),r.jsxs("span",{className:"metric",children:[r.jsx("span",{className:"label",children:"MEM"}),r.jsx("span",{className:"value",children:G1(e.pm2Status.memory||0)})]}),e.pm2Status.restarts!==void 0&&e.pm2Status.restarts>0&&r.jsxs("span",{className:"metric",children:[r.jsx("span",{className:"label",children:"RST"}),r.jsx("span",{className:"value",children:e.pm2Status.restarts})]}),e.pm2Status.uptime&&r.jsxs("span",{className:"metric",children:[r.jsx("span",{className:"label",children:"UP"}),r.jsx("span",{className:"value",children:W1(e.pm2Status.uptime)})]})]}),C&&e.dockerStatus&&r.jsxs("div",{className:"building-popup-metrics",children:[r.jsxs("span",{className:"metric",children:[r.jsx("span",{className:"label",children:"ID"}),r.jsx("span",{className:"value",children:e.dockerStatus.containerId||"-"})]}),e.dockerStatus.cpu!==void 0&&r.jsxs("span",{className:"metric",children:[r.jsx("span",{className:"label",children:"CPU"}),r.jsxs("span",{className:"value",children:[e.dockerStatus.cpu.toFixed(1),"%"]})]}),e.dockerStatus.memory!==void 0&&r.jsxs("span",{className:"metric",children:[r.jsx("span",{className:"label",children:"MEM"}),r.jsx("span",{className:"value",children:G1(e.dockerStatus.memory)})]}),e.dockerStatus.health&&e.dockerStatus.health!=="none"&&r.jsxs("span",{className:"metric",children:[r.jsx("span",{className:"label",children:"HEALTH"}),r.jsx("span",{className:"value",style:{color:e.dockerStatus.health==="healthy"?"#4ade80":e.dockerStatus.health==="unhealthy"?"#f87171":"#fbbf24"},children:e.dockerStatus.health==="healthy"?"✓":e.dockerStatus.health==="unhealthy"?"✗":"..."})]}),e.dockerStatus.startedAt&&r.jsxs("span",{className:"metric",children:[r.jsx("span",{className:"label",children:"UP"}),r.jsx("span",{className:"value",children:W1(e.dockerStatus.startedAt)})]})]}),C&&((ue=e.dockerStatus)==null?void 0:ue.services)&&e.dockerStatus.services.length>0&&r.jsx("div",{className:"building-popup-services",children:e.dockerStatus.services.map((Le,ke)=>r.jsxs("span",{className:"service-item",title:`${Le.name}: ${Le.status}`,children:[r.jsx("span",{className:"service-indicator",style:{backgroundColor:Le.status==="running"?"#4ade80":"#f87171"}}),r.jsx("span",{className:"service-name",children:Le.name})]},ke))}),(e.lastError||j&&((be=e.pm2Status)==null?void 0:be.status)==="errored"||C&&((ve=e.dockerStatus)==null?void 0:ve.status)==="dead")&&r.jsxs("div",{className:"building-popup-error",children:[e.lastError||l("terminal:building.processFailedToStart"),j&&((ge=e.pm2Status)==null?void 0:ge.restarts)&&e.pm2Status.restarts>5&&r.jsxs("span",{className:"error-hint",children:[" - ",l("terminal:building.checkLogsOrConfig")]}),C&&((_e=e.dockerStatus)==null?void 0:_e.health)==="unhealthy"&&r.jsxs("span",{className:"error-hint",children:[" - ",l("terminal:building.healthCheckFailing")]})]}),r.jsxs("div",{className:"building-popup-actions",children:[r.jsxs("button",{className:"action-btn start",onClick:()=>L("start"),disabled:!O||e.status==="running"||e.status==="starting",title:l(O?"terminal:buildingAction.start":"terminal:buildingAction.noStartCommand"),children:[r.jsx("span",{className:"icon",children:"▶"}),l("terminal:buildingAction.start")]}),r.jsxs("button",{className:"action-btn stop",onClick:()=>L("stop"),disabled:!I||e.status==="stopped"||e.status==="stopping",title:l(I?"terminal:buildingAction.stop":"terminal:buildingAction.noStopCommand"),children:[r.jsx("span",{className:"icon",children:"■"}),l("terminal:buildingAction.stop")]}),r.jsxs("button",{className:"action-btn restart",onClick:()=>L("restart"),disabled:!B,title:l(B?"terminal:buildingAction.restart":"terminal:buildingAction.noRestartCommand"),children:[r.jsx("span",{className:"icon",children:"↺"}),l("terminal:buildingAction.restart")]}),r.jsxs("button",{className:"action-btn logs",onClick:()=>L("logs"),title:l("terminal:buildingAction.viewLogs"),children:[r.jsx("span",{className:"icon",children:"📄"}),l("terminal:logs.title")]}),R.length===1&&r.jsxs("button",{className:"action-btn open-url",onClick:Le=>M(R[0],Le.altKey),title:`Open http://localhost:${R[0]} (Alt+Click for modal)`,children:[r.jsx("span",{className:"icon",children:"🔗"}),l("terminal:buildingAction.openInBrowser")]}),R.length>1&&r.jsxs("div",{className:"action-btn-group",children:[r.jsxs("span",{className:"action-btn-label",children:[l("terminal:buildingAction.openInBrowser"),":"]}),R.map(Le=>r.jsxs("button",{className:"action-btn open-url port-btn",onClick:ke=>M(Le,ke.altKey),title:`Open http://localhost:${Le} (Alt+Click for modal)`,children:[":",Le]},Le))]})]}),c&&S.length>0&&r.jsxs("div",{className:"building-popup-logs",children:[r.jsxs("div",{className:"logs-header",children:[r.jsx("span",{children:l("terminal:logs.title")}),r.jsx("button",{onClick:()=>z.clearBuildingLogs(e.id),children:l("terminal:logs.clear")})]}),r.jsx("div",{className:"logs-content",children:S.slice(-50).map((Le,ke)=>r.jsx("pre",{children:PU(Le)},ke))})]}),r.jsx("button",{className:"building-popup-settings",onClick:a,children:l("terminal:buildingAction.fullSettings")})]})});function LU(s){if(s===0)return"0 B";const e=1024,t=["B","KB","MB","GB"],n=Math.floor(Math.log(s)/Math.log(e));return parseFloat((s/Math.pow(e,n)).toFixed(1))+" "+t[n]}function OU(s){const t=Date.now()-s,n=Math.floor(t/(1e3*60*60)),a=Math.floor(t%(1e3*60*60)/(1e3*60));return n>0?`${n}h ${a}m`:`${a}m`}const IU=y.memo(function({building:e,screenPos:t,onClose:n,onOpenSettings:a,onOpenLogsModal:i,onOpenUrlInModal:o}){const{t:l}=$e(["terminal","common"]),[c,d]=y.useState(null),[m,p]=y.useState(!1),f=y.useRef(null),b=y.useRef(c);b.current=c;const{buildings:x}=qn(),k=(e.subordinateBuildingIds||[]).map(D=>x.get(D)).filter(D=>D!==void 0),S=y.useRef(null),j=y.useRef(null),C=y.useCallback(D=>{D.preventDefault();const E=b.current?b.current.x:0,R=b.current?b.current.y:0;f.current={mouseX:D.clientX,mouseY:D.clientY,popupX:E,popupY:R},p(!0),S.current=O=>{if(!f.current)return;const I=O.clientX-f.current.mouseX,B=O.clientY-f.current.mouseY;d({x:f.current.popupX+I,y:f.current.popupY+B})},j.current=()=>{p(!1),f.current=null,S.current&&document.removeEventListener("mousemove",S.current),j.current&&document.removeEventListener("mouseup",j.current)},document.addEventListener("mousemove",S.current),document.addEventListener("mouseup",j.current)},[]);y.useEffect(()=>()=>{S.current&&document.removeEventListener("mousemove",S.current),j.current&&document.removeEventListener("mouseup",j.current)},[]);const N=D=>{z.sendBossBuildingCommand(e.id,D)},P=k.reduce((D,E)=>(D[E.status]=(D[E.status]||0)+1,D),{}),_=k.some(D=>{var E;return(E=D.pm2)==null?void 0:E.enabled}),L=(D,E)=>{const R=`http://localhost:${D}`;E&&o?o(R):window.open(R,"_blank")},M=y.useMemo(()=>{let R=t.x+20,O=t.y-80;return typeof window<"u"&&!c&&(t.x+20+340>window.innerWidth&&(R=t.x-340-20),t.y-80<0?O=10:t.y-80+350>window.innerHeight&&(O=window.innerHeight-350-10)),{position:"fixed",left:R+((c==null?void 0:c.x)||0),top:O+((c==null?void 0:c.y)||0),zIndex:1e3,cursor:m?"grabbing":void 0}},[t.x,t.y,c,m]);return r.jsxs("div",{className:"building-action-popup boss-building-popup",style:M,onClick:D=>D.stopPropagation(),children:[r.jsxs("div",{className:`building-popup-header boss-header ${m?"dragging":""}`,onMouseDown:C,children:[r.jsx("span",{className:"boss-icon",children:"👑"}),r.jsx("span",{className:"building-popup-name",children:e.name}),r.jsx("span",{className:"subordinate-count",children:l("terminal:building.unitsCount",{count:k.length})}),r.jsx("button",{className:"building-popup-close",onClick:n,children:"x"})]}),r.jsxs("div",{className:"boss-status-overview",children:[Object.entries(P).map(([D,E])=>r.jsxs("span",{className:"status-badge",style:{backgroundColor:co[D]||"#666"},children:[E," ",D]},D)),k.length===0&&r.jsx("span",{className:"no-subordinates",children:l("terminal:building.noSubordinates")})]}),k.length>0&&r.jsx("div",{className:"subordinate-list",children:k.map(D=>{var E,R,O;return r.jsxs("div",{className:"subordinate-item",children:[r.jsx("span",{className:"sub-status-dot",style:{backgroundColor:co[D.status]}}),r.jsx("span",{className:"sub-name",children:D.name}),((E=D.pm2Status)==null?void 0:E.ports)&&D.pm2Status.ports.length>0&&r.jsx("span",{className:"sub-port",children:D.pm2Status.ports.map(I=>r.jsxs("a",{href:`http://localhost:${I}`,className:"building-popup-port-link",onClick:B=>{B.preventDefault(),B.stopPropagation(),L(I,B.altKey)},title:`Open http://localhost:${I} (Alt+Click for modal)`,children:[":",I]},I))}),D.pm2Status&&r.jsxs("span",{className:"sub-metrics",children:[(R=D.pm2Status.cpu)==null?void 0:R.toFixed(0),"% | ",LU(D.pm2Status.memory||0)]}),((O=D.pm2Status)==null?void 0:O.uptime)&&r.jsx("span",{className:"sub-uptime",children:OU(D.pm2Status.uptime)})]},D.id)})}),r.jsxs("div",{className:"building-popup-actions boss-actions",children:[r.jsxs("button",{className:"action-btn start",onClick:()=>N("start_all"),disabled:k.length===0,title:l("terminal:building.startAllSubs"),children:[r.jsx("span",{className:"icon",children:"▶"}),l("terminal:building.startAll")]}),r.jsxs("button",{className:"action-btn stop",onClick:()=>N("stop_all"),disabled:k.length===0,title:l("terminal:building.stopAllSubs"),children:[r.jsx("span",{className:"icon",children:"■"}),l("terminal:building.stopAll")]}),r.jsxs("button",{className:"action-btn restart",onClick:()=>N("restart_all"),disabled:k.length===0,title:l("terminal:building.restartAllSubs"),children:[r.jsx("span",{className:"icon",children:"↺"}),l("terminal:building.restartAll")]}),_&&r.jsxs("button",{className:"action-btn logs",onClick:i,title:l("terminal:building.viewUnifiedLogs"),children:[r.jsx("span",{className:"icon",children:"📄"}),l("terminal:building.logs")]})]}),r.jsx("button",{className:"building-popup-settings",onClick:a,children:l("terminal:building.fullSettings")})]})}),BU=y.memo(function({building:e,screenPos:t,onClose:n,onOpenSettings:a,onOpenDatabasePanel:i}){var P;const{t:o}=$e(["terminal","common"]),[l,c]=y.useState(null),[d,m]=y.useState(!1),p=y.useRef(null),f=y.useRef(l);f.current=l;const b=Sm(e.id),x=((P=e.database)==null?void 0:P.connections)??[],w=y.useRef(null),k=y.useRef(null),S=y.useCallback(_=>{_.preventDefault();const L=f.current?f.current.x:0,M=f.current?f.current.y:0;p.current={mouseX:_.clientX,mouseY:_.clientY,popupX:L,popupY:M},m(!0),w.current=D=>{if(!p.current)return;const E=D.clientX-p.current.mouseX,R=D.clientY-p.current.mouseY;c({x:p.current.popupX+E,y:p.current.popupY+R})},k.current=()=>{m(!1),p.current=null,w.current&&document.removeEventListener("mousemove",w.current),k.current&&document.removeEventListener("mouseup",k.current)},document.addEventListener("mousemove",w.current),document.addEventListener("mouseup",k.current)},[]);y.useEffect(()=>()=>{w.current&&document.removeEventListener("mousemove",w.current),k.current&&document.removeEventListener("mouseup",k.current)},[]);const j=_=>{z.testDatabaseConnection(e.id,_)},C=_=>b.connectionStatus.get(_),N=y.useMemo(()=>{let M=t.x+20,D=t.y-80;return typeof window<"u"&&!l&&(t.x+20+320>window.innerWidth&&(M=t.x-320-20),t.y-80<0?D=10:t.y-80+300>window.innerHeight&&(D=window.innerHeight-300-10)),{position:"fixed",left:M+((l==null?void 0:l.x)||0),top:D+((l==null?void 0:l.y)||0),zIndex:1e3,cursor:d?"grabbing":void 0}},[t.x,t.y,l,d]);return r.jsxs("div",{className:"building-action-popup database-building-popup",style:N,onClick:_=>_.stopPropagation(),children:[r.jsxs("div",{className:`building-popup-header database-header ${d?"dragging":""}`,onMouseDown:S,children:[r.jsx("span",{className:"database-icon",children:"🗄️"}),r.jsx("span",{className:"building-popup-name",children:e.name}),r.jsx("span",{className:"connection-count",children:o("terminal:building.connCount",{count:x.length})}),r.jsx("button",{className:"building-popup-close",onClick:n,children:"x"})]}),x.length>0?r.jsx("div",{className:"database-connection-list",children:x.map(_=>{const L=C(_.id);return r.jsxs("div",{className:"database-connection-item",children:[r.jsx("span",{className:"conn-engine",children:_.engine==="mysql"?"🐬":"🐘"}),r.jsx("span",{className:"conn-name",children:_.name}),r.jsxs("span",{className:"conn-host",children:[_.host,":",_.port]}),L&&r.jsx("span",{className:`conn-status ${L.connected?"connected":"disconnected"}`,children:L.connected?"●":"○"}),r.jsx("button",{className:"conn-test-btn",onClick:()=>j(_.id),title:o("terminal:building.testConnection"),children:"↻"})]},_.id)})}):r.jsxs("div",{className:"database-no-connections",children:[r.jsx("p",{children:o("terminal:building.noConnections")}),r.jsx("p",{className:"hint",children:o("terminal:building.clickSettingsToAdd")})]}),r.jsxs("div",{className:"building-popup-actions database-actions",children:[r.jsxs("button",{className:"action-btn query",onClick:i,disabled:x.length===0,title:o("terminal:building.openDbExplorer"),children:[r.jsx("span",{className:"icon",children:"⌨"}),o("terminal:building.query")]}),r.jsxs("button",{className:"action-btn test-all",onClick:()=>x.forEach(_=>j(_.id)),disabled:x.length===0,title:o("terminal:building.testAllConnections"),children:[r.jsx("span",{className:"icon",children:"↻"}),o("terminal:building.testAll")]})]}),r.jsx("button",{className:"building-popup-settings",onClick:a,children:o("common:buttons.settings")})]})}),zU=({building:s,connections:e,activeConnectionId:t,activeDatabase:n,collapsed:a,onToggleCollapse:i,onConnectionChange:o,onDatabaseChange:l,onInsertTable:c,onSelectTableQuery:d})=>{const{t:m}=$e(["terminal"]),p=Sm(s.id),[f,b]=y.useState(new Set),[x,w]=y.useState(""),[k,S]=y.useState(!1),[j,C]=y.useState(null),N=y.useRef(null),P=y.useRef(null),_=t?p.databases.get(t)??[]:[],L=t&&n?`${t}:${n}`:"",M=L?p.tables.get(L)??[]:[],D=t?p.connectionStatus.get(t):void 0,E=y.useMemo(()=>{if(!x.trim())return _;const I=x.toLowerCase();return _.filter(B=>B.toLowerCase().includes(I))},[_,x]);y.useEffect(()=>{const I=B=>{P.current&&!P.current.contains(B.target)&&S(!1)};return k&&document.addEventListener("mousedown",I),()=>document.removeEventListener("mousedown",I)},[k]),y.useEffect(()=>{t&&!D&&z.testDatabaseConnection(s.id,t)},[s.id,t,D]),y.useEffect(()=>{t&&(D!=null&&D.connected)&&_.length===0&&z.listDatabases(s.id,t)},[s.id,t,D==null?void 0:D.connected,_.length]),y.useEffect(()=>{t&&n&&M.length===0&&z.listTables(s.id,t,n)},[s.id,t,n,M.length]),y.useEffect(()=>{C(null)},[t,n]);const R=y.useCallback(I=>{b(B=>{const Y=new Set(B);if(Y.has(I))Y.delete(I);else if(Y.add(I),t&&n){const $=`${t}:${n}:${I}`;p.tableSchemas.has($)||z.getTableSchema(s.id,t,n,I)}return Y})},[s.id,t,n,p.tableSchemas]),O=I=>{if(!t||!n)return null;const B=`${t}:${n}:${I}`;return p.tableSchemas.get(B)};return a?r.jsx("div",{className:"database-sidebar database-sidebar--collapsed",children:r.jsx("button",{className:"database-sidebar__toggle",onClick:i,title:m("terminal:database.expandSidebar"),children:"»"})}):r.jsxs("div",{className:"database-sidebar",children:[r.jsxs("div",{className:"database-sidebar__header",children:[r.jsx("span",{children:m("terminal:database.explorer")}),r.jsx("button",{className:"database-sidebar__toggle",onClick:i,title:m("terminal:database.collapseSidebar"),children:"«"})]}),r.jsxs("div",{className:"database-sidebar__section",children:[r.jsx("div",{className:"database-sidebar__section-title",children:m("terminal:database.connection")}),r.jsx("select",{className:"database-sidebar__select",value:t||"",onChange:I=>o(I.target.value),children:e.length===0?r.jsx("option",{value:"",children:m("terminal:database.noConnections")}):e.map(I=>r.jsxs("option",{value:I.id,children:[I.engine==="mysql"?"🐬":"🐘"," ",I.name]},I.id))}),D&&r.jsx("div",{className:`database-sidebar__status ${D.connected?"database-sidebar__status--connected":"database-sidebar__status--error"}`,children:D.connected?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"database-sidebar__status-icon",children:"✓"}),m("terminal:database.connected"),D.serverVersion&&r.jsxs("span",{className:"database-sidebar__version",children:["(",D.serverVersion,")"]})]}):r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"database-sidebar__status-icon",children:"✗"}),D.error||m("terminal:database.disconnected")]})})]}),_.length>0&&r.jsxs("div",{className:"database-sidebar__section",children:[r.jsx("div",{className:"database-sidebar__section-title",children:m("terminal:database.databaseTitle")}),r.jsxs("div",{className:"database-sidebar__searchable-select",ref:P,children:[r.jsx("input",{ref:N,className:"database-sidebar__search-input",type:"text",value:k?x:n||"",placeholder:m("terminal:database.selectDatabase"),onChange:I=>{w(I.target.value),k||S(!0)},onFocus:()=>{S(!0),w("")},onKeyDown:I=>{var B,Y;I.key==="Escape"?(S(!1),w(""),(B=N.current)==null||B.blur()):I.key==="Enter"&&E.length===1&&(l(E[0]),S(!1),w(""),(Y=N.current)==null||Y.blur())}}),k&&r.jsx("div",{className:"database-sidebar__dropdown",children:E.length===0?r.jsx("div",{className:"database-sidebar__dropdown-empty",children:"No matches"}):E.map(I=>r.jsx("div",{className:`database-sidebar__dropdown-item ${I===n?"database-sidebar__dropdown-item--active":""}`,onMouseDown:B=>{B.preventDefault(),l(I),S(!1),w("")},children:I},I))})]})]}),M.length>0&&r.jsxs("div",{className:"database-sidebar__section database-sidebar__section--tables",children:[r.jsx("div",{className:"database-sidebar__section-title",children:m("terminal:database.tablesCount",{count:M.length})}),r.jsx("div",{className:"database-sidebar__tables",children:M.map(I=>{const B=f.has(I.name),Y=B?O(I.name):null;return r.jsxs("div",{className:"database-sidebar__table",children:[r.jsxs("div",{className:"database-sidebar__table-header",children:[r.jsx("button",{className:"database-sidebar__table-expand",onClick:()=>R(I.name),title:B?"Collapse table schema":"Expand table schema",children:B?"▼":"▶"}),r.jsx("span",{className:"database-sidebar__table-icon",children:I.type==="view"?"👁":"📋"}),r.jsx("span",{className:`database-sidebar__table-name ${j===I.name?"database-sidebar__table-name--selected":""}`,onClick:()=>C(I.name),onDoubleClick:()=>{C(I.name),d(I.name)},children:I.name}),r.jsx("button",{className:"database-sidebar__table-insert",onClick:$=>{$.stopPropagation(),c(I.name)},title:m("terminal:database.insertTableName"),children:"+"})]}),B&&Y&&r.jsx("div",{className:"database-sidebar__table-columns",children:Y.columns.map($=>r.jsxs("div",{className:"database-sidebar__column",onClick:()=>c($.name),title:`${$.type}${$.nullable?" NULL":" NOT NULL"}${$.primaryKey?" PK":""}`,children:[r.jsx("span",{className:"database-sidebar__column-icon",children:$.primaryKey?"🔑":""}),r.jsx("span",{className:"database-sidebar__column-name",children:$.name}),r.jsx("span",{className:"database-sidebar__column-type",children:$.type})]},$.name))})]},I.name)})})]})]})};function xv(s){const e=[];let t=!1,n=!1,a=!1,i=!1,o=0;for(let c=0;c<s.length;c++){const d=s[c],m=s[c+1];if(a){d===`
236
236
  `&&(a=!1);continue}if(i){d==="*"&&m==="/"&&(i=!1,c++);continue}if(t){if(d==="'"&&m==="'"){c++;continue}d==="'"&&(t=!1);continue}if(n){if(d==='"'&&m==='"'){c++;continue}d==='"'&&(n=!1);continue}if(d==="-"&&m==="-"){a=!0,c++;continue}if(d==="/"&&m==="*"){i=!0,c++;continue}if(d==="'"){t=!0;continue}if(d==='"'){n=!0;continue}if(d===";"){const p=s.slice(o,c).trim();p&&e.push({sql:p,start:o,end:c}),o=c+1}}const l=s.slice(o).trim();return l&&e.push({sql:l,start:o,end:s.length}),e}function FU(s,e){const t=xv(s);if(t.length===0)return null;for(const n of t)if(e>=n.start&&e<=n.end)return n.sql;return t[t.length-1].sql}const $U=({query:s,onChange:e,onExecute:t,isExecuting:n,disabled:a,autoFocus:i=!0})=>{const{t:o}=$e(["terminal"]),l=y.useRef(null),c=y.useRef(null),d=y.useRef(!1),m="query-editor-height",p=80,f=800,[b,x]=y.useState(()=>{try{const L=localStorage.getItem(m);if(L){const M=Number(L);if(M>=p&&M<=f)return M}}catch{}return 150}),w=y.useCallback(L=>{try{localStorage.setItem(m,String(L))}catch{}},[]),k=y.useCallback(L=>{L.preventDefault(),d.current=!0;const M=L.clientY,D=b,E=O=>{const I=O.clientY-M,B=Math.max(p,Math.min(f,D+I));x(B)},R=()=>{var I;d.current=!1,document.removeEventListener("mousemove",E),document.removeEventListener("mouseup",R),document.body.style.cursor="",document.body.style.userSelect="";const O=(I=l.current)==null?void 0:I.parentElement;O&&w(O.getBoundingClientRect().height)};document.addEventListener("mousemove",E),document.addEventListener("mouseup",R),document.body.style.cursor="row-resize",document.body.style.userSelect="none"},[b,w]);y.useEffect(()=>{if(i&&!a&&l.current){const L=setTimeout(()=>{var M;(M=l.current)==null||M.focus()},100);return()=>clearTimeout(L)}},[i,a]);const S=y.useCallback(L=>{const M=L.currentTarget;c.current&&(c.current.scrollLeft=M.scrollLeft,c.current.scrollTop=M.scrollTop)},[]),j=y.useMemo(()=>xv(s).length>1,[s]),C=y.useCallback(L=>{if((L.ctrlKey||L.metaKey)&&L.shiftKey&&L.key==="Enter"){L.preventDefault(),!a&&!n&&t("all");return}if((L.ctrlKey||L.metaKey)&&L.key==="Enter"&&(L.preventDefault(),!a&&!n&&t("cursor")),L.key==="Tab"){L.preventDefault();const M=L.currentTarget,D=M.selectionStart,E=M.selectionEnd,R=s.substring(0,D)+" "+s.substring(E);e(R),setTimeout(()=>{M.selectionStart=M.selectionEnd=D+2},0)}},[s,e,t,a,n]),N=y.useMemo(()=>{if(!s)return"";try{return xr.highlight(s,xr.languages.sql,"sql")}catch{return s}},[s]),P=y.useMemo(()=>s.split(`
237
237
  `).map((M,D)=>D+1),[s]),_=y.useCallback(()=>{var L;return((L=l.current)==null?void 0:L.selectionStart)??0},[]);return r.jsxs("div",{className:"query-editor",children:[r.jsxs("div",{className:"query-editor__toolbar",children:[r.jsxs("div",{className:"query-editor__buttons",children:[r.jsx("button",{className:"query-editor__execute",onClick:()=>t("cursor"),disabled:a||n||!s.trim(),title:o("terminal:database.executeShortcut"),children:n?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"query-editor__spinner"}),o("common:status.running")]}):r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"query-editor__play-icon",children:"▶"}),o(j?"terminal:database.runAtCursor":"terminal:database.runQuery")]})}),j&&r.jsxs("button",{className:"query-editor__execute-cursor",onClick:()=>t("all"),disabled:a||n||!s.trim(),title:o("terminal:database.executeCursorShortcut"),children:[r.jsx("span",{className:"query-editor__cursor-icon",children:"▶▶"}),o("terminal:database.runAll")]})]}),r.jsx("div",{className:"query-editor__hint",children:o(j?"terminal:database.pressCtrlEnterMulti":"terminal:database.pressCtrlEnter")})]}),r.jsxs("div",{className:"query-editor__input-wrapper",children:[r.jsx("div",{className:"query-editor__line-numbers",children:P.map(L=>r.jsx("span",{children:L},L))}),r.jsxs("div",{className:"query-editor__editor",style:{height:b},children:[r.jsx("pre",{ref:c,className:"query-editor__highlight","aria-hidden":"true",dangerouslySetInnerHTML:{__html:N+`
238
238
  `}}),r.jsx("textarea",{ref:l,className:"query-editor__textarea",value:s,onChange:L=>e(L.target.value),onKeyDown:C,onScroll:S,placeholder:o(a?"terminal:database.selectDbPlaceholder":"terminal:database.enterQueryPlaceholder"),disabled:a,spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off","data-cursor-pos":_()})]})]}),r.jsx("div",{className:"query-editor__resize-handle",onMouseDown:k})]})};function LE(s){var e,t,n="";if(typeof s=="string"||typeof s=="number")n+=s;else if(typeof s=="object")if(Array.isArray(s)){var a=s.length;for(e=0;e<a;e++)s[e]&&(t=LE(s[e]))&&(n&&(n+=" "),n+=t)}else for(t in s)s[t]&&(n&&(n+=" "),n+=t);return n}function js(){for(var s,e,t=0,n="",a=arguments.length;t<a;t++)(s=arguments[t])&&(e=LE(s))&&(n&&(n+=" "),n+=e);return n}const OE=6048e5,HU=864e5,_m=6e4,Dm=36e5,UU=1e3,Y1=Symbol.for("constructDateFrom");function Nn(s,e){return typeof s=="function"?s(e):s&&typeof s=="object"&&Y1 in s?s[Y1](e):s instanceof Date?new s.constructor(e):new Date(e)}function wt(s,e){return Nn(e||s,s)}function ci(s,e,t){const n=wt(s,t==null?void 0:t.in);return isNaN(e)?Nn((t==null?void 0:t.in)||s,NaN):(e&&n.setDate(n.getDate()+e),n)}function di(s,e,t){const n=wt(s,t==null?void 0:t.in);if(isNaN(e))return Nn(s,NaN);if(!e)return n;const a=n.getDate(),i=Nn(s,n.getTime());i.setMonth(n.getMonth()+e+1,0);const o=i.getDate();return a>=o?i:(n.setFullYear(i.getFullYear(),i.getMonth(),a),n)}function IE(s,e,t){return Nn(s,+wt(s)+e)}function GU(s,e,t){return IE(s,e*Dm)}let WU={};function ml(){return WU}function vr(s,e){var l,c,d,m;const t=ml(),n=(e==null?void 0:e.weekStartsOn)??((c=(l=e==null?void 0:e.locale)==null?void 0:l.options)==null?void 0:c.weekStartsOn)??t.weekStartsOn??((m=(d=t.locale)==null?void 0:d.options)==null?void 0:m.weekStartsOn)??0,a=wt(s,e==null?void 0:e.in),i=a.getDay(),o=(i<n?7:0)+i-n;return a.setDate(a.getDate()-o),a.setHours(0,0,0,0),a}function jc(s,e){return vr(s,{...e,weekStartsOn:1})}function BE(s,e){const t=wt(s,e==null?void 0:e.in),n=t.getFullYear(),a=Nn(t,0);a.setFullYear(n+1,0,4),a.setHours(0,0,0,0);const i=jc(a),o=Nn(t,0);o.setFullYear(n,0,4),o.setHours(0,0,0,0);const l=jc(o);return t.getTime()>=i.getTime()?n+1:t.getTime()>=l.getTime()?n:n-1}function Zp(s){const e=wt(s),t=new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()));return t.setUTCFullYear(e.getFullYear()),+s-+t}function jr(s,...e){const t=Nn.bind(null,e.find(n=>typeof n=="object"));return e.map(t)}function ul(s,e){const t=wt(s,e==null?void 0:e.in);return t.setHours(0,0,0,0),t}function Cc(s,e,t){const[n,a]=jr(t==null?void 0:t.in,s,e),i=ul(n),o=ul(a),l=+i-Zp(i),c=+o-Zp(o);return Math.round((l-c)/HU)}function qU(s,e){const t=BE(s,e),n=Nn(s,0);return n.setFullYear(t,0,4),n.setHours(0,0,0,0),jc(n)}function bd(s,e,t){const n=wt(s,t==null?void 0:t.in);return n.setTime(n.getTime()+e*_m),n}function vv(s,e,t){return di(s,e*3,t)}function YU(s,e,t){return IE(s,e*1e3)}function Qp(s,e,t){return ci(s,e*7,t)}function ui(s,e,t){return di(s,e*12,t)}function V1(s,e){let t,n=e==null?void 0:e.in;return s.forEach(a=>{!n&&typeof a=="object"&&(n=Nn.bind(null,a));const i=wt(a,n);(!t||t<i||isNaN(+i))&&(t=i)}),Nn(n,t||NaN)}function K1(s,e){let t,n=e==null?void 0:e.in;return s.forEach(a=>{!n&&typeof a=="object"&&(n=Nn.bind(null,a));const i=wt(a,n);(!t||t>i||isNaN(+i))&&(t=i)}),Nn(n,t||NaN)}function VU(s,e,t){const[n,a]=jr(t==null?void 0:t.in,s,e);return+ul(n)==+ul(a)}function Li(s){return s instanceof Date||typeof s=="object"&&Object.prototype.toString.call(s)==="[object Date]"}function Nc(s){return!(!Li(s)&&typeof s!="number"||isNaN(+wt(s)))}function Jp(s,e,t){const[n,a]=jr(t==null?void 0:t.in,s,e),i=n.getFullYear()-a.getFullYear(),o=n.getMonth()-a.getMonth();return i*12+o}function ao(s,e){const t=wt(s,e==null?void 0:e.in);return Math.trunc(t.getMonth()/3)+1}function em(s,e,t){const[n,a]=jr(t==null?void 0:t.in,s,e),i=n.getFullYear()-a.getFullYear(),o=ao(n)-ao(a);return i*4+o}function tm(s,e,t){const[n,a]=jr(t==null?void 0:t.in,s,e);return n.getFullYear()-a.getFullYear()}function KU(s,e,t){const[n,a]=jr(t==null?void 0:t.in,s,e),i=X1(n,a),o=Math.abs(Cc(n,a));n.setDate(n.getDate()-i*o);const l=+(X1(n,a)===-i),c=i*(o-l);return c===0?0:c}function X1(s,e){const t=s.getFullYear()-e.getFullYear()||s.getMonth()-e.getMonth()||s.getDate()-e.getDate()||s.getHours()-e.getHours()||s.getMinutes()-e.getMinutes()||s.getSeconds()-e.getSeconds()||s.getMilliseconds()-e.getMilliseconds();return t<0?-1:t>0?1:t}function zE(s,e){const t=wt(s,e==null?void 0:e.in);return t.setHours(23,59,59,999),t}function FE(s,e){const t=wt(s,e==null?void 0:e.in),n=t.getMonth();return t.setFullYear(t.getFullYear(),n+1,0),t.setHours(23,59,59,999),t}function Ky(s,e){const t=wt(s,e==null?void 0:e.in),n=t.getMonth(),a=n-n%3;return t.setMonth(a,1),t.setHours(0,0,0,0),t}function $E(s,e){const t=wt(s,e==null?void 0:e.in);return t.setDate(1),t.setHours(0,0,0,0),t}function HE(s,e){const t=wt(s,e==null?void 0:e.in),n=t.getFullYear();return t.setFullYear(n+1,0,0),t.setHours(23,59,59,999),t}function Pm(s,e){const t=wt(s,e==null?void 0:e.in);return t.setFullYear(t.getFullYear(),0,1),t.setHours(0,0,0,0),t}function XU(s,e){var l,c;const t=ml(),n=t.weekStartsOn??((c=(l=t.locale)==null?void 0:l.options)==null?void 0:c.weekStartsOn)??0,a=wt(s,e==null?void 0:e.in),i=a.getDay(),o=(i<n?-7:0)+6-(i-n);return a.setDate(a.getDate()+o),a.setHours(23,59,59,999),a}const ZU={lessThanXSeconds:{one:"less than a second",other:"less than {{count}} seconds"},xSeconds:{one:"1 second",other:"{{count}} seconds"},halfAMinute:"half a minute",lessThanXMinutes:{one:"less than a minute",other:"less than {{count}} minutes"},xMinutes:{one:"1 minute",other:"{{count}} minutes"},aboutXHours:{one:"about 1 hour",other:"about {{count}} hours"},xHours:{one:"1 hour",other:"{{count}} hours"},xDays:{one:"1 day",other:"{{count}} days"},aboutXWeeks:{one:"about 1 week",other:"about {{count}} weeks"},xWeeks:{one:"1 week",other:"{{count}} weeks"},aboutXMonths:{one:"about 1 month",other:"about {{count}} months"},xMonths:{one:"1 month",other:"{{count}} months"},aboutXYears:{one:"about 1 year",other:"about {{count}} years"},xYears:{one:"1 year",other:"{{count}} years"},overXYears:{one:"over 1 year",other:"over {{count}} years"},almostXYears:{one:"almost 1 year",other:"almost {{count}} years"}},QU=(s,e,t)=>{let n;const a=ZU[s];return typeof a=="string"?n=a:e===1?n=a.one:n=a.other.replace("{{count}}",e.toString()),t!=null&&t.addSuffix?t.comparison&&t.comparison>0?"in "+n:n+" ago":n};function zb(s){return(e={})=>{const t=e.width?String(e.width):s.defaultWidth;return s.formats[t]||s.formats[s.defaultWidth]}}const JU={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},eG={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},tG={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},nG={date:zb({formats:JU,defaultWidth:"full"}),time:zb({formats:eG,defaultWidth:"full"}),dateTime:zb({formats:tG,defaultWidth:"full"})},sG={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},aG=(s,e,t,n)=>sG[s];function zu(s){return(e,t)=>{const n=t!=null&&t.context?String(t.context):"standalone";let a;if(n==="formatting"&&s.formattingValues){const o=s.defaultFormattingWidth||s.defaultWidth,l=t!=null&&t.width?String(t.width):o;a=s.formattingValues[l]||s.formattingValues[o]}else{const o=s.defaultWidth,l=t!=null&&t.width?String(t.width):s.defaultWidth;a=s.values[l]||s.values[o]}const i=s.argumentCallback?s.argumentCallback(e):e;return a[i]}}const iG={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},rG={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},oG={narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wide:["January","February","March","April","May","June","July","August","September","October","November","December"]},lG={narrow:["S","M","T","W","T","F","S"],short:["Su","Mo","Tu","We","Th","Fr","Sa"],abbreviated:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],wide:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},cG={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"}},uG={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"}},dG=(s,e)=>{const t=Number(s),n=t%100;if(n>20||n<10)switch(n%10){case 1:return t+"st";case 2:return t+"nd";case 3:return t+"rd"}return t+"th"},hG={ordinalNumber:dG,era:zu({values:iG,defaultWidth:"wide"}),quarter:zu({values:rG,defaultWidth:"wide",argumentCallback:s=>s-1}),month:zu({values:oG,defaultWidth:"wide"}),day:zu({values:lG,defaultWidth:"wide"}),dayPeriod:zu({values:cG,defaultWidth:"wide",formattingValues:uG,defaultFormattingWidth:"wide"})};function Fu(s){return(e,t={})=>{const n=t.width,a=n&&s.matchPatterns[n]||s.matchPatterns[s.defaultMatchWidth],i=e.match(a);if(!i)return null;const o=i[0],l=n&&s.parsePatterns[n]||s.parsePatterns[s.defaultParseWidth],c=Array.isArray(l)?mG(l,p=>p.test(o)):pG(l,p=>p.test(o));let d;d=s.valueCallback?s.valueCallback(c):c,d=t.valueCallback?t.valueCallback(d):d;const m=e.slice(o.length);return{value:d,rest:m}}}function pG(s,e){for(const t in s)if(Object.prototype.hasOwnProperty.call(s,t)&&e(s[t]))return t}function mG(s,e){for(let t=0;t<s.length;t++)if(e(s[t]))return t}function fG(s){return(e,t={})=>{const n=e.match(s.matchPattern);if(!n)return null;const a=n[0],i=e.match(s.parsePattern);if(!i)return null;let o=s.valueCallback?s.valueCallback(i[0]):i[0];o=t.valueCallback?t.valueCallback(o):o;const l=e.slice(a.length);return{value:o,rest:l}}}const gG=/^(\d+)(th|st|nd|rd)?/i,bG=/\d+/i,yG={narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},xG={any:[/^b/i,/^(a|c)/i]},vG={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},wG={any:[/1/i,/2/i,/3/i,/4/i]},kG={narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/i},SG={narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},jG={narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},CG={narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},NG={narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},AG={any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},MG={ordinalNumber:fG({matchPattern:gG,parsePattern:bG,valueCallback:s=>parseInt(s,10)}),era:Fu({matchPatterns:yG,defaultMatchWidth:"wide",parsePatterns:xG,defaultParseWidth:"any"}),quarter:Fu({matchPatterns:vG,defaultMatchWidth:"wide",parsePatterns:wG,defaultParseWidth:"any",valueCallback:s=>s+1}),month:Fu({matchPatterns:kG,defaultMatchWidth:"wide",parsePatterns:SG,defaultParseWidth:"any"}),day:Fu({matchPatterns:jG,defaultMatchWidth:"wide",parsePatterns:CG,defaultParseWidth:"any"}),dayPeriod:Fu({matchPatterns:NG,defaultMatchWidth:"any",parsePatterns:AG,defaultParseWidth:"any"})},UE={code:"en-US",formatDistance:QU,formatLong:nG,formatRelative:aG,localize:hG,match:MG,options:{weekStartsOn:0,firstWeekContainsDate:1}};function TG(s,e){const t=wt(s,e==null?void 0:e.in);return Cc(t,Pm(t))+1}function wv(s,e){const t=wt(s,e==null?void 0:e.in),n=+jc(t)-+qU(t);return Math.round(n/OE)+1}function kv(s,e){var m,p,f,b;const t=wt(s,e==null?void 0:e.in),n=t.getFullYear(),a=ml(),i=(e==null?void 0:e.firstWeekContainsDate)??((p=(m=e==null?void 0:e.locale)==null?void 0:m.options)==null?void 0:p.firstWeekContainsDate)??a.firstWeekContainsDate??((b=(f=a.locale)==null?void 0:f.options)==null?void 0:b.firstWeekContainsDate)??1,o=Nn((e==null?void 0:e.in)||s,0);o.setFullYear(n+1,0,i),o.setHours(0,0,0,0);const l=vr(o,e),c=Nn((e==null?void 0:e.in)||s,0);c.setFullYear(n,0,i),c.setHours(0,0,0,0);const d=vr(c,e);return+t>=+l?n+1:+t>=+d?n:n-1}function EG(s,e){var l,c,d,m;const t=ml(),n=(e==null?void 0:e.firstWeekContainsDate)??((c=(l=e==null?void 0:e.locale)==null?void 0:l.options)==null?void 0:c.firstWeekContainsDate)??t.firstWeekContainsDate??((m=(d=t.locale)==null?void 0:d.options)==null?void 0:m.firstWeekContainsDate)??1,a=kv(s,e),i=Nn((e==null?void 0:e.in)||s,0);return i.setFullYear(a,0,n),i.setHours(0,0,0,0),vr(i,e)}function GE(s,e){const t=wt(s,e==null?void 0:e.in),n=+vr(t,e)-+EG(t,e);return Math.round(n/OE)+1}function Cn(s,e){const t=s<0?"-":"",n=Math.abs(s).toString().padStart(e,"0");return t+n}const Qr={y(s,e){const t=s.getFullYear(),n=t>0?t:1-t;return Cn(e==="yy"?n%100:n,e.length)},M(s,e){const t=s.getMonth();return e==="M"?String(t+1):Cn(t+1,2)},d(s,e){return Cn(s.getDate(),e.length)},a(s,e){const t=s.getHours()/12>=1?"pm":"am";switch(e){case"a":case"aa":return t.toUpperCase();case"aaa":return t;case"aaaaa":return t[0];case"aaaa":default:return t==="am"?"a.m.":"p.m."}},h(s,e){return Cn(s.getHours()%12||12,e.length)},H(s,e){return Cn(s.getHours(),e.length)},m(s,e){return Cn(s.getMinutes(),e.length)},s(s,e){return Cn(s.getSeconds(),e.length)},S(s,e){const t=e.length,n=s.getMilliseconds(),a=Math.trunc(n*Math.pow(10,t-3));return Cn(a,e.length)}},Jl={midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},Z1={G:function(s,e,t){const n=s.getFullYear()>0?1:0;switch(e){case"G":case"GG":case"GGG":return t.era(n,{width:"abbreviated"});case"GGGGG":return t.era(n,{width:"narrow"});case"GGGG":default:return t.era(n,{width:"wide"})}},y:function(s,e,t){if(e==="yo"){const n=s.getFullYear(),a=n>0?n:1-n;return t.ordinalNumber(a,{unit:"year"})}return Qr.y(s,e)},Y:function(s,e,t,n){const a=kv(s,n),i=a>0?a:1-a;if(e==="YY"){const o=i%100;return Cn(o,2)}return e==="Yo"?t.ordinalNumber(i,{unit:"year"}):Cn(i,e.length)},R:function(s,e){const t=BE(s);return Cn(t,e.length)},u:function(s,e){const t=s.getFullYear();return Cn(t,e.length)},Q:function(s,e,t){const n=Math.ceil((s.getMonth()+1)/3);switch(e){case"Q":return String(n);case"QQ":return Cn(n,2);case"Qo":return t.ordinalNumber(n,{unit:"quarter"});case"QQQ":return t.quarter(n,{width:"abbreviated",context:"formatting"});case"QQQQQ":return t.quarter(n,{width:"narrow",context:"formatting"});case"QQQQ":default:return t.quarter(n,{width:"wide",context:"formatting"})}},q:function(s,e,t){const n=Math.ceil((s.getMonth()+1)/3);switch(e){case"q":return String(n);case"qq":return Cn(n,2);case"qo":return t.ordinalNumber(n,{unit:"quarter"});case"qqq":return t.quarter(n,{width:"abbreviated",context:"standalone"});case"qqqqq":return t.quarter(n,{width:"narrow",context:"standalone"});case"qqqq":default:return t.quarter(n,{width:"wide",context:"standalone"})}},M:function(s,e,t){const n=s.getMonth();switch(e){case"M":case"MM":return Qr.M(s,e);case"Mo":return t.ordinalNumber(n+1,{unit:"month"});case"MMM":return t.month(n,{width:"abbreviated",context:"formatting"});case"MMMMM":return t.month(n,{width:"narrow",context:"formatting"});case"MMMM":default:return t.month(n,{width:"wide",context:"formatting"})}},L:function(s,e,t){const n=s.getMonth();switch(e){case"L":return String(n+1);case"LL":return Cn(n+1,2);case"Lo":return t.ordinalNumber(n+1,{unit:"month"});case"LLL":return t.month(n,{width:"abbreviated",context:"standalone"});case"LLLLL":return t.month(n,{width:"narrow",context:"standalone"});case"LLLL":default:return t.month(n,{width:"wide",context:"standalone"})}},w:function(s,e,t,n){const a=GE(s,n);return e==="wo"?t.ordinalNumber(a,{unit:"week"}):Cn(a,e.length)},I:function(s,e,t){const n=wv(s);return e==="Io"?t.ordinalNumber(n,{unit:"week"}):Cn(n,e.length)},d:function(s,e,t){return e==="do"?t.ordinalNumber(s.getDate(),{unit:"date"}):Qr.d(s,e)},D:function(s,e,t){const n=TG(s);return e==="Do"?t.ordinalNumber(n,{unit:"dayOfYear"}):Cn(n,e.length)},E:function(s,e,t){const n=s.getDay();switch(e){case"E":case"EE":case"EEE":return t.day(n,{width:"abbreviated",context:"formatting"});case"EEEEE":return t.day(n,{width:"narrow",context:"formatting"});case"EEEEEE":return t.day(n,{width:"short",context:"formatting"});case"EEEE":default:return t.day(n,{width:"wide",context:"formatting"})}},e:function(s,e,t,n){const a=s.getDay(),i=(a-n.weekStartsOn+8)%7||7;switch(e){case"e":return String(i);case"ee":return Cn(i,2);case"eo":return t.ordinalNumber(i,{unit:"day"});case"eee":return t.day(a,{width:"abbreviated",context:"formatting"});case"eeeee":return t.day(a,{width:"narrow",context:"formatting"});case"eeeeee":return t.day(a,{width:"short",context:"formatting"});case"eeee":default:return t.day(a,{width:"wide",context:"formatting"})}},c:function(s,e,t,n){const a=s.getDay(),i=(a-n.weekStartsOn+8)%7||7;switch(e){case"c":return String(i);case"cc":return Cn(i,e.length);case"co":return t.ordinalNumber(i,{unit:"day"});case"ccc":return t.day(a,{width:"abbreviated",context:"standalone"});case"ccccc":return t.day(a,{width:"narrow",context:"standalone"});case"cccccc":return t.day(a,{width:"short",context:"standalone"});case"cccc":default:return t.day(a,{width:"wide",context:"standalone"})}},i:function(s,e,t){const n=s.getDay(),a=n===0?7:n;switch(e){case"i":return String(a);case"ii":return Cn(a,e.length);case"io":return t.ordinalNumber(a,{unit:"day"});case"iii":return t.day(n,{width:"abbreviated",context:"formatting"});case"iiiii":return t.day(n,{width:"narrow",context:"formatting"});case"iiiiii":return t.day(n,{width:"short",context:"formatting"});case"iiii":default:return t.day(n,{width:"wide",context:"formatting"})}},a:function(s,e,t){const a=s.getHours()/12>=1?"pm":"am";switch(e){case"a":case"aa":return t.dayPeriod(a,{width:"abbreviated",context:"formatting"});case"aaa":return t.dayPeriod(a,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return t.dayPeriod(a,{width:"narrow",context:"formatting"});case"aaaa":default:return t.dayPeriod(a,{width:"wide",context:"formatting"})}},b:function(s,e,t){const n=s.getHours();let a;switch(n===12?a=Jl.noon:n===0?a=Jl.midnight:a=n/12>=1?"pm":"am",e){case"b":case"bb":return t.dayPeriod(a,{width:"abbreviated",context:"formatting"});case"bbb":return t.dayPeriod(a,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return t.dayPeriod(a,{width:"narrow",context:"formatting"});case"bbbb":default:return t.dayPeriod(a,{width:"wide",context:"formatting"})}},B:function(s,e,t){const n=s.getHours();let a;switch(n>=17?a=Jl.evening:n>=12?a=Jl.afternoon:n>=4?a=Jl.morning:a=Jl.night,e){case"B":case"BB":case"BBB":return t.dayPeriod(a,{width:"abbreviated",context:"formatting"});case"BBBBB":return t.dayPeriod(a,{width:"narrow",context:"formatting"});case"BBBB":default:return t.dayPeriod(a,{width:"wide",context:"formatting"})}},h:function(s,e,t){if(e==="ho"){let n=s.getHours()%12;return n===0&&(n=12),t.ordinalNumber(n,{unit:"hour"})}return Qr.h(s,e)},H:function(s,e,t){return e==="Ho"?t.ordinalNumber(s.getHours(),{unit:"hour"}):Qr.H(s,e)},K:function(s,e,t){const n=s.getHours()%12;return e==="Ko"?t.ordinalNumber(n,{unit:"hour"}):Cn(n,e.length)},k:function(s,e,t){let n=s.getHours();return n===0&&(n=24),e==="ko"?t.ordinalNumber(n,{unit:"hour"}):Cn(n,e.length)},m:function(s,e,t){return e==="mo"?t.ordinalNumber(s.getMinutes(),{unit:"minute"}):Qr.m(s,e)},s:function(s,e,t){return e==="so"?t.ordinalNumber(s.getSeconds(),{unit:"second"}):Qr.s(s,e)},S:function(s,e){return Qr.S(s,e)},X:function(s,e,t){const n=s.getTimezoneOffset();if(n===0)return"Z";switch(e){case"X":return J1(n);case"XXXX":case"XX":return Ho(n);case"XXXXX":case"XXX":default:return Ho(n,":")}},x:function(s,e,t){const n=s.getTimezoneOffset();switch(e){case"x":return J1(n);case"xxxx":case"xx":return Ho(n);case"xxxxx":case"xxx":default:return Ho(n,":")}},O:function(s,e,t){const n=s.getTimezoneOffset();switch(e){case"O":case"OO":case"OOO":return"GMT"+Q1(n,":");case"OOOO":default:return"GMT"+Ho(n,":")}},z:function(s,e,t){const n=s.getTimezoneOffset();switch(e){case"z":case"zz":case"zzz":return"GMT"+Q1(n,":");case"zzzz":default:return"GMT"+Ho(n,":")}},t:function(s,e,t){const n=Math.trunc(+s/1e3);return Cn(n,e.length)},T:function(s,e,t){return Cn(+s,e.length)}};function Q1(s,e=""){const t=s>0?"-":"+",n=Math.abs(s),a=Math.trunc(n/60),i=n%60;return i===0?t+String(a):t+String(a)+e+Cn(i,2)}function J1(s,e){return s%60===0?(s>0?"-":"+")+Cn(Math.abs(s)/60,2):Ho(s,e)}function Ho(s,e=""){const t=s>0?"-":"+",n=Math.abs(s),a=Cn(Math.trunc(n/60),2),i=Cn(n%60,2);return t+a+e+i}const eN=(s,e)=>{switch(s){case"P":return e.date({width:"short"});case"PP":return e.date({width:"medium"});case"PPP":return e.date({width:"long"});case"PPPP":default:return e.date({width:"full"})}},WE=(s,e)=>{switch(s){case"p":return e.time({width:"short"});case"pp":return e.time({width:"medium"});case"ppp":return e.time({width:"long"});case"pppp":default:return e.time({width:"full"})}},_G=(s,e)=>{const t=s.match(/(P+)(p+)?/)||[],n=t[1],a=t[2];if(!a)return eN(s,e);let i;switch(n){case"P":i=e.dateTime({width:"short"});break;case"PP":i=e.dateTime({width:"medium"});break;case"PPP":i=e.dateTime({width:"long"});break;case"PPPP":default:i=e.dateTime({width:"full"});break}return i.replace("{{date}}",eN(n,e)).replace("{{time}}",WE(a,e))},Xy={p:WE,P:_G},DG=/^D+$/,PG=/^Y+$/,RG=["D","DD","YY","YYYY"];function LG(s){return DG.test(s)}function OG(s){return PG.test(s)}function IG(s,e,t){const n=BG(s,e,t);if(console.warn(n),RG.includes(s))throw new RangeError(n)}function BG(s,e,t){const n=s[0]==="Y"?"years":"days of the month";return`Use \`${s.toLowerCase()}\` instead of \`${s}\` (in \`${e}\`) for formatting ${n} to the input \`${t}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}const zG=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,FG=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,$G=/^'([^]*?)'?$/,HG=/''/g,UG=/[a-zA-Z]/;function tN(s,e,t){var m,p,f,b,x,w,k,S;const n=ml(),a=(t==null?void 0:t.locale)??n.locale??UE,i=(t==null?void 0:t.firstWeekContainsDate)??((p=(m=t==null?void 0:t.locale)==null?void 0:m.options)==null?void 0:p.firstWeekContainsDate)??n.firstWeekContainsDate??((b=(f=n.locale)==null?void 0:f.options)==null?void 0:b.firstWeekContainsDate)??1,o=(t==null?void 0:t.weekStartsOn)??((w=(x=t==null?void 0:t.locale)==null?void 0:x.options)==null?void 0:w.weekStartsOn)??n.weekStartsOn??((S=(k=n.locale)==null?void 0:k.options)==null?void 0:S.weekStartsOn)??0,l=wt(s,t==null?void 0:t.in);if(!Nc(l))throw new RangeError("Invalid time value");let c=e.match(FG).map(j=>{const C=j[0];if(C==="p"||C==="P"){const N=Xy[C];return N(j,a.formatLong)}return j}).join("").match(zG).map(j=>{if(j==="''")return{isToken:!1,value:"'"};const C=j[0];if(C==="'")return{isToken:!1,value:GG(j)};if(Z1[C])return{isToken:!0,value:j};if(C.match(UG))throw new RangeError("Format string contains an unescaped latin alphabet character `"+C+"`");return{isToken:!1,value:j}});a.localize.preprocessor&&(c=a.localize.preprocessor(l,c));const d={firstWeekContainsDate:i,weekStartsOn:o,locale:a};return c.map(j=>{if(!j.isToken)return j.value;const C=j.value;(!(t!=null&&t.useAdditionalWeekYearTokens)&&OG(C)||!(t!=null&&t.useAdditionalDayOfYearTokens)&&LG(C))&&IG(C,e,String(s));const N=Z1[C[0]];return N(l,C,a.localize,d)}).join("")}function GG(s){const e=s.match($G);return e?e[1].replace(HG,"'"):s}function nN(s,e){return wt(s,e==null?void 0:e.in).getDate()}function WG(s,e){return wt(s,e==null?void 0:e.in).getDay()}function qG(s,e){const t=wt(s,e==null?void 0:e.in),n=t.getFullYear(),a=t.getMonth(),i=Nn(t,0);return i.setFullYear(n,a+1,0),i.setHours(0,0,0,0),i.getDate()}function YG(){return Object.assign({},ml())}function Fs(s,e){return wt(s,e==null?void 0:e.in).getHours()}function VG(s,e){const t=wt(s,e==null?void 0:e.in).getDay();return t===0?7:t}function $s(s,e){return wt(s,e==null?void 0:e.in).getMinutes()}function oa(s,e){return wt(s,e==null?void 0:e.in).getMonth()}function ro(s){return wt(s).getSeconds()}function Zy(s){return+wt(s)}function sn(s,e){return wt(s,e==null?void 0:e.in).getFullYear()}function gr(s,e){return+wt(s)>+wt(e)}function _i(s,e){return+wt(s)<+wt(e)}function KG(s,e){return+wt(s)==+wt(e)}function XG(s,e){const t=ZG(e)?new e(0):Nn(e,0);return t.setFullYear(s.getFullYear(),s.getMonth(),s.getDate()),t.setHours(s.getHours(),s.getMinutes(),s.getSeconds(),s.getMilliseconds()),t}function ZG(s){var e;return typeof s=="function"&&((e=s.prototype)==null?void 0:e.constructor)===s}const QG=10;class qE{constructor(){U(this,"subPriority",0)}validate(e,t){return!0}}class JG extends qE{constructor(e,t,n,a,i){super(),this.value=e,this.validateValue=t,this.setValue=n,this.priority=a,i&&(this.subPriority=i)}validate(e,t){return this.validateValue(e,this.value,t)}set(e,t,n){return this.setValue(e,t,this.value,n)}}class eW extends qE{constructor(t,n){super();U(this,"priority",QG);U(this,"subPriority",-1);this.context=t||(a=>Nn(n,a))}set(t,n){return n.timestampIsSet?t:Nn(t,XG(t,this.context))}}class vn{run(e,t,n,a){const i=this.parse(e,t,n,a);return i?{setter:new JG(i.value,this.validate,this.set,this.priority,this.subPriority),rest:i.rest}:null}validate(e,t,n){return!0}}class tW extends vn{constructor(){super(...arguments);U(this,"priority",140);U(this,"incompatibleTokens",["R","u","t","T"])}parse(t,n,a){switch(n){case"G":case"GG":case"GGG":return a.era(t,{width:"abbreviated"})||a.era(t,{width:"narrow"});case"GGGGG":return a.era(t,{width:"narrow"});case"GGGG":default:return a.era(t,{width:"wide"})||a.era(t,{width:"abbreviated"})||a.era(t,{width:"narrow"})}}set(t,n,a){return n.era=a,t.setFullYear(a,0,1),t.setHours(0,0,0,0),t}}const cs={month:/^(1[0-2]|0?\d)/,date:/^(3[0-1]|[0-2]?\d)/,dayOfYear:/^(36[0-6]|3[0-5]\d|[0-2]?\d?\d)/,week:/^(5[0-3]|[0-4]?\d)/,hour23h:/^(2[0-3]|[0-1]?\d)/,hour24h:/^(2[0-4]|[0-1]?\d)/,hour11h:/^(1[0-1]|0?\d)/,hour12h:/^(1[0-2]|0?\d)/,minute:/^[0-5]?\d/,second:/^[0-5]?\d/,singleDigit:/^\d/,twoDigits:/^\d{1,2}/,threeDigits:/^\d{1,3}/,fourDigits:/^\d{1,4}/,anyDigitsSigned:/^-?\d+/,singleDigitSigned:/^-?\d/,twoDigitsSigned:/^-?\d{1,2}/,threeDigitsSigned:/^-?\d{1,3}/,fourDigitsSigned:/^-?\d{1,4}/},Ai={basicOptionalMinutes:/^([+-])(\d{2})(\d{2})?|Z/,basic:/^([+-])(\d{2})(\d{2})|Z/,basicOptionalSeconds:/^([+-])(\d{2})(\d{2})((\d{2}))?|Z/,extended:/^([+-])(\d{2}):(\d{2})|Z/,extendedOptionalSeconds:/^([+-])(\d{2}):(\d{2})(:(\d{2}))?|Z/};function us(s,e){return s&&{value:e(s.value),rest:s.rest}}function Zn(s,e){const t=e.match(s);return t?{value:parseInt(t[0],10),rest:e.slice(t[0].length)}:null}function Mi(s,e){const t=e.match(s);if(!t)return null;if(t[0]==="Z")return{value:0,rest:e.slice(1)};const n=t[1]==="+"?1:-1,a=t[2]?parseInt(t[2],10):0,i=t[3]?parseInt(t[3],10):0,o=t[5]?parseInt(t[5],10):0;return{value:n*(a*Dm+i*_m+o*UU),rest:e.slice(t[0].length)}}function YE(s){return Zn(cs.anyDigitsSigned,s)}function as(s,e){switch(s){case 1:return Zn(cs.singleDigit,e);case 2:return Zn(cs.twoDigits,e);case 3:return Zn(cs.threeDigits,e);case 4:return Zn(cs.fourDigits,e);default:return Zn(new RegExp("^\\d{1,"+s+"}"),e)}}function nm(s,e){switch(s){case 1:return Zn(cs.singleDigitSigned,e);case 2:return Zn(cs.twoDigitsSigned,e);case 3:return Zn(cs.threeDigitsSigned,e);case 4:return Zn(cs.fourDigitsSigned,e);default:return Zn(new RegExp("^-?\\d{1,"+s+"}"),e)}}function Sv(s){switch(s){case"morning":return 4;case"evening":return 17;case"pm":case"noon":case"afternoon":return 12;case"am":case"midnight":case"night":default:return 0}}function VE(s,e){const t=e>0,n=t?e:1-e;let a;if(n<=50)a=s||100;else{const i=n+50,o=Math.trunc(i/100)*100,l=s>=i%100;a=s+o-(l?100:0)}return t?a:1-a}function KE(s){return s%400===0||s%4===0&&s%100!==0}class nW extends vn{constructor(){super(...arguments);U(this,"priority",130);U(this,"incompatibleTokens",["Y","R","u","w","I","i","e","c","t","T"])}parse(t,n,a){const i=o=>({year:o,isTwoDigitYear:n==="yy"});switch(n){case"y":return us(as(4,t),i);case"yo":return us(a.ordinalNumber(t,{unit:"year"}),i);default:return us(as(n.length,t),i)}}validate(t,n){return n.isTwoDigitYear||n.year>0}set(t,n,a){const i=t.getFullYear();if(a.isTwoDigitYear){const l=VE(a.year,i);return t.setFullYear(l,0,1),t.setHours(0,0,0,0),t}const o=!("era"in n)||n.era===1?a.year:1-a.year;return t.setFullYear(o,0,1),t.setHours(0,0,0,0),t}}class sW extends vn{constructor(){super(...arguments);U(this,"priority",130);U(this,"incompatibleTokens",["y","R","u","Q","q","M","L","I","d","D","i","t","T"])}parse(t,n,a){const i=o=>({year:o,isTwoDigitYear:n==="YY"});switch(n){case"Y":return us(as(4,t),i);case"Yo":return us(a.ordinalNumber(t,{unit:"year"}),i);default:return us(as(n.length,t),i)}}validate(t,n){return n.isTwoDigitYear||n.year>0}set(t,n,a,i){const o=kv(t,i);if(a.isTwoDigitYear){const c=VE(a.year,o);return t.setFullYear(c,0,i.firstWeekContainsDate),t.setHours(0,0,0,0),vr(t,i)}const l=!("era"in n)||n.era===1?a.year:1-a.year;return t.setFullYear(l,0,i.firstWeekContainsDate),t.setHours(0,0,0,0),vr(t,i)}}class aW extends vn{constructor(){super(...arguments);U(this,"priority",130);U(this,"incompatibleTokens",["G","y","Y","u","Q","q","M","L","w","d","D","e","c","t","T"])}parse(t,n){return nm(n==="R"?4:n.length,t)}set(t,n,a){const i=Nn(t,0);return i.setFullYear(a,0,4),i.setHours(0,0,0,0),jc(i)}}class iW extends vn{constructor(){super(...arguments);U(this,"priority",130);U(this,"incompatibleTokens",["G","y","Y","R","w","I","i","e","c","t","T"])}parse(t,n){return nm(n==="u"?4:n.length,t)}set(t,n,a){return t.setFullYear(a,0,1),t.setHours(0,0,0,0),t}}class rW extends vn{constructor(){super(...arguments);U(this,"priority",120);U(this,"incompatibleTokens",["Y","R","q","M","L","w","I","d","D","i","e","c","t","T"])}parse(t,n,a){switch(n){case"Q":case"QQ":return as(n.length,t);case"Qo":return a.ordinalNumber(t,{unit:"quarter"});case"QQQ":return a.quarter(t,{width:"abbreviated",context:"formatting"})||a.quarter(t,{width:"narrow",context:"formatting"});case"QQQQQ":return a.quarter(t,{width:"narrow",context:"formatting"});case"QQQQ":default:return a.quarter(t,{width:"wide",context:"formatting"})||a.quarter(t,{width:"abbreviated",context:"formatting"})||a.quarter(t,{width:"narrow",context:"formatting"})}}validate(t,n){return n>=1&&n<=4}set(t,n,a){return t.setMonth((a-1)*3,1),t.setHours(0,0,0,0),t}}class oW extends vn{constructor(){super(...arguments);U(this,"priority",120);U(this,"incompatibleTokens",["Y","R","Q","M","L","w","I","d","D","i","e","c","t","T"])}parse(t,n,a){switch(n){case"q":case"qq":return as(n.length,t);case"qo":return a.ordinalNumber(t,{unit:"quarter"});case"qqq":return a.quarter(t,{width:"abbreviated",context:"standalone"})||a.quarter(t,{width:"narrow",context:"standalone"});case"qqqqq":return a.quarter(t,{width:"narrow",context:"standalone"});case"qqqq":default:return a.quarter(t,{width:"wide",context:"standalone"})||a.quarter(t,{width:"abbreviated",context:"standalone"})||a.quarter(t,{width:"narrow",context:"standalone"})}}validate(t,n){return n>=1&&n<=4}set(t,n,a){return t.setMonth((a-1)*3,1),t.setHours(0,0,0,0),t}}class lW extends vn{constructor(){super(...arguments);U(this,"incompatibleTokens",["Y","R","q","Q","L","w","I","D","i","e","c","t","T"]);U(this,"priority",110)}parse(t,n,a){const i=o=>o-1;switch(n){case"M":return us(Zn(cs.month,t),i);case"MM":return us(as(2,t),i);case"Mo":return us(a.ordinalNumber(t,{unit:"month"}),i);case"MMM":return a.month(t,{width:"abbreviated",context:"formatting"})||a.month(t,{width:"narrow",context:"formatting"});case"MMMMM":return a.month(t,{width:"narrow",context:"formatting"});case"MMMM":default:return a.month(t,{width:"wide",context:"formatting"})||a.month(t,{width:"abbreviated",context:"formatting"})||a.month(t,{width:"narrow",context:"formatting"})}}validate(t,n){return n>=0&&n<=11}set(t,n,a){return t.setMonth(a,1),t.setHours(0,0,0,0),t}}class cW extends vn{constructor(){super(...arguments);U(this,"priority",110);U(this,"incompatibleTokens",["Y","R","q","Q","M","w","I","D","i","e","c","t","T"])}parse(t,n,a){const i=o=>o-1;switch(n){case"L":return us(Zn(cs.month,t),i);case"LL":return us(as(2,t),i);case"Lo":return us(a.ordinalNumber(t,{unit:"month"}),i);case"LLL":return a.month(t,{width:"abbreviated",context:"standalone"})||a.month(t,{width:"narrow",context:"standalone"});case"LLLLL":return a.month(t,{width:"narrow",context:"standalone"});case"LLLL":default:return a.month(t,{width:"wide",context:"standalone"})||a.month(t,{width:"abbreviated",context:"standalone"})||a.month(t,{width:"narrow",context:"standalone"})}}validate(t,n){return n>=0&&n<=11}set(t,n,a){return t.setMonth(a,1),t.setHours(0,0,0,0),t}}function uW(s,e,t){const n=wt(s,t==null?void 0:t.in),a=GE(n,t)-e;return n.setDate(n.getDate()-a*7),wt(n,t==null?void 0:t.in)}class dW extends vn{constructor(){super(...arguments);U(this,"priority",100);U(this,"incompatibleTokens",["y","R","u","q","Q","M","L","I","d","D","i","t","T"])}parse(t,n,a){switch(n){case"w":return Zn(cs.week,t);case"wo":return a.ordinalNumber(t,{unit:"week"});default:return as(n.length,t)}}validate(t,n){return n>=1&&n<=53}set(t,n,a,i){return vr(uW(t,a,i),i)}}function hW(s,e,t){const n=wt(s,t==null?void 0:t.in),a=wv(n,t)-e;return n.setDate(n.getDate()-a*7),n}class pW extends vn{constructor(){super(...arguments);U(this,"priority",100);U(this,"incompatibleTokens",["y","Y","u","q","Q","M","L","w","d","D","e","c","t","T"])}parse(t,n,a){switch(n){case"I":return Zn(cs.week,t);case"Io":return a.ordinalNumber(t,{unit:"week"});default:return as(n.length,t)}}validate(t,n){return n>=1&&n<=53}set(t,n,a){return jc(hW(t,a))}}const mW=[31,28,31,30,31,30,31,31,30,31,30,31],fW=[31,29,31,30,31,30,31,31,30,31,30,31];class gW extends vn{constructor(){super(...arguments);U(this,"priority",90);U(this,"subPriority",1);U(this,"incompatibleTokens",["Y","R","q","Q","w","I","D","i","e","c","t","T"])}parse(t,n,a){switch(n){case"d":return Zn(cs.date,t);case"do":return a.ordinalNumber(t,{unit:"date"});default:return as(n.length,t)}}validate(t,n){const a=t.getFullYear(),i=KE(a),o=t.getMonth();return i?n>=1&&n<=fW[o]:n>=1&&n<=mW[o]}set(t,n,a){return t.setDate(a),t.setHours(0,0,0,0),t}}class bW extends vn{constructor(){super(...arguments);U(this,"priority",90);U(this,"subpriority",1);U(this,"incompatibleTokens",["Y","R","q","Q","M","L","w","I","d","E","i","e","c","t","T"])}parse(t,n,a){switch(n){case"D":case"DD":return Zn(cs.dayOfYear,t);case"Do":return a.ordinalNumber(t,{unit:"date"});default:return as(n.length,t)}}validate(t,n){const a=t.getFullYear();return KE(a)?n>=1&&n<=366:n>=1&&n<=365}set(t,n,a){return t.setMonth(0,a),t.setHours(0,0,0,0),t}}function jv(s,e,t){var p,f,b,x;const n=ml(),a=(t==null?void 0:t.weekStartsOn)??((f=(p=t==null?void 0:t.locale)==null?void 0:p.options)==null?void 0:f.weekStartsOn)??n.weekStartsOn??((x=(b=n.locale)==null?void 0:b.options)==null?void 0:x.weekStartsOn)??0,i=wt(s,t==null?void 0:t.in),o=i.getDay(),c=(e%7+7)%7,d=7-a,m=e<0||e>6?e-(o+d)%7:(c+d)%7-(o+d)%7;return ci(i,m,t)}class yW extends vn{constructor(){super(...arguments);U(this,"priority",90);U(this,"incompatibleTokens",["D","i","e","c","t","T"])}parse(t,n,a){switch(n){case"E":case"EE":case"EEE":return a.day(t,{width:"abbreviated",context:"formatting"})||a.day(t,{width:"short",context:"formatting"})||a.day(t,{width:"narrow",context:"formatting"});case"EEEEE":return a.day(t,{width:"narrow",context:"formatting"});case"EEEEEE":return a.day(t,{width:"short",context:"formatting"})||a.day(t,{width:"narrow",context:"formatting"});case"EEEE":default:return a.day(t,{width:"wide",context:"formatting"})||a.day(t,{width:"abbreviated",context:"formatting"})||a.day(t,{width:"short",context:"formatting"})||a.day(t,{width:"narrow",context:"formatting"})}}validate(t,n){return n>=0&&n<=6}set(t,n,a,i){return t=jv(t,a,i),t.setHours(0,0,0,0),t}}class xW extends vn{constructor(){super(...arguments);U(this,"priority",90);U(this,"incompatibleTokens",["y","R","u","q","Q","M","L","I","d","D","E","i","c","t","T"])}parse(t,n,a,i){const o=l=>{const c=Math.floor((l-1)/7)*7;return(l+i.weekStartsOn+6)%7+c};switch(n){case"e":case"ee":return us(as(n.length,t),o);case"eo":return us(a.ordinalNumber(t,{unit:"day"}),o);case"eee":return a.day(t,{width:"abbreviated",context:"formatting"})||a.day(t,{width:"short",context:"formatting"})||a.day(t,{width:"narrow",context:"formatting"});case"eeeee":return a.day(t,{width:"narrow",context:"formatting"});case"eeeeee":return a.day(t,{width:"short",context:"formatting"})||a.day(t,{width:"narrow",context:"formatting"});case"eeee":default:return a.day(t,{width:"wide",context:"formatting"})||a.day(t,{width:"abbreviated",context:"formatting"})||a.day(t,{width:"short",context:"formatting"})||a.day(t,{width:"narrow",context:"formatting"})}}validate(t,n){return n>=0&&n<=6}set(t,n,a,i){return t=jv(t,a,i),t.setHours(0,0,0,0),t}}class vW extends vn{constructor(){super(...arguments);U(this,"priority",90);U(this,"incompatibleTokens",["y","R","u","q","Q","M","L","I","d","D","E","i","e","t","T"])}parse(t,n,a,i){const o=l=>{const c=Math.floor((l-1)/7)*7;return(l+i.weekStartsOn+6)%7+c};switch(n){case"c":case"cc":return us(as(n.length,t),o);case"co":return us(a.ordinalNumber(t,{unit:"day"}),o);case"ccc":return a.day(t,{width:"abbreviated",context:"standalone"})||a.day(t,{width:"short",context:"standalone"})||a.day(t,{width:"narrow",context:"standalone"});case"ccccc":return a.day(t,{width:"narrow",context:"standalone"});case"cccccc":return a.day(t,{width:"short",context:"standalone"})||a.day(t,{width:"narrow",context:"standalone"});case"cccc":default:return a.day(t,{width:"wide",context:"standalone"})||a.day(t,{width:"abbreviated",context:"standalone"})||a.day(t,{width:"short",context:"standalone"})||a.day(t,{width:"narrow",context:"standalone"})}}validate(t,n){return n>=0&&n<=6}set(t,n,a,i){return t=jv(t,a,i),t.setHours(0,0,0,0),t}}function wW(s,e,t){const n=wt(s,t==null?void 0:t.in),a=VG(n,t),i=e-a;return ci(n,i,t)}class kW extends vn{constructor(){super(...arguments);U(this,"priority",90);U(this,"incompatibleTokens",["y","Y","u","q","Q","M","L","w","d","D","E","e","c","t","T"])}parse(t,n,a){const i=o=>o===0?7:o;switch(n){case"i":case"ii":return as(n.length,t);case"io":return a.ordinalNumber(t,{unit:"day"});case"iii":return us(a.day(t,{width:"abbreviated",context:"formatting"})||a.day(t,{width:"short",context:"formatting"})||a.day(t,{width:"narrow",context:"formatting"}),i);case"iiiii":return us(a.day(t,{width:"narrow",context:"formatting"}),i);case"iiiiii":return us(a.day(t,{width:"short",context:"formatting"})||a.day(t,{width:"narrow",context:"formatting"}),i);case"iiii":default:return us(a.day(t,{width:"wide",context:"formatting"})||a.day(t,{width:"abbreviated",context:"formatting"})||a.day(t,{width:"short",context:"formatting"})||a.day(t,{width:"narrow",context:"formatting"}),i)}}validate(t,n){return n>=1&&n<=7}set(t,n,a){return t=wW(t,a),t.setHours(0,0,0,0),t}}class SW extends vn{constructor(){super(...arguments);U(this,"priority",80);U(this,"incompatibleTokens",["b","B","H","k","t","T"])}parse(t,n,a){switch(n){case"a":case"aa":case"aaa":return a.dayPeriod(t,{width:"abbreviated",context:"formatting"})||a.dayPeriod(t,{width:"narrow",context:"formatting"});case"aaaaa":return a.dayPeriod(t,{width:"narrow",context:"formatting"});case"aaaa":default:return a.dayPeriod(t,{width:"wide",context:"formatting"})||a.dayPeriod(t,{width:"abbreviated",context:"formatting"})||a.dayPeriod(t,{width:"narrow",context:"formatting"})}}set(t,n,a){return t.setHours(Sv(a),0,0,0),t}}class jW extends vn{constructor(){super(...arguments);U(this,"priority",80);U(this,"incompatibleTokens",["a","B","H","k","t","T"])}parse(t,n,a){switch(n){case"b":case"bb":case"bbb":return a.dayPeriod(t,{width:"abbreviated",context:"formatting"})||a.dayPeriod(t,{width:"narrow",context:"formatting"});case"bbbbb":return a.dayPeriod(t,{width:"narrow",context:"formatting"});case"bbbb":default:return a.dayPeriod(t,{width:"wide",context:"formatting"})||a.dayPeriod(t,{width:"abbreviated",context:"formatting"})||a.dayPeriod(t,{width:"narrow",context:"formatting"})}}set(t,n,a){return t.setHours(Sv(a),0,0,0),t}}class CW extends vn{constructor(){super(...arguments);U(this,"priority",80);U(this,"incompatibleTokens",["a","b","t","T"])}parse(t,n,a){switch(n){case"B":case"BB":case"BBB":return a.dayPeriod(t,{width:"abbreviated",context:"formatting"})||a.dayPeriod(t,{width:"narrow",context:"formatting"});case"BBBBB":return a.dayPeriod(t,{width:"narrow",context:"formatting"});case"BBBB":default:return a.dayPeriod(t,{width:"wide",context:"formatting"})||a.dayPeriod(t,{width:"abbreviated",context:"formatting"})||a.dayPeriod(t,{width:"narrow",context:"formatting"})}}set(t,n,a){return t.setHours(Sv(a),0,0,0),t}}class NW extends vn{constructor(){super(...arguments);U(this,"priority",70);U(this,"incompatibleTokens",["H","K","k","t","T"])}parse(t,n,a){switch(n){case"h":return Zn(cs.hour12h,t);case"ho":return a.ordinalNumber(t,{unit:"hour"});default:return as(n.length,t)}}validate(t,n){return n>=1&&n<=12}set(t,n,a){const i=t.getHours()>=12;return i&&a<12?t.setHours(a+12,0,0,0):!i&&a===12?t.setHours(0,0,0,0):t.setHours(a,0,0,0),t}}class AW extends vn{constructor(){super(...arguments);U(this,"priority",70);U(this,"incompatibleTokens",["a","b","h","K","k","t","T"])}parse(t,n,a){switch(n){case"H":return Zn(cs.hour23h,t);case"Ho":return a.ordinalNumber(t,{unit:"hour"});default:return as(n.length,t)}}validate(t,n){return n>=0&&n<=23}set(t,n,a){return t.setHours(a,0,0,0),t}}class MW extends vn{constructor(){super(...arguments);U(this,"priority",70);U(this,"incompatibleTokens",["h","H","k","t","T"])}parse(t,n,a){switch(n){case"K":return Zn(cs.hour11h,t);case"Ko":return a.ordinalNumber(t,{unit:"hour"});default:return as(n.length,t)}}validate(t,n){return n>=0&&n<=11}set(t,n,a){return t.getHours()>=12&&a<12?t.setHours(a+12,0,0,0):t.setHours(a,0,0,0),t}}class TW extends vn{constructor(){super(...arguments);U(this,"priority",70);U(this,"incompatibleTokens",["a","b","h","H","K","t","T"])}parse(t,n,a){switch(n){case"k":return Zn(cs.hour24h,t);case"ko":return a.ordinalNumber(t,{unit:"hour"});default:return as(n.length,t)}}validate(t,n){return n>=1&&n<=24}set(t,n,a){const i=a<=24?a%24:a;return t.setHours(i,0,0,0),t}}class EW extends vn{constructor(){super(...arguments);U(this,"priority",60);U(this,"incompatibleTokens",["t","T"])}parse(t,n,a){switch(n){case"m":return Zn(cs.minute,t);case"mo":return a.ordinalNumber(t,{unit:"minute"});default:return as(n.length,t)}}validate(t,n){return n>=0&&n<=59}set(t,n,a){return t.setMinutes(a,0,0),t}}class _W extends vn{constructor(){super(...arguments);U(this,"priority",50);U(this,"incompatibleTokens",["t","T"])}parse(t,n,a){switch(n){case"s":return Zn(cs.second,t);case"so":return a.ordinalNumber(t,{unit:"second"});default:return as(n.length,t)}}validate(t,n){return n>=0&&n<=59}set(t,n,a){return t.setSeconds(a,0),t}}class DW extends vn{constructor(){super(...arguments);U(this,"priority",30);U(this,"incompatibleTokens",["t","T"])}parse(t,n){const a=i=>Math.trunc(i*Math.pow(10,-n.length+3));return us(as(n.length,t),a)}set(t,n,a){return t.setMilliseconds(a),t}}class PW extends vn{constructor(){super(...arguments);U(this,"priority",10);U(this,"incompatibleTokens",["t","T","x"])}parse(t,n){switch(n){case"X":return Mi(Ai.basicOptionalMinutes,t);case"XX":return Mi(Ai.basic,t);case"XXXX":return Mi(Ai.basicOptionalSeconds,t);case"XXXXX":return Mi(Ai.extendedOptionalSeconds,t);case"XXX":default:return Mi(Ai.extended,t)}}set(t,n,a){return n.timestampIsSet?t:Nn(t,t.getTime()-Zp(t)-a)}}class RW extends vn{constructor(){super(...arguments);U(this,"priority",10);U(this,"incompatibleTokens",["t","T","X"])}parse(t,n){switch(n){case"x":return Mi(Ai.basicOptionalMinutes,t);case"xx":return Mi(Ai.basic,t);case"xxxx":return Mi(Ai.basicOptionalSeconds,t);case"xxxxx":return Mi(Ai.extendedOptionalSeconds,t);case"xxx":default:return Mi(Ai.extended,t)}}set(t,n,a){return n.timestampIsSet?t:Nn(t,t.getTime()-Zp(t)-a)}}class LW extends vn{constructor(){super(...arguments);U(this,"priority",40);U(this,"incompatibleTokens","*")}parse(t){return YE(t)}set(t,n,a){return[Nn(t,a*1e3),{timestampIsSet:!0}]}}class OW extends vn{constructor(){super(...arguments);U(this,"priority",20);U(this,"incompatibleTokens","*")}parse(t){return YE(t)}set(t,n,a){return[Nn(t,a),{timestampIsSet:!0}]}}const IW={G:new tW,y:new nW,Y:new sW,R:new aW,u:new iW,Q:new rW,q:new oW,M:new lW,L:new cW,w:new dW,I:new pW,d:new gW,D:new bW,E:new yW,e:new xW,c:new vW,i:new kW,a:new SW,b:new jW,B:new CW,h:new NW,H:new AW,K:new MW,k:new TW,m:new EW,s:new _W,S:new DW,X:new PW,x:new RW,t:new LW,T:new OW},BW=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,zW=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,FW=/^'([^]*?)'?$/,$W=/''/g,HW=/\S/,UW=/[a-zA-Z]/;function GW(s,e,t,n){var k,S,j,C,N,P,_,L;const a=()=>Nn((n==null?void 0:n.in)||t,NaN),i=YG(),o=(n==null?void 0:n.locale)??i.locale??UE,l=(n==null?void 0:n.firstWeekContainsDate)??((S=(k=n==null?void 0:n.locale)==null?void 0:k.options)==null?void 0:S.firstWeekContainsDate)??i.firstWeekContainsDate??((C=(j=i.locale)==null?void 0:j.options)==null?void 0:C.firstWeekContainsDate)??1,c=(n==null?void 0:n.weekStartsOn)??((P=(N=n==null?void 0:n.locale)==null?void 0:N.options)==null?void 0:P.weekStartsOn)??i.weekStartsOn??((L=(_=i.locale)==null?void 0:_.options)==null?void 0:L.weekStartsOn)??0;if(!e)return s?a():wt(t,n==null?void 0:n.in);const d={firstWeekContainsDate:l,weekStartsOn:c,locale:o},m=[new eW(n==null?void 0:n.in,t)],p=e.match(zW).map(M=>{const D=M[0];if(D in Xy){const E=Xy[D];return E(M,o.formatLong)}return M}).join("").match(BW),f=[];for(let M of p){const D=M[0],E=IW[D];if(E){const{incompatibleTokens:R}=E;if(Array.isArray(R)){const I=f.find(B=>R.includes(B.token)||B.token===D);if(I)throw new RangeError(`The format string mustn't contain \`${I.fullToken}\` and \`${M}\` at the same time`)}else if(E.incompatibleTokens==="*"&&f.length>0)throw new RangeError(`The format string mustn't contain \`${M}\` and any other token at the same time`);f.push({token:D,fullToken:M});const O=E.run(s,M,o.match,d);if(!O)return a();m.push(O.setter),s=O.rest}else{if(D.match(UW))throw new RangeError("Format string contains an unescaped latin alphabet character `"+D+"`");if(M==="''"?M="'":D==="'"&&(M=WW(M)),s.indexOf(M)===0)s=s.slice(M.length);else return a()}}if(s.length>0&&HW.test(s))return a();const b=m.map(M=>M.priority).sort((M,D)=>D-M).filter((M,D,E)=>E.indexOf(M)===D).map(M=>m.filter(D=>D.priority===M).sort((D,E)=>E.subPriority-D.subPriority)).map(M=>M[0]);let x=wt(t,n==null?void 0:n.in);if(isNaN(+x))return a();const w={};for(const M of b){if(!M.validate(x,d))return a();const D=M.set(x,w,d);Array.isArray(D)?(x=D[0],Object.assign(w,D[1])):x=D}return x}function WW(s){return s.match(FW)[1].replace($W,"'")}function qW(s,e,t){const[n,a]=jr(t==null?void 0:t.in,s,e);return n.getFullYear()===a.getFullYear()&&n.getMonth()===a.getMonth()}function YW(s,e,t){const[n,a]=jr(t==null?void 0:t.in,s,e);return+Ky(n)==+Ky(a)}function VW(s,e,t){const[n,a]=jr(t==null?void 0:t.in,s,e);return n.getFullYear()===a.getFullYear()}function yd(s,e,t){const n=+wt(s,t==null?void 0:t.in),[a,i]=[+wt(e.start,t==null?void 0:t.in),+wt(e.end,t==null?void 0:t.in)].sort((o,l)=>o-l);return n>=a&&n<=i}function KW(s,e,t){return ci(s,-1,t)}function XW(s,e){const t=()=>Nn(e==null?void 0:e.in,NaN),a=e7(s);let i;if(a.date){const d=t7(a.date,2);i=n7(d.restDateString,d.year)}if(!i||isNaN(+i))return t();const o=+i;let l=0,c;if(a.time&&(l=s7(a.time),isNaN(l)))return t();if(a.timezone){if(c=a7(a.timezone),isNaN(c))return t()}else{const d=new Date(o+l),m=wt(0,e==null?void 0:e.in);return m.setFullYear(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate()),m.setHours(d.getUTCHours(),d.getUTCMinutes(),d.getUTCSeconds(),d.getUTCMilliseconds()),m}return wt(o+l+c,e==null?void 0:e.in)}const ap={dateTimeDelimiter:/[T ]/,timeZoneDelimiter:/[Z ]/i,timezone:/([Z+-].*)$/},ZW=/^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/,QW=/^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/,JW=/^([+-])(\d{2})(?::?(\d{2}))?$/;function e7(s){const e={},t=s.split(ap.dateTimeDelimiter);let n;if(t.length>2)return e;if(/:/.test(t[0])?n=t[0]:(e.date=t[0],n=t[1],ap.timeZoneDelimiter.test(e.date)&&(e.date=s.split(ap.timeZoneDelimiter)[0],n=s.substr(e.date.length,s.length))),n){const a=ap.timezone.exec(n);a?(e.time=n.replace(a[1],""),e.timezone=a[1]):e.time=n}return e}function t7(s,e){const t=new RegExp("^(?:(\\d{4}|[+-]\\d{"+(4+e)+"})|(\\d{2}|[+-]\\d{"+(2+e)+"})$)"),n=s.match(t);if(!n)return{year:NaN,restDateString:""};const a=n[1]?parseInt(n[1]):null,i=n[2]?parseInt(n[2]):null;return{year:i===null?a:i*100,restDateString:s.slice((n[1]||n[2]).length)}}function n7(s,e){if(e===null)return new Date(NaN);const t=s.match(ZW);if(!t)return new Date(NaN);const n=!!t[4],a=$u(t[1]),i=$u(t[2])-1,o=$u(t[3]),l=$u(t[4]),c=$u(t[5])-1;if(n)return c7(e,l,c)?i7(e,l,c):new Date(NaN);{const d=new Date(0);return!o7(e,i,o)||!l7(e,a)?new Date(NaN):(d.setUTCFullYear(e,i,Math.max(a,o)),d)}}function $u(s){return s?parseInt(s):1}function s7(s){const e=s.match(QW);if(!e)return NaN;const t=Fb(e[1]),n=Fb(e[2]),a=Fb(e[3]);return u7(t,n,a)?t*Dm+n*_m+a*1e3:NaN}function Fb(s){return s&&parseFloat(s.replace(",","."))||0}function a7(s){if(s==="Z")return 0;const e=s.match(JW);if(!e)return 0;const t=e[1]==="+"?-1:1,n=parseInt(e[2]),a=e[3]&&parseInt(e[3])||0;return d7(n,a)?t*(n*Dm+a*_m):NaN}function i7(s,e,t){const n=new Date(0);n.setUTCFullYear(s,0,4);const a=n.getUTCDay()||7,i=(e-1)*7+t+1-a;return n.setUTCDate(n.getUTCDate()+i),n}const r7=[31,null,31,30,31,30,31,31,30,31,30,31];function XE(s){return s%400===0||s%4===0&&s%100!==0}function o7(s,e,t){return e>=0&&e<=11&&t>=1&&t<=(r7[e]||(XE(s)?29:28))}function l7(s,e){return e>=1&&e<=(XE(s)?366:365)}function c7(s,e,t){return e>=1&&e<=53&&t>=0&&t<=6}function u7(s,e,t){return s===24?e===0&&t===0:t>=0&&t<60&&e>=0&&e<60&&s>=0&&s<25}function d7(s,e){return e>=0&&e<=59}function Ma(s,e,t){const n=wt(s,t==null?void 0:t.in),a=n.getFullYear(),i=n.getDate(),o=Nn(s,0);o.setFullYear(a,e,15),o.setHours(0,0,0,0);const l=qG(o);return n.setMonth(e,Math.min(i,l)),n}function kp(s,e,t){const n=wt(s,t==null?void 0:t.in);return n.setHours(e),n}function Sp(s,e,t){const n=wt(s,t==null?void 0:t.in);return n.setMinutes(e),n}function ac(s,e,t){const n=wt(s,t==null?void 0:t.in),a=Math.trunc(n.getMonth()/3)+1,i=e-a;return Ma(n,n.getMonth()+i*3)}function jp(s,e,t){const n=wt(s,t==null?void 0:t.in);return n.setSeconds(e),n}function ji(s,e,t){const n=wt(s,t==null?void 0:t.in);return isNaN(+n)?Nn(s,NaN):(n.setFullYear(e),n)}function el(s,e,t){return di(s,-e,t)}function ZE(s,e,t){return vv(s,-1,t)}function sN(s,e,t){return Qp(s,-1,t)}function ho(s,e,t){return ui(s,-e,t)}function Rm(){return typeof window<"u"}function Oc(s){return QE(s)?(s.nodeName||"").toLowerCase():"#document"}function _a(s){var e;return(s==null||(e=s.ownerDocument)==null?void 0:e.defaultView)||window}function Hi(s){var e;return(e=(QE(s)?s.ownerDocument:s.document)||window.document)==null?void 0:e.documentElement}function QE(s){return Rm()?s instanceof Node||s instanceof _a(s).Node:!1}function Xs(s){return Rm()?s instanceof Element||s instanceof _a(s).Element:!1}function Bi(s){return Rm()?s instanceof HTMLElement||s instanceof _a(s).HTMLElement:!1}function aN(s){return!Rm()||typeof ShadowRoot>"u"?!1:s instanceof ShadowRoot||s instanceof _a(s).ShadowRoot}const h7=new Set(["inline","contents"]);function Ed(s){const{overflow:e,overflowX:t,overflowY:n,display:a}=Xa(s);return/auto|scroll|overlay|hidden|clip/.test(e+n+t)&&!h7.has(a)}const p7=new Set(["table","td","th"]);function m7(s){return p7.has(Oc(s))}const f7=[":popover-open",":modal"];function Lm(s){return f7.some(e=>{try{return s.matches(e)}catch{return!1}})}const g7=["transform","translate","scale","rotate","perspective"],b7=["transform","translate","scale","rotate","perspective","filter"],y7=["paint","layout","strict","content"];function Cv(s){const e=Nv(),t=Xs(s)?Xa(s):s;return g7.some(n=>t[n]?t[n]!=="none":!1)||(t.containerType?t.containerType!=="normal":!1)||!e&&(t.backdropFilter?t.backdropFilter!=="none":!1)||!e&&(t.filter?t.filter!=="none":!1)||b7.some(n=>(t.willChange||"").includes(n))||y7.some(n=>(t.contain||"").includes(n))}function x7(s){let e=po(s);for(;Bi(e)&&!Ac(e);){if(Cv(e))return e;if(Lm(e))return null;e=po(e)}return null}function Nv(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}const v7=new Set(["html","body","#document"]);function Ac(s){return v7.has(Oc(s))}function Xa(s){return _a(s).getComputedStyle(s)}function Om(s){return Xs(s)?{scrollLeft:s.scrollLeft,scrollTop:s.scrollTop}:{scrollLeft:s.scrollX,scrollTop:s.scrollY}}function po(s){if(Oc(s)==="html")return s;const e=s.assignedSlot||s.parentNode||aN(s)&&s.host||Hi(s);return aN(e)?e.host:e}function JE(s){const e=po(s);return Ac(e)?s.ownerDocument?s.ownerDocument.body:s.body:Bi(e)&&Ed(e)?e:JE(e)}function xd(s,e,t){var n;e===void 0&&(e=[]),t===void 0&&(t=!0);const a=JE(s),i=a===((n=s.ownerDocument)==null?void 0:n.body),o=_a(a);if(i){const l=Qy(o);return e.concat(o,o.visualViewport||[],Ed(a)?a:[],l&&t?xd(l):[])}return e.concat(a,xd(a,[],t))}function Qy(s){return s.parent&&Object.getPrototypeOf(s.parent)?s.frameElement:null}const Mc=Math.min,tl=Math.max,sm=Math.round,ip=Math.floor,Oi=s=>({x:s,y:s}),w7={left:"right",right:"left",bottom:"top",top:"bottom"},k7={start:"end",end:"start"};function S7(s,e,t){return tl(s,Mc(e,t))}function Im(s,e){return typeof s=="function"?s(e):s}function Tc(s){return s.split("-")[0]}function _d(s){return s.split("-")[1]}function j7(s){return s==="x"?"y":"x"}function Av(s){return s==="y"?"height":"width"}const C7=new Set(["top","bottom"]);function Yo(s){return C7.has(Tc(s))?"y":"x"}function Mv(s){return j7(Yo(s))}function N7(s,e,t){t===void 0&&(t=!1);const n=_d(s),a=Mv(s),i=Av(a);let o=a==="x"?n===(t?"end":"start")?"right":"left":n==="start"?"bottom":"top";return e.reference[i]>e.floating[i]&&(o=am(o)),[o,am(o)]}function A7(s){const e=am(s);return[Jy(s),e,Jy(e)]}function Jy(s){return s.replace(/start|end/g,e=>k7[e])}const iN=["left","right"],rN=["right","left"],M7=["top","bottom"],T7=["bottom","top"];function E7(s,e,t){switch(s){case"top":case"bottom":return t?e?rN:iN:e?iN:rN;case"left":case"right":return e?M7:T7;default:return[]}}function _7(s,e,t,n){const a=_d(s);let i=E7(Tc(s),t==="start",n);return a&&(i=i.map(o=>o+"-"+a),e&&(i=i.concat(i.map(Jy)))),i}function am(s){return s.replace(/left|right|bottom|top/g,e=>w7[e])}function D7(s){return{top:0,right:0,bottom:0,left:0,...s}}function e_(s){return typeof s!="number"?D7(s):{top:s,right:s,bottom:s,left:s}}function im(s){const{x:e,y:t,width:n,height:a}=s;return{width:n,height:a,top:t,left:e,right:e+n,bottom:t+a,x:e,y:t}}var P7=typeof document<"u",R7=function(){},rm=P7?y.useLayoutEffect:R7;const L7={...GA},O7=L7.useInsertionEffect,I7=O7||(s=>s());function B7(s){const e=y.useRef(()=>{});return I7(()=>{e.current=s}),y.useCallback(function(){for(var t=arguments.length,n=new Array(t),a=0;a<t;a++)n[a]=arguments[a];return e.current==null?void 0:e.current(...n)},[])}function oN(s,e,t){let{reference:n,floating:a}=s;const i=Yo(e),o=Mv(e),l=Av(o),c=Tc(e),d=i==="y",m=n.x+n.width/2-a.width/2,p=n.y+n.height/2-a.height/2,f=n[l]/2-a[l]/2;let b;switch(c){case"top":b={x:m,y:n.y-a.height};break;case"bottom":b={x:m,y:n.y+n.height};break;case"right":b={x:n.x+n.width,y:p};break;case"left":b={x:n.x-a.width,y:p};break;default:b={x:n.x,y:n.y}}switch(_d(e)){case"start":b[o]-=f*(t&&d?-1:1);break;case"end":b[o]+=f*(t&&d?-1:1);break}return b}async function z7(s,e){var t;e===void 0&&(e={});const{x:n,y:a,platform:i,rects:o,elements:l,strategy:c}=s,{boundary:d="clippingAncestors",rootBoundary:m="viewport",elementContext:p="floating",altBoundary:f=!1,padding:b=0}=Im(e,s),x=e_(b),k=l[f?p==="floating"?"reference":"floating":p],S=im(await i.getClippingRect({element:(t=await(i.isElement==null?void 0:i.isElement(k)))==null||t?k:k.contextElement||await(i.getDocumentElement==null?void 0:i.getDocumentElement(l.floating)),boundary:d,rootBoundary:m,strategy:c})),j=p==="floating"?{x:n,y:a,width:o.floating.width,height:o.floating.height}:o.reference,C=await(i.getOffsetParent==null?void 0:i.getOffsetParent(l.floating)),N=await(i.isElement==null?void 0:i.isElement(C))?await(i.getScale==null?void 0:i.getScale(C))||{x:1,y:1}:{x:1,y:1},P=im(i.convertOffsetParentRelativeRectToViewportRelativeRect?await i.convertOffsetParentRelativeRectToViewportRelativeRect({elements:l,rect:j,offsetParent:C,strategy:c}):j);return{top:(S.top-P.top+x.top)/N.y,bottom:(P.bottom-S.bottom+x.bottom)/N.y,left:(S.left-P.left+x.left)/N.x,right:(P.right-S.right+x.right)/N.x}}const F7=async(s,e,t)=>{const{placement:n="bottom",strategy:a="absolute",middleware:i=[],platform:o}=t,l=i.filter(Boolean),c=await(o.isRTL==null?void 0:o.isRTL(e));let d=await o.getElementRects({reference:s,floating:e,strategy:a}),{x:m,y:p}=oN(d,n,c),f=n,b={},x=0;for(let k=0;k<l.length;k++){var w;const{name:S,fn:j}=l[k],{x:C,y:N,data:P,reset:_}=await j({x:m,y:p,initialPlacement:n,placement:f,strategy:a,middlewareData:b,rects:d,platform:{...o,detectOverflow:(w=o.detectOverflow)!=null?w:z7},elements:{reference:s,floating:e}});m=C??m,p=N??p,b={...b,[S]:{...b[S],...P}},_&&x<=50&&(x++,typeof _=="object"&&(_.placement&&(f=_.placement),_.rects&&(d=_.rects===!0?await o.getElementRects({reference:s,floating:e,strategy:a}):_.rects),{x:m,y:p}=oN(d,f,c)),k=-1)}return{x:m,y:p,placement:f,strategy:a,middlewareData:b}},$7=s=>({name:"arrow",options:s,async fn(e){const{x:t,y:n,placement:a,rects:i,platform:o,elements:l,middlewareData:c}=e,{element:d,padding:m=0}=Im(s,e)||{};if(d==null)return{};const p=e_(m),f={x:t,y:n},b=Mv(a),x=Av(b),w=await o.getDimensions(d),k=b==="y",S=k?"top":"left",j=k?"bottom":"right",C=k?"clientHeight":"clientWidth",N=i.reference[x]+i.reference[b]-f[b]-i.floating[x],P=f[b]-i.reference[b],_=await(o.getOffsetParent==null?void 0:o.getOffsetParent(d));let L=_?_[C]:0;(!L||!await(o.isElement==null?void 0:o.isElement(_)))&&(L=l.floating[C]||i.floating[x]);const M=N/2-P/2,D=L/2-w[x]/2-1,E=Mc(p[S],D),R=Mc(p[j],D),O=E,I=L-w[x]-R,B=L/2-w[x]/2+M,Y=S7(O,B,I),$=!c.arrow&&_d(a)!=null&&B!==Y&&i.reference[x]/2-(B<O?E:R)-w[x]/2<0,W=$?B<O?B-O:B-I:0;return{[b]:f[b]+W,data:{[b]:Y,centerOffset:B-Y-W,...$&&{alignmentOffset:W}},reset:$}}}),H7=function(s){return s===void 0&&(s={}),{name:"flip",options:s,async fn(e){var t,n;const{placement:a,middlewareData:i,rects:o,initialPlacement:l,platform:c,elements:d}=e,{mainAxis:m=!0,crossAxis:p=!0,fallbackPlacements:f,fallbackStrategy:b="bestFit",fallbackAxisSideDirection:x="none",flipAlignment:w=!0,...k}=Im(s,e);if((t=i.arrow)!=null&&t.alignmentOffset)return{};const S=Tc(a),j=Yo(l),C=Tc(l)===l,N=await(c.isRTL==null?void 0:c.isRTL(d.floating)),P=f||(C||!w?[am(l)]:A7(l)),_=x!=="none";!f&&_&&P.push(..._7(l,w,x,N));const L=[l,...P],M=await c.detectOverflow(e,k),D=[];let E=((n=i.flip)==null?void 0:n.overflows)||[];if(m&&D.push(M[S]),p){const B=N7(a,o,N);D.push(M[B[0]],M[B[1]])}if(E=[...E,{placement:a,overflows:D}],!D.every(B=>B<=0)){var R,O;const B=(((R=i.flip)==null?void 0:R.index)||0)+1,Y=L[B];if(Y&&(!(p==="alignment"?j!==Yo(Y):!1)||E.every(K=>Yo(K.placement)===j?K.overflows[0]>0:!0)))return{data:{index:B,overflows:E},reset:{placement:Y}};let $=(O=E.filter(W=>W.overflows[0]<=0).sort((W,K)=>W.overflows[1]-K.overflows[1])[0])==null?void 0:O.placement;if(!$)switch(b){case"bestFit":{var I;const W=(I=E.filter(K=>{if(_){const X=Yo(K.placement);return X===j||X==="y"}return!0}).map(K=>[K.placement,K.overflows.filter(X=>X>0).reduce((X,H)=>X+H,0)]).sort((K,X)=>K[1]-X[1])[0])==null?void 0:I[0];W&&($=W);break}case"initialPlacement":$=l;break}if(a!==$)return{reset:{placement:$}}}return{}}}},U7=new Set(["left","top"]);async function G7(s,e){const{placement:t,platform:n,elements:a}=s,i=await(n.isRTL==null?void 0:n.isRTL(a.floating)),o=Tc(t),l=_d(t),c=Yo(t)==="y",d=U7.has(o)?-1:1,m=i&&c?-1:1,p=Im(e,s);let{mainAxis:f,crossAxis:b,alignmentAxis:x}=typeof p=="number"?{mainAxis:p,crossAxis:0,alignmentAxis:null}:{mainAxis:p.mainAxis||0,crossAxis:p.crossAxis||0,alignmentAxis:p.alignmentAxis};return l&&typeof x=="number"&&(b=l==="end"?x*-1:x),c?{x:b*m,y:f*d}:{x:f*d,y:b*m}}const W7=function(s){return s===void 0&&(s=0),{name:"offset",options:s,async fn(e){var t,n;const{x:a,y:i,placement:o,middlewareData:l}=e,c=await G7(e,s);return o===((t=l.offset)==null?void 0:t.placement)&&(n=l.arrow)!=null&&n.alignmentOffset?{}:{x:a+c.x,y:i+c.y,data:{...c,placement:o}}}}};function t_(s){const e=Xa(s);let t=parseFloat(e.width)||0,n=parseFloat(e.height)||0;const a=Bi(s),i=a?s.offsetWidth:t,o=a?s.offsetHeight:n,l=sm(t)!==i||sm(n)!==o;return l&&(t=i,n=o),{width:t,height:n,$:l}}function Tv(s){return Xs(s)?s:s.contextElement}function fc(s){const e=Tv(s);if(!Bi(e))return Oi(1);const t=e.getBoundingClientRect(),{width:n,height:a,$:i}=t_(e);let o=(i?sm(t.width):t.width)/n,l=(i?sm(t.height):t.height)/a;return(!o||!Number.isFinite(o))&&(o=1),(!l||!Number.isFinite(l))&&(l=1),{x:o,y:l}}const q7=Oi(0);function n_(s){const e=_a(s);return!Nv()||!e.visualViewport?q7:{x:e.visualViewport.offsetLeft,y:e.visualViewport.offsetTop}}function Y7(s,e,t){return e===void 0&&(e=!1),!t||e&&t!==_a(s)?!1:e}function dl(s,e,t,n){e===void 0&&(e=!1),t===void 0&&(t=!1);const a=s.getBoundingClientRect(),i=Tv(s);let o=Oi(1);e&&(n?Xs(n)&&(o=fc(n)):o=fc(s));const l=Y7(i,t,n)?n_(i):Oi(0);let c=(a.left+l.x)/o.x,d=(a.top+l.y)/o.y,m=a.width/o.x,p=a.height/o.y;if(i){const f=_a(i),b=n&&Xs(n)?_a(n):n;let x=f,w=Qy(x);for(;w&&n&&b!==x;){const k=fc(w),S=w.getBoundingClientRect(),j=Xa(w),C=S.left+(w.clientLeft+parseFloat(j.paddingLeft))*k.x,N=S.top+(w.clientTop+parseFloat(j.paddingTop))*k.y;c*=k.x,d*=k.y,m*=k.x,p*=k.y,c+=C,d+=N,x=_a(w),w=Qy(x)}}return im({width:m,height:p,x:c,y:d})}function Bm(s,e){const t=Om(s).scrollLeft;return e?e.left+t:dl(Hi(s)).left+t}function s_(s,e){const t=s.getBoundingClientRect(),n=t.left+e.scrollLeft-Bm(s,t),a=t.top+e.scrollTop;return{x:n,y:a}}function V7(s){let{elements:e,rect:t,offsetParent:n,strategy:a}=s;const i=a==="fixed",o=Hi(n),l=e?Lm(e.floating):!1;if(n===o||l&&i)return t;let c={scrollLeft:0,scrollTop:0},d=Oi(1);const m=Oi(0),p=Bi(n);if((p||!p&&!i)&&((Oc(n)!=="body"||Ed(o))&&(c=Om(n)),Bi(n))){const b=dl(n);d=fc(n),m.x=b.x+n.clientLeft,m.y=b.y+n.clientTop}const f=o&&!p&&!i?s_(o,c):Oi(0);return{width:t.width*d.x,height:t.height*d.y,x:t.x*d.x-c.scrollLeft*d.x+m.x+f.x,y:t.y*d.y-c.scrollTop*d.y+m.y+f.y}}function K7(s){return Array.from(s.getClientRects())}function X7(s){const e=Hi(s),t=Om(s),n=s.ownerDocument.body,a=tl(e.scrollWidth,e.clientWidth,n.scrollWidth,n.clientWidth),i=tl(e.scrollHeight,e.clientHeight,n.scrollHeight,n.clientHeight);let o=-t.scrollLeft+Bm(s);const l=-t.scrollTop;return Xa(n).direction==="rtl"&&(o+=tl(e.clientWidth,n.clientWidth)-a),{width:a,height:i,x:o,y:l}}const lN=25;function Z7(s,e){const t=_a(s),n=Hi(s),a=t.visualViewport;let i=n.clientWidth,o=n.clientHeight,l=0,c=0;if(a){i=a.width,o=a.height;const m=Nv();(!m||m&&e==="fixed")&&(l=a.offsetLeft,c=a.offsetTop)}const d=Bm(n);if(d<=0){const m=n.ownerDocument,p=m.body,f=getComputedStyle(p),b=m.compatMode==="CSS1Compat"&&parseFloat(f.marginLeft)+parseFloat(f.marginRight)||0,x=Math.abs(n.clientWidth-p.clientWidth-b);x<=lN&&(i-=x)}else d<=lN&&(i+=d);return{width:i,height:o,x:l,y:c}}const Q7=new Set(["absolute","fixed"]);function J7(s,e){const t=dl(s,!0,e==="fixed"),n=t.top+s.clientTop,a=t.left+s.clientLeft,i=Bi(s)?fc(s):Oi(1),o=s.clientWidth*i.x,l=s.clientHeight*i.y,c=a*i.x,d=n*i.y;return{width:o,height:l,x:c,y:d}}function cN(s,e,t){let n;if(e==="viewport")n=Z7(s,t);else if(e==="document")n=X7(Hi(s));else if(Xs(e))n=J7(e,t);else{const a=n_(s);n={x:e.x-a.x,y:e.y-a.y,width:e.width,height:e.height}}return im(n)}function a_(s,e){const t=po(s);return t===e||!Xs(t)||Ac(t)?!1:Xa(t).position==="fixed"||a_(t,e)}function eq(s,e){const t=e.get(s);if(t)return t;let n=xd(s,[],!1).filter(l=>Xs(l)&&Oc(l)!=="body"),a=null;const i=Xa(s).position==="fixed";let o=i?po(s):s;for(;Xs(o)&&!Ac(o);){const l=Xa(o),c=Cv(o);!c&&l.position==="fixed"&&(a=null),(i?!c&&!a:!c&&l.position==="static"&&!!a&&Q7.has(a.position)||Ed(o)&&!c&&a_(s,o))?n=n.filter(m=>m!==o):a=l,o=po(o)}return e.set(s,n),n}function tq(s){let{element:e,boundary:t,rootBoundary:n,strategy:a}=s;const o=[...t==="clippingAncestors"?Lm(e)?[]:eq(e,this._c):[].concat(t),n],l=o[0],c=o.reduce((d,m)=>{const p=cN(e,m,a);return d.top=tl(p.top,d.top),d.right=Mc(p.right,d.right),d.bottom=Mc(p.bottom,d.bottom),d.left=tl(p.left,d.left),d},cN(e,l,a));return{width:c.right-c.left,height:c.bottom-c.top,x:c.left,y:c.top}}function nq(s){const{width:e,height:t}=t_(s);return{width:e,height:t}}function sq(s,e,t){const n=Bi(e),a=Hi(e),i=t==="fixed",o=dl(s,!0,i,e);let l={scrollLeft:0,scrollTop:0};const c=Oi(0);function d(){c.x=Bm(a)}if(n||!n&&!i)if((Oc(e)!=="body"||Ed(a))&&(l=Om(e)),n){const b=dl(e,!0,i,e);c.x=b.x+e.clientLeft,c.y=b.y+e.clientTop}else a&&d();i&&!n&&a&&d();const m=a&&!n&&!i?s_(a,l):Oi(0),p=o.left+l.scrollLeft-c.x-m.x,f=o.top+l.scrollTop-c.y-m.y;return{x:p,y:f,width:o.width,height:o.height}}function $b(s){return Xa(s).position==="static"}function uN(s,e){if(!Bi(s)||Xa(s).position==="fixed")return null;if(e)return e(s);let t=s.offsetParent;return Hi(s)===t&&(t=t.ownerDocument.body),t}function i_(s,e){const t=_a(s);if(Lm(s))return t;if(!Bi(s)){let a=po(s);for(;a&&!Ac(a);){if(Xs(a)&&!$b(a))return a;a=po(a)}return t}let n=uN(s,e);for(;n&&m7(n)&&$b(n);)n=uN(n,e);return n&&Ac(n)&&$b(n)&&!Cv(n)?t:n||x7(s)||t}const aq=async function(s){const e=this.getOffsetParent||i_,t=this.getDimensions,n=await t(s.floating);return{reference:sq(s.reference,await e(s.floating),s.strategy),floating:{x:0,y:0,width:n.width,height:n.height}}};function iq(s){return Xa(s).direction==="rtl"}const rq={convertOffsetParentRelativeRectToViewportRelativeRect:V7,getDocumentElement:Hi,getClippingRect:tq,getOffsetParent:i_,getElementRects:aq,getClientRects:K7,getDimensions:nq,getScale:fc,isElement:Xs,isRTL:iq};function r_(s,e){return s.x===e.x&&s.y===e.y&&s.width===e.width&&s.height===e.height}function oq(s,e){let t=null,n;const a=Hi(s);function i(){var l;clearTimeout(n),(l=t)==null||l.disconnect(),t=null}function o(l,c){l===void 0&&(l=!1),c===void 0&&(c=1),i();const d=s.getBoundingClientRect(),{left:m,top:p,width:f,height:b}=d;if(l||e(),!f||!b)return;const x=ip(p),w=ip(a.clientWidth-(m+f)),k=ip(a.clientHeight-(p+b)),S=ip(m),C={rootMargin:-x+"px "+-w+"px "+-k+"px "+-S+"px",threshold:tl(0,Mc(1,c))||1};let N=!0;function P(_){const L=_[0].intersectionRatio;if(L!==c){if(!N)return o();L?o(!1,L):n=setTimeout(()=>{o(!1,1e-7)},1e3)}L===1&&!r_(d,s.getBoundingClientRect())&&o(),N=!1}try{t=new IntersectionObserver(P,{...C,root:a.ownerDocument})}catch{t=new IntersectionObserver(P,C)}t.observe(s)}return o(!0),i}function lq(s,e,t,n){n===void 0&&(n={});const{ancestorScroll:a=!0,ancestorResize:i=!0,elementResize:o=typeof ResizeObserver=="function",layoutShift:l=typeof IntersectionObserver=="function",animationFrame:c=!1}=n,d=Tv(s),m=a||i?[...d?xd(d):[],...xd(e)]:[];m.forEach(S=>{a&&S.addEventListener("scroll",t,{passive:!0}),i&&S.addEventListener("resize",t)});const p=d&&l?oq(d,t):null;let f=-1,b=null;o&&(b=new ResizeObserver(S=>{let[j]=S;j&&j.target===d&&b&&(b.unobserve(e),cancelAnimationFrame(f),f=requestAnimationFrame(()=>{var C;(C=b)==null||C.observe(e)})),t()}),d&&!c&&b.observe(d),b.observe(e));let x,w=c?dl(s):null;c&&k();function k(){const S=dl(s);w&&!r_(w,S)&&t(),w=S,x=requestAnimationFrame(k)}return t(),()=>{var S;m.forEach(j=>{a&&j.removeEventListener("scroll",t),i&&j.removeEventListener("resize",t)}),p==null||p(),(S=b)==null||S.disconnect(),b=null,c&&cancelAnimationFrame(x)}}const cq=W7,uq=H7,dN=$7,dq=(s,e,t)=>{const n=new Map,a={platform:rq,...t},i={...a.platform,_c:n};return F7(s,e,{...a,platform:i})};var hq=typeof document<"u",pq=function(){},Cp=hq?y.useLayoutEffect:pq;function om(s,e){if(s===e)return!0;if(typeof s!=typeof e)return!1;if(typeof s=="function"&&s.toString()===e.toString())return!0;let t,n,a;if(s&&e&&typeof s=="object"){if(Array.isArray(s)){if(t=s.length,t!==e.length)return!1;for(n=t;n--!==0;)if(!om(s[n],e[n]))return!1;return!0}if(a=Object.keys(s),t=a.length,t!==Object.keys(e).length)return!1;for(n=t;n--!==0;)if(!{}.hasOwnProperty.call(e,a[n]))return!1;for(n=t;n--!==0;){const i=a[n];if(!(i==="_owner"&&s.$$typeof)&&!om(s[i],e[i]))return!1}return!0}return s!==s&&e!==e}function o_(s){return typeof window>"u"?1:(s.ownerDocument.defaultView||window).devicePixelRatio||1}function hN(s,e){const t=o_(s);return Math.round(e*t)/t}function Hb(s){const e=y.useRef(s);return Cp(()=>{e.current=s}),e}function mq(s){s===void 0&&(s={});const{placement:e="bottom",strategy:t="absolute",middleware:n=[],platform:a,elements:{reference:i,floating:o}={},transform:l=!0,whileElementsMounted:c,open:d}=s,[m,p]=y.useState({x:0,y:0,strategy:t,placement:e,middlewareData:{},isPositioned:!1}),[f,b]=y.useState(n);om(f,n)||b(n);const[x,w]=y.useState(null),[k,S]=y.useState(null),j=y.useCallback(K=>{K!==_.current&&(_.current=K,w(K))},[]),C=y.useCallback(K=>{K!==L.current&&(L.current=K,S(K))},[]),N=i||x,P=o||k,_=y.useRef(null),L=y.useRef(null),M=y.useRef(m),D=c!=null,E=Hb(c),R=Hb(a),O=Hb(d),I=y.useCallback(()=>{if(!_.current||!L.current)return;const K={placement:e,strategy:t,middleware:f};R.current&&(K.platform=R.current),dq(_.current,L.current,K).then(X=>{const H={...X,isPositioned:O.current!==!1};B.current&&!om(M.current,H)&&(M.current=H,Dc.flushSync(()=>{p(H)}))})},[f,e,t,R,O]);Cp(()=>{d===!1&&M.current.isPositioned&&(M.current.isPositioned=!1,p(K=>({...K,isPositioned:!1})))},[d]);const B=y.useRef(!1);Cp(()=>(B.current=!0,()=>{B.current=!1}),[]),Cp(()=>{if(N&&(_.current=N),P&&(L.current=P),N&&P){if(E.current)return E.current(N,P,I);I()}},[N,P,I,E,D]);const Y=y.useMemo(()=>({reference:_,floating:L,setReference:j,setFloating:C}),[j,C]),$=y.useMemo(()=>({reference:N,floating:P}),[N,P]),W=y.useMemo(()=>{const K={position:t,left:0,top:0};if(!$.floating)return K;const X=hN($.floating,m.x),H=hN($.floating,m.y);return l?{...K,transform:"translate("+X+"px, "+H+"px)",...o_($.floating)>=1.5&&{willChange:"transform"}}:{position:t,left:X,top:H}},[t,l,$.floating,m.x,m.y]);return y.useMemo(()=>({...m,update:I,refs:Y,elements:$,floatingStyles:W}),[m,I,Y,$,W])}const fq=s=>{function e(t){return{}.hasOwnProperty.call(t,"current")}return{name:"arrow",options:s,fn(t){const{element:n,padding:a}=typeof s=="function"?s(t):s;return n&&e(n)?n.current!=null?dN({element:n.current,padding:a}).fn(t):{}:n?dN({element:n,padding:a}).fn(t):{}}}},gq=(s,e)=>({...cq(s),options:[s,e]}),bq=(s,e)=>({...uq(s),options:[s,e]}),yq=(s,e)=>({...fq(s),options:[s,e]}),xq={...GA};let pN=!1,vq=0;const mN=()=>"floating-ui-"+Math.random().toString(36).slice(2,6)+vq++;function wq(){const[s,e]=y.useState(()=>pN?mN():void 0);return rm(()=>{s==null&&e(mN())},[]),y.useEffect(()=>{pN=!0},[]),s}const kq=xq.useId,l_=kq||wq,Sq=y.forwardRef(function(e,t){const{context:{placement:n,elements:{floating:a},middlewareData:{arrow:i,shift:o}},width:l=14,height:c=7,tipRadius:d=0,strokeWidth:m=0,staticOffset:p,stroke:f,d:b,style:{transform:x,...w}={},...k}=e,S=l_(),[j,C]=y.useState(!1);if(rm(()=>{if(!a)return;Xa(a).direction==="rtl"&&C(!0)},[a]),!a)return null;const[N,P]=n.split("-"),_=N==="top"||N==="bottom";let L=p;(_&&o!=null&&o.x||!_&&o!=null&&o.y)&&(L=null);const M=m*2,D=M/2,E=l/2*(d/-8+1),R=c/2*d/4,O=!!b,I=L&&P==="end"?"bottom":"top";let B=L&&P==="end"?"right":"left";L&&j&&(B=P==="end"?"left":"right");const Y=(i==null?void 0:i.x)!=null?L||i.x:"",$=(i==null?void 0:i.y)!=null?L||i.y:"",W=b||"M0,0"+(" H"+l)+(" L"+(l-E)+","+(c-R))+(" Q"+l/2+","+c+" "+E+","+(c-R))+" Z",K={top:O?"rotate(180deg)":"",left:O?"rotate(90deg)":"rotate(-90deg)",bottom:O?"":"rotate(180deg)",right:O?"rotate(-90deg)":"rotate(90deg)"}[N];return r.jsxs("svg",{...k,"aria-hidden":!0,ref:t,width:O?l:l+M,height:l,viewBox:"0 0 "+l+" "+(c>l?c:l),style:{position:"absolute",pointerEvents:"none",[B]:Y,[I]:$,[N]:_||O?"100%":"calc(100% - "+M/2+"px)",transform:[K,x].filter(X=>!!X).join(" "),...w},children:[M>0&&r.jsx("path",{clipPath:"url(#"+S+")",fill:"none",stroke:f,strokeWidth:M+(b?0:1),d:W}),r.jsx("path",{stroke:M&&!b?k.fill:"none",d:W}),r.jsx("clipPath",{id:S,children:r.jsx("rect",{x:-D,y:D*(O?-1:1),width:l+M,height:l})})]})});function jq(){const s=new Map;return{emit(e,t){var n;(n=s.get(e))==null||n.forEach(a=>a(t))},on(e,t){s.has(e)||s.set(e,new Set),s.get(e).add(t)},off(e,t){var n;(n=s.get(e))==null||n.delete(t)}}}const Cq=y.createContext(null),Nq=y.createContext(null),Aq=()=>{var s;return((s=y.useContext(Cq))==null?void 0:s.id)||null},Mq=()=>y.useContext(Nq);function Tq(s){const{open:e=!1,onOpenChange:t,elements:n}=s,a=l_(),i=y.useRef({}),[o]=y.useState(()=>jq()),l=Aq()!=null,[c,d]=y.useState(n.reference),m=B7((b,x,w)=>{i.current.openEvent=b?x:void 0,o.emit("openchange",{open:b,event:x,reason:w,nested:l}),t==null||t(b,x,w)}),p=y.useMemo(()=>({setPositionReference:d}),[]),f=y.useMemo(()=>({reference:c||n.reference||null,floating:n.floating||null,domReference:n.reference}),[c,n.reference,n.floating]);return y.useMemo(()=>({dataRef:i,open:e,onOpenChange:m,elements:f,events:o,floatingId:a,refs:p}),[e,m,f,o,a,p])}function Eq(s){s===void 0&&(s={});const{nodeId:e}=s,t=Tq({...s,elements:{reference:null,floating:null,...s.elements}}),n=s.rootContext||t,a=n.elements,[i,o]=y.useState(null),[l,c]=y.useState(null),m=(a==null?void 0:a.domReference)||i,p=y.useRef(null),f=Mq();rm(()=>{m&&(p.current=m)},[m]);const b=mq({...s,elements:{...a,...l&&{reference:l}}}),x=y.useCallback(C=>{const N=Xs(C)?{getBoundingClientRect:()=>C.getBoundingClientRect(),getClientRects:()=>C.getClientRects(),contextElement:C}:C;c(N),b.refs.setReference(N)},[b.refs]),w=y.useCallback(C=>{(Xs(C)||C===null)&&(p.current=C,o(C)),(Xs(b.refs.reference.current)||b.refs.reference.current===null||C!==null&&!Xs(C))&&b.refs.setReference(C)},[b.refs]),k=y.useMemo(()=>({...b.refs,setReference:w,setPositionReference:x,domReference:p}),[b.refs,w,x]),S=y.useMemo(()=>({...b.elements,domReference:m}),[b.elements,m]),j=y.useMemo(()=>({...b,...n,refs:k,elements:S,nodeId:e}),[b,k,S,e,n]);return rm(()=>{n.dataRef.current.floatingContext=j;const C=f==null?void 0:f.nodesRef.current.find(N=>N.id===e);C&&(C.context=j)}),y.useMemo(()=>({...b,context:j,refs:k,elements:S}),[b,k,S,j])}/*!