tide-commander 0.78.0 → 0.78.1
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-
|
|
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-Cjmp1lCs.js","assets/modulepreload-polyfill-B5Qt9EMX.js","assets/vendor-three-DJ4p3FLF.js"])))=>i.map(i=>d[i]);
|
|
2
2
|
var $D=Object.defineProperty;var HD=(s,e,t)=>e in s?$D(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var U=(s,e,t)=>HD(s,typeof e!="symbol"?e+"":e,t);import"./modulepreload-polyfill-B5Qt9EMX.js";import{r as ox,g as bd,a as xA,c as cS}from"./vendor-react-uS-d4TUT.js";import{T as UD,a as Jb,b as vA,L as wA,c as Yu,F as jp,M as Pi,V as Rs,C as It,d as Di,S as ei,e as GD,P as kA,D as lc,f as Jo,g as xt,I as or,Q as el,h as WD,O as SA,i as lx,j as qD,B as ti,k as YD,l as Vu,N as VD,m as KD,n as XD,o as En,p as jA,R as $o,q as ZD,r as QD,s as um,t as Zr,u as Ho,v as ut,w as ks,x as Ye,y as JD,z as Fa,A as ey,E as Re,G as cx,H as Yr,J as eR,K as yd,U as _n,W as ux,X as CA,Y as NA,Z as tR,_ as nR,$ as sR,a0 as aR,a1 as AA,a2 as iR,a3 as uS,a4 as dS,a5 as hS,a6 as pS,a7 as ty,a8 as MA,a9 as rR,aa as Cp,ab as oR,ac as lR,ad as Ku,ae as ny,af as Bn,ag as Gn,ah as tl,ai as Kn,aj as zn,ak as cR,al as TA,am as uR,an as dR,ao as cr,ap as nl,aq as zt,ar as EA,as as en,at as fc,au as mS,av as hR,aw as dx,ax as pR,ay as mR,az as _A,aA as Np,aB as sy,aC as cc,aD as DA,aE as fS,aF as fR,aG as gR,aH as qo,aI as sc,aJ as bR,aK as gS,aL as ay,aM as yR,aN as xR,aO as vR,aP as wR,aQ as RA,aR as hx,aS as PA,aT as kR,aU as SR}from"./vendor-three-DJ4p3FLF.js";function jR(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 Fg={exports:{}},ku={};/**
|
|
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 zS;function hP(){if(zS)return Vg;zS=1;var s=ox();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 Vg.useSyncExternalStore=s.useSyncExternalStore!==void 0?s.useSyncExternalStore:m,Vg}var FS;function pP(){return FS||(FS=1,Yg.exports=hP()),Yg.exports}var mP=pP();const fP=(s,e)=>sl(e)?e:eP(e)&&sl(e.defaultValue)?e.defaultValue:Array.isArray(s)?s[s.length-1]:s,gP={t:fP,ready:!1},bP=()=>()=>{},Ue=(s,e={})=>{var D,R,L;const{i18n:t}=e,{i18n:n,defaultNS:a}=y.useContext(uP)||{},i=t||n||lP();i&&!i.reportNamespaces&&(i.reportNamespaces=new dP),i||zA(i,"NO_I18NEXT_INSTANCE","useTranslation: You will need to pass in an i18next instance by using initReactI18next");const o=y.useMemo(()=>{var O;return{...rP(),...(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=sl(d)?[d]:d||["translation"],p=y.useMemo(()=>m,m);(L=(R=i==null?void 0:i.reportNamespaces)==null?void 0:R.addUsedNamespaces)==null||L.call(R,p);const f=y.useRef(0),b=y.useCallback(O=>{if(!i)return bP;const{bindI18n:I,bindI18nStore:B}=o,G=()=>{f.current+=1,O()};return I&&i.on(I,G),B&&i.store.on(B,G),()=>{I&&I.split(" ").forEach($=>i.off($,G)),B&&B.split(" ").forEach($=>i.store.off($,G))}},[i,o]),x=y.useRef(),w=y.useCallback(()=>{if(!i)return gP;const O=!!(i.isInitialized||i.initializedStoreOnce)&&p.every(K=>JR(K,i,o)),I=e.lng||i.language,B=f.current,G=x.current;if(G&&G.ready===O&&G.lng===I&&G.keyPrefix===c&&G.revision===B)return G;const Y={t:i.getFixedT(I,o.nsMode==="fallback"?p:p[0],c),ready:O,lng:I,keyPrefix:c,revision:B};return x.current=Y,Y},[i,p,c,o,e.lng]),[k,j]=y.useState(0),{t:S,ready:C}=mP.useSyncExternalStore(b,w,w);y.useEffect(()=>{if(i&&!C&&!l){const O=()=>j(I=>I+1);e.lng?BS(i,e.lng,p,O):oy(i,p,O)}},[i,e.lng,p,C,l,k]);const A=i||{},_=y.useRef(null),T=y.useRef(),P=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=A,I=O==null?void 0:O.language;let B=O;O&&(_.current&&_.current.__original===O?T.current!==I?(B=P(O),_.current=B,T.current=I):B=_.current:(B=P(O),_.current=B,T.current=I));const G=[S,B,C];return G.t=S,G.i18n=B,G.ready=C,G},[S,A,C,A.resolvedLanguage,A.language,A.languages]);if(i&&l&&!C)throw new Promise(O=>{const I=()=>O();e.lng?BS(i,e.lng,p,I):oy(i,p,I)});return M};function cy(s){"@babel/helpers - typeof";return cy=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},cy(s)}function HA(){return typeof XMLHttpRequest=="function"||(typeof XMLHttpRequest>"u"?"undefined":cy(XMLHttpRequest))==="object"}function yP(s){return!!s&&typeof s.then=="function"}function xP(s){return yP(s)?s:Promise.resolve(s)}const vP="modulepreload",wP=function(s){return"/"+s},$S={},UA=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=wP(d),d in $S)return;$S[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":vP,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 HS(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 US(s){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?HS(Object(t),!0).forEach(function(n){kP(s,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(t)):HS(Object(t)).forEach(function(n){Object.defineProperty(s,n,Object.getOwnPropertyDescriptor(t,n))})}return s}function kP(s,e,t){return(e=SP(e))in s?Object.defineProperty(s,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):s[e]=t,s}function SP(s){var e=jP(s,"string");return al(e)=="symbol"?e:e+""}function jP(s,e){if(al(s)!="object"||!s)return s;var t=s[Symbol.toPrimitive];if(t!==void 0){var n=t.call(s,e);if(al(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(s)}function al(s){"@babel/helpers - typeof";return al=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},al(s)}var so=typeof fetch=="function"?fetch:void 0;typeof global<"u"&&global.fetch?so=global.fetch:typeof window<"u"&&window.fetch&&(so=window.fetch);var rd;HA()&&(typeof global<"u"&&global.XMLHttpRequest?rd=global.XMLHttpRequest:typeof window<"u"&&window.XMLHttpRequest&&(rd=window.XMLHttpRequest));var Ep;typeof ActiveXObject=="function"&&(typeof global<"u"&&global.ActiveXObject?Ep=global.ActiveXObject:typeof window<"u"&&window.ActiveXObject&&(Ep=window.ActiveXObject));typeof so!="function"&&(so=void 0);if(!so&&!rd&&!Ep)try{UA(()=>import("./browser-ponyfill-DIm4hKhx.js").then(s=>s.b),__vite__mapDeps([0,1])).then(function(s){so=s.default}).catch(function(){})}catch{}var uy=function(e,t){if(t&&al(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},GS=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):so(e,t).then(i).catch(n)},WS=!1,CP=function(e,t,n,a){e.queryStringParams&&(t=uy(t,e.queryStringParams));var i=US({},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=US({method:n?"POST":"GET",body:n?e.stringify(n):void 0,headers:i},WS?{}:o),c=typeof e.alternateFetch=="function"&&e.alternateFetch.length>=1?e.alternateFetch:void 0;try{GS(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]}),GS(t,l,a,c),WS=!0}catch(m){a(m)}}},NP=function(e,t,n,a){n&&al(n)==="object"&&(n=uy("",n).slice(1)),e.queryStringParams&&(t=uy(t,e.queryStringParams));try{var i=rd?new rd:new Ep("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)}},AP=function(e,t,n,a){if(typeof n=="function"&&(a=n,n=void 0),a=a||function(){},so&&t.indexOf("file:")!==0)return CP(e,t,n,a);if(HA()||typeof ActiveXObject=="function")return NP(e,t,n,a);a(new Error("No fetch and no xhr implementation found!"))};function gc(s){"@babel/helpers - typeof";return gc=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},gc(s)}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 Kg(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){GA(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 MP(s,e){if(!(s instanceof e))throw new TypeError("Cannot call a class as a function")}function TP(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,WA(n.key),n)}}function EP(s,e,t){return e&&TP(s.prototype,e),Object.defineProperty(s,"prototype",{writable:!1}),s}function GA(s,e,t){return(e=WA(e))in s?Object.defineProperty(s,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):s[e]=t,s}function WA(s){var e=_P(s,"string");return gc(e)=="symbol"?e:e+""}function _P(s,e){if(gc(s)!="object"||!s)return s;var t=s[Symbol.toPrimitive];if(t!==void 0){var n=t.call(s,e);if(gc(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(s)}var DP=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 GA({},n,a||"")},parseLoadPayload:function(t,n){},request:AP,reloadInterval:typeof window<"u"?!1:3600*1e3,customHeaders:{},queryStringParams:{},crossDomain:!1,withCredentials:!1,overrideMimeType:!1,requestOptions:{mode:"cors",credentials:"same-origin",cache:"default"}}},qA=(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]:{};MP(this,s),this.services=e,this.options=t,this.allOptions=n,this.type="backend",this.init(e,t,n)}return EP(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=Kg(Kg(Kg({},DP()),this.options||{}),a),this.allOptions=i,this.services&&this.options.reloadInterval){var o=setInterval(function(){return n.reload()},this.options.reloadInterval);gc(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=xP(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)})})})}}}])})();qA.type="backend";const{slice:RP,forEach:PP}=[];function LP(s){return PP.call(RP.call(arguments,1),e=>{if(e)for(const t in e)s[t]===void 0&&(s[t]=e[t])}),s}function OP(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 YS=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/,IP=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(!YS.test(n.domain))throw new TypeError("option domain is invalid");i+=`; Domain=${n.domain}`}if(n.path){if(!YS.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},VS={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=IP(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 BP={name:"cookie",lookup(s){let{lookupCookie:e}=s;if(e&&typeof document<"u")return VS.read(e)||void 0},cacheUserLanguage(s,e){let{lookupCookie:t,cookieMinutes:n,cookieDomain:a,cookieOptions:i}=e;t&&typeof document<"u"&&VS.create(t,s,n,a,i)}},zP={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}},FP={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 Wl=null;const KS=()=>{if(Wl!==null)return Wl;try{if(Wl=typeof window<"u"&&window.localStorage!==null,!Wl)return!1;const s="i18next.translate.boo";window.localStorage.setItem(s,"foo"),window.localStorage.removeItem(s)}catch{Wl=!1}return Wl};var $P={name:"localStorage",lookup(s){let{lookupLocalStorage:e}=s;if(e&&KS())return window.localStorage.getItem(e)||void 0},cacheUserLanguage(s,e){let{lookupLocalStorage:t}=e;t&&KS()&&window.localStorage.setItem(t,s)}};let ql=null;const XS=()=>{if(ql!==null)return ql;try{if(ql=typeof window<"u"&&window.sessionStorage!==null,!ql)return!1;const s="i18next.translate.boo";window.sessionStorage.setItem(s,"foo"),window.sessionStorage.removeItem(s)}catch{ql=!1}return ql};var HP={name:"sessionStorage",lookup(s){let{lookupSessionStorage:e}=s;if(e&&XS())return window.sessionStorage.getItem(e)||void 0},cacheUserLanguage(s,e){let{lookupSessionStorage:t}=e;t&&XS()&&window.sessionStorage.setItem(t,s)}},UP={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}},GP={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}},WP={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}},qP={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 YA=!1;try{document.cookie,YA=!0}catch{}const VA=["querystring","cookie","localStorage","sessionStorage","navigator","htmlTag"];YA||VA.splice(1,1);const YP=()=>({order:VA,lookupQuerystring:"lng",lookupCookie:"i18next",lookupLocalStorage:"i18nextLng",lookupSessionStorage:"i18nextLng",caches:["localStorage"],excludeCacheFor:["cimode"],convertDetectedLanguage:s=>s});class KA{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=LP(t,this.options||{},YP()),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(BP),this.addDetector(zP),this.addDetector($P),this.addDetector(HP),this.addDetector(UP),this.addDetector(GP),this.addDetector(WP),this.addDetector(qP),this.addDetector(FP)}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&&!OP(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)}))}}KA.type="languageDetector";const _p={idle:"#4aff9e",working:"#4a9eff",waiting:"#ff9e4a",waiting_permission:"#ffcc00",error:"#ff4a4a",offline:"#888888",orphaned:"#ff9e4a",default:"#888888"},ao={running:"#4aff9e",stopped:"#888888",error:"#ff4a4a",unknown:"#ffaa00",starting:"#4a9eff",stopping:"#ffaa00"},XA={on_track:"#4aff9e",stalled:"#ff9e4a",blocked:"#ff4a4a",completed:"#4a9eff",idle:"#888888"},VP=["#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"],Hh={recent:"#50fa7b",short:"#f1fa8c",medium:"#ffb86c",long:"#ff5555"};function hm(s){const t=Math.floor((Date.now()-s)/1e3)/60;return t<1?Hh.recent:t<5?Hh.short:t<30?Hh.medium:Hh.long}function px(s){return _p[s]??_p.default}let mp=null;function ZA(){if(!mp)try{mp=globalThis.__i18n}catch{}return mp}function KP(s){mp=s}function XP(s){return s>=1e6?(s/1e6).toFixed(1)+"M":s>=1e3?(s/1e3).toFixed(1)+"K":s.toString()}function dy(s){return s>=1e6?(s/1e6).toFixed(1)+"M":s>=1e3?(s/1e3).toFixed(1)+"K":s.toString()}function QA(s){var a;const e=ZA(),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 pm(s){var d;const e=ZA(),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 Qr(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:""}pn.use(qA).use(KA).use(cP).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(()=>{KP(pn)});const mt={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"};function Ja(s,e){try{const t=localStorage.getItem(s);return t===null?e:JSON.parse(t)}catch{return e}}function Ms(s,e=""){try{return localStorage.getItem(s)??e}catch{return e}}function hy(s,e=!1){try{const t=localStorage.getItem(s);return t===null?e:t==="true"}catch{return e}}function JA(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 Ci(s,e){try{localStorage.setItem(s,JSON.stringify(e))}catch(t){console.error(`Failed to save to localStorage: ${s}`,t)}}function ra(s,e){try{localStorage.setItem(s,e)}catch(t){console.error(`Failed to save to localStorage: ${s}`,t)}}function py(s,e){try{localStorage.setItem(s,String(e))}catch(t){console.error(`Failed to save to localStorage: ${s}`,t)}}function eM(s,e){try{localStorage.setItem(s,String(e))}catch(t){console.error(`Failed to save to localStorage: ${s}`,t)}}function ZS(s){try{localStorage.removeItem(s)}catch(e){console.error(`Failed to remove from localStorage: ${s}`,e)}}function tM(){const s=Ms(mt.BACKEND_URL,"");return s?s.replace(/\/$/,""):`${window.location.protocol}//${window.location.host}`}function oi(){return Ms(mt.AUTH_TOKEN,"")}function at(s){return`${tM()}${s}`}async function ft(s,e){const t=oi(),n=new Headers(e==null?void 0:e.headers);return t&&n.set("X-Auth-Token",t),fetch(s,{...e,headers:n})}function xd(s){const e=oi();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 $s(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 ZP(){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 QP(){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 Qa=[],JP=new Set;function Dp(){JP.forEach(s=>s())}function eL(s,e){const t=Qa.findIndex(n=>n.id===s);return t!==-1&&Qa.splice(t,1),Qa.push({id:s,close:e}),Dp(),()=>{const n=Qa.findIndex(a=>a.id===s);n!==-1&&(Qa.splice(n,1),Dp())}}function my(){return Qa.length===0?!1:(Qa.pop().close(),Dp(),!0)}function tL(...s){const e=new Set(s);for(;Qa.length>0;){const t=Qa[Qa.length-1];if(e.has(t.id))break;Qa.pop().close()}Dp()}function Sn(s,e,t){const n=y.useRef(t);n.current=t,y.useEffect(()=>e?eL(s,()=>n.current()):void 0,[s,e])}let fy,gy;try{fy=require("@capacitor/haptics").Haptics,gy=require("@capacitor/haptics").ImpactStyle}catch{}function QS(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 S=window.innerWidth*.4,C=Math.max(-1,Math.min(1,w/S));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],j=k.clientX-d.current.startX,S=Math.abs(k.clientY-d.current.startY),C=Date.now()-d.current.startTime;d.current.isTracking=!1,d.current.hasMovedEnough=!1,Math.abs(j)>=t&&S<=n&&C<500?(fy&&gy?fy.impact({style:gy.Light}).catch(()=>{navigator.vibrate&&navigator.vibrate(8)}):navigator.vibrate&&navigator.vibrate(8),j>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 nL={width:400,height:300,copyStyleSheets:!0,keepOnTop:"focus"};function sL(){return"documentPictureInPicture"in window}function aL(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 iL(){const[s,e]=y.useState(!1),[t,n]=y.useState(null),[a,i]=y.useState(null),o=y.useRef(null),l=sL(),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={...nL,...p};try{const x=await window.documentPictureInPicture.requestWindow({width:f.width,height:f.height,disallowReturnToOpener:!0});o.current=x,f.copyStyleSheets&&aL(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 j=f.keepOnTop==="raise",S=()=>{o.current&&!o.current.closed&&setTimeout(()=>{o.current&&!o.current.closed&&(o.current.focus(),j&&setTimeout(()=>window.focus(),10))},50)},C=()=>{document.visibilityState==="visible"&&o.current&&!o.current.closed&&setTimeout(()=>{o.current&&!o.current.closed&&(o.current.focus(),j&&setTimeout(()=>window.focus(),10))},100)};window.addEventListener("focus",S),document.addEventListener("visibilitychange",C),k.push(()=>window.removeEventListener("focus",S),()=>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 Cu(){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 rL{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:Cu(),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:Cu(),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:Cu(),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:Cu(),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:Cu(),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 ws=new rL,od={debug:(s,e,t)=>ws.debug(s,e,t),info:(s,e,t)=>ws.info(s,e,t),warn:(s,e,t)=>ws.warn(s,e,t),error:(s,e,t)=>ws.error(s,e,t)};/*! Capacitor: https://capacitorjs.com/ - MIT License */var bc;(function(s){s.Unimplemented="UNIMPLEMENTED",s.Unavailable="UNAVAILABLE"})(bc||(bc={}));class Xg extends Error{constructor(e,t,n){super(e),this.message=e,this.code=t,this.data=n}}const oL=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"},lL=s=>{const e=s.CapacitorCustomPlatform||null,t=s.Capacitor||{},n=t.Plugins=t.Plugins||{},a=()=>e!==null?e.name:oL(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 j=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),S=(M,D)=>{var R,L;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(R=M[D])===null||R===void 0?void 0:R.bind(M)}else{if(M)return(L=M[D])===null||L===void 0?void 0:L.bind(M);throw new Xg(`"${p}" plugin is not implemented on ${x}`,bc.Unimplemented)}},C=M=>{let D;const R=(...L)=>{const O=j().then(I=>{const B=S(I,M);if(B){const G=B(...L);return D=G==null?void 0:G.remove,G}else throw new Xg(`"${p}.${M}()" is not implemented on ${x}`,bc.Unimplemented)});return M==="addListener"&&(O.remove=async()=>D()),O};return R.toString=()=>`${M.toString()}() { [capacitor code] }`,Object.defineProperty(R,"name",{value:M,writable:!1,configurable:!1}),R},A=C("addListener"),_=C("removeListener"),T=(M,D)=>{const R=A({eventName:M},D),L=async()=>{const I=await R;_({eventName:M,callbackId:I},D)},O=new Promise(I=>R.then(()=>I({remove:L})));return O.remove=async()=>{console.warn("Using addListener() without 'await' is deprecated."),await L()},O},P=new Proxy({},{get(M,D){switch(D){case"$$typeof":return;case"toJSON":return()=>({});case"addListener":return w?T:A;case"removeListener":return _;default:return C(D)}}});return n[p]=P,d.set(p,{name:p,proxy:P,platforms:new Set([...Object.keys(f),...w?[x]:[]])}),P};return t.convertFileSrc||(t.convertFileSrc=p=>p),t.getPlatform=a,t.handleError=c,t.isNativePlatform=i,t.isPluginAvailable=o,t.registerPlugin=m,t.Exception=Xg,t.DEBUG=!!t.DEBUG,t.isLoggingEnabled=!!t.isLoggingEnabled,t},cL=s=>s.Capacitor=lL(s),ka=cL(typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}),vd=ka.registerPlugin;class mx{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 ka.Exception(e,bc.Unimplemented)}unavailable(e="not available"){return new ka.Exception(e,bc.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 JS=s=>encodeURIComponent(s).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape),ej=s=>s.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent);class uL extends mx{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=ej(a).trim(),i=ej(i).trim(),t[a]=i}),t}async setCookie(e){try{const t=JS(e.key),n=JS(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)}}}vd("CapacitorCookies",{web:()=>new uL});const dL=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)}),hL=(s={})=>{const e=Object.keys(s);return Object.keys(s).map(a=>a.toLocaleLowerCase()).reduce((a,i,o)=>(a[i]=s[e[o]],a),{})},pL=(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,mL=(s,e={})=>{const t=Object.assign({method:s.method||"GET",headers:s.headers},e),a=hL(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 fL extends mx{async request(e){const t=mL(e,e.webFetchExtra),n=pL(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 dL(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 tj=vd("CapacitorHttp",{web:()=>new fL});var nj;(function(s){s.Dark="DARK",s.Light="LIGHT",s.Default="DEFAULT"})(nj||(nj={}));var sj;(function(s){s.StatusBar="StatusBar",s.NavigationBar="NavigationBar"})(sj||(sj={}));class gL extends mx{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")}}vd("SystemBars",{web:()=>new gL});var aj;(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"})(aj||(aj={}));const fx=vd("LocalNotifications",{web:()=>UA(()=>import("./web-OIx7WerG.js"),__vite__mapDeps([2,3,1,4])).then(s=>new s.LocalNotificationsWeb)}),bL=vd("ServerConfig");let yL=100;const xL="agent_alerts",by="tide-notification-tap";function vL(){return typeof window<"u"&&window.innerWidth<=768&&"ontouchstart"in window}function nM(s){if(vL()){z.openTerminalOnMobile(s);return}if(document.querySelector(".commander-overlay")){z.requestCommanderExpand(s);return}z.selectAgent(s),z.setTerminalOpen(!0)}function wd(){try{return ka.isNativePlatform()}catch{return!1}}async function wL(){if(wd())try{const s=await fx.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 kL(s){const{title:e,body:t,icon:n,data:a}=s;if(wd())try{const i=yL++;console.log("[Notifications] Scheduling native notification id="+i,e),await fx.schedule({notifications:[{id:i,title:e,body:t,extra:a,channelId:xL,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(by,{detail:a}))}}}let Zg=!1;async function SL(s){const e=[];if(Zg)return()=>{};if(Zg=!0,s){const t=n=>{const a=n;a.detail&&s(a.detail)};window.addEventListener(by,t),e.push(()=>window.removeEventListener(by,t))}if(wd())try{const t=await fx.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()),Zg=!1}}function jL(s,e){wd()&&bL.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 gx=()=>window.__tideWsState.ws,ij=s=>{window.__tideWsState.ws=s},CL=()=>window.__tideWsState.isConnecting,Nu=s=>{window.__tideWsState.isConnecting=s},yy=()=>window.__tideWsState.reconnectAttempts,xy=s=>{window.__tideWsState.reconnectAttempts=s},sM=()=>window.__tideWsState.reconnectTimeout,aM=s=>{window.__tideWsState.reconnectTimeout=s},rj=10,bx="tide_ws_has_connected";function oj(){return sessionStorage.getItem(bx)==="true"}function NL(s){sessionStorage.setItem(bx,"true")}function AL(){sessionStorage.removeItem(bx)}let iM=null;const ML=s=>{iM=s},lj=()=>iM,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 rM(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 TL(){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 EL(){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 Uh=new Map,_L=new Map,vy={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?Uh.has(s)?[[s,Uh.get(s)]]:[]:Array.from(Uh.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(){Uh.clear(),_L.clear()},report(){}};class DL{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 ac=new DL;class RL{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 ec=new RL;function Hu(s,e,t,n,a,i){}function oM(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 lM(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 yx(s){var t,n,a,i,o,l;const e=gx();if(!e){(t=lj())==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=lj())==null||i(),(o=He.onToast)==null||o.call(He,"warning","Reconnecting...","Connection lost. Reconnecting to server..."));return}try{const c=JSON.stringify(s);if(ws.isEnabled()){const m=lM(s);console.log("[AgentDebugger] SENT - type:",s.type,"agentId:",m,"payload:",s.payload),m&&ws.captureSent(m,c)}e.send(c)}catch(c){(l=He.onToast)==null||l.call(He,"error","Send Failed",`Failed to send message: ${c}`)}}const Uu=new Set,PL=5e3;function cj(s){if(!s.isDetached||!s.sessionId){Uu.delete(s.id);return}Uu.has(s.id)||(Uu.add(s.id),yx({type:"reattach_agent",payload:{agentId:s.id}}),setTimeout(()=>{Uu.delete(s.id)},PL))}function LL(s){var e,t,n,a,i,o,l,c,d,m,p,f,b,x,w,k,j,S,C,A,_,T,P;switch(vy.start(`ws:${s.type}`),s.type){case"agents_update":{const M=s.payload,D=M.filter(R=>R.class==="boss"||R.isBoss);D.length>0&&console.log("[WS agents_update] Boss agents received:",D.map(R=>({id:R.id,name:R.name,subordinateIds:R.subordinateIds}))),z.setAgents(M),(e=He.onAgentsSync)==null||e.call(He,M),z.loadToolHistory();for(const R of M)cj(R);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,R=z.getState().agents.get(M.id),L=(R==null?void 0:R.status)!==M.status;console.log(`[Tide] Agent updated: ${M.name} (${M.id}) status=${M.status} (was ${R==null?void 0:R.status})${L?" ⚡ STATUS CHANGED":""}`),L&&console.log(`[Tide] 🔔 Status change for ${M.name}: ${R==null?void 0:R.status} → ${M.status}`);const O=R?R.position.x!==M.position.x||R.position.z!==M.position.z:!1;z.updateAgent(M),cj(M),(i=He.onAgentUpdated)==null||i.call(He,M,O);break}case"agent_deleted":{const{id:M}=s.payload;Uu.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(od.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;od.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:R}=s.payload;z.updateAgentContext(M,D,R);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,R=D.trim();if(R==="/context"||R==="/cost"||R==="/compact")break;z.addUserPromptToOutput(M,D);break}case"session_updated":{const{agentId:M}=s.payload;z.loadToolHistory();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:R,chunk:L,isError:O}=s.payload;z.appendBossStreamingLogChunk(M,D,R,L,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),yx({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:R,taskDescription:L}=s.payload;console.log(`[WebSocket] Agent ${R} started task for boss ${M}: ${L.slice(0,50)}...`),z.handleAgentTaskStarted(M,D,R,L);break}case"agent_task_output":{const{bossId:M,subordinateId:D,output:R}=s.payload;z.handleAgentTaskOutput(M,D,R);break}case"agent_task_completed":{const{bossId:M,subordinateId:D,success:R}=s.payload;console.log(`[WebSocket] Agent task completed for boss ${M}, subordinate ${D}, success: ${R}`),z.handleAgentTaskCompleted(M,D,R);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 R of M)D.set(R.id,R);(j=He.onCustomClassesSync)==null||j.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}`),(S=He.onCustomClassesSync)==null||S.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}`),(A=He.onCustomClassesSync)==null||A.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}`),(_=He.onAgentNotification)==null||_.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 L=[0,80,220,500,1e3];for(const O of L)window.setTimeout(()=>{window.focus()},O);break}case"exec_task_started":{const{taskId:M,agentId:D,agentName:R,command:L,cwd:O}=s.payload;console.log(`[WebSocket] Exec task started: ${M} for agent ${R}: ${L.slice(0,50)}...`),z.handleExecTaskStarted(M,D,R,L,O);break}case"exec_task_output":{const{taskId:M,agentId:D,output:R,isError:L}=s.payload;z.handleExecTaskOutput(M,D,R,L);break}case"exec_task_completed":{const{taskId:M,agentId:D,exitCode:R,success:L}=s.payload;console.log(`[WebSocket] Exec task completed: ${M} for agent ${D}, success: ${L}`),z.handleExecTaskCompleted(M,D,R,L);break}case"subagent_started":{const M=s.payload;console.log(`[WebSocket] Subagent started: ${M.name} (${M.id}) for agent ${M.parentAgentId}`),z.addSubagent(M),(T=He.onSubagentStarted)==null||T.call(He,M);break}case"subagent_output":{const{subagentId:M,parentAgentId:D,text:R,timestamp:L}=s.payload,O=R.indexOf(":");if(O>0){const I=R.slice(0,O).trim(),B=R.slice(O+1).trim();z.addSubagentActivity(M,D,{toolName:I,description:B,timestamp:L})}else R.startsWith("Using ")&&z.addSubagentActivity(M,D,{toolName:R.slice(6).trim(),description:"",timestamp:L});break}case"subagent_completed":{const{subagentId:M,parentAgentId:D,success:R,resultPreview:L,subagentName:O,durationMs:I,tokensUsed:B,toolUseCount:G}=s.payload;console.log(`[WebSocket] Subagent completed: ${M} for agent ${D}, success: ${R}`),(I||B||G)&&z.updateSubagentStats(M,D,{durationMs:I||0,tokensUsed:B||0,toolUseCount:G||0}),z.completeSubagent(M,D,R),(P=He.onSubagentCompleted)==null||P.call(He,M);const $=z.getSubagent(M)||z.getSubagentByToolUseId(M),Y=O||($==null?void 0:$.name)||M,K=R?"✅":"❌",Q=I?` (${(I/1e3).toFixed(0)}s · ${((B||0)/1e3).toFixed(1)}K tokens · ${G||0} tools)`:"";z.addOutput(D,{text:`${K} Subagent ${Y} ${R?"completed":"failed"}${Q}`,isStreaming:!1,timestamp:Date.now(),subagentName:Y,toolOutput:L});break}case"subagent_stream":{const{toolUseId:M,parentAgentId:D,entries:R}=s.payload;z.addSubagentStreamEntries(M,D,R);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:R,error:L,serverVersion:O}=s.payload;z.setConnectionStatus(M,D,{connected:R,error:L,serverVersion:O}),console.log(`[WebSocket] Database connection ${R?"succeeded":"failed"}: ${D}`);break}case"databases_list":{const{buildingId:M,connectionId:D,databases:R}=s.payload;z.setDatabases(M,D,R),console.log(`[WebSocket] Received ${R.length} databases for ${D}`);break}case"tables_list":{const{buildingId:M,connectionId:D,database:R,tables:L}=s.payload;z.setTables(M,D,R,L),console.log(`[WebSocket] Received ${L.length} tables for ${R}`);break}case"table_schema":{const{buildingId:M,connectionId:D,database:R,table:L,columns:O,indexes:I,foreignKeys:B}=s.payload;z.setTableSchema(M,D,R,L,{columns:O,indexes:I||[],foreignKeys:B||[]}),console.log(`[WebSocket] Received schema for ${L}`);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:R,success:L,affectedRows:O,error:I}=s.payload;z.setSilentQueryResult(M,{query:D,requestId:R,success:L,affectedRows:O,error:I}),console.log(`[WebSocket] Silent query ${L?"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}}vy.end(`ws:${s.type}`)}ML(()=>ld());let uj=!1;function cM(){const s=gx();s&&s.readyState===WebSocket.OPEN&&s.close(1e3,"Page unloading");const e=sM();e&&clearTimeout(e),window.__tideWsState&&(window.__tideWsState.ws=null,window.__tideWsState.reconnectTimeout=null,window.__tideWsState.isConnecting=!1,window.__tideWsState.reconnectAttempts=0),AL()}function OL(){uj||(window.addEventListener("beforeunload",cM),uj=!0)}function uM(){cM(),z.setConnected(!1),z.stopStatusPolling()}function Qu(){uM(),xy(0),setTimeout(()=>ld(),100)}function ld(){OL();const s=sM();s&&(clearTimeout(s),aM(null));const e=gx();if(CL()||e&&e.readyState===WebSocket.CONNECTING)return;if(e&&e.readyState===WebSocket.OPEN){oj()&&He.onReconnect&&He.onReconnect();return}xy(yy()+1),Nu(!0);const t=Ms(mt.BACKEND_URL,""),n=oi(),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{Nu(!1),dj();return}ij(o),o.onopen=()=>{var c,d,m;const l=oj();Nu(!1),xy(0),NL(),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"),jL(t,n)},o.onmessage=l=>{try{const c=JSON.parse(l.data);if(ws.isEnabled()){const m=lM(c);console.log("[AgentDebugger] RECEIVED - type:",c.type,"agentId:",m,"payload:",c.payload),m&&ws.captureReceived(m,l.data)}LL(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;Nu(!1),ij(null),z.setConnected(!1),z.stopStatusPolling();const l=yy();l<rj?((c=He.onToast)==null||c.call(He,"warning","Disconnected",`Connection lost. Reconnecting... (attempt ${l+1}/${rj})`),dj()):(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=()=>{Nu(!1)},z.setSendMessage(yx)}function dj(){const s=yy(),e=Math.min(1e3*Math.pow(2,s-1),3e4);aM(setTimeout(ld,e))}function hj(s,e){if(e===UD)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),s;if(e===Jb||e===vA){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===Jb)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 xx extends wA{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new $L(t)}),this.register(function(t){return new HL(t)}),this.register(function(t){return new ZL(t)}),this.register(function(t){return new QL(t)}),this.register(function(t){return new JL(t)}),this.register(function(t){return new GL(t)}),this.register(function(t){return new WL(t)}),this.register(function(t){return new qL(t)}),this.register(function(t){return new YL(t)}),this.register(function(t){return new FL(t)}),this.register(function(t){return new VL(t)}),this.register(function(t){return new UL(t)}),this.register(function(t){return new XL(t)}),this.register(function(t){return new KL(t)}),this.register(function(t){return new BL(t)}),this.register(function(t){return new eO(t)}),this.register(function(t){return new tO(t)})}load(e,t,n,a){const i=this;let o;if(this.resourcePath!=="")o=this.resourcePath;else if(this.path!==""){const d=Yu.extractUrlBase(e);o=Yu.resolveURL(d,this.path)}else o=Yu.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 jp(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))===dM){try{o[Vt.KHR_BINARY_GLTF]=new nO(e)}catch(p){a&&a(p);return}i=JSON.parse(o[Vt.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 fO(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 Vt.KHR_MATERIALS_UNLIT:o[p]=new zL;break;case Vt.KHR_DRACO_MESH_COMPRESSION:o[p]=new sO(i,this.dracoLoader);break;case Vt.KHR_TEXTURE_TRANSFORM:o[p]=new aO;break;case Vt.KHR_MESH_QUANTIZATION:o[p]=new iO;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 IL(){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 Vt={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 BL{constructor(e){this.parser=e,this.name=Vt.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 It(16777215);c.color!==void 0&&m.setRGB(c.color[0],c.color[1],c.color[2],Di);const p=c.range!==void 0?c.range:0;switch(c.type){case"directional":d=new lc(m),d.target.position.set(0,0,-1),d.add(d.target);break;case"point":d=new kA(m),d.distance=p;break;case"spot":d=new GD(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,rr(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=Vt.KHR_MATERIALS_UNLIT}getMaterialType(){return Ye}extendParams(e,t,n){const a=[];e.color=new It(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],Di),e.opacity=o[3]}i.baseColorTexture!==void 0&&a.push(n.assignTexture(e,"map",i.baseColorTexture,ei))}return Promise.all(a)}}class FL{constructor(e){this.parser=e,this.name=Vt.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 $L{constructor(e){this.parser=e,this.name=Vt.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Pi}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 Rs(l,l)}return Promise.all(i)}}class HL{constructor(e){this.parser=e,this.name=Vt.KHR_MATERIALS_DISPERSION}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Pi}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 UL{constructor(e){this.parser=e,this.name=Vt.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Pi}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 GL{constructor(e){this.parser=e,this.name=Vt.KHR_MATERIALS_SHEEN}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Pi}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 It(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],Di)}return o.sheenRoughnessFactor!==void 0&&(t.sheenRoughness=o.sheenRoughnessFactor),o.sheenColorTexture!==void 0&&i.push(n.assignTexture(t,"sheenColorMap",o.sheenColorTexture,ei)),o.sheenRoughnessTexture!==void 0&&i.push(n.assignTexture(t,"sheenRoughnessMap",o.sheenRoughnessTexture)),Promise.all(i)}}class WL{constructor(e){this.parser=e,this.name=Vt.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Pi}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 qL{constructor(e){this.parser=e,this.name=Vt.KHR_MATERIALS_VOLUME}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Pi}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 It().setRGB(l[0],l[1],l[2],Di),Promise.all(i)}}class YL{constructor(e){this.parser=e,this.name=Vt.KHR_MATERIALS_IOR}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Pi}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 VL{constructor(e){this.parser=e,this.name=Vt.KHR_MATERIALS_SPECULAR}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Pi}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 It().setRGB(l[0],l[1],l[2],Di),o.specularColorTexture!==void 0&&i.push(n.assignTexture(t,"specularColorMap",o.specularColorTexture,ei)),Promise.all(i)}}class KL{constructor(e){this.parser=e,this.name=Vt.EXT_MATERIALS_BUMP}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Pi}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 XL{constructor(e){this.parser=e,this.name=Vt.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Pi}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 ZL{constructor(e){this.parser=e,this.name=Vt.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 QL{constructor(e){this.parser=e,this.name=Vt.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 JL{constructor(e){this.parser=e,this.name=Vt.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 eO{constructor(e){this.name=Vt.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 tO{constructor(e){this.name=Vt.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!==Oa.TRIANGLES&&d.mode!==Oa.TRIANGLE_STRIP&&d.mode!==Oa.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 Jo,k=new xt,j=new el,S=new xt(1,1,1),C=new or(x.geometry,x.material,f);for(let A=0;A<f;A++)c.TRANSLATION&&k.fromBufferAttribute(c.TRANSLATION,A),c.ROTATION&&j.fromBufferAttribute(c.ROTATION,A),c.SCALE&&S.fromBufferAttribute(c.SCALE,A),C.setMatrixAt(A,w.compose(k,j,S));for(const A in c)if(A==="_COLOR_0"){const _=c[A];C.instanceColor=new WD(_.array,_.itemSize,_.normalized)}else A!=="TRANSLATION"&&A!=="ROTATION"&&A!=="SCALE"&&x.geometry.setAttribute(A,c[A]);SA.prototype.copy.call(C,x),this.parser.assignFinalMaterial(C),b.push(C)}return m.isGroup?(m.clear(),m.add(...b),m):b[0]}))}}const dM="glTF",Au=12,pj={JSON:1313821514,BIN:5130562};class nO{constructor(e){this.name=Vt.KHR_BINARY_GLTF,this.content=null,this.body=null;const t=new DataView(e,0,Au),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!==dM)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-Au,i=new DataView(e,Au);let o=0;for(;o<a;){const l=i.getUint32(o,!0);o+=4;const c=i.getUint32(o,!0);if(o+=4,c===pj.JSON){const d=new Uint8Array(e,Au+o,l);this.content=n.decode(d)}else if(c===pj.BIN){const d=Au+o;this.body=e.slice(d,d+l)}o+=l}if(this.content===null)throw new Error("THREE.GLTFLoader: JSON content not found.")}}class sO{constructor(e,t){if(!t)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=Vt.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=wy[m]||m.toLowerCase();l[p]=o[m]}for(const m in e.attributes){const p=wy[m]||m.toLowerCase();if(o[m]!==void 0){const f=n.accessors[e.attributes[m]],b=uc[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,Di,f)})})}}class aO{constructor(){this.name=Vt.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 iO{constructor(){this.name=Vt.KHR_MESH_QUANTIZATION}}class hM extends rR{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,j=b-f,S=1-k,C=j-f+p;for(let A=0;A!==l;A++){const _=o[w+A+l],T=o[w+A+c]*m,P=o[x+A+l],M=o[x+A]*m;i[A]=S*_+C*T+k*P+j*M}return i}}const rO=new el;class oO extends hM{interpolate_(e,t,n,a){const i=super.interpolate_(e,t,n,a);return rO.fromArray(i).normalize().toArray(i),i}}const Oa={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6},uc={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},mj={9728:jA,9729:En,9984:XD,9985:KD,9986:VD,9987:Vu},fj={33071:QD,33648:ZD,10497:$o},Qg={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},wy={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"},Ur={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},lO={CUBICSPLINE:void 0,LINEAR:AA,STEP:aR},Jg={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function cO(s){return s.DefaultMaterial===void 0&&(s.DefaultMaterial=new ut({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:MA})),s.DefaultMaterial}function Po(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 rr(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 uO(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 dO(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 hO(s){let e;const t=s.extensions&&s.extensions[Vt.KHR_DRACO_MESH_COMPRESSION];if(t?e="draco:"+t.bufferView+":"+t.indices+":"+eb(t.attributes):e=s.indices+":"+eb(s.attributes)+":"+s.mode,s.targets!==void 0)for(let n=0,a=s.targets.length;n<a;n++)e+=":"+eb(s.targets[n]);return e}function eb(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 ky(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 pO(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 mO=new Jo;class fO{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new IL,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 lx(this.options.manager):this.textureLoader=new qD(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new jp(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 Po(i,l,a),rr(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[Vt.KHR_BINARY_GLTF].body);const a=this.options;return new Promise(function(i,o){n.load(Yu.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=Qg[a.type],l=uc[a.componentType],c=a.normalized===!0,d=new l(a.count*o);return Promise.resolve(new ti(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=Qg[a.type],d=uc[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 j=Math.floor(f/b),S="InterleavedBuffer:"+a.bufferView+":"+a.componentType+":"+j+":"+a.count;let C=t.cache.get(S);C||(w=new d(l,j*b,a.count*b/m),C=new YD(w,b/m),t.cache.add(S,C)),k=new iR(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 ti(w,c,x);if(a.sparse!==void 0){const j=Qg.SCALAR,S=uc[a.sparse.indices.componentType],C=a.sparse.indices.byteOffset||0,A=a.sparse.values.byteOffset||0,_=new S(o[1],C,a.sparse.count*j),T=new d(o[2],A,a.sparse.count*c);l!==null&&(k=new ti(k.array.slice(),k.itemSize,k.normalized)),k.normalized=!1;for(let P=0,M=_.length;P<M;P++){const D=_[P];if(k.setX(D,T[P*c]),c>=2&&k.setY(D,T[P*c+1]),c>=3&&k.setZ(D,T[P*c+2]),c>=4&&k.setW(D,T[P*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=mj[f.magFilter]||En,m.minFilter=mj[f.minFilter]||Vu,m.wrapS=fj[f.wrapS]||$o,m.wrapT=fj[f.wrapT]||$o,m.generateMipmaps=!m.isCompressedTexture&&m.minFilter!==jA&&m.minFilter!==En,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 uS(w);k.needsUpdate=!0,f(k)}),t.load(Yu.resolveURL(p,i.path),x,void 0,b)})}).then(function(p){return d===!0&&l.revokeObjectURL(c),rr(p,o),p.userData.mimeType=o.mimeType||pO(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[Vt.KHR_TEXTURE_TRANSFORM]){const l=n.extensions!==void 0?n.extensions[Vt.KHR_TEXTURE_TRANSFORM]:void 0;if(l){const c=i.associations.get(o);o=i.extensions[Vt.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 um,Zr.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 Ho,Zr.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 ut}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[Vt.KHR_MATERIALS_UNLIT]){const p=a[Vt.KHR_MATERIALS_UNLIT];o=p.getMaterialType(),d.push(p.extendParams(l,i,t))}else{const p=i.pbrMetallicRoughness||{};if(l.color=new It(1,1,1),l.opacity=1,Array.isArray(p.baseColorFactor)){const f=p.baseColorFactor;l.color.setRGB(f[0],f[1],f[2],Di),l.opacity=f[3]}p.baseColorTexture!==void 0&&d.push(t.assignTexture(l,"map",p.baseColorTexture,ei)),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=ks);const m=i.alphaMode||Jg.OPAQUE;if(m===Jg.BLEND?(l.transparent=!0,l.depthWrite=!1):(l.transparent=!1,m===Jg.MASK&&(l.alphaTest=i.alphaCutoff!==void 0?i.alphaCutoff:.5)),i.normalTexture!==void 0&&o!==Ye&&(d.push(t.assignTexture(l,"normalMap",i.normalTexture)),l.normalScale=new Rs(1,1),i.normalTexture.scale!==void 0)){const p=i.normalTexture.scale;l.normalScale.set(p,p)}if(i.occlusionTexture!==void 0&&o!==Ye&&(d.push(t.assignTexture(l,"aoMap",i.occlusionTexture)),i.occlusionTexture.strength!==void 0&&(l.aoMapIntensity=i.occlusionTexture.strength)),i.emissiveFactor!==void 0&&o!==Ye){const p=i.emissiveFactor;l.emissive=new It().setRGB(p[0],p[1],p[2],Di)}return i.emissiveTexture!==void 0&&o!==Ye&&d.push(t.assignTexture(l,"emissiveMap",i.emissiveTexture,ei)),Promise.all(d).then(function(){const p=new o(l);return i.name&&(p.name=i.name),rr(p,i),t.associations.set(p,{materials:e}),i.extensions&&Po(a,p,i),p})}createUniqueName(e){const t=JD.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[Vt.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(l,t).then(function(c){return gj(c,l,t)})}const o=[];for(let l=0,c=e.length;l<c;l++){const d=e[l],m=hO(d),p=a[m];if(p)o.push(p.promise);else{let f;d.extensions&&d.extensions[Vt.KHR_DRACO_MESH_COMPRESSION]?f=i(d):f=gj(new Fa,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?cO(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 j;const S=d[b];if(k.mode===Oa.TRIANGLES||k.mode===Oa.TRIANGLE_STRIP||k.mode===Oa.TRIANGLE_FAN||k.mode===void 0)j=i.isSkinnedMesh===!0?new ey(w,S):new Re(w,S),j.isSkinnedMesh===!0&&j.normalizeSkinWeights(),k.mode===Oa.TRIANGLE_STRIP?j.geometry=hj(j.geometry,vA):k.mode===Oa.TRIANGLE_FAN&&(j.geometry=hj(j.geometry,Jb));else if(k.mode===Oa.LINES)j=new cx(w,S);else if(k.mode===Oa.LINE_STRIP)j=new Yr(w,S);else if(k.mode===Oa.LINE_LOOP)j=new eR(w,S);else if(k.mode===Oa.POINTS)j=new yd(w,S);else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+k.mode);Object.keys(j.geometry.morphAttributes).length>0&&dO(j,i),j.name=t.createUniqueName(i.name||"mesh_"+e),rr(j,i),k.extensions&&Po(a,j,k),t.assignFinalMaterial(j),p.push(j)}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&&Po(a,p[0],i),p[0];const f=new _n;i.extensions&&Po(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 ux(CA.radToDeg(a.yfov),a.aspectRatio||1,a.znear||1,a.zfar||2e6):n.type==="orthographic"&&(t=new NA(-a.xmag,a.xmag,a.ymag,-a.ymag,a.znear,a.zfar)),n.name&&(t.name=this.createUniqueName(n.name)),rr(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 Jo;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 tR(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,j=a.parameters!==void 0?a.parameters[x.input]:x.input,S=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",j)),c.push(this.getDependency("accessor",S)),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],j=[];for(let S=0,C=f.length;S<C;S++){const A=f[S],_=b[S],T=x[S],P=w[S],M=k[S];if(A===void 0)continue;A.updateMatrix&&A.updateMatrix();const D=n._createAnimationTracks(A,_,T,P,M);if(D)for(let R=0;R<D.length;R++)j.push(D[R])}return new nR(i,void 0,j)})}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,mO)});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 sR:d.length>1?m=new _n:d.length===1?m=d[0]:m=new SA,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),rr(m,i),i.extensions&&Po(n,m,i),i.matrix!==void 0){const p=new Jo;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 _n;n.name&&(i.name=a.createUniqueName(n.name)),rr(i,n),n.extensions&&Po(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 Zr||f instanceof uS)&&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=[];Ur[i.path]===Ur.weights?e.traverse(function(f){f.morphTargetInfluences&&c.push(f.name?f.name:f.uuid)}):c.push(l);let d;switch(Ur[i.path]){case Ur.weights:d=hS;break;case Ur.rotation:d=pS;break;case Ur.position:case Ur.scale:d=dS;break;default:switch(n.itemSize){case 1:d=hS;break;case 2:case 3:default:d=dS;break}break}const m=a.interpolation!==void 0?lO[a.interpolation]:AA,p=this._getArrayFromAccessor(n);for(let f=0,b=c.length;f<b;f++){const x=new d(c[f]+"."+Ur[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=ky(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 pS?oO:hM;return new a(this.times,this.values,this.getValueSize()/3,n)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function gO(s,e,t){const n=e.attributes,a=new Cp;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 xt(c[0],c[1],c[2]),new xt(d[0],d[1],d[2])),l.normalized){const m=ky(uc[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 xt,c=new xt;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=ky(uc[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 oR;a.getCenter(o.center),o.radius=a.min.distanceTo(a.max)/2,s.boundingSphere=o}function gj(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=wy[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 ty.workingColorSpace!==Di&&"COLOR_0"in n&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${ty.workingColorSpace}" not supported.`),rr(s,e),gO(s,e,t),Promise.all(a).then(function(){return e.targets!==void 0?uO(s,e.targets,t):s})}const tb=new WeakMap;class vx extends wA{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 jp(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,ei,n).catch(n)}decodeDracoFile(e,t,n,a,i=Di,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(tb.has(e)){const c=tb.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)}),tb.set(e,{key:n,promise:l}),l}_createGeometry(e){const t=new Fa;e.index&&t.setIndex(new ti(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 ti(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!==ei)return;const n=new It;for(let a=0,i=e.count;a<i;a++)n.fromBufferAttribute(e,a),ty.toWorkingColorSpace(n,ei),e.setXYZ(a,n.r,n.g,n.b)}_loadLibrary(e,t){const n=new jp(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=bO.toString(),o=["/* draco decoder */",a,"","/* worker */",i.substring(i.indexOf("{")+1,i.lastIndexOf("}"))].join(`
|
|
42
|
+
*/var zS;function hP(){if(zS)return Vg;zS=1;var s=ox();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 Vg.useSyncExternalStore=s.useSyncExternalStore!==void 0?s.useSyncExternalStore:m,Vg}var FS;function pP(){return FS||(FS=1,Yg.exports=hP()),Yg.exports}var mP=pP();const fP=(s,e)=>sl(e)?e:eP(e)&&sl(e.defaultValue)?e.defaultValue:Array.isArray(s)?s[s.length-1]:s,gP={t:fP,ready:!1},bP=()=>()=>{},Ue=(s,e={})=>{var D,R,L;const{i18n:t}=e,{i18n:n,defaultNS:a}=y.useContext(uP)||{},i=t||n||lP();i&&!i.reportNamespaces&&(i.reportNamespaces=new dP),i||zA(i,"NO_I18NEXT_INSTANCE","useTranslation: You will need to pass in an i18next instance by using initReactI18next");const o=y.useMemo(()=>{var O;return{...rP(),...(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=sl(d)?[d]:d||["translation"],p=y.useMemo(()=>m,m);(L=(R=i==null?void 0:i.reportNamespaces)==null?void 0:R.addUsedNamespaces)==null||L.call(R,p);const f=y.useRef(0),b=y.useCallback(O=>{if(!i)return bP;const{bindI18n:I,bindI18nStore:B}=o,G=()=>{f.current+=1,O()};return I&&i.on(I,G),B&&i.store.on(B,G),()=>{I&&I.split(" ").forEach($=>i.off($,G)),B&&B.split(" ").forEach($=>i.store.off($,G))}},[i,o]),x=y.useRef(),w=y.useCallback(()=>{if(!i)return gP;const O=!!(i.isInitialized||i.initializedStoreOnce)&&p.every(K=>JR(K,i,o)),I=e.lng||i.language,B=f.current,G=x.current;if(G&&G.ready===O&&G.lng===I&&G.keyPrefix===c&&G.revision===B)return G;const Y={t:i.getFixedT(I,o.nsMode==="fallback"?p:p[0],c),ready:O,lng:I,keyPrefix:c,revision:B};return x.current=Y,Y},[i,p,c,o,e.lng]),[k,j]=y.useState(0),{t:S,ready:C}=mP.useSyncExternalStore(b,w,w);y.useEffect(()=>{if(i&&!C&&!l){const O=()=>j(I=>I+1);e.lng?BS(i,e.lng,p,O):oy(i,p,O)}},[i,e.lng,p,C,l,k]);const A=i||{},_=y.useRef(null),T=y.useRef(),P=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=A,I=O==null?void 0:O.language;let B=O;O&&(_.current&&_.current.__original===O?T.current!==I?(B=P(O),_.current=B,T.current=I):B=_.current:(B=P(O),_.current=B,T.current=I));const G=[S,B,C];return G.t=S,G.i18n=B,G.ready=C,G},[S,A,C,A.resolvedLanguage,A.language,A.languages]);if(i&&l&&!C)throw new Promise(O=>{const I=()=>O();e.lng?BS(i,e.lng,p,I):oy(i,p,I)});return M};function cy(s){"@babel/helpers - typeof";return cy=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},cy(s)}function HA(){return typeof XMLHttpRequest=="function"||(typeof XMLHttpRequest>"u"?"undefined":cy(XMLHttpRequest))==="object"}function yP(s){return!!s&&typeof s.then=="function"}function xP(s){return yP(s)?s:Promise.resolve(s)}const vP="modulepreload",wP=function(s){return"/"+s},$S={},UA=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=wP(d),d in $S)return;$S[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":vP,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 HS(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 US(s){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?HS(Object(t),!0).forEach(function(n){kP(s,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(t)):HS(Object(t)).forEach(function(n){Object.defineProperty(s,n,Object.getOwnPropertyDescriptor(t,n))})}return s}function kP(s,e,t){return(e=SP(e))in s?Object.defineProperty(s,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):s[e]=t,s}function SP(s){var e=jP(s,"string");return al(e)=="symbol"?e:e+""}function jP(s,e){if(al(s)!="object"||!s)return s;var t=s[Symbol.toPrimitive];if(t!==void 0){var n=t.call(s,e);if(al(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(s)}function al(s){"@babel/helpers - typeof";return al=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},al(s)}var so=typeof fetch=="function"?fetch:void 0;typeof global<"u"&&global.fetch?so=global.fetch:typeof window<"u"&&window.fetch&&(so=window.fetch);var rd;HA()&&(typeof global<"u"&&global.XMLHttpRequest?rd=global.XMLHttpRequest:typeof window<"u"&&window.XMLHttpRequest&&(rd=window.XMLHttpRequest));var Ep;typeof ActiveXObject=="function"&&(typeof global<"u"&&global.ActiveXObject?Ep=global.ActiveXObject:typeof window<"u"&&window.ActiveXObject&&(Ep=window.ActiveXObject));typeof so!="function"&&(so=void 0);if(!so&&!rd&&!Ep)try{UA(()=>import("./browser-ponyfill-DIm4hKhx.js").then(s=>s.b),__vite__mapDeps([0,1])).then(function(s){so=s.default}).catch(function(){})}catch{}var uy=function(e,t){if(t&&al(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},GS=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):so(e,t).then(i).catch(n)},WS=!1,CP=function(e,t,n,a){e.queryStringParams&&(t=uy(t,e.queryStringParams));var i=US({},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=US({method:n?"POST":"GET",body:n?e.stringify(n):void 0,headers:i},WS?{}:o),c=typeof e.alternateFetch=="function"&&e.alternateFetch.length>=1?e.alternateFetch:void 0;try{GS(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]}),GS(t,l,a,c),WS=!0}catch(m){a(m)}}},NP=function(e,t,n,a){n&&al(n)==="object"&&(n=uy("",n).slice(1)),e.queryStringParams&&(t=uy(t,e.queryStringParams));try{var i=rd?new rd:new Ep("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)}},AP=function(e,t,n,a){if(typeof n=="function"&&(a=n,n=void 0),a=a||function(){},so&&t.indexOf("file:")!==0)return CP(e,t,n,a);if(HA()||typeof ActiveXObject=="function")return NP(e,t,n,a);a(new Error("No fetch and no xhr implementation found!"))};function gc(s){"@babel/helpers - typeof";return gc=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},gc(s)}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 Kg(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){GA(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 MP(s,e){if(!(s instanceof e))throw new TypeError("Cannot call a class as a function")}function TP(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,WA(n.key),n)}}function EP(s,e,t){return e&&TP(s.prototype,e),Object.defineProperty(s,"prototype",{writable:!1}),s}function GA(s,e,t){return(e=WA(e))in s?Object.defineProperty(s,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):s[e]=t,s}function WA(s){var e=_P(s,"string");return gc(e)=="symbol"?e:e+""}function _P(s,e){if(gc(s)!="object"||!s)return s;var t=s[Symbol.toPrimitive];if(t!==void 0){var n=t.call(s,e);if(gc(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(s)}var DP=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 GA({},n,a||"")},parseLoadPayload:function(t,n){},request:AP,reloadInterval:typeof window<"u"?!1:3600*1e3,customHeaders:{},queryStringParams:{},crossDomain:!1,withCredentials:!1,overrideMimeType:!1,requestOptions:{mode:"cors",credentials:"same-origin",cache:"default"}}},qA=(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]:{};MP(this,s),this.services=e,this.options=t,this.allOptions=n,this.type="backend",this.init(e,t,n)}return EP(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=Kg(Kg(Kg({},DP()),this.options||{}),a),this.allOptions=i,this.services&&this.options.reloadInterval){var o=setInterval(function(){return n.reload()},this.options.reloadInterval);gc(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=xP(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)})})})}}}])})();qA.type="backend";const{slice:RP,forEach:PP}=[];function LP(s){return PP.call(RP.call(arguments,1),e=>{if(e)for(const t in e)s[t]===void 0&&(s[t]=e[t])}),s}function OP(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 YS=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/,IP=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(!YS.test(n.domain))throw new TypeError("option domain is invalid");i+=`; Domain=${n.domain}`}if(n.path){if(!YS.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},VS={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=IP(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 BP={name:"cookie",lookup(s){let{lookupCookie:e}=s;if(e&&typeof document<"u")return VS.read(e)||void 0},cacheUserLanguage(s,e){let{lookupCookie:t,cookieMinutes:n,cookieDomain:a,cookieOptions:i}=e;t&&typeof document<"u"&&VS.create(t,s,n,a,i)}},zP={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}},FP={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 Wl=null;const KS=()=>{if(Wl!==null)return Wl;try{if(Wl=typeof window<"u"&&window.localStorage!==null,!Wl)return!1;const s="i18next.translate.boo";window.localStorage.setItem(s,"foo"),window.localStorage.removeItem(s)}catch{Wl=!1}return Wl};var $P={name:"localStorage",lookup(s){let{lookupLocalStorage:e}=s;if(e&&KS())return window.localStorage.getItem(e)||void 0},cacheUserLanguage(s,e){let{lookupLocalStorage:t}=e;t&&KS()&&window.localStorage.setItem(t,s)}};let ql=null;const XS=()=>{if(ql!==null)return ql;try{if(ql=typeof window<"u"&&window.sessionStorage!==null,!ql)return!1;const s="i18next.translate.boo";window.sessionStorage.setItem(s,"foo"),window.sessionStorage.removeItem(s)}catch{ql=!1}return ql};var HP={name:"sessionStorage",lookup(s){let{lookupSessionStorage:e}=s;if(e&&XS())return window.sessionStorage.getItem(e)||void 0},cacheUserLanguage(s,e){let{lookupSessionStorage:t}=e;t&&XS()&&window.sessionStorage.setItem(t,s)}},UP={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}},GP={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}},WP={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}},qP={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 YA=!1;try{document.cookie,YA=!0}catch{}const VA=["querystring","cookie","localStorage","sessionStorage","navigator","htmlTag"];YA||VA.splice(1,1);const YP=()=>({order:VA,lookupQuerystring:"lng",lookupCookie:"i18next",lookupLocalStorage:"i18nextLng",lookupSessionStorage:"i18nextLng",caches:["localStorage"],excludeCacheFor:["cimode"],convertDetectedLanguage:s=>s});class KA{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=LP(t,this.options||{},YP()),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(BP),this.addDetector(zP),this.addDetector($P),this.addDetector(HP),this.addDetector(UP),this.addDetector(GP),this.addDetector(WP),this.addDetector(qP),this.addDetector(FP)}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&&!OP(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)}))}}KA.type="languageDetector";const _p={idle:"#4aff9e",working:"#4a9eff",waiting:"#ff9e4a",waiting_permission:"#ffcc00",error:"#ff4a4a",offline:"#888888",orphaned:"#ff9e4a",default:"#888888"},ao={running:"#4aff9e",stopped:"#888888",error:"#ff4a4a",unknown:"#ffaa00",starting:"#4a9eff",stopping:"#ffaa00"},XA={on_track:"#4aff9e",stalled:"#ff9e4a",blocked:"#ff4a4a",completed:"#4a9eff",idle:"#888888"},VP=["#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"],Hh={recent:"#50fa7b",short:"#f1fa8c",medium:"#ffb86c",long:"#ff5555"};function hm(s){const t=Math.floor((Date.now()-s)/1e3)/60;return t<1?Hh.recent:t<5?Hh.short:t<30?Hh.medium:Hh.long}function px(s){return _p[s]??_p.default}let mp=null;function ZA(){if(!mp)try{mp=globalThis.__i18n}catch{}return mp}function KP(s){mp=s}function XP(s){return s>=1e6?(s/1e6).toFixed(1)+"M":s>=1e3?(s/1e3).toFixed(1)+"K":s.toString()}function dy(s){return s>=1e6?(s/1e6).toFixed(1)+"M":s>=1e3?(s/1e3).toFixed(1)+"K":s.toString()}function QA(s){var a;const e=ZA(),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 pm(s){var d;const e=ZA(),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 Qr(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:""}pn.use(qA).use(KA).use(cP).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(()=>{KP(pn)});const mt={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"};function Ja(s,e){try{const t=localStorage.getItem(s);return t===null?e:JSON.parse(t)}catch{return e}}function Ms(s,e=""){try{return localStorage.getItem(s)??e}catch{return e}}function hy(s,e=!1){try{const t=localStorage.getItem(s);return t===null?e:t==="true"}catch{return e}}function JA(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 Ci(s,e){try{localStorage.setItem(s,JSON.stringify(e))}catch(t){console.error(`Failed to save to localStorage: ${s}`,t)}}function ra(s,e){try{localStorage.setItem(s,e)}catch(t){console.error(`Failed to save to localStorage: ${s}`,t)}}function py(s,e){try{localStorage.setItem(s,String(e))}catch(t){console.error(`Failed to save to localStorage: ${s}`,t)}}function eM(s,e){try{localStorage.setItem(s,String(e))}catch(t){console.error(`Failed to save to localStorage: ${s}`,t)}}function ZS(s){try{localStorage.removeItem(s)}catch(e){console.error(`Failed to remove from localStorage: ${s}`,e)}}function tM(){const s=Ms(mt.BACKEND_URL,"");return s?s.replace(/\/$/,""):`${window.location.protocol}//${window.location.host}`}function oi(){return Ms(mt.AUTH_TOKEN,"")}function at(s){return`${tM()}${s}`}async function ft(s,e){const t=oi(),n=new Headers(e==null?void 0:e.headers);return t&&n.set("X-Auth-Token",t),fetch(s,{...e,headers:n})}function xd(s){const e=oi();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 $s(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 ZP(){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 QP(){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 Qa=[],JP=new Set;function Dp(){JP.forEach(s=>s())}function eL(s,e){const t=Qa.findIndex(n=>n.id===s);return t!==-1&&Qa.splice(t,1),Qa.push({id:s,close:e}),Dp(),()=>{const n=Qa.findIndex(a=>a.id===s);n!==-1&&(Qa.splice(n,1),Dp())}}function my(){return Qa.length===0?!1:(Qa.pop().close(),Dp(),!0)}function tL(...s){const e=new Set(s);for(;Qa.length>0;){const t=Qa[Qa.length-1];if(e.has(t.id))break;Qa.pop().close()}Dp()}function Sn(s,e,t){const n=y.useRef(t);n.current=t,y.useEffect(()=>e?eL(s,()=>n.current()):void 0,[s,e])}let fy,gy;try{fy=require("@capacitor/haptics").Haptics,gy=require("@capacitor/haptics").ImpactStyle}catch{}function QS(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 S=window.innerWidth*.4,C=Math.max(-1,Math.min(1,w/S));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],j=k.clientX-d.current.startX,S=Math.abs(k.clientY-d.current.startY),C=Date.now()-d.current.startTime;d.current.isTracking=!1,d.current.hasMovedEnough=!1,Math.abs(j)>=t&&S<=n&&C<500?(fy&&gy?fy.impact({style:gy.Light}).catch(()=>{navigator.vibrate&&navigator.vibrate(8)}):navigator.vibrate&&navigator.vibrate(8),j>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 nL={width:400,height:300,copyStyleSheets:!0,keepOnTop:"focus"};function sL(){return"documentPictureInPicture"in window}function aL(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 iL(){const[s,e]=y.useState(!1),[t,n]=y.useState(null),[a,i]=y.useState(null),o=y.useRef(null),l=sL(),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={...nL,...p};try{const x=await window.documentPictureInPicture.requestWindow({width:f.width,height:f.height,disallowReturnToOpener:!0});o.current=x,f.copyStyleSheets&&aL(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 j=f.keepOnTop==="raise",S=()=>{o.current&&!o.current.closed&&setTimeout(()=>{o.current&&!o.current.closed&&(o.current.focus(),j&&setTimeout(()=>window.focus(),10))},50)},C=()=>{document.visibilityState==="visible"&&o.current&&!o.current.closed&&setTimeout(()=>{o.current&&!o.current.closed&&(o.current.focus(),j&&setTimeout(()=>window.focus(),10))},100)};window.addEventListener("focus",S),document.addEventListener("visibilitychange",C),k.push(()=>window.removeEventListener("focus",S),()=>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 Cu(){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 rL{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:Cu(),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:Cu(),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:Cu(),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:Cu(),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:Cu(),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 ws=new rL,od={debug:(s,e,t)=>ws.debug(s,e,t),info:(s,e,t)=>ws.info(s,e,t),warn:(s,e,t)=>ws.warn(s,e,t),error:(s,e,t)=>ws.error(s,e,t)};/*! Capacitor: https://capacitorjs.com/ - MIT License */var bc;(function(s){s.Unimplemented="UNIMPLEMENTED",s.Unavailable="UNAVAILABLE"})(bc||(bc={}));class Xg extends Error{constructor(e,t,n){super(e),this.message=e,this.code=t,this.data=n}}const oL=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"},lL=s=>{const e=s.CapacitorCustomPlatform||null,t=s.Capacitor||{},n=t.Plugins=t.Plugins||{},a=()=>e!==null?e.name:oL(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 j=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),S=(M,D)=>{var R,L;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(R=M[D])===null||R===void 0?void 0:R.bind(M)}else{if(M)return(L=M[D])===null||L===void 0?void 0:L.bind(M);throw new Xg(`"${p}" plugin is not implemented on ${x}`,bc.Unimplemented)}},C=M=>{let D;const R=(...L)=>{const O=j().then(I=>{const B=S(I,M);if(B){const G=B(...L);return D=G==null?void 0:G.remove,G}else throw new Xg(`"${p}.${M}()" is not implemented on ${x}`,bc.Unimplemented)});return M==="addListener"&&(O.remove=async()=>D()),O};return R.toString=()=>`${M.toString()}() { [capacitor code] }`,Object.defineProperty(R,"name",{value:M,writable:!1,configurable:!1}),R},A=C("addListener"),_=C("removeListener"),T=(M,D)=>{const R=A({eventName:M},D),L=async()=>{const I=await R;_({eventName:M,callbackId:I},D)},O=new Promise(I=>R.then(()=>I({remove:L})));return O.remove=async()=>{console.warn("Using addListener() without 'await' is deprecated."),await L()},O},P=new Proxy({},{get(M,D){switch(D){case"$$typeof":return;case"toJSON":return()=>({});case"addListener":return w?T:A;case"removeListener":return _;default:return C(D)}}});return n[p]=P,d.set(p,{name:p,proxy:P,platforms:new Set([...Object.keys(f),...w?[x]:[]])}),P};return t.convertFileSrc||(t.convertFileSrc=p=>p),t.getPlatform=a,t.handleError=c,t.isNativePlatform=i,t.isPluginAvailable=o,t.registerPlugin=m,t.Exception=Xg,t.DEBUG=!!t.DEBUG,t.isLoggingEnabled=!!t.isLoggingEnabled,t},cL=s=>s.Capacitor=lL(s),ka=cL(typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}),vd=ka.registerPlugin;class mx{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 ka.Exception(e,bc.Unimplemented)}unavailable(e="not available"){return new ka.Exception(e,bc.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 JS=s=>encodeURIComponent(s).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape),ej=s=>s.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent);class uL extends mx{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=ej(a).trim(),i=ej(i).trim(),t[a]=i}),t}async setCookie(e){try{const t=JS(e.key),n=JS(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)}}}vd("CapacitorCookies",{web:()=>new uL});const dL=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)}),hL=(s={})=>{const e=Object.keys(s);return Object.keys(s).map(a=>a.toLocaleLowerCase()).reduce((a,i,o)=>(a[i]=s[e[o]],a),{})},pL=(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,mL=(s,e={})=>{const t=Object.assign({method:s.method||"GET",headers:s.headers},e),a=hL(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 fL extends mx{async request(e){const t=mL(e,e.webFetchExtra),n=pL(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 dL(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 tj=vd("CapacitorHttp",{web:()=>new fL});var nj;(function(s){s.Dark="DARK",s.Light="LIGHT",s.Default="DEFAULT"})(nj||(nj={}));var sj;(function(s){s.StatusBar="StatusBar",s.NavigationBar="NavigationBar"})(sj||(sj={}));class gL extends mx{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")}}vd("SystemBars",{web:()=>new gL});var aj;(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"})(aj||(aj={}));const fx=vd("LocalNotifications",{web:()=>UA(()=>import("./web-Cjmp1lCs.js"),__vite__mapDeps([2,3,1,4])).then(s=>new s.LocalNotificationsWeb)}),bL=vd("ServerConfig");let yL=100;const xL="agent_alerts",by="tide-notification-tap";function vL(){return typeof window<"u"&&window.innerWidth<=768&&"ontouchstart"in window}function nM(s){if(vL()){z.openTerminalOnMobile(s);return}if(document.querySelector(".commander-overlay")){z.requestCommanderExpand(s);return}z.selectAgent(s),z.setTerminalOpen(!0)}function wd(){try{return ka.isNativePlatform()}catch{return!1}}async function wL(){if(wd())try{const s=await fx.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 kL(s){const{title:e,body:t,icon:n,data:a}=s;if(wd())try{const i=yL++;console.log("[Notifications] Scheduling native notification id="+i,e),await fx.schedule({notifications:[{id:i,title:e,body:t,extra:a,channelId:xL,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(by,{detail:a}))}}}let Zg=!1;async function SL(s){const e=[];if(Zg)return()=>{};if(Zg=!0,s){const t=n=>{const a=n;a.detail&&s(a.detail)};window.addEventListener(by,t),e.push(()=>window.removeEventListener(by,t))}if(wd())try{const t=await fx.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()),Zg=!1}}function jL(s,e){wd()&&bL.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 gx=()=>window.__tideWsState.ws,ij=s=>{window.__tideWsState.ws=s},CL=()=>window.__tideWsState.isConnecting,Nu=s=>{window.__tideWsState.isConnecting=s},yy=()=>window.__tideWsState.reconnectAttempts,xy=s=>{window.__tideWsState.reconnectAttempts=s},sM=()=>window.__tideWsState.reconnectTimeout,aM=s=>{window.__tideWsState.reconnectTimeout=s},rj=10,bx="tide_ws_has_connected";function oj(){return sessionStorage.getItem(bx)==="true"}function NL(s){sessionStorage.setItem(bx,"true")}function AL(){sessionStorage.removeItem(bx)}let iM=null;const ML=s=>{iM=s},lj=()=>iM,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 rM(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 TL(){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 EL(){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 Uh=new Map,_L=new Map,vy={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?Uh.has(s)?[[s,Uh.get(s)]]:[]:Array.from(Uh.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(){Uh.clear(),_L.clear()},report(){}};class DL{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 ac=new DL;class RL{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 ec=new RL;function Hu(s,e,t,n,a,i){}function oM(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 lM(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 yx(s){var t,n,a,i,o,l;const e=gx();if(!e){(t=lj())==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=lj())==null||i(),(o=He.onToast)==null||o.call(He,"warning","Reconnecting...","Connection lost. Reconnecting to server..."));return}try{const c=JSON.stringify(s);if(ws.isEnabled()){const m=lM(s);console.log("[AgentDebugger] SENT - type:",s.type,"agentId:",m,"payload:",s.payload),m&&ws.captureSent(m,c)}e.send(c)}catch(c){(l=He.onToast)==null||l.call(He,"error","Send Failed",`Failed to send message: ${c}`)}}const Uu=new Set,PL=5e3;function cj(s){if(!s.isDetached||!s.sessionId){Uu.delete(s.id);return}Uu.has(s.id)||(Uu.add(s.id),yx({type:"reattach_agent",payload:{agentId:s.id}}),setTimeout(()=>{Uu.delete(s.id)},PL))}function LL(s){var e,t,n,a,i,o,l,c,d,m,p,f,b,x,w,k,j,S,C,A,_,T,P;switch(vy.start(`ws:${s.type}`),s.type){case"agents_update":{const M=s.payload,D=M.filter(R=>R.class==="boss"||R.isBoss);D.length>0&&console.log("[WS agents_update] Boss agents received:",D.map(R=>({id:R.id,name:R.name,subordinateIds:R.subordinateIds}))),z.setAgents(M),(e=He.onAgentsSync)==null||e.call(He,M),z.loadToolHistory();for(const R of M)cj(R);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,R=z.getState().agents.get(M.id),L=(R==null?void 0:R.status)!==M.status;console.log(`[Tide] Agent updated: ${M.name} (${M.id}) status=${M.status} (was ${R==null?void 0:R.status})${L?" ⚡ STATUS CHANGED":""}`),L&&console.log(`[Tide] 🔔 Status change for ${M.name}: ${R==null?void 0:R.status} → ${M.status}`);const O=R?R.position.x!==M.position.x||R.position.z!==M.position.z:!1;z.updateAgent(M),cj(M),(i=He.onAgentUpdated)==null||i.call(He,M,O);break}case"agent_deleted":{const{id:M}=s.payload;Uu.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(od.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;od.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:R}=s.payload;z.updateAgentContext(M,D,R);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,R=D.trim();if(R==="/context"||R==="/cost"||R==="/compact")break;z.addUserPromptToOutput(M,D);break}case"session_updated":{const{agentId:M}=s.payload;z.loadToolHistory();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:R,chunk:L,isError:O}=s.payload;z.appendBossStreamingLogChunk(M,D,R,L,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),yx({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:R,taskDescription:L}=s.payload;console.log(`[WebSocket] Agent ${R} started task for boss ${M}: ${L.slice(0,50)}...`),z.handleAgentTaskStarted(M,D,R,L);break}case"agent_task_output":{const{bossId:M,subordinateId:D,output:R}=s.payload;z.handleAgentTaskOutput(M,D,R);break}case"agent_task_completed":{const{bossId:M,subordinateId:D,success:R}=s.payload;console.log(`[WebSocket] Agent task completed for boss ${M}, subordinate ${D}, success: ${R}`),z.handleAgentTaskCompleted(M,D,R);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 R of M)D.set(R.id,R);(j=He.onCustomClassesSync)==null||j.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}`),(S=He.onCustomClassesSync)==null||S.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}`),(A=He.onCustomClassesSync)==null||A.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}`),(_=He.onAgentNotification)==null||_.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 L=[0,80,220,500,1e3];for(const O of L)window.setTimeout(()=>{window.focus()},O);break}case"exec_task_started":{const{taskId:M,agentId:D,agentName:R,command:L,cwd:O}=s.payload;console.log(`[WebSocket] Exec task started: ${M} for agent ${R}: ${L.slice(0,50)}...`),z.handleExecTaskStarted(M,D,R,L,O);break}case"exec_task_output":{const{taskId:M,agentId:D,output:R,isError:L}=s.payload;z.handleExecTaskOutput(M,D,R,L);break}case"exec_task_completed":{const{taskId:M,agentId:D,exitCode:R,success:L}=s.payload;console.log(`[WebSocket] Exec task completed: ${M} for agent ${D}, success: ${L}`),z.handleExecTaskCompleted(M,D,R,L);break}case"subagent_started":{const M=s.payload;console.log(`[WebSocket] Subagent started: ${M.name} (${M.id}) for agent ${M.parentAgentId}`),z.addSubagent(M),(T=He.onSubagentStarted)==null||T.call(He,M);break}case"subagent_output":{const{subagentId:M,parentAgentId:D,text:R,timestamp:L}=s.payload,O=R.indexOf(":");if(O>0){const I=R.slice(0,O).trim(),B=R.slice(O+1).trim();z.addSubagentActivity(M,D,{toolName:I,description:B,timestamp:L})}else R.startsWith("Using ")&&z.addSubagentActivity(M,D,{toolName:R.slice(6).trim(),description:"",timestamp:L});break}case"subagent_completed":{const{subagentId:M,parentAgentId:D,success:R,resultPreview:L,subagentName:O,durationMs:I,tokensUsed:B,toolUseCount:G}=s.payload;console.log(`[WebSocket] Subagent completed: ${M} for agent ${D}, success: ${R}`),(I||B||G)&&z.updateSubagentStats(M,D,{durationMs:I||0,tokensUsed:B||0,toolUseCount:G||0}),z.completeSubagent(M,D,R),(P=He.onSubagentCompleted)==null||P.call(He,M);const $=z.getSubagent(M)||z.getSubagentByToolUseId(M),Y=O||($==null?void 0:$.name)||M,K=R?"✅":"❌",Q=I?` (${(I/1e3).toFixed(0)}s · ${((B||0)/1e3).toFixed(1)}K tokens · ${G||0} tools)`:"";z.addOutput(D,{text:`${K} Subagent ${Y} ${R?"completed":"failed"}${Q}`,isStreaming:!1,timestamp:Date.now(),subagentName:Y,toolOutput:L});break}case"subagent_stream":{const{toolUseId:M,parentAgentId:D,entries:R}=s.payload;z.addSubagentStreamEntries(M,D,R);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:R,error:L,serverVersion:O}=s.payload;z.setConnectionStatus(M,D,{connected:R,error:L,serverVersion:O}),console.log(`[WebSocket] Database connection ${R?"succeeded":"failed"}: ${D}`);break}case"databases_list":{const{buildingId:M,connectionId:D,databases:R}=s.payload;z.setDatabases(M,D,R),console.log(`[WebSocket] Received ${R.length} databases for ${D}`);break}case"tables_list":{const{buildingId:M,connectionId:D,database:R,tables:L}=s.payload;z.setTables(M,D,R,L),console.log(`[WebSocket] Received ${L.length} tables for ${R}`);break}case"table_schema":{const{buildingId:M,connectionId:D,database:R,table:L,columns:O,indexes:I,foreignKeys:B}=s.payload;z.setTableSchema(M,D,R,L,{columns:O,indexes:I||[],foreignKeys:B||[]}),console.log(`[WebSocket] Received schema for ${L}`);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:R,success:L,affectedRows:O,error:I}=s.payload;z.setSilentQueryResult(M,{query:D,requestId:R,success:L,affectedRows:O,error:I}),console.log(`[WebSocket] Silent query ${L?"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}}vy.end(`ws:${s.type}`)}ML(()=>ld());let uj=!1;function cM(){const s=gx();s&&s.readyState===WebSocket.OPEN&&s.close(1e3,"Page unloading");const e=sM();e&&clearTimeout(e),window.__tideWsState&&(window.__tideWsState.ws=null,window.__tideWsState.reconnectTimeout=null,window.__tideWsState.isConnecting=!1,window.__tideWsState.reconnectAttempts=0),AL()}function OL(){uj||(window.addEventListener("beforeunload",cM),uj=!0)}function uM(){cM(),z.setConnected(!1),z.stopStatusPolling()}function Qu(){uM(),xy(0),setTimeout(()=>ld(),100)}function ld(){OL();const s=sM();s&&(clearTimeout(s),aM(null));const e=gx();if(CL()||e&&e.readyState===WebSocket.CONNECTING)return;if(e&&e.readyState===WebSocket.OPEN){oj()&&He.onReconnect&&He.onReconnect();return}xy(yy()+1),Nu(!0);const t=Ms(mt.BACKEND_URL,""),n=oi(),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{Nu(!1),dj();return}ij(o),o.onopen=()=>{var c,d,m;const l=oj();Nu(!1),xy(0),NL(),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"),jL(t,n)},o.onmessage=l=>{try{const c=JSON.parse(l.data);if(ws.isEnabled()){const m=lM(c);console.log("[AgentDebugger] RECEIVED - type:",c.type,"agentId:",m,"payload:",c.payload),m&&ws.captureReceived(m,l.data)}LL(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;Nu(!1),ij(null),z.setConnected(!1),z.stopStatusPolling();const l=yy();l<rj?((c=He.onToast)==null||c.call(He,"warning","Disconnected",`Connection lost. Reconnecting... (attempt ${l+1}/${rj})`),dj()):(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=()=>{Nu(!1)},z.setSendMessage(yx)}function dj(){const s=yy(),e=Math.min(1e3*Math.pow(2,s-1),3e4);aM(setTimeout(ld,e))}function hj(s,e){if(e===UD)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),s;if(e===Jb||e===vA){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===Jb)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 xx extends wA{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new $L(t)}),this.register(function(t){return new HL(t)}),this.register(function(t){return new ZL(t)}),this.register(function(t){return new QL(t)}),this.register(function(t){return new JL(t)}),this.register(function(t){return new GL(t)}),this.register(function(t){return new WL(t)}),this.register(function(t){return new qL(t)}),this.register(function(t){return new YL(t)}),this.register(function(t){return new FL(t)}),this.register(function(t){return new VL(t)}),this.register(function(t){return new UL(t)}),this.register(function(t){return new XL(t)}),this.register(function(t){return new KL(t)}),this.register(function(t){return new BL(t)}),this.register(function(t){return new eO(t)}),this.register(function(t){return new tO(t)})}load(e,t,n,a){const i=this;let o;if(this.resourcePath!=="")o=this.resourcePath;else if(this.path!==""){const d=Yu.extractUrlBase(e);o=Yu.resolveURL(d,this.path)}else o=Yu.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 jp(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))===dM){try{o[Vt.KHR_BINARY_GLTF]=new nO(e)}catch(p){a&&a(p);return}i=JSON.parse(o[Vt.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 fO(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 Vt.KHR_MATERIALS_UNLIT:o[p]=new zL;break;case Vt.KHR_DRACO_MESH_COMPRESSION:o[p]=new sO(i,this.dracoLoader);break;case Vt.KHR_TEXTURE_TRANSFORM:o[p]=new aO;break;case Vt.KHR_MESH_QUANTIZATION:o[p]=new iO;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 IL(){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 Vt={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 BL{constructor(e){this.parser=e,this.name=Vt.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 It(16777215);c.color!==void 0&&m.setRGB(c.color[0],c.color[1],c.color[2],Di);const p=c.range!==void 0?c.range:0;switch(c.type){case"directional":d=new lc(m),d.target.position.set(0,0,-1),d.add(d.target);break;case"point":d=new kA(m),d.distance=p;break;case"spot":d=new GD(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,rr(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=Vt.KHR_MATERIALS_UNLIT}getMaterialType(){return Ye}extendParams(e,t,n){const a=[];e.color=new It(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],Di),e.opacity=o[3]}i.baseColorTexture!==void 0&&a.push(n.assignTexture(e,"map",i.baseColorTexture,ei))}return Promise.all(a)}}class FL{constructor(e){this.parser=e,this.name=Vt.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 $L{constructor(e){this.parser=e,this.name=Vt.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Pi}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 Rs(l,l)}return Promise.all(i)}}class HL{constructor(e){this.parser=e,this.name=Vt.KHR_MATERIALS_DISPERSION}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Pi}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 UL{constructor(e){this.parser=e,this.name=Vt.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Pi}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 GL{constructor(e){this.parser=e,this.name=Vt.KHR_MATERIALS_SHEEN}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Pi}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 It(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],Di)}return o.sheenRoughnessFactor!==void 0&&(t.sheenRoughness=o.sheenRoughnessFactor),o.sheenColorTexture!==void 0&&i.push(n.assignTexture(t,"sheenColorMap",o.sheenColorTexture,ei)),o.sheenRoughnessTexture!==void 0&&i.push(n.assignTexture(t,"sheenRoughnessMap",o.sheenRoughnessTexture)),Promise.all(i)}}class WL{constructor(e){this.parser=e,this.name=Vt.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Pi}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 qL{constructor(e){this.parser=e,this.name=Vt.KHR_MATERIALS_VOLUME}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Pi}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 It().setRGB(l[0],l[1],l[2],Di),Promise.all(i)}}class YL{constructor(e){this.parser=e,this.name=Vt.KHR_MATERIALS_IOR}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Pi}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 VL{constructor(e){this.parser=e,this.name=Vt.KHR_MATERIALS_SPECULAR}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Pi}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 It().setRGB(l[0],l[1],l[2],Di),o.specularColorTexture!==void 0&&i.push(n.assignTexture(t,"specularColorMap",o.specularColorTexture,ei)),Promise.all(i)}}class KL{constructor(e){this.parser=e,this.name=Vt.EXT_MATERIALS_BUMP}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Pi}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 XL{constructor(e){this.parser=e,this.name=Vt.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Pi}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 ZL{constructor(e){this.parser=e,this.name=Vt.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 QL{constructor(e){this.parser=e,this.name=Vt.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 JL{constructor(e){this.parser=e,this.name=Vt.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 eO{constructor(e){this.name=Vt.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 tO{constructor(e){this.name=Vt.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!==Oa.TRIANGLES&&d.mode!==Oa.TRIANGLE_STRIP&&d.mode!==Oa.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 Jo,k=new xt,j=new el,S=new xt(1,1,1),C=new or(x.geometry,x.material,f);for(let A=0;A<f;A++)c.TRANSLATION&&k.fromBufferAttribute(c.TRANSLATION,A),c.ROTATION&&j.fromBufferAttribute(c.ROTATION,A),c.SCALE&&S.fromBufferAttribute(c.SCALE,A),C.setMatrixAt(A,w.compose(k,j,S));for(const A in c)if(A==="_COLOR_0"){const _=c[A];C.instanceColor=new WD(_.array,_.itemSize,_.normalized)}else A!=="TRANSLATION"&&A!=="ROTATION"&&A!=="SCALE"&&x.geometry.setAttribute(A,c[A]);SA.prototype.copy.call(C,x),this.parser.assignFinalMaterial(C),b.push(C)}return m.isGroup?(m.clear(),m.add(...b),m):b[0]}))}}const dM="glTF",Au=12,pj={JSON:1313821514,BIN:5130562};class nO{constructor(e){this.name=Vt.KHR_BINARY_GLTF,this.content=null,this.body=null;const t=new DataView(e,0,Au),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!==dM)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-Au,i=new DataView(e,Au);let o=0;for(;o<a;){const l=i.getUint32(o,!0);o+=4;const c=i.getUint32(o,!0);if(o+=4,c===pj.JSON){const d=new Uint8Array(e,Au+o,l);this.content=n.decode(d)}else if(c===pj.BIN){const d=Au+o;this.body=e.slice(d,d+l)}o+=l}if(this.content===null)throw new Error("THREE.GLTFLoader: JSON content not found.")}}class sO{constructor(e,t){if(!t)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=Vt.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=wy[m]||m.toLowerCase();l[p]=o[m]}for(const m in e.attributes){const p=wy[m]||m.toLowerCase();if(o[m]!==void 0){const f=n.accessors[e.attributes[m]],b=uc[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,Di,f)})})}}class aO{constructor(){this.name=Vt.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 iO{constructor(){this.name=Vt.KHR_MESH_QUANTIZATION}}class hM extends rR{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,j=b-f,S=1-k,C=j-f+p;for(let A=0;A!==l;A++){const _=o[w+A+l],T=o[w+A+c]*m,P=o[x+A+l],M=o[x+A]*m;i[A]=S*_+C*T+k*P+j*M}return i}}const rO=new el;class oO extends hM{interpolate_(e,t,n,a){const i=super.interpolate_(e,t,n,a);return rO.fromArray(i).normalize().toArray(i),i}}const Oa={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6},uc={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},mj={9728:jA,9729:En,9984:XD,9985:KD,9986:VD,9987:Vu},fj={33071:QD,33648:ZD,10497:$o},Qg={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},wy={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"},Ur={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},lO={CUBICSPLINE:void 0,LINEAR:AA,STEP:aR},Jg={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function cO(s){return s.DefaultMaterial===void 0&&(s.DefaultMaterial=new ut({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:MA})),s.DefaultMaterial}function Po(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 rr(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 uO(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 dO(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 hO(s){let e;const t=s.extensions&&s.extensions[Vt.KHR_DRACO_MESH_COMPRESSION];if(t?e="draco:"+t.bufferView+":"+t.indices+":"+eb(t.attributes):e=s.indices+":"+eb(s.attributes)+":"+s.mode,s.targets!==void 0)for(let n=0,a=s.targets.length;n<a;n++)e+=":"+eb(s.targets[n]);return e}function eb(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 ky(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 pO(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 mO=new Jo;class fO{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new IL,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 lx(this.options.manager):this.textureLoader=new qD(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new jp(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 Po(i,l,a),rr(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[Vt.KHR_BINARY_GLTF].body);const a=this.options;return new Promise(function(i,o){n.load(Yu.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=Qg[a.type],l=uc[a.componentType],c=a.normalized===!0,d=new l(a.count*o);return Promise.resolve(new ti(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=Qg[a.type],d=uc[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 j=Math.floor(f/b),S="InterleavedBuffer:"+a.bufferView+":"+a.componentType+":"+j+":"+a.count;let C=t.cache.get(S);C||(w=new d(l,j*b,a.count*b/m),C=new YD(w,b/m),t.cache.add(S,C)),k=new iR(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 ti(w,c,x);if(a.sparse!==void 0){const j=Qg.SCALAR,S=uc[a.sparse.indices.componentType],C=a.sparse.indices.byteOffset||0,A=a.sparse.values.byteOffset||0,_=new S(o[1],C,a.sparse.count*j),T=new d(o[2],A,a.sparse.count*c);l!==null&&(k=new ti(k.array.slice(),k.itemSize,k.normalized)),k.normalized=!1;for(let P=0,M=_.length;P<M;P++){const D=_[P];if(k.setX(D,T[P*c]),c>=2&&k.setY(D,T[P*c+1]),c>=3&&k.setZ(D,T[P*c+2]),c>=4&&k.setW(D,T[P*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=mj[f.magFilter]||En,m.minFilter=mj[f.minFilter]||Vu,m.wrapS=fj[f.wrapS]||$o,m.wrapT=fj[f.wrapT]||$o,m.generateMipmaps=!m.isCompressedTexture&&m.minFilter!==jA&&m.minFilter!==En,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 uS(w);k.needsUpdate=!0,f(k)}),t.load(Yu.resolveURL(p,i.path),x,void 0,b)})}).then(function(p){return d===!0&&l.revokeObjectURL(c),rr(p,o),p.userData.mimeType=o.mimeType||pO(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[Vt.KHR_TEXTURE_TRANSFORM]){const l=n.extensions!==void 0?n.extensions[Vt.KHR_TEXTURE_TRANSFORM]:void 0;if(l){const c=i.associations.get(o);o=i.extensions[Vt.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 um,Zr.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 Ho,Zr.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 ut}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[Vt.KHR_MATERIALS_UNLIT]){const p=a[Vt.KHR_MATERIALS_UNLIT];o=p.getMaterialType(),d.push(p.extendParams(l,i,t))}else{const p=i.pbrMetallicRoughness||{};if(l.color=new It(1,1,1),l.opacity=1,Array.isArray(p.baseColorFactor)){const f=p.baseColorFactor;l.color.setRGB(f[0],f[1],f[2],Di),l.opacity=f[3]}p.baseColorTexture!==void 0&&d.push(t.assignTexture(l,"map",p.baseColorTexture,ei)),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=ks);const m=i.alphaMode||Jg.OPAQUE;if(m===Jg.BLEND?(l.transparent=!0,l.depthWrite=!1):(l.transparent=!1,m===Jg.MASK&&(l.alphaTest=i.alphaCutoff!==void 0?i.alphaCutoff:.5)),i.normalTexture!==void 0&&o!==Ye&&(d.push(t.assignTexture(l,"normalMap",i.normalTexture)),l.normalScale=new Rs(1,1),i.normalTexture.scale!==void 0)){const p=i.normalTexture.scale;l.normalScale.set(p,p)}if(i.occlusionTexture!==void 0&&o!==Ye&&(d.push(t.assignTexture(l,"aoMap",i.occlusionTexture)),i.occlusionTexture.strength!==void 0&&(l.aoMapIntensity=i.occlusionTexture.strength)),i.emissiveFactor!==void 0&&o!==Ye){const p=i.emissiveFactor;l.emissive=new It().setRGB(p[0],p[1],p[2],Di)}return i.emissiveTexture!==void 0&&o!==Ye&&d.push(t.assignTexture(l,"emissiveMap",i.emissiveTexture,ei)),Promise.all(d).then(function(){const p=new o(l);return i.name&&(p.name=i.name),rr(p,i),t.associations.set(p,{materials:e}),i.extensions&&Po(a,p,i),p})}createUniqueName(e){const t=JD.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[Vt.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(l,t).then(function(c){return gj(c,l,t)})}const o=[];for(let l=0,c=e.length;l<c;l++){const d=e[l],m=hO(d),p=a[m];if(p)o.push(p.promise);else{let f;d.extensions&&d.extensions[Vt.KHR_DRACO_MESH_COMPRESSION]?f=i(d):f=gj(new Fa,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?cO(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 j;const S=d[b];if(k.mode===Oa.TRIANGLES||k.mode===Oa.TRIANGLE_STRIP||k.mode===Oa.TRIANGLE_FAN||k.mode===void 0)j=i.isSkinnedMesh===!0?new ey(w,S):new Re(w,S),j.isSkinnedMesh===!0&&j.normalizeSkinWeights(),k.mode===Oa.TRIANGLE_STRIP?j.geometry=hj(j.geometry,vA):k.mode===Oa.TRIANGLE_FAN&&(j.geometry=hj(j.geometry,Jb));else if(k.mode===Oa.LINES)j=new cx(w,S);else if(k.mode===Oa.LINE_STRIP)j=new Yr(w,S);else if(k.mode===Oa.LINE_LOOP)j=new eR(w,S);else if(k.mode===Oa.POINTS)j=new yd(w,S);else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+k.mode);Object.keys(j.geometry.morphAttributes).length>0&&dO(j,i),j.name=t.createUniqueName(i.name||"mesh_"+e),rr(j,i),k.extensions&&Po(a,j,k),t.assignFinalMaterial(j),p.push(j)}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&&Po(a,p[0],i),p[0];const f=new _n;i.extensions&&Po(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 ux(CA.radToDeg(a.yfov),a.aspectRatio||1,a.znear||1,a.zfar||2e6):n.type==="orthographic"&&(t=new NA(-a.xmag,a.xmag,a.ymag,-a.ymag,a.znear,a.zfar)),n.name&&(t.name=this.createUniqueName(n.name)),rr(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 Jo;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 tR(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,j=a.parameters!==void 0?a.parameters[x.input]:x.input,S=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",j)),c.push(this.getDependency("accessor",S)),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],j=[];for(let S=0,C=f.length;S<C;S++){const A=f[S],_=b[S],T=x[S],P=w[S],M=k[S];if(A===void 0)continue;A.updateMatrix&&A.updateMatrix();const D=n._createAnimationTracks(A,_,T,P,M);if(D)for(let R=0;R<D.length;R++)j.push(D[R])}return new nR(i,void 0,j)})}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,mO)});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 sR:d.length>1?m=new _n:d.length===1?m=d[0]:m=new SA,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),rr(m,i),i.extensions&&Po(n,m,i),i.matrix!==void 0){const p=new Jo;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 _n;n.name&&(i.name=a.createUniqueName(n.name)),rr(i,n),n.extensions&&Po(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 Zr||f instanceof uS)&&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=[];Ur[i.path]===Ur.weights?e.traverse(function(f){f.morphTargetInfluences&&c.push(f.name?f.name:f.uuid)}):c.push(l);let d;switch(Ur[i.path]){case Ur.weights:d=hS;break;case Ur.rotation:d=pS;break;case Ur.position:case Ur.scale:d=dS;break;default:switch(n.itemSize){case 1:d=hS;break;case 2:case 3:default:d=dS;break}break}const m=a.interpolation!==void 0?lO[a.interpolation]:AA,p=this._getArrayFromAccessor(n);for(let f=0,b=c.length;f<b;f++){const x=new d(c[f]+"."+Ur[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=ky(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 pS?oO:hM;return new a(this.times,this.values,this.getValueSize()/3,n)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function gO(s,e,t){const n=e.attributes,a=new Cp;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 xt(c[0],c[1],c[2]),new xt(d[0],d[1],d[2])),l.normalized){const m=ky(uc[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 xt,c=new xt;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=ky(uc[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 oR;a.getCenter(o.center),o.radius=a.min.distanceTo(a.max)/2,s.boundingSphere=o}function gj(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=wy[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 ty.workingColorSpace!==Di&&"COLOR_0"in n&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${ty.workingColorSpace}" not supported.`),rr(s,e),gO(s,e,t),Promise.all(a).then(function(){return e.targets!==void 0?uO(s,e.targets,t):s})}const tb=new WeakMap;class vx extends wA{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 jp(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,ei,n).catch(n)}decodeDracoFile(e,t,n,a,i=Di,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(tb.has(e)){const c=tb.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)}),tb.set(e,{key:n,promise:l}),l}_createGeometry(e){const t=new Fa;e.index&&t.setIndex(new ti(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 ti(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!==ei)return;const n=new It;for(let a=0,i=e.count;a<i;a++)n.fromBufferAttribute(e,a),ty.toWorkingColorSpace(n,ei),e.setXYZ(a,n.r,n.g,n.b)}_loadLibrary(e,t){const n=new jp(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=bO.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 bO(){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 j=self[p[k]];let S,C;if(d.useUniqueIDs)C=m[k],S=l.GetAttributeByUniqueId(f,C);else{if(C=l.GetAttributeId(f,o[m[k]]),C===-1)continue;S=l.GetAttribute(f,C)}const A=a(o,l,f,k,j,S);k==="color"&&(A.vertexColorSpace=d.vertexColorSpace),w.attributes.push(A)}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),j=o._malloc(w);l.GetAttributeDataArrayForAllPoints(c,p,k,w,j);const S=new m(o.HEAPF32.buffer,j,x).slice();return o._free(j),{name:d,array:S,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 wx=(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(j){i=j.instance,i.exports.__wasm_call_ctors()});function l(j){for(var S=new Uint8Array(j.length),C=0;C<j.length;++C){var A=j.charCodeAt(C);S[C]=A>96?A-97:A>64?A-39:A+4}for(var _=0,C=0;C<j.length;++C)S[_++]=S[C]<60?n[S[C]]:(S[C]-60)*64+S[++C];return S.buffer.slice(0,_)}function c(j,S,C,A,_,T){var P=i.exports.sbrk,M=C+3&-4,D=P(M*A),R=P(_.length),L=new Uint8Array(i.exports.memory.buffer);L.set(_,R);var O=j(D,C,A,R,_.length);if(O==0&&T&&T(D,M,A),S.set(L.subarray(D,D+C*A)),P(D-P(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(j){var S={object:new Worker(j),pending:0,requests:{}};return S.object.onmessage=function(C){var A=C.data;S.pending-=A.count,S.requests[A.id][A.action](A.value),delete S.requests[A.id]},S}function x(j){for(var S="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([S],{type:"text/javascript"}),A=URL.createObjectURL(C),_=0;_<j;++_)p[_]=b(A);URL.revokeObjectURL(A)}function w(j,S,C,A,_){for(var T=p[0],P=1;P<p.length;++P)p[P].pending<T.pending&&(T=p[P]);return new Promise(function(M,D){var R=new Uint8Array(C),L=f++;T.pending+=j,T.requests[L]={resolve:M,reject:D},T.object.postMessage({id:L,count:j,size:S,source:R,mode:A,filter:_},[R.buffer])})}function k(j){o.then(function(){var S=j.data;try{var C=new Uint8Array(S.count*S.size);c(i.exports[S.mode],C,S.count,S.size,S.source,i.exports[S.filter]),self.postMessage({id:S.id,count:S.count,action:"resolve",value:C},[C.buffer])}catch(A){self.postMessage({id:S.id,count:S.count,action:"reject",value:A})}})}return{ready:o,supported:!0,useWorkers:function(j){x(j)},decodeVertexBuffer:function(j,S,C,A,_){c(i.exports.meshopt_decodeVertexBuffer,j,S,C,A,i.exports[d[_]])},decodeIndexBuffer:function(j,S,C,A){c(i.exports.meshopt_decodeIndexBuffer,j,S,C,A)},decodeIndexSequence:function(j,S,C,A){c(i.exports.meshopt_decodeIndexSequence,j,S,C,A)},decodeGltfBuffer:function(j,S,C,A,_,T){c(i.exports[m[_]],j,S,C,A,i.exports[d[T]])},decodeGltfBufferAsync:function(j,S,C,A,_){return p.length>0?w(j,S,C,m[A],d[_]):o.then(function(){var T=new Uint8Array(j*S);return c(i.exports[m[A]],T,j,S,C,i.exports[d[_]]),T})}}})();function bj(s){const e=new Map,t=new Map,n=s.clone();return pM(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 pM(s,e,t){t(s,e);for(let n=0;n<s.children.length;n++)pM(s.children[n],e.children[n],t)}const Ua={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"}},kx=["Alex","Sam","Jordan","Taylor","Casey","Morgan","Riley","Quinn","Avery","Blake","Cameron","Drew","Emery","Finley","Harper","Jamie","Kai","Logan","Max","Nico","Parker","Reese","Sage","Sky"],Yo=kx,ic={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"},Vo=[{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"}],bi=[{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"}],yO=3,rc=5,xO=1e3,wi=1.2;class vO{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 xx,this.dracoLoader=new vx,this.dracoLoader.setDecoderPath("https://www.gstatic.com/draco/versioned/decoders/1.5.7/"),this.loader.setDRACOLoader(this.dracoLoader),this.loader.setMeshoptDecoder(wx)}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(ic),...bi.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 Re&&(t.castShadow=!0,t.receiveShadow=!0,t.material)){const n=t.material;n.map&&(n.map.colorSpace=ei),n.isMeshStandardMaterial&&(n.roughness=n.roughness??.6,n.metalness=n.metalness??0,n.envMapIntensity=.8,n.needsUpdate=!0)}}),e}clone(e){const t=ic[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=bj(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 Re&&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=ic[e],n=this.models.get(t);return(n==null?void 0:n.animations)??null}hasModel(e){const t=ic[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(xd(at(`/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=bj(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 Re&&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 Re&&((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 ut||e instanceof Ye||e instanceof lR)&&((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 wO="character-male-a.glb";class kO{constructor(e){U(this,"customClasses",new Map);this.characterLoader=e}setCustomClasses(e){this.customClasses=e}getClassConfig(e){const t=Ua[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=ic[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:wO,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 Ku(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 ny(.5,1,4,16),o=new ut({color:t,roughness:.4,metalness:.3}),l=new Re(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 Re)||!(n.geometry instanceof ny))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 Ku(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 Re||p instanceof ey)&&((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 Ku(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 Re?((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 Bn?this.disposeMaterial(t.material):t instanceof ey&&((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 ut||e instanceof Ye||e instanceof Gn)&&((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 SO{createAnimationSetup(e,t,n){n!=null&&n.animationMapping&&(e.userData.animationMapping=n.animationMapping);const a=new Ku(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 yj={idle:4915102,working:4890367,waiting:16752202,waiting_permission:16763904,error:16730698,orphaned:16711935,default:8947848};function mM(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 jO{constructor(e){U(this,"idleTimerCanvas",null);U(this,"idleTimerCtx",null);U(this,"manaBarCanvas",null);U(this,"manaBarCtx",null);this.animConfig=e}getStatusColor(e){return yj[e]??yj.default}createSelectionRing(e,t=!1){const n=t?1.5:1,a=new tl(.8*n,.95*n,32),i=new Ye({color:e,side:ks,transparent:!0,opacity:0,depthTest:!1}),o=new Re(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 Kn(o);c.minFilter=Vu,c.magFilter=En,c.generateMipmaps=!0,c.anisotropy=16,c.needsUpdate=!0;const d=new Gn({map:c,transparent:!0,depthTest:!1}),m=new Bn(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.userData.modelHeight=i,m.userData.baseIndicatorScale=f,m.userData.aspectRatio=b,m}createNameLabelSprite(e,t,n,a){const i=document.createElement("canvas"),o=i.getContext("2d");i.width=4096,i.height=1024,this.drawNameLabel(o,i.width,i.height,e,t,a);const l=new Kn(i);l.minFilter=Vu,l.magFilter=En,l.generateMipmaps=!0,l.anisotropy=16,l.needsUpdate=!0;const c=new Gn({map:l,transparent:!0,depthTest:!1}),d=new Bn(c);d.position.y=n?-.74:-.56;const m=n?1.5:1.25,p=i.height/i.width;return d.scale.set(m,m*p,1),d.name="nameLabelSprite",d.userData.baseIndicatorScale=m,d.userData.aspectRatio=p,d}drawNameLabel(e,t,n,a,i,o){e.clearRect(0,0,t,n);const l=`#${i.toString(16).padStart(6,"0")}`;let c=800;const d=300,m=o==="claude"||o==="codex",p=m?c*.42:0,f=m?c*.3:0,b=t-400-(m?p+f:0);e.font=`bold ${c}px Arial`;let x=e.measureText(a).width;for(;x>b&&c>d;)c-=40,e.font=`bold ${c}px Arial`,x=e.measureText(a).width;const w=m?c*.42:0,k=m?c*.3:0,j=w+k,S=x+j,C=t/2+j/2;if(e.textAlign="center",e.textBaseline="middle",e.shadowColor="rgba(0, 0, 0, 0.9)",e.shadowBlur=c*.12,e.shadowOffsetX=c*.04,e.shadowOffsetY=c*.04,e.strokeStyle="#000",e.lineWidth=c*.14,e.lineJoin="round",e.strokeText(a,C,n/2),e.shadowColor="transparent",e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0,m){const A=t/2-S/2+w/2,_=n/2,T=o==="codex"?"#4a9eff":"#ff9e4a";e.beginPath(),e.arc(A,_,w/2,0,Math.PI*2),e.fillStyle=T,e.fill(),e.strokeStyle="rgba(255, 255, 255, 0.9)",e.lineWidth=Math.max(4,w*.1),e.stroke()}e.fillStyle=l,e.fillText(a,C,n/2)}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 j;switch(i){case"working":j="#4a9eff";break;case"orphaned":j="#c060e0";break;case"error":j="#e05050";break;case"waiting":case"waiting_permission":j="#e0a030";break;default:j="#40c090"}e.beginPath(),e.arc(w,k,x/2,0,Math.PI*2),e.fillStyle=j,e.shadowColor=j,e.shadowBlur=20*c,e.fill(),e.shadowBlur=0,e.strokeStyle="rgba(0, 0, 0, 0.4)",e.lineWidth=4*c,e.stroke();const S=f+x+60*c,C=p-x-90*c,A=m-80*c,_=b+40*c,T=30*c;e.fillStyle="#0d0d14",e.beginPath(),e.roundRect(S,_,C,A,T),e.fill(),e.strokeStyle="rgba(80, 90, 110, 0.5)",e.lineWidth=4*c,e.stroke();const P=Math.max(0,Math.min(100,a))/100,M=8*c,D=Math.max(0,(C-M*2)*P);if(D>0){let I;P>.5?I="#00c896":P>.2?I="#e8a020":I="#e84040",e.fillStyle=I,e.beginPath(),e.roundRect(S+M,_+M,D,A-M*2,T-M),e.fill(),e.shadowColor=I,e.shadowBlur=12*c,e.fill(),e.shadowBlur=0}const R=`${Math.round(P*100)}%`;e.font=`bold ${180*c}px "Segoe UI", Arial, sans-serif`,e.textAlign="center",e.textBaseline="middle";const L=S+C/2,O=_+A/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(R,L,O),e.shadowColor="transparent",e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0,e.fillStyle="rgba(255, 255, 255, 0.95)",e.fillText(R,L,O),d+=m+60*c,i==="idle"&&o>0){const I=Math.floor((Date.now()-o)/1e3),B=this.animConfig.formatIdleTimeShort(I),G=this.animConfig.getIdleTimerColor(I);e.font=`bold ${140*c}px Arial`;const Y=e.measureText(`⏱ ${B}`).width+140*c,K=180*c,Q=(t-Y)/2,H=d;e.fillStyle="rgba(0, 0, 0, 0.85)",e.beginPath(),e.roundRect(Q,H,Y,K,28*c),e.fill(),e.strokeStyle=G.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=G.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 Kn(l);d.minFilter=Vu,d.magFilter=En,d.generateMipmaps=!0,d.anisotropy=16,d.needsUpdate=!0;const m=new Gn({map:d,transparent:!0,depthTest:!1}),p=new Bn(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 j=f+b/2;e.strokeStyle="#000",e.lineWidth=24*p,e.lineJoin="round",e.strokeText(w,t/2,j),e.fillStyle=m,e.fillText(w,t/2,j),f+=b+64*p;const S=200*p,C=1350*p,A=(t-C)/2,_=f,T=176*p,P=A+T/2+24*p,M=_+S/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(P,M,T/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 R=A+T+64*p,L=C-T-88*p,O=S-48*p,I=_+24*p;e.fillStyle="#000",e.beginPath(),e.roundRect(R,I,L,O,24*p),e.fill(),e.strokeStyle="#5a8a8a",e.lineWidth=8*p,e.stroke();const B=Math.max(0,Math.min(100,o))/100,G=16*p,$=Math.max(0,(L-G*2)*B);if($>0){let H;B>.5?H="#00ff88":B>.2?H="#ffaa00":H="#ff3366",e.fillStyle=H,e.beginPath(),e.roundRect(R+G,I+G,$,O-G*2,16*p),e.fill(),e.shadowColor=H,e.shadowBlur=32*p,e.fill(),e.shadowBlur=0}const Y=`${Math.round(B*100)}%`;e.font=`bold ${128*p}px Arial`,e.textAlign="center",e.textBaseline="middle";const K=R+L/2,Q=I+O/2;if(e.strokeStyle="#000",e.lineWidth=28*p,e.lineJoin="round",e.strokeText(Y,K,Q),e.fillStyle="#fff",e.shadowColor="#000",e.shadowBlur=8*p,e.fillText(Y,K,Q),e.shadowBlur=0,f+=S+48*p,l==="idle"&&c>0){const H=Math.floor((Date.now()-c)/1e3),re=this.animConfig.formatIdleTimeShort(H),de=this.animConfig.getIdleTimerColor(H);e.font=`bold ${160*p}px Arial`;const V=e.measureText(`⏱ ${re}`).width+160*p,J=216*p,ie=(t-V)/2,Z=f;e.fillStyle="rgba(0, 0, 0, 0.85)",e.beginPath(),e.roundRect(ie,Z,V,J,32*p),e.fill(),e.strokeStyle=de.border,e.lineWidth=12*p,e.stroke(),e.textAlign="center",e.textBaseline="middle",e.strokeStyle="#000",e.lineWidth=16*p,e.strokeText(`⏱ ${re}`,t/2,Z+J/2),e.fillStyle=de.text,e.fillText(`⏱ ${re}`,t/2,Z+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 Kn(a);k.minFilter=En,k.magFilter=En,k.needsUpdate=!0;const j=new Gn({map:k,transparent:!0,depthTest:!1}),S=new Bn(j);S.position.y=n?-.2:-.3;const C=n?.75:.6,_=(n?1.5:1.2)*(a.width/512);return S.scale.set(_,C,1),S.name="nameLabel",S.userData.aspectRatio=a.width/a.height,S}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 Kn(a);o.minFilter=En,o.magFilter=En,o.needsUpdate=!0;const l=new Gn({map:o,transparent:!0,depthTest:!1}),c=new Bn(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,j=n/2;e.beginPath(),e.arc(k,j,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 S=Math.max(0,(f-4*l)*o);if(S>0){let A,_;o>.5?(A="#00ff88",_="#00ff88"):o>.2?(A="#ffaa00",_="#ffaa00"):(A="#ff3366",_="#ff3366"),e.fillStyle=A,e.beginPath(),e.roundRect(m+2*l,p+2*l,S,b-4*l,x-2),e.fill(),e.shadowColor=_,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 Kn(a);o.minFilter=En,o.magFilter=En,o.needsUpdate=!0;const l=new Gn({map:o,transparent:!0,depthTest:!1}),c=new Bn(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 Kn(e);n.minFilter=En,n.magFilter=En,n.needsUpdate=!0;const a=new Gn({map:n,transparent:!0,depthTest:!1}),i=new Bn(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=Ua[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){const o=t.isBoss===!0||t.class==="boss",l=Math.round(mM(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 p=e.getObjectByName("statusBar");if(p){const w=p.material;if(w.map){const k=w.map.image;if(k instanceof HTMLCanvasElement){const j=k.getContext("2d");j&&(this.drawStatusBar(j,k.width,k.height,l,t.status,t.lastActivity,o),w.map.needsUpdate=!0)}}}const f=e.getObjectByName("combinedUI");if(f){const w=f.material;if(w.map){const k=w.map.image;if(k instanceof HTMLCanvasElement){const j=k.getContext("2d");j&&(this.drawCombinedUI(j,k.width,k.height,t.name,i,l,t.status,t.lastActivity,o),w.map.needsUpdate=!0)}}}const b=!!e.getObjectByName("statusBar"),x=!!e.getObjectByName("combinedUI");!b&&!x&&(this.updateManaBar(e,l,t.status),this.updateIdleTimer(e,t.status,t.lastActivity))}if(c.agentName!==t.name){const p=e.getObjectByName("nameLabelSprite");if(p){const x=p.material;if(x.map){const w=x.map.image;if(w instanceof HTMLCanvasElement){const k=w.getContext("2d");k&&(this.drawNameLabel(k,w.width,w.height,t.name,i),x.map.needsUpdate=!0,c.agentName=t.name)}}}const f=!!e.getObjectByName("statusBar"),b=!!e.getObjectByName("combinedUI");!f&&!b&&(this.updateNameLabel(e,t.name,t.class,t.provider),c.agentName=t.name)}const m=e.getObjectByName("selectionRing");if(m){const p=m.material;if(n){const f=Ua[t.class];p.color.setHex((f==null?void 0:f.color)??i),p.opacity=.8}else a?(p.color.setHex(16766720),p.opacity=.5):p.opacity=0}}}class CO{constructor(e){U(this,"modelLoader");U(this,"animConfig");U(this,"visualConfig");this.modelLoader=new kO(e),this.animConfig=new SO,this.visualConfig=new jO(this.animConfig)}setCustomClasses(e){this.modelLoader.setCustomClasses(e)}createAgentMesh(e){const t=new _n;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=mM(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);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 zn(b,b,x,8),k=new Ye({visible:!1,transparent:!0,opacity:0}),j=new Re(w,k);return j.position.y=x/2,j.name="clickHitbox",t.add(j),{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 Vn={STATIC:"static",IDLE:"idle",WALK:"walk",JUMP:"jump",SIT:"sit",DIE:"die",EMOTE_YES:"emote-yes",EMOTE_NO:"emote-no"},xj={height:.5,speed:1.5};class NO{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 Vn.IDLE;case"walk":return Vn.WALK;case"working":return Vn.JUMP;default:return Vn.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 xt(n.x,n.y,n.z),l=a.distanceTo(i)/yO*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?cR:TA,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===Vn.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 xt().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*xj.speed*Math.PI*2))*xj.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 xt().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 es={Read:"📖",Write:"✏️",Edit:"📝",Bash:"💻",Glob:"🔍",Grep:"🔎",Task:"📋",WebFetch:"🌐",WebSearch:"🌍",TodoWrite:"✅",NotebookEdit:"📓",AskFollowupQuestion:"❓",AskUserQuestion:"❓",AttemptCompletion:"✨",ListFiles:"📂",SearchFiles:"🔎",ExecuteCommand:"⚙️",default:"⚡"},AO={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 fM(s,e){const t=AO[s];return t&&e(t,{defaultValue:s})||s}function Rp(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 gM(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 bM(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"?"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 MO(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 bM(s){return MO(s)||s}const vj=/(^|[\s("'`])((?:\.{1,2}\/|~\/|\/)?[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*\.[A-Za-z0-9._-]+(?::\d+(?::\d+)?)?)/g;function TO(s){return!s||s.startsWith("-")||s.includes("://")||s.includes("*")?!1:s.includes(".")&&!s.endsWith(".")}function yM(s){if(!s)return[{text:""}];const e=[];let t=0;vj.lastIndex=0;let n;for(;(n=vj.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}),TO(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 Pp="tide-file://",EO=/(^|[\s(>])((?:\.\.?\/|\/)?(?:[A-Za-z0-9._-]+\/)*[A-Za-z0-9._-]+(?:\.[A-Za-z0-9._-]+)+(?:#L\d+(?:C\d+)?)?(?::\d+(?::\d+)?)?)(?=$|[\s),.;])/g,_O=/`((?:\.\.?\/|\/)?(?:[A-Za-z0-9._-]+\/)*[A-Za-z0-9._-]+(?:\.[A-Za-z0-9._-]+)+(?:#L\d+(?:C\d+)?)?(?::\d+(?::\d+)?)?)`/g,DO=/\.(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 wj(s){if(!s||s.includes("://")||s.startsWith("www.")||s.includes("@"))return!1;const e=s.split("/")[0];return DO.test(e)?!1:s.includes(".")&&!s.endsWith(".")}function nb(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(_O,(l,c)=>{if(!wj(c))return l;const d=encodeURIComponent(c);return`[\`${c}\`](${Pp}${d})`});return o.replace(EO,(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==="]"||!wj(d))return l;const x=encodeURIComponent(d);return`${c}[${d}](${Pp}${x})`})}).join(`
|
|
45
45
|
`)}function RO(s){if(!s||!s.startsWith(Pp))return null;const e=s.slice(Pp.length);if(!e)return null;try{return decodeURIComponent(e)}catch{return e}}function Lp(s){return s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'")?s.slice(1,-1):s}function xM(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=Lp(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=Lp(l||o);return c?{shellPrefix:t,commandBody:n,searchTerm:c}:null}function vM(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=Lp(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=Lp(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}}const sd=class sd{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 tl(.3,.4,32),this.pulseGeometry=new tl(.1,.2,32);const e=new uR;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 dR(e),this.createDelegationPaperTexture(),this.createSleepingBubbleTexture(),this.createWaitingPermissionTexture(),this.initializePools()}initializePools(){for(let e=0;e<sd.POOL_SIZE;e++)if(this.delegationPaperTexture){const t=new Gn({map:this.delegationPaperTexture,transparent:!0,opacity:0,depthTest:!1}),n=new Bn(t);n.scale.set(.3,.3,1),n.visible=!1,this.delegationSpritePool.push({sprite:n,inUse:!1})}for(let e=0;e<sd.POOL_SIZE;e++){const t=this.createMoveOrderGroup();t.visible=!1,this.moveOrderGroupPool.push(t)}}createMoveOrderGroup(){const e=new _n,t=new Ye({color:4915102,side:ks,transparent:!0,opacity:.8}),n=new Re(this.ringGeometry,t);n.rotation.x=-Math.PI/2,n.name="ring",e.add(n);const a=new Ye({color:4915102,side:ks,transparent:!0,opacity:.6}),i=new Re(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 Ye({color:4915102,side:ks,transparent:!0,opacity:.9}),c=new Re(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 Gn({map:this.delegationPaperTexture,transparent:!0,opacity:1,depthTest:!1}),t=new Bn(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 Re){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 Re&&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 Kn(e),this.delegationPaperTexture.minFilter=En,this.delegationPaperTexture.magFilter=En}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 Kn(e),this.sleepingBubbleTexture.minFilter=En,this.sleepingBubbleTexture.magFilter=En}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 Kn(e),this.waitingPermissionTexture.minFilter=En,this.waitingPermissionTexture.magFilter=En}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 Gn({map:this.sleepingBubbleTexture,transparent:!0,opacity:.95,depthTest:!1}),i=new Bn(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 Gn({map:this.waitingPermissionTexture,transparent:!0,opacity:.95,depthTest:!1}),i=new Bn(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 xt(n.position.x,n.position.y+1.5,n.position.z),l=new xt(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=es[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 j=d;const S=l.width-40;for(;c.measureText(j).width>S&&j.length>3;)j=j.slice(0,-4)+"...";c.fillText(j,l.width/2,l.height/2);const C=new Kn(l);C.minFilter=En,C.magFilter=En,C.needsUpdate=!0;const A=new Gn({map:C,transparent:!0,opacity:0,depthTest:!1}),_=new Bn(A);_.scale.set(2.4,.6,1),_.renderOrder=1e3;const T=a.position.y-1.3;_.position.copy(a.position),_.position.y=T,this.scene.add(_),this.speechBubbles.push({sprite:_,agentId:e,startTime:performance.now(),duration:4e3,baseY:T})}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 f=this.calculateZoomScale(c.position);i.sprite.scale.set(2.4*f,.6*f,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;i.sprite.position.y=p-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 Re&&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(j=>j.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 Kn(o);m.needsUpdate=!0;const p=new Gn({map:m,transparent:!0,opacity:.85,depthTest:!1}),f=new Bn(p);f.scale.set(1.5,.4,1);const b=this.subagentEffects.filter(j=>j.parentAgentId===t&&!j.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 Re&&c.material.dispose()});this.moveOrderGroupPool=[],this.agentMeshes.clear()}};U(sd,"POOL_SIZE",10);let Sy=sd;class PO{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,j=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+j,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 kj(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":OO(t,e.width,e.height);break;case"metal":IO(t,e.width,e.height);break;case"hex":BO(t,e.width,e.height);break;case"circuit":zO(t,e.width,e.height);break;case"pokemon-stadium":FO(t,e.width,e.height);break;default:LO(t,e.width,e.height)}return new Kn(e)}function LO(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 OO(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 IO(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 BO(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 FO(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,j=Math.random()*t,S=Math.random()>.5;s.fillStyle=S?"rgba(30, 50, 28, 0.3)":"rgba(55, 90, 52, 0.12)",s.fillRect(k,j,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 $O(s){const e=new _n;e.name="galacticFloor";const t=[];HO(e);const n=UO(e);return GO(e,t),qO(e),WO(e),s.add(e),console.log("[Battlefield] Galactic group added to scene:",e),{group:e,stars:n,nebulas:t,time:0}}function HO(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,j=Math.sin(x)*b+(Math.random()-.5)*w,S=1-b/800*.6,C=(1-b/800)*4+Math.random()*3,A=Math.floor(220*S+35),_=Math.floor(200*S+55),T=Math.floor(255);if(t.fillStyle=`rgba(${A}, ${_}, ${T}, ${S})`,t.beginPath(),t.arc(k,j,C,0,Math.PI*2),t.fill(),S>.7&&Math.random()>.5){const P=t.createRadialGradient(k,j,0,k,j,C*3);P.addColorStop(0,`rgba(${A}, ${_}, ${T}, 0.6)`),P.addColorStop(1,"transparent"),t.fillStyle=P,t.beginPath(),t.arc(k,j,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,j,S;if(w<.6?(k=x,j=x,S=255):w<.8?(k=255,j=x,S=x*.7):(k=255,j=x*.6,S=x),t.fillStyle=`rgba(${k}, ${j}, ${S}, 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}, ${j}, ${S}, 0.7)`),C.addColorStop(.5,`rgba(${k}, ${j}, ${S}, 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 Kn(e);o.colorSpace=ei;const l=new cr(30,30),c=new Ye({map:o,side:ks}),d=new Re(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 UO(s){const e=new Fa,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 ti(n,3)),e.setAttribute("color",new ti(a,3));const i=new um({size:.15,transparent:!0,opacity:.9,vertexColors:!0,blending:nl,depthWrite:!1}),o=new yd(e,i);return o.name="galacticStars",o.renderOrder=5,s.add(o),o}function GO(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 Kn(a),c=6+Math.random()*6,d=new cr(c,c),m=new Ye({map:l,color:t[n%t.length],transparent:!0,opacity:.25,blending:nl,depthWrite:!1,side:ks}),p=new Re(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 WO(s){const e=new Fa,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 ti(n,3));const a=new um({size:.15,color:8947967,transparent:!0,opacity:.5,blending:nl,depthWrite:!1}),i=new yd(e,a);i.name="cosmicDust",s.add(i)}function qO(s){const e=new tl(14.5,15.5,64),t=new Ye({color:4491519,transparent:!0,opacity:.6,side:ks,blending:nl}),n=new Re(e,t);n.rotation.x=-Math.PI/2,n.position.y=.02,n.name="portalRim",s.add(n);const a=new tl(13.5,14.5,64),i=new Ye({color:8930559,transparent:!0,opacity:.3,side:ks,blending:nl}),o=new Re(a,i);o.rotation.x=-Math.PI/2,o.position.y=.01,o.name="portalInnerRim",s.add(o)}function Sj(s,e,t){e&&(e.group.traverse(n=>{var a,i;n instanceof Re?((a=n.geometry)==null||a.dispose(),n.material instanceof Zr?t(n.material):Array.isArray(n.material)&&n.material.forEach(o=>t(o))):n instanceof yd&&((i=n.geometry)==null||i.dispose(),n.material instanceof Zr&&n.material.dispose())}),s.remove(e.group))}function YO(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 jj=new xt,Cj=new xt;function Nj(){return{phase:"dawn",sunPosition:new xt(50,10,-60),moonPosition:new xt(-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 Aj(){return{phase:"dusk",sunPosition:new xt(-50,8,-60),moonPosition:new xt(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 sb(){return{phase:"night",sunPosition:new xt(30,-20,-50),moonPosition:new xt(-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 ab(){return{phase:"day",sunPosition:new xt(30,50,-30),moonPosition:new xt(-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 Gh(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 jj.lerpVectors(s.sunPosition,e.sunPosition,t),Cj.lerpVectors(s.moonPosition,e.moonPosition,t),{phase:n,sunPosition:jj,moonPosition:Cj,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 VO(s){if(s>=5&&s<6){const e=s-5;return Gh(sb(),Nj(),e,"dawn")}else if(s>=6&&s<7){const e=s-6;return Gh(Nj(),ab(),e,"dawn")}else{if(s>=7&&s<18)return ab();if(s>=18&&s<19.5){const e=(s-18)/1.5;return Gh(ab(),Aj(),e,"dusk")}else if(s>=19.5&&s<21){const e=(s-19.5)/1.5;return Gh(Aj(),sb(),e,"dusk")}else return sb()}}function KO(){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 Kn(s),l=new Gn({map:o,transparent:!0,depthWrite:!1,blending:nl}),c=new Bn(l);return c.position.set(30,50,-30),c.scale.set(50,50,1),c.name="sun",c.visible=!1,c}function XO(){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 Kn(s),l=new Gn({map:o,transparent:!0,depthWrite:!1,blending:nl}),c=new Bn(l);return c.position.set(-30,35,-50),c.scale.set(40,40,1),c.name="moon",c}function ZO(s=1){const e=new _n,t=new ut({color:16777215,transparent:!0,opacity:.85,roughness:1,metalness:0,depthWrite:!1}),n=new zt(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 Re(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 QO(){const s=new _n;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=ZO(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 JO(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 eI(s,e){s.clouds.forEach(t=>{const n=t.userData.material;n&&(n.opacity=e*.85)})}function tI(){const s=new Fa,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 ti(t,3));const n=new um({color:16777215,size:.5,transparent:!0,opacity:.8}),a=new yd(s,n);return a.name="stars",a}function nI(s){const e=sI(s),t=iI(s),{house:n,windowMaterials:a}=rI(s),{lamps:i,lampLights:o}=oI(s);return{trees:e,bushes:t,house:n,lamps:i,lampLights:o,windowMaterials:a}}const Mj=[{x:-20,z:-18,scale:1.2},{x:-22,z:-8,scale:1.4},{x:-20,z:5,scale:1.1},{x:18,z:-20,scale:1.3},{x:22,z:-5,scale:1},{x:20,z:10,scale:1.5},{x:-8,z:-22,scale:1.25},{x:5,z:-20,scale:1.35}];function sI(s){const e=new _n;e.name="trees_instanced";const t=Mj.length,n=new ut({color:4863784,roughness:.9}),a=new ut({color:2972199,roughness:.8}),i=new zn(.3,.5,3,8),o=new zt(2,8,6),l=new zt(1.5,8,6),c=new or(i,n,t),d=new or(o,a,t),m=new or(l,a,t);c.castShadow=!0,c.receiveShadow=!0,d.castShadow=!0,m.castShadow=!0,c.name="trees_trunks",d.name="trees_foliage1",m.name="trees_foliage2";const p=new Jo,f=new xt,b=new el,x=new xt;return Mj.forEach((w,k)=>{const j=w.scale,S=Math.random()*Math.PI*2;f.set(w.x,1.5*j,w.z),b.setFromEuler(new EA(0,S,0)),x.set(j,j,j),p.compose(f,b,x),c.setMatrixAt(k,p),f.set(w.x,4*j,w.z),x.set(j,j*.8,j),p.compose(f,b,x),d.setMatrixAt(k,p),f.set(w.x,5.5*j,w.z),x.set(j,j,j),p.compose(f,b,x),m.setMatrixAt(k,p)}),c.instanceMatrix.needsUpdate=!0,d.instanceMatrix.needsUpdate=!0,m.instanceMatrix.needsUpdate=!0,e.add(c),e.add(d),e.add(m),s.add(e),e}const aI=[{x:-17,z:-14},{x:-16,z:0},{x:-17,z:12},{x:17,z:-15},{x:16,z:3},{x:17,z:15},{x:-12,z:-17},{x:0,z:-17},{x:12,z:-17},{x:-10,z:17},{x:3,z:17},{x:14,z:17},{x:-25,z:8},{x:-28,z:12}];function iI(s){const e=[],t=m=>{const p=Math.sin(m)*1e4;return p-Math.floor(p)};aI.forEach((m,p)=>{const f=2+Math.floor(t(p*100)*2);for(let b=0;b<f;b++){const x=p*100+b,w=.6+t(x)*.4,k=(t(x+1)-.5)*.8,j=(t(x+2)-.5)*.8,S=.7+t(x+3)*.2;e.push({x:m.x+k,y:w*.7,z:m.z+j,scaleX:w,scaleY:w*S,scaleZ:w})}});const n=new ut({color:4024887,roughness:.85}),a=new zt(1,8,6),i=new or(a,n,e.length);i.castShadow=!0,i.receiveShadow=!0,i.name="bushes_instanced";const o=new Jo,l=new xt,c=new el,d=new xt;return e.forEach((m,p)=>{l.set(m.x,m.y,m.z),c.identity(),d.set(m.scaleX,m.scaleY,m.scaleZ),o.compose(l,c,d),i.setMatrixAt(p,o)}),i.instanceMatrix.needsUpdate=!0,s.add(i),i}function rI(s){const e=new _n,t=[],n=new en(6,4,5),a=new ut({color:13935988,roughness:.8}),i=new Re(n,a);i.position.y=2,i.castShadow=!0,i.receiveShadow=!0,e.add(i);const o=new fc(5,3,4),l=new ut({color:9127187,roughness:.7}),c=new Re(o,l);c.position.y=5.5,c.rotation.y=Math.PI/4,c.castShadow=!0,e.add(c);const d=new en(1.2,2,.1),m=new ut({color:6045747,roughness:.6}),p=new Re(d,m);p.position.set(0,1,2.55),e.add(p);const f=new en(.8,.8,.1),b=new ut({color:16777130,emissive:16755268,emissiveIntensity:.5,roughness:.3});t.push(b);const x=new Re(f,b);x.position.set(-1.5,2.5,2.55),e.add(x);const w=new Re(f,b);w.position.set(1.5,2.5,2.55),e.add(w);const k=new en(.8,2,.8),j=new ut({color:9127187,roughness:.8}),S=new Re(k,j);return S.position.set(1.5,6,-1),S.castShadow=!0,e.add(S),e.position.set(-25,0,10),e.rotation.y=Math.PI/6,e.name="house",s.add(e),{house:e,windowMaterials:t}}const Tj=[{x:-16,z:-16},{x:16,z:-16},{x:-16,z:16},{x:16,z:16}];function oI(s){const e=new _n;e.name="lamps_instanced";const t=[],n=Tj.length,a=new ut({color:3355443,roughness:.5,metalness:.5}),i=new ut({color:2236962,roughness:.4,metalness:.6}),o=new ut({color:16772778,emissive:16755268,emissiveIntensity:2,roughness:.2}),l=new zn(.1,.15,5,8),c=new zn(.05,.05,1,8),d=new zn(.4,.3,.6,8),m=new zt(.25,8,8),p=new or(l,a,n),f=new or(c,a,n),b=new or(d,i,n),x=new or(m,o,n);p.castShadow=!0,p.name="lamps_poles",f.name="lamps_arms",b.name="lamps_housings",x.name="lamps_bulbs";const w=new Jo,k=new xt,j=new el,S=new xt(1,1,1);return Tj.forEach((C,A)=>{k.set(C.x,2.5,C.z),j.identity(),w.compose(k,j,S),p.setMatrixAt(A,w),k.set(C.x+.4,4.8,C.z),j.setFromEuler(new EA(0,0,Math.PI/2)),w.compose(k,j,S),f.setMatrixAt(A,w),k.set(C.x+.8,4.8,C.z),j.identity(),w.compose(k,j,S),b.setMatrixAt(A,w),k.set(C.x+.8,4.5,C.z),w.compose(k,j,S),x.setMatrixAt(A,w);const _=new kA(16755285,1.5,15);_.position.set(C.x,5,C.z),t.push(_),s.add(_)}),p.instanceMatrix.needsUpdate=!0,f.instanceMatrix.needsUpdate=!0,b.instanceMatrix.needsUpdate=!0,x.instanceMatrix.needsUpdate=!0,e.add(p),e.add(f),e.add(b),e.add(x),s.add(e),{lamps:e,lampLights:t}}function lI(s){const e=new cr(80,80),t=new ut({color:2972199,roughness:.9,metalness:0}),n=new Re(e,t);return n.rotation.x=-Math.PI/2,n.position.y=-.05,n.receiveShadow=!0,n.name="grass",s.add(n),n}class cI{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 It);this.scene=e}setGridVisible(e){this.gridHelper&&(this.gridHelper.visible=e)}create(){this.createGround(),this.grass=lI(this.scene),this.createGrid(),this.sun=KO(),this.scene.add(this.sun),this.moon=XO(),this.scene.add(this.moon),this.stars=tI(),this.scene.add(this.stars),this.cloudState=QO(),this.scene.add(this.cloudState.group);const e=nI(this.scene);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=VO(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){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()}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"&&(Sj(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=$O(this.scene),console.log("[Battlefield] Galactic elements created");else{this.ground.visible=!0,a.transparent=!1,a.opacity=1,a.side=MA,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=kj(e);o.wrapS=$o,o.wrapT=$o,o.repeat.set(e==="pokemon-stadium"?1:6,e==="pokemon-stadium"?1:6),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||YO(this.galacticState,e)}updateCloudAnimation(e){!this.cloudState||!this.cloudsVisible||JO(this.cloudState,e)}disposeMaterial(e){var t;(e instanceof Ye||e instanceof ut||e instanceof Gn)&&((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 It?this.scene.background.setHex(t):this.scene.background=this.tempColor.setHex(t).clone(),this.scene.fog instanceof mS){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}eI(this.cloudState,n)}}getGround(){return this.ground}createGround(){const e=new cr(30,30),t=kj(this.currentFloorStyle);t.wrapS=$o,t.wrapT=$o,t.repeat.set(this.currentFloorStyle==="galactic"?1:6,this.currentFloorStyle==="galactic"?1:6);const n=new ut({map:t,color:5592405,roughness:.8,metalness:.1});this.ground=new Re(e,n),this.ground.rotation.x=-Math.PI/2,this.ground.receiveShadow=!0,this.ground.name="ground",this.scene.add(this.ground)}createGrid(){this.gridHelper=new hR(30,30,2763322,1710634),this.gridHelper.position.y=.01,this.scene.add(this.gridHelper)}createLogo(){const t=new lx().load("/assets/textures/logo-blanco.png"),n=10,a=4,i=new cr(n,a),o=new Ye({map:t,transparent:!0,opacity:.8,side:ks,depthWrite:!1}),l=new Re(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 mS(662058,.01),this.scene.background=new It(662058)}createLighting(){this.ambientLight=new dx(16777215,.6),this.scene.add(this.ambientLight),this.hemiLight=new pR(16777198,5596791,.7),this.hemiLight.position.set(0,20,0),this.scene.add(this.hemiLight),this.mainLight=new lc(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=150,this.mainLight.shadow.camera.left=-35,this.mainLight.shadow.camera.right=35,this.mainLight.shadow.camera.top=35,this.mainLight.shadow.camera.bottom=-35,this.scene.add(this.mainLight),this.fillLight=new lc(16777215,.6),this.fillLight.position.set(-10,15,10),this.scene.add(this.fillLight);const e=new lc(11193599,.5);e.position.set(0,20,30),this.scene.add(e)}dispose(){var t,n;Sj(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 Zr&&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 Re&&((n=t.geometry)==null||n.dispose(),t.material instanceof Zr?this.disposeMaterial(t.material):Array.isArray(t.material)&&t.material.forEach(a=>this.disposeMaterial(a)))})}}function Tt(s,e,t,n,a={},i="global"){return{id:s,name:e,description:t,key:n,modifiers:a,enabled:!0,context:i}}const ib=[Tt("toggle-commander","Toggle Commander","Open/close Commander View","k",{ctrl:!0}),Tt("toggle-commander-tab","Toggle Commander (Tab)","Open/close Commander View with Tab","Tab",{}),Tt("spawn-agent","Spawn Agent","Open new agent spawn modal","n",{alt:!0}),Tt("select-agent-1","Select Agent 1","Select first agent","1",{ctrl:!0}),Tt("select-agent-2","Select Agent 2","Select second agent","2",{ctrl:!0}),Tt("select-agent-3","Select Agent 3","Select third agent","3",{ctrl:!0}),Tt("select-agent-4","Select Agent 4","Select fourth agent","4",{ctrl:!0}),Tt("select-agent-5","Select Agent 5","Select fifth agent","5",{ctrl:!0}),Tt("select-agent-6","Select Agent 6","Select sixth agent","6",{ctrl:!0}),Tt("select-agent-7","Select Agent 7","Select seventh agent","7",{ctrl:!0}),Tt("select-agent-8","Select Agent 8","Select eighth agent","8",{ctrl:!0}),Tt("select-agent-9","Select Agent 9","Select ninth agent","9",{ctrl:!0}),Tt("delete-selected","Delete Selected","Remove selected agents","Delete",{}),Tt("delete-selected-backspace","Delete Selected (Backspace)","Remove selected agents","Backspace",{}),Tt("deselect-all","Deselect All","Clear agent selection","Escape",{}),Tt("open-terminal","Open Terminal","Open terminal for selected agent","Space",{}),Tt("dashboard-selector-toggle","Dashboard Selector","Enable dashboard card selector",",",{}),Tt("dashboard-vim-left","Dashboard Left","Move dashboard selector left","h",{}),Tt("dashboard-vim-down","Dashboard Down","Move dashboard selector down","j",{}),Tt("dashboard-vim-up","Dashboard Up","Move dashboard selector up","k",{}),Tt("dashboard-vim-right","Dashboard Right","Move dashboard selector right","l",{}),Tt("next-agent","Next Agent","Select next agent on battlefield","l",{alt:!0}),Tt("prev-agent","Previous Agent","Select previous agent on battlefield","h",{alt:!0}),Tt("next-working-agent","Next Working Agent","Select next working agent on battlefield","l",{alt:!0,shift:!0}),Tt("prev-working-agent","Previous Working Agent","Select previous working agent on battlefield","h",{alt:!0,shift:!0}),Tt("next-message","Next Message","Navigate to next message in terminal","j",{alt:!0}),Tt("prev-message","Previous Message","Navigate to previous message in terminal","k",{alt:!0}),Tt("page-down-messages","Page Down Messages","Jump down 10 messages in terminal","d",{alt:!0,shift:!0}),Tt("page-up-messages","Page Up Messages","Jump up 10 messages in terminal","u",{alt:!0}),Tt("next-agent-terminal","Next Agent (Terminal)","Switch to next agent in terminal","l",{alt:!0}),Tt("prev-agent-terminal","Previous Agent (Terminal)","Switch to previous agent in terminal","h",{alt:!0}),Tt("activate-message","Activate Message","Click on interactive element in selected message","Space",{}),Tt("toggle-file-explorer","Toggle File Explorer","Open/close file explorer","e",{alt:!0}),Tt("file-explorer-close-tab","Close File Tab","Close active file tab in explorer","w",{alt:!0}),Tt("toggle-spotlight","Toggle Spotlight","Open/close global search","p",{alt:!0}),Tt("open-database","Open Database","Open last used database query builder","d",{alt:!0}),Tt("toggle-2d-view","Cycle View Mode","Cycle between 3D, 2D, and Dashboard views","2",{alt:!0}),Tt("commander-close","Close Commander","Close Commander View","Escape",{},"commander"),Tt("commander-vim-left","Navigate Left","Move focus left (Vim H)","h",{alt:!0},"commander"),Tt("commander-vim-down","Navigate Down","Move focus down (Vim J)","j",{alt:!0},"commander"),Tt("commander-vim-up","Navigate Up","Move focus up (Vim K)","k",{alt:!0},"commander"),Tt("commander-vim-right","Navigate Right","Move focus right (Vim L)","l",{alt:!0},"commander"),Tt("commander-expand","Expand/Collapse","Toggle agent expansion","o",{alt:!0},"commander"),Tt("commander-new-agent","New Agent","Open spawn form in commander","n",{alt:!0},"commander"),Tt("commander-next-tab","Next Tab","Switch to next area tab","Tab",{},"commander"),Tt("commander-prev-tab","Previous Tab","Switch to previous area tab","Tab",{shift:!0},"commander"),Tt("toolbox-close","Close Toolbox","Close Settings panel","Escape",{},"toolbox")];function yt(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 Ko(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 uI(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 Wh{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 lm=class lm{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)},lm.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)>rc||Math.abs(n)>rc)&&(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(lm,"LONG_PRESS_DURATION",500);let jy=lm;function dI(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 hI{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||!dI(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 pI{constructor(e,t){U(this,"camera");U(this,"canvas");U(this,"raycaster",new mR);U(this,"mouse",new Rs);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.ground)return null;this.updateMouseFromEvent(e),this.raycaster.setFromCamera(this.mouse,this.camera);const t=this.raycaster.intersectObject(this.ground);if(t.length>0){const n=t[0].point;return{x:n.x,z:n.z}}return null}raycastGroundFromPoint(e,t){if(!this.ground)return null;this.updateMouseFromPoint(e,t),this.raycaster.setFromCamera(this.mouse,this.camera);const n=this.raycaster.intersectObject(this.ground);if(n.length>0){const a=n[0].point;return{x:a.x,z:a.z}}return 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 _A(new xt(0,1,0),0),a=new xt;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 mI{constructor(e,t,n){U(this,"camera");U(this,"controls");U(this,"canvas");U(this,"raycastProvider",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){e.preventDefault();const n=Math.sign(e.deltaY)*Math.min(Math.abs(e.deltaY),100)/100,a=n<0,i=.03*Math.abs(n)*t,o=this.camera.position.clone().sub(this.controls.target),l=o.length(),c=this.controls.minDistance,d=this.controls.maxDistance,m=a?Math.max(c,l*(1-i)):Math.min(d,l*(1+i));if(m===l)return;let p=null;if(this.raycastProvider){const j=this.raycastProvider.getNormalizedMouseFromEvent(e);p=this.raycastProvider.raycastToPlane(j.x,j.y)}if(!p){const j=o.normalize();this.camera.position.copy(this.controls.target).add(j.multiplyScalar(m));return}const f=m/l,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=o.normalize();this.camera.position.copy(w).add(k.multiplyScalar(m))}handlePinchZoom(e,t){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 j=n.normalize();this.camera.position.copy(this.controls.target).add(j.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){const n=new xt;this.camera.getWorldDirection(n);const a=new xt(-n.z,0,n.x).normalize(),i=new xt(n.x,0,n.z).normalize(),l=this.camera.position.distanceTo(this.controls.target)*.005,c=new xt;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){const a=-e*.005,i=-t*.005,o=this.camera.position.clone().sub(this.controls.target),l=new Np;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){const t=this.camera.position.clone().sub(this.controls.target),n=new Np;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)}}const rb={panSpeed:1,orbitSpeed:1,zoomSpeed:1,smoothing:.3,invertPanX:!1,invertPanY:!1,invertOrbitX:!1,invertOrbitY:!1},qh={enabled:!0,pinchToZoom:!0,twoFingerPan:!0,shiftTwoFingerOrbit:!0,sensitivity:{zoom:1,pan:1,orbit:1}};function Lo(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 ob=[Lo("left-click-select","Select/Click","Select agents, click on buildings/areas","left",{},"primary-action"),Lo("left-drag-selection","Selection Box","Drag to select multiple agents","left",{},"selection-box"),Lo("right-click-context","Context Menu / Move","Show context menu or move selected agents","right",{},"context-menu"),Lo("alt-right-drag-pan","Camera Pan","Pan camera with Alt+Right-drag","right",{alt:!0},"camera-pan",1),Lo("middle-drag-orbit","Camera Orbit","Orbit camera with middle-drag","middle",{},"camera-orbit",1),Lo("shift-middle-drag-pan","Camera Pan (Alt)","Alternative pan with Shift+Middle-drag","middle",{shift:!0},"camera-pan",1),Lo("wheel-zoom","Zoom","Zoom camera with scroll wheel","middle",{},"camera-zoom",1)],fI={0:"left",1:"middle",2:"right",3:"back",4:"forward"},gI={left:"Left Click",right:"Right Click",middle:"Middle Click",back:"Back Button",forward:"Forward Button"};function Ej(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):gI[s.button]),t.join("+")}function bI(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 yI{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=fI[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(bI(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 Vr=class Vr{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){if(this.controls.mouseButtons.LEFT=null,!t){const m=this.raycaster.checkResizeHandleClick(e);if(m){const p=this.raycaster.raycastGroundFromEvent(e);p&&(this.isResizing=!0,(o=(i=this.callbacks).onResizeStart)==null||o.call(i,m,p));return}}if(!t&&this.drawingModeChecker()){const m=this.raycaster.raycastGroundFromEvent(e);m&&(this.isDrawing=!0,(c=(l=this.callbacks).onDrawStart)==null||c.call(l,m));return}const d=this.raycaster.raycastGroundFromEvent(e);if(d){const m=this.buildingAtPositionGetter(d);if(m&&!t){this.draggingBuildingId=m.id,this.buildingDragStartPos=d,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)>rc||Math.abs(p)>rc)&&(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)>rc||Math.abs(p)>rc)&&(this.isRightDragging=!0)}if(!(e.buttons&4&&this.mouseControlHandler.handlePointerMove(e))&&e.buttons===0&&e.pointerType!=="touch"){const m=performance.now();m-this.lastHoverCheckTime>Vr.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.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(!yt(e,c)){if(a){const x=z.getShortcuts();if((yt(e,x.find(k=>k.id==="next-agent"))||yt(e,x.find(k=>k.id==="prev-agent"))||yt(e,x.find(k=>k.id==="next-working-agent"))||yt(e,x.find(k=>k.id==="prev-working-agent")))&&o)t.blur();else if(yt(e,p)&&o)t.blur();else return}if((yt(e,d)||yt(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(S=>S.id===w):-1;let j;yt(e,d)?j=k===-1?0:(k+1)%x.length:j=k===-1?x.length-1:(k-1+x.length)%x.length,e.preventDefault(),z.selectAgent(x[j].id),(b=(f=this.callbacks).onActivity)==null||b.call(f);return}if(yt(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 xt(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=>{this.touchHandler.onTouchStart(e)});U(this,"onTouchMove",e=>{this.touchHandler.onTouchMove(e)});U(this,"onTouchEnd",e=>{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 xt(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 pI(t,e),this.cameraController=new mI(t,n,e),this.cameraController.setRaycastProvider(this.raycaster),this.mouseControlHandler=new yI(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 hI(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 Wh(300),this.agentTapDetector=new Wh(450),this.buildingClickDetector=new Wh(300),this.areaClickDetector=new Wh(300),this.touchHandler=new jy(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()}calculateFormationPositions(e,t){const n=[];if(t===1)return[{x:e.x,y:0,z:e.z}];if(t<=6){const a=wi*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)*wi/2,l=(i-1)*wi/2;for(let c=0;c<t;c++){const d=c%a,m=Math.floor(c/a);n.push({x:e.x+d*wi-o,y:0,z:e.z+m*wi-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()},Vr.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()},Vr.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=Ja(mt.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(Vr,"HOVER_DELAY",400),U(Vr,"HOVER_CHECK_INTERVAL",50),U(Vr,"BUILDING_HOVER_DELAY",5e3);let Cy=Vr;class xI{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 Re&&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 _n;t.userData.areaId=e.id,t.userData.zIndex=e.zIndex??0;const n=new It(e.color),a=(e.zIndex??0)*.001;if(e.type==="rectangle"&&e.width&&e.height){const l=new cr(e.width,e.height),c=new Ye({color:n,transparent:!0,opacity:.15*this.brightness,side:ks}),d=new Re(l,c);d.rotation.x=-Math.PI/2,d.position.y=.02+a,t.add(d);const m=[new xt(-e.width/2,0,-e.height/2),new xt(e.width/2,0,-e.height/2),new xt(e.width/2,0,e.height/2),new xt(-e.width/2,0,e.height/2),new xt(-e.width/2,0,-e.height/2)],p=new Fa().setFromPoints(m),f=new Ho({color:n,linewidth:2}),b=new Yr(p,f);b.position.y=.03+a,t.add(b)}else if(e.type==="circle"&&e.radius){const l=new sy(e.radius,32),c=new Ye({color:n,transparent:!0,opacity:.15*this.brightness,side:ks}),d=new Re(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 xt(Math.cos(w)*e.radius,0,Math.sin(w)*e.radius))}const p=new Fa().setFromPoints(m),f=new Ho({color:n,linewidth:2}),b=new Yr(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 _;const x=Math.floor(b/p),w=b%p,k=((_=e.directoryGitCounts)==null?void 0:_[b])??0,j=this.createFolderIconSprite(e.color,k);j.name="folderIcon",j.userData.areaId=e.id,j.userData.folderPath=f,j.userData.isFolderIcon=!0,j.position.set(d+w*.81,.3+a,m+x*.81),t.add(j);const S=new zt(.3,8,8),C=new Ye({visible:!1}),A=new Re(S,C);A.position.copy(j.position),A.position.x+=e.center.x,A.position.z+=e.center.z,A.name="folderIconHit",A.userData.areaId=e.id,A.userData.folderPath=f,A.userData.isFolderIcon=!0,this.scene.add(A),this.folderIconMeshes.push(A)})}(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 Kn(n);m.needsUpdate=!0;const p=new Gn({map:m,transparent:!0,depthTest:!1}),f=new Bn(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,j=a*.78;i.fillStyle="#e8943a",i.beginPath(),i.arc(k,j,w,0,Math.PI*2),i.fill(),i.strokeStyle="rgba(0, 0, 0, 0.7)",i.lineWidth=2,i.beginPath(),i.arc(k,j,w,0,Math.PI*2),i.stroke();const S=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(S,k,j)}const f=new Kn(n);f.needsUpdate=!0;const b=new Gn({map:f,transparent:!0,depthTest:!1}),x=new Bn(b);return x.scale.set(.6,.6,1),x}addLogoToGroup(e,t,n){const a=t.logo,i=xd(at(`/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 lx().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 cr(i.width,i.height),l=new Ye({map:n,transparent:!0,opacity:i.opacity??.8,side:ks,depthWrite:!0,alphaTest:.01}),c=new Re(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 Re&&i.name!=="resizeHandle"&&i.name!=="areaLogo"){const o=i.material,l=a?.3:.15;o.opacity=l*this.brightness}if(i instanceof Yr){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 zt(.15,16,16),n=new Ye({color:16777215,transparent:!0,opacity:.9}),a=new Ye({color:16763904,transparent:!0,opacity:.9}),i=(e.zIndex??0)*.001,o=new Re(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 Re(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 Ye({color:11197951,transparent:!0,opacity:.9}),d=new zt(.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 Re(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 Re(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 _n,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 Re||n instanceof Yr)&&(n.geometry.dispose(),n.material.dispose())}const t=new It("#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 cr(n,a),c=new Ye({color:t,transparent:!0,opacity:.2,side:ks}),d=new Re(l,c);d.rotation.x=-Math.PI/2,d.position.set(i,.02,o),this.previewMesh.add(d);const m=[new xt(this.drawStartPos.x,.03,this.drawStartPos.z),new xt(e.x,.03,this.drawStartPos.z),new xt(e.x,.03,e.z),new xt(this.drawStartPos.x,.03,e.z),new xt(this.drawStartPos.x,.03,this.drawStartPos.z)],p=new Fa().setFromPoints(m),f=new Ho({color:t}),b=new Yr(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 sy(i,32),l=new Ye({color:t,transparent:!0,opacity:.2,side:ks}),c=new Re(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 xt(this.drawStartPos.x+Math.cos(x)*i,.03,this.drawStartPos.z+Math.sin(x)*i))}const m=new Fa().setFromPoints(d),p=new Ho({color:t}),f=new Yr(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 Re&&(t.geometry.dispose(),Array.isArray(t.material)?t.material.forEach(n=>n.dispose()):t.material.dispose()),t instanceof Yr&&(t.geometry.dispose(),t.material.dispose()),t instanceof Bn){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 ss={running:4915102,stopped:8947848,error:16730698,unknown:16755200,starting:4890367,stopping:16755200},kd={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 Li(s){return s.name}function li(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 Kn(e);b.minFilter=En,b.magFilter=En,b.needsUpdate=!0;const x=new Gn({map:b,transparent:!0,depthTest:!1}),w=new Bn(x),k=.5,j=e.width/e.height;return w.scale.set(k*j,k,1),w.userData.aspectRatio=j,w}function wM(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 Kn(e);n.minFilter=En,n.magFilter=En;const a=new Gn({map:n,transparent:!0,depthTest:!1}),i=new Bn(a);return i.scale.set(.35,.35,1),i.name="gitIndicator",i}function vI(s,e){const t=s.material;t.map&&t.map.dispose(),t.dispose();const n=wM(e);s.material=n.material}function wI(s,e){const t=s.label,n=li(e);n.position.copy(t.position),n.name="buildingLabel",s.group.remove(t),t.material instanceof Gn&&(t.material.map&&t.material.map.dispose(),t.material.dispose()),s.group.add(n),s.label=n}function kI(s){const e=new _n;e.userData.buildingId=s.id,e.userData.isBuilding=!0;const t=s.color?new It(s.color):new It(2763322),n=new en(1.2,2.5,.8),a=new ut({color:t,metalness:.7,roughness:.3}),i=new Re(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 A=new en(1.1,.02,.75),_=new ut({color:1710634,metalness:.5,roughness:.5}),T=new Re(A,_);T.position.set(0,.5+C*.45,.03),e.add(T)}for(let C=0;C<5;C++){const A=new en(.08,.08,.05),_=new Ye({color:4915102,transparent:!0,opacity:.9}),T=new Re(A,_);T.position.set(-.45,.5+C*.45,.43),T.name=`led_${C}`,e.add(T);const P=new Re(A.clone(),_.clone());P.position.set(-.3,.5+C*.45,.43),P.name=`activityLed_${C}`,e.add(P)}const o=new en(1,.1,.6),l=new ut({color:1710634,metalness:.3,roughness:.7}),c=new Re(o,l);c.position.set(0,2.55,0),e.add(c);const d=new zt(.15,16,16),m=new Ye({color:ss[s.status],transparent:!0,opacity:.95}),p=new Re(d,m);p.position.set(0,2.75,0),p.name="statusLight",e.add(p);const f=new zt(.25,16,16),b=new Ye({color:ss[s.status],transparent:!0,opacity:.3}),x=new Re(f,b);x.position.set(0,2.75,0),x.name="statusGlow",e.add(x);const w=new en(1.5,.1,1.1),k=new ut({color:3816010,metalness:.5,roughness:.5}),j=new Re(w,k);j.position.y=.05,j.receiveShadow=!0,e.add(j);const S=li(Li(s));return S.position.set(0,3.2,0),S.name="buildingLabel",e.add(S),e.position.set(s.position.x,0,s.position.z),{group:e,statusLight:p,label:S}}function SI(s,e){for(let t=0;t<5;t++){const n=s.group.getObjectByName(`led_${t}`);if(n&&n.material instanceof Ye){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 Ye&&(a.material.opacity=Math.random()>.97?.5:.1)}}function jI(s,e){for(let t=0;t<5;t++){const n=s.group.getObjectByName(`activityLed_${t}`);n&&n.material instanceof Ye&&Math.random()>.95&&(n.material.opacity=n.material.opacity>.5?.2:.9)}}function CI(s){const e=new _n;e.userData.buildingId=s.id,e.userData.isBuilding=!0;const t=s.color?new It(s.color):new It(2767434),n=new zn(.5,.7,3,8),a=new ut({color:t,metalness:.6,roughness:.4}),i=new Re(n,a);i.position.y=1.5,i.castShadow=!0,i.receiveShadow=!0,i.name="buildingBody",e.add(i);for(let L=0;L<4;L++){const O=new zn(.52-L*.03,.62-L*.03,.1,8),I=new Ye({color:4890367,transparent:!0,opacity:.7}),B=new Re(O,I);B.position.y=.7+L*.6,B.name=`windowBand_${L}`,e.add(B)}const o=new zn(.6,.5,.2,8),l=new ut({color:3816010,metalness:.7,roughness:.3}),c=new Re(o,l);c.position.y=3.1,e.add(c);const d=new zn(.15,.2,.3,6),m=new ut({color:4868698,metalness:.8,roughness:.2}),p=new Re(d,m);p.position.y=3.35,e.add(p);const f=new _n;f.position.y=3.6,f.name="antenna";const b=new en(.05,.6,.05),x=new ut({color:6974074,metalness:.9,roughness:.1}),w=new Re(b,x);w.position.y=.3,f.add(w);const k=new fc(.15,.1,8);for(let L=0;L<2;L++){const O=new Re(k,x);O.rotation.x=Math.PI/2,O.position.set(L===0?.2:-.2,.4,0),O.rotation.z=L===0?Math.PI/2:-Math.PI/2,f.add(O)}e.add(f);const j=new zt(.12,16,16),S=new Ye({color:ss[s.status],transparent:!0,opacity:.95}),C=new Re(j,S);C.position.set(0,4.3,0),C.name="statusLight",e.add(C);const A=new zt(.2,16,16),_=new Ye({color:ss[s.status],transparent:!0,opacity:.3}),T=new Re(A,_);T.position.set(0,4.3,0),T.name="statusGlow",e.add(T);const P=new zn(.9,1,.15,8),M=new ut({color:3816010,metalness:.5,roughness:.5}),D=new Re(P,M);D.position.y=.075,D.receiveShadow=!0,e.add(D);const R=li(Li(s));return R.position.set(0,4.7,0),R.name="buildingLabel",e.add(R),e.position.set(s.position.x,0,s.position.z),{group:e,statusLight:C,label:R}}function NI(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 Ye&&(i.material.opacity=.3+Math.sin(e*.5+a*.4)*.15)}}function AI(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 Ye){const o=Math.sin(e*4+a*.5)*.3+.7;i.material.opacity=o}}}function MI(s){const e=new _n;e.userData.buildingId=s.id,e.userData.isBuilding=!0;const t=s.color?new It(s.color):new It(2763338),n=new zt(1.2,32,16,0,Math.PI*2,0,Math.PI/2),a=new ut({color:t,metalness:.4,roughness:.6,transparent:!0,opacity:.9}),i=new Re(n,a);i.position.y=.15,i.castShadow=!0,i.receiveShadow=!0,i.name="buildingBody",e.add(i);const o=new zt(.8,24,12,0,Math.PI*2,0,Math.PI/2),l=new Ye({color:4890367,transparent:!0,opacity:.3}),c=new Re(o,l);c.position.y=.15,c.name="innerDome",e.add(c);const d=new cc(1,.05,8,32),m=new Ye({color:4915102,transparent:!0,opacity:.8}),p=new Re(d,m);p.position.y=.6,p.rotation.x=Math.PI/2,p.name="energyRing",e.add(p);const f=new Re(d.clone(),m.clone());f.position.y=.8,f.rotation.x=Math.PI/3,f.name="energyRing2",e.add(f);for(let P=0;P<4;P++){const M=new zn(.03,.03,1.2,8),D=new Ye({color:4890367,transparent:!0,opacity:.6}),R=new Re(M,D),L=P/4*Math.PI*2;R.position.set(Math.cos(L)*.5,.75,Math.sin(L)*.5),R.name=`beam_${P}`,e.add(R)}const b=new zt(.15,16,16),x=new Ye({color:ss[s.status],transparent:!0,opacity:.95}),w=new Re(b,x);w.position.set(0,1.4,0),w.name="statusLight",e.add(w);const k=new zt(.25,16,16),j=new Ye({color:ss[s.status],transparent:!0,opacity:.3}),S=new Re(k,j);S.position.set(0,1.4,0),S.name="statusGlow",e.add(S);const C=new zn(1.4,1.5,.15,32),A=new ut({color:3816010,metalness:.6,roughness:.4}),_=new Re(C,A);_.position.y=.075,_.receiveShadow=!0,e.add(_);const T=li(Li(s));return T.position.set(0,1.9,0),T.name="buildingLabel",e.add(T),e.position.set(s.position.x,0,s.position.z),{group:e,statusLight:w,label:T}}function TI(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 Ye&&(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 Ye&&(l.material.opacity=.2+Math.sin(e*.5+o*.3)*.1)}}function EI(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 Ye&&(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 Ye){const c=Math.sin(e*5+o*1.5)*.3+.6;l.material.opacity=c}}}function _I(s){const e=new _n;e.userData.buildingId=s.id,e.userData.isBuilding=!0;const t=s.color?new It(s.color):new It(3815978),n=new fc(1.3,2.5,4),a=new ut({color:t,metalness:.3,roughness:.7}),i=new Re(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 fc(.6,1.2,4),l=new Ye({color:16755200,transparent:!0,opacity:.6}),c=new Re(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 R=0;R<4;R++){const L=new zn(.02,.02,2.7,8),O=new Ye({color:4915102,transparent:!0,opacity:.7}),I=new Re(L,O),B=d[R];I.position.set(B.x*.5,1.25,B.z*.5);const G=Math.atan2(1.25,.65);R<2?I.rotation.z=R===0?-G:G:I.rotation.x=R===2?G:-G,I.name=`edgeLine_${R}`,e.add(I)}const m=new zt(.15,16,16),p=new Ye({color:16755200,transparent:!0,opacity:.9}),f=new Re(m,p);f.position.y=2.7,f.name="pyramidEye",e.add(f);const b=new zt(.25,16,16),x=new Ye({color:16755200,transparent:!0,opacity:.3}),w=new Re(b,x);w.position.y=2.7,w.name="pyramidEyeGlow",e.add(w);const k=new zt(.12,16,16),j=new Ye({color:ss[s.status],transparent:!0,opacity:.95}),S=new Re(k,j);S.position.set(1.2,.3,0),S.name="statusLight",e.add(S);const C=new zt(.2,16,16),A=new Ye({color:ss[s.status],transparent:!0,opacity:.3}),_=new Re(C,A);_.position.set(1.2,.3,0),_.name="statusGlow",e.add(_);const T=new en(2.8,.15,2.8),P=new ut({color:4868666,metalness:.2,roughness:.8}),M=new Re(T,P);M.position.y=.075,M.receiveShadow=!0,e.add(M);const D=li(Li(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:S,label:D}}function DI(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 Ye&&(t.material.opacity=.4+Math.sin(e*.7)*.2)),n&&(n.position.y=2.7+Math.sin(e*.5)*.03,n.material instanceof Ye&&(n.material.opacity=.15+Math.sin(e*.7)*.1));const a=s.group.getObjectByName("pyramidCore");a&&a.material instanceof Ye&&(a.material.opacity=.2+Math.sin(e*.5)*.1)}function RI(s,e){const t=s.group.getObjectByName("pyramidCore");t&&t.material instanceof Ye&&(t.material.opacity=.4+Math.sin(e*2)*.2);const n=s.group.getObjectByName("pyramidEye"),a=s.group.getObjectByName("pyramidEyeGlow");n&&n.material instanceof Ye&&(n.material.opacity=.7+Math.sin(e*3)*.3),a&&a.material instanceof Ye&&(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 PI(s){const e=new _n;e.userData.buildingId=s.id,e.userData.isBuilding=!0;const t=kd.desktop,n=s.color?new It(s.color):new It(t.primary),a=new en(1.4,1,.15),i=new ut({color:n,metalness:.4,roughness:.6}),o=new Re(a,i);o.position.set(0,1.4,0),o.castShadow=!0,o.name="buildingBody",e.add(o);const l=new en(1.2,.8,.02),c=new Ye({color:661032,transparent:!0,opacity:.95}),d=new Re(l,c);d.position.set(0,1.4,.09),d.name="screen",e.add(d);for(let K=0;K<6;K++){const Q=new en(.8-K%3*.2,.05,.01),H=new Ye({color:t.glow,transparent:!0,opacity:.9}),re=new Re(Q,H);re.position.set(-.1+K%2*.1,1.65-K*.1,.1),re.name=`codeLine_${K}`,e.add(re)}const m=new en(.15,.6,.15),p=new ut({color:t.secondary,metalness:.5,roughness:.5}),f=new Re(m,p);f.position.set(0,.6,0),e.add(f);const b=new en(.6,.08,.4),x=new Re(b,p);x.position.set(0,.25,0),e.add(x);const w=new en(1,.08,.35),k=new ut({color:t.secondary,metalness:.3,roughness:.7}),j=new Re(w,k);j.position.set(0,.2,.6),j.rotation.x=-.1,e.add(j);for(let K=0;K<3;K++)for(let Q=0;Q<10;Q++){const H=new en(.07,.03,.07),re=new ut({color:t.accent,metalness:.2,roughness:.8}),de=new Re(H,re);de.position.set(-.38+Q*.085,.25,.45+K*.1),e.add(de)}const S=new en(.4,.9,.8),C=new ut({color:n,metalness:.4,roughness:.6}),A=new Re(S,C);A.position.set(-1.1,.55,0),A.castShadow=!0,e.add(A);const _=new en(.05,.05,.02),T=new Ye({color:4915102,transparent:!0,opacity:.9}),P=new Re(_,T);P.position.set(-.88,.7,.3),P.name="cpuLed",e.add(P);const M=new zt(.1,16,16),D=new Ye({color:ss[s.status],transparent:!0,opacity:.95}),R=new Re(M,D);R.position.set(.6,1.85,.1),R.name="statusLight",e.add(R);const L=new zt(.18,16,16),O=new Ye({color:ss[s.status],transparent:!0,opacity:.3}),I=new Re(L,O);I.position.set(.6,1.85,.1),I.name="statusGlow",e.add(I);const B=new en(2.6,.1,1.4),G=new ut({color:3816010,metalness:.5,roughness:.5}),$=new Re(B,G);$.position.y=.05,$.receiveShadow=!0,e.add($);const Y=li(Li(s));return Y.position.set(0,2.3,0),Y.name="buildingLabel",e.add(Y),e.position.set(s.position.x,0,s.position.z),{group:e,statusLight:R,label:Y}}function LI(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 Ye&&(a.material.opacity=.3+Math.sin(e*.4+n*.2)*.1)}}function OI(s,e){for(let n=0;n<6;n++){const a=s.group.getObjectByName(`codeLine_${n}`);if(a&&a.material instanceof Ye){const i=Math.random()>.98?.4:.8;a.material.opacity=i}}const t=s.group.getObjectByName("cpuLed");if(t&&t.material instanceof Ye){const n=Math.sin(e*6)>0?.9:.3;t.material.opacity=n}}function II(s){const e=new _n;e.userData.buildingId=s.id,e.userData.isBuilding=!0;const t=kd["filing-cabinet"],n=s.color?new It(s.color):new It(t.primary),a=new en(1,2.4,.8),i=new ut({color:n,metalness:.5,roughness:.5}),o=new Re(a,i);o.position.y=1.2,o.castShadow=!0,o.name="buildingBody",e.add(o);for(let j=0;j<4;j++){const S=new en(.9,.5,.05),C=new ut({color:t.secondary,metalness:.4,roughness:.6}),A=new Re(S,C);A.position.set(0,.35+j*.55,.4),A.name=`drawer_${j}`,e.add(A);const _=new en(.3,.06,.05),T=new ut({color:t.accent,metalness:.7,roughness:.3}),P=new Re(_,T);P.position.set(0,.35+j*.55,.47),P.name=`handle_${j}`,e.add(P);const M=new en(.4,.15,.02),D=new Ye({color:16777198}),R=new Re(M,D);R.position.set(0,.45+j*.55,.44),e.add(R)}for(let j=0;j<4;j++){const S=new en(.06,.06,.02),C=new Ye({color:j%2===0?t.glow:t.accent,transparent:!0,opacity:.9}),A=new Re(S,C);A.position.set(-.38,.35+j*.55,.42),A.name=`indicator_${j}`,e.add(A)}const l=new zt(.12,16,16),c=new Ye({color:ss[s.status],transparent:!0,opacity:.95}),d=new Re(l,c);d.position.set(0,2.55,0),d.name="statusLight",e.add(d);const m=new zt(.2,16,16),p=new Ye({color:ss[s.status],transparent:!0,opacity:.3}),f=new Re(m,p);f.position.set(0,2.55,0),f.name="statusGlow",e.add(f);const b=new en(1.3,.1,1.1),x=new ut({color:3816010,metalness:.5,roughness:.5}),w=new Re(b,x);w.position.y=.05,w.receiveShadow=!0,e.add(w);const k=li(Li(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 BI(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 Ye&&(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 Ye){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 FI(s){const e=new _n;e.userData.buildingId=s.id,e.userData.isBuilding=!0;const t=kd.satellite,n=s.color?new It(s.color):new It(t.primary),a=new zn(.1,.15,2,8),i=new ut({color:t.secondary,metalness:.6,roughness:.4}),o=new Re(a,i);o.position.y=1,o.castShadow=!0,e.add(o);const l=new en(.3,.2,.3),c=new Re(l,i);c.position.y=2.1,e.add(c);const d=new _n;d.position.y=2.3,d.name="dishGroup";const m=new zt(1,32,16,0,Math.PI*2,0,Math.PI/3),p=new ut({color:n,metalness:.5,roughness:.5,side:ks}),f=new Re(m,p);f.rotation.x=Math.PI/2+.3,f.name="buildingBody",d.add(f);const b=new zt(.95,32,16,0,Math.PI*2,0,Math.PI/3),x=new ut({color:t.accent,metalness:.3,roughness:.7,side:DA}),w=new Re(b,x);w.rotation.x=Math.PI/2+.3,d.add(w);const k=new zn(.03,.03,.8,8),j=new ut({color:t.secondary,metalness:.6,roughness:.4}),S=new Re(k,j);S.position.set(0,.1,.5),S.rotation.x=-.6,d.add(S);const C=new fc(.1,.2,8),A=new ut({color:t.accent,metalness:.4,roughness:.6}),_=new Re(C,A);_.position.set(0,.5,.85),_.rotation.x=Math.PI/2-.6,d.add(_);const T=new zt(.08,16,16),P=new Ye({color:t.glow,transparent:!0,opacity:.9}),M=new Re(T,P);M.position.set(0,.55,.92),M.name="signal",d.add(M),e.add(d);for(let Q=0;Q<3;Q++){const H=new tl(.2+Q*.15,.22+Q*.15,16),re=new Ye({color:t.glow,transparent:!0,opacity:.6-Q*.15,side:ks}),de=new Re(H,re);de.position.set(0,2.85+Q*.1,.92+Q*.1),de.rotation.x=-.6,de.name=`wave_${Q}`,e.add(de)}const D=new zt(.1,16,16),R=new Ye({color:ss[s.status],transparent:!0,opacity:.95}),L=new Re(D,R);L.position.set(0,.3,.5),L.name="statusLight",e.add(L);const O=new zt(.18,16,16),I=new Ye({color:ss[s.status],transparent:!0,opacity:.3}),B=new Re(O,I);B.position.set(0,.3,.5),B.name="statusGlow",e.add(B);const G=new zn(.6,.7,.15,16),$=new ut({color:t.secondary,metalness:.5,roughness:.5}),Y=new Re(G,$);Y.position.y=.075,Y.receiveShadow=!0,e.add(Y);const K=li(Li(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:L,label:K}}function $I(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 Ye&&(i.material.opacity=.15+Math.sin(e*.5+a*.3)*.1)}}function HI(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 Ye&&(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 Ye){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 UI(s){const e=new _n;e.userData.buildingId=s.id,e.userData.isBuilding=!0;const t=kd.crystal,n=s.color?new It(s.color):new It(t.primary),a=new fS(.8),i=new ut({color:n,metalness:.3,roughness:.2,transparent:!0,opacity:.85}),o=new Re(a,i);o.position.y=1.8,o.castShadow=!0,o.name="buildingBody",e.add(o);const l=new fS(.5),c=new Ye({color:t.glow,transparent:!0,opacity:.6}),d=new Re(l,c);d.position.y=1.8,d.name="crystalInner",e.add(d);for(let I=0;I<6;I++){const B=new zt(.06,8,8),G=new Ye({color:I%2===0?t.accent:t.glow,transparent:!0,opacity:.9}),$=new Re(B,G),Y=I/6*Math.PI*2;$.position.set(Math.cos(Y)*1.2,1.8+Math.sin(Y*2)*.3,Math.sin(Y)*1.2),$.name=`particle_${I}`,e.add($)}const m=new fR(1.3,1),p=new Ye({color:t.accent,wireframe:!0,transparent:!0,opacity:.4}),f=new Re(m,p);f.position.y=1.8,f.name="energyField",e.add(f);const b=new zn(.3,.5,.8,6),x=new ut({color:t.secondary,metalness:.5,roughness:.5}),w=new Re(b,x);w.position.y=.4,e.add(w);const k=new zn(.05,.05,.9,8),j=new Ye({color:t.glow,transparent:!0,opacity:.7}),S=new Re(k,j);S.position.y=1.25,S.name="energyBeam",e.add(S);const C=new zt(.1,16,16),A=new Ye({color:ss[s.status],transparent:!0,opacity:.95}),_=new Re(C,A);_.position.set(.7,.5,0),_.name="statusLight",e.add(_);const T=new zt(.18,16,16),P=new Ye({color:ss[s.status],transparent:!0,opacity:.3}),M=new Re(T,P);M.position.set(.7,.5,0),M.name="statusGlow",e.add(M);const D=new zn(.8,.9,.1,6),R=new ut({color:t.secondary,metalness:.6,roughness:.4}),L=new Re(D,R);L.position.y=.05,L.receiveShadow=!0,e.add(L);const O=li(Li(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:_,label:O}}function GI(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 Ye&&(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 Ye&&(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 Ye&&(o.material.opacity=.2+Math.sin(e*.7)*.15)}function WI(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 Ye&&(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 Ye&&(o.material.opacity=.4+Math.sin(e*4)*.3)}function qI(s){const e=new _n;e.userData.buildingId=s.id,e.userData.isBuilding=!0;const t=kd.factory,n=s.color?new It(s.color):new It(t.primary),a=new en(1.8,1.2,1.2),i=new ut({color:n,metalness:.4,roughness:.6}),o=new Re(a,i);o.position.set(0,.6,0),o.castShadow=!0,o.name="buildingBody",e.add(o);const l=new en(2,.15,1.4),c=new ut({color:t.secondary,metalness:.5,roughness:.5}),d=new Re(l,c);d.position.set(0,1.25,0),d.rotation.z=.05,e.add(d);const m=new zn(.15,.18,1.2,8),p=new ut({color:t.secondary,metalness:.5,roughness:.5}),f=new Re(m,p);f.position.set(.5,1.8,.3),e.add(f);const b=new cc(.17,.03,8,16),x=new Re(b,p);x.position.set(.5,2.4,.3),x.rotation.x=Math.PI/2,e.add(x);for(let Q=0;Q<4;Q++){const H=new zt(.08+Q*.03,8,8),re=new Ye({color:11184810,transparent:!0,opacity:.7-Q*.12}),de=new Re(H,re);de.position.set(.5,2.5+Q*.25,.3),de.name=`smoke_${Q}`,e.add(de)}for(let Q=0;Q<3;Q++){const H=new en(.25,.35,.05),re=new Ye({color:t.glow,transparent:!0,opacity:.9}),de=new Re(H,re);de.position.set(-.6+Q*.5,.7,.63),de.name=`window_${Q}`,e.add(de)}const w=new en(.4,.6,.05),k=new ut({color:t.secondary,metalness:.4,roughness:.6}),j=new Re(w,k);j.position.set(.6,.35,.63),e.add(j);const S=new en(.3,.1,1.6),C=new ut({color:t.secondary,metalness:.6,roughness:.4}),A=new Re(S,C);A.position.set(-1,.25,0),e.add(A);for(let Q=0;Q<3;Q++){const H=new en(.15,.15,.15),re=new Ye({color:Q%2===0?t.accent:t.glow}),de=new Re(H,re);de.position.set(-1,.38,-.5+Q*.4),de.name=`conveyorItem_${Q}`,e.add(de)}const _=new cc(.2,.05,6,8),T=new ut({color:t.accent,metalness:.6,roughness:.4}),P=new Re(_,T);P.position.set(-.8,.9,.63),P.name="gear1",e.add(P);const M=new Re(_.clone(),T.clone());M.position.set(-.5,1.05,.63),M.name="gear2",e.add(M);const D=new zt(.12,16,16),R=new Ye({color:ss[s.status],transparent:!0,opacity:.95}),L=new Re(D,R);L.position.set(.85,1,.65),L.name="statusLight",e.add(L);const O=new zt(.2,16,16),I=new Ye({color:ss[s.status],transparent:!0,opacity:.3}),B=new Re(O,I);B.position.set(.85,1,.65),B.name="statusGlow",e.add(B);const G=new en(2.4,.1,1.8),$=new ut({color:4868682,metalness:.4,roughness:.6}),Y=new Re(G,$);Y.position.y=.05,Y.receiveShadow=!0,e.add(Y);const K=li(Li(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:L,label:K}}function YI(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 Ye&&(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 Ye&&(o.material.opacity=Math.max(0,(.25-i*.05)*(1-c/1.5)))}}}function VI(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 Ye&&(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 Ye){const l=Math.random()>.99?.5:.8;o.material.opacity=l}}}function KI(s){const e=new _n;e.userData.buildingId=s.id,e.userData.isBuilding=!0;const t=s.color?new It(s.color):new It(2763322),n=16766720,a=new zn(1.8,2,.3,6),i=new ut({color:t,metalness:.7,roughness:.3}),o=new Re(a,i);o.position.y=.15,o.receiveShadow=!0,e.add(o);const l=new zn(1.2,1.4,.2,6),c=new ut({color:3816010,metalness:.8,roughness:.2}),d=new Re(l,c);d.position.y=.4,e.add(d);const m=new zn(.4,.6,2,6),p=new ut({color:t,metalness:.6,roughness:.4}),f=new Re(m,p);f.position.y=1.5,f.castShadow=!0,f.receiveShadow=!0,f.name="buildingBody",e.add(f);const b=new zn(.5,.4,.3,6),x=new ut({color:n,metalness:.9,roughness:.1,emissive:new It(n),emissiveIntensity:.3}),w=new Re(b,x);w.position.y=2.65,w.name="crownBase",e.add(w);for(let $=0;$<5;$++){const Y=$/5*Math.PI*2,K=new fc(.08,.4,4),Q=new Re(K,x);Q.position.set(Math.cos(Y)*.35,2.95,Math.sin(Y)*.35),Q.name=`crownSpike_${$}`,e.add(Q)}const k=new cc(.8,.03,8,32),j=new Ye({color:n,transparent:!0,opacity:.6}),S=new Re(k,j);S.position.y=1.2,S.rotation.x=Math.PI/2,S.name="holoRing1",e.add(S);const C=new cc(1.1,.02,8,32),A=new Ye({color:4915102,transparent:!0,opacity:.5}),_=new Re(C,A);_.position.y=1.5,_.rotation.x=Math.PI/2,_.name="holoRing2",e.add(_);const T=new cc(1.4,.02,8,32),P=new Ye({color:4890367,transparent:!0,opacity:.4}),M=new Re(T,P);M.position.y=1.8,M.rotation.x=Math.PI/2,M.name="holoRing3",e.add(M);for(let $=0;$<6;$++){const Y=$/6*Math.PI*2,K=new _n,Q=new en(.3,.25,.2),H=new ut({color:3816010,metalness:.6,roughness:.4}),re=new Re(Q,H);re.position.y=.45,K.add(re);const de=new cr(.25,.15),F=new Ye({color:4890367,transparent:!0,opacity:.8}),V=new Re(de,F);V.position.y=.52,V.position.z=.11,V.rotation.x=-.3,V.name=`consoleScreen_${$}`,K.add(V),K.position.set(Math.cos(Y)*1.5,0,Math.sin(Y)*1.5),K.rotation.y=-Y+Math.PI,e.add(K)}const D=new zt(.15,16,16),R=new Ye({color:ss[s.status],transparent:!0,opacity:.95}),L=new Re(D,R);L.position.set(0,3.3,0),L.name="statusLight",e.add(L);const O=new zt(.25,16,16),I=new Ye({color:ss[s.status],transparent:!0,opacity:.3}),B=new Re(O,I);B.position.set(0,3.3,0),B.name="statusGlow",e.add(B);for(let $=0;$<6;$++){const Y=$/6*Math.PI*2+Math.PI/6,K=new zn(.06,.08,1,6),Q=new ut({color:n,metalness:.8,roughness:.2,emissive:new It(n),emissiveIntensity:.2}),H=new Re(K,Q);H.position.set(Math.cos(Y)*1.85,.8,Math.sin(Y)*1.85),H.name=`energyPillar_${$}`,e.add(H);const re=new zt(.08,8,8),de=new Ye({color:n,transparent:!0,opacity:.8}),F=new Re(re,de);F.position.set(Math.cos(Y)*1.85,1.35,Math.sin(Y)*1.85),F.name=`pillarLight_${$}`,e.add(F)}const G=li(Li(s));return G.position.set(0,3.8,0),G.name="buildingLabel",e.add(G),e.position.set(s.position.x,0,s.position.z),{group:e,statusLight:L,label:G}}function XI(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 Ye&&(n.material.opacity=.3+Math.sin(e*.5)*.1)),a&&(a.rotation.z-=t*.2,a.material instanceof Ye&&(a.material.opacity=.25+Math.sin(e*.7+1)*.1)),i&&(i.rotation.z+=t*.1,i.material instanceof Ye&&(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 Ye&&(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 Ye&&(l.material.opacity=.4+Math.sin(e*.3+o*.3)*.1)}}function ZI(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 Ye&&(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 Ye&&(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 Ye&&(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 Ye){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 Ye){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 ut&&(o.material.emissiveIntensity=.4+Math.sin(e*2)*.2)}function QI(s){switch(s.style||"server-rack"){case"tower":return CI(s);case"dome":return MI(s);case"pyramid":return _I(s);case"desktop":return PI(s);case"filing-cabinet":return II(s);case"satellite":return FI(s);case"crystal":return UI(s);case"factory":return qI(s);case"command-center":return KI(s);case"server-rack":default:return kI(s)}}function JI(s,e,t,n){switch(e.style||"server-rack"){case"server-rack":SI(s,t);break;case"desktop":LI(s,t);break;case"filing-cabinet":BI(s,t);break;case"satellite":$I(s,t,n);break;case"crystal":GI(s,t,n);break;case"factory":YI(s,t,n);break;case"tower":NI(s,t,n);break;case"dome":TI(s,t,n);break;case"pyramid":DI(s,t);break;case"command-center":XI(s,t,n);break}}function eB(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 Ye&&(i.material.opacity=.3*o),a){case"server-rack":jI(s);break;case"tower":AI(s,t,n);break;case"dome":EI(s,t,n);break;case"pyramid":RI(s,t);break;case"desktop":OI(s,t);break;case"filing-cabinet":zI(s,t);break;case"satellite":HI(s,t,n);break;case"crystal":WI(s,t,n);break;case"factory":VI(s,t,n);break;case"command-center":ZI(s,t,n);break}}function tB(s,e){const t=s.group.getObjectByName("statusGlow"),n=Math.sin(e*8)*.5+.5;t&&t.material instanceof Ye&&(t.material.opacity=.5*n)}function nB(s,e){const t=s.group.getObjectByName("statusGlow"),n=Math.sin(e*2)*.5+.5;t&&t.material instanceof Ye&&(t.material.opacity=.4*n)}class sB{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 Ye&&(n.material.opacity=.3*e),t.group.traverse(a=>{if(a instanceof Re&&a.material instanceof ut){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=QI(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=ss[e.status],l=t.group.getObjectByName("statusLight");l&&l.material instanceof Ye&&l.material.color.setHex(o);const c=t.group.getObjectByName("statusGlow");c&&c.material instanceof Ye&&c.material.color.setHex(o),((b=t.label.material.map)==null?void 0:b.image)&&wI(t,e.name);const p=e.gitChangesCount||0,f=t.group.getObjectByName("gitIndicator");if(p>0){if(f)f.userData.gitCount!==p&&(vI(f,p),f.userData.gitCount=p);else{const x=wM(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 ut&&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 ut&&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 ut&&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 ut&&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&&(JI(a,i,this.animationTime,e),i.status==="running"?eB(a,i,this.animationTime,e):i.status==="starting"||i.status==="stopping"?tB(a,this.animationTime):i.status==="error"&&nB(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 Fa;c.setAttribute("position",new ti(l,3)),c.setDrawRange(0,0),this.bossSubordinateMaterial=new Ho({color:16766720,transparent:!0,opacity:.4}),this.bossSubordinateLines=new cx(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 ut&&(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 Re&&(t.geometry.dispose(),Array.isArray(t.material)?t.material.forEach(n=>n.dispose()):t.material.dispose()),t instanceof Bn){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 ad=class ad{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",Vn.SIT);U(this,"workingAnimation",Vn.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 Cp().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=ad.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:ad.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:DA});a.add(new Re(i,o)),a.add(new dx(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,x=Math.max(l?1.35:1.1,Math.min(l?1.65:1.35,p)),w=typeof d.userData.aspectRatio=="number"?d.userData.aspectRatio:1024/4096;d.scale.set(x*o,x*w*o,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 xt(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:ec.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 Op="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 fm(){return typeof window<"u"?window.__tidePersistedScene??null:null}function jM(){return typeof window<"u"?window.__tidePersistedCanvas??null:null}function LB(){return typeof window<"u"?window.__tideWsConnected??!1:!1}function cd(s){typeof window<"u"&&(window.__tidePersistedScene=s)}function Ip(s){typeof window<"u"&&(window.__tidePersistedCanvas=s)}function CM(s){typeof window<"u"&&(window.__tideWsConnected=s)}function OB(s){typeof window<"u"&&(window.__tideIsPageUnloading=s)}function IB(){sessionStorage.setItem(Op,"true")}function Vh(s){OB(!0),sessionStorage.removeItem(Op),uM(),TL(),window.__tideScene&&(window.__tideScene=null);const e=fm();e?(console.log("[App] Calling persistedScene.dispose()"),e.dispose(),cd(null)):console.log("[App] No persistedScene to dispose"),Ip(null),CM(!1);const t=document.getElementById("battlefield");t&&t.remove();const n=document.getElementById("app");n&&(n.innerHTML="")}function BB(){var a,i;if(window.__tideAppInitialized)return;if(window.__tideAppInitialized=!0,sessionStorage.getItem(Op)==="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=fm();if(e){console.log("[App] Cleaning up stale persistedScene");try{e.dispose()}catch{}cd(null)}const t=document.getElementById("battlefield"),n=jM();t&&t!==n&&t.remove(),sessionStorage.removeItem(Op)}function zB(){typeof window>"u"||(BB(),window.addEventListener("pageshow",s=>{s.persisted&&(console.log("[App] Page restored from bfcache - cleaning up"),Vh(),window.location.reload())}),window.onunload=()=>Vh(),window.onbeforeunload=s=>{Vh()},window.addEventListener("pagehide",s=>{Vh(`pagehide (persisted=${s.persisted})`)}))}zB();const Bj={showTrees:!0,showBushes:!0,showHouse:!0,showLamps:!0,showGrass:!0,showClouds:!0,fogDensity:1,floorStyle:"metal",brightness:1,skyColor:null},zj={saturation:2,roughness:.5,metalness:-1,emissiveBoost:0,envMapIntensity:1,wireframe:!1,colorMode:"normal"},Fj={idleAnimation:"sit",workingAnimation:"sprint"},FB=0;function NM(){const s={characterScale:2,indicatorScale:1,gridVisible:!1,timeMode:"day",terrain:Bj,modelStyle:zj,animations:Fj,fpsLimit:FB},e=Ja(mt.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:{...Bj,...e.terrain},modelStyle:{...zj,...e.modelStyle},animations:{...Fj,...e.animations},fpsLimit:e.fpsLimit??s.fpsLimit}:s}function $B(s){Ci(mt.CONFIG,s)}typeof window<"u"&&!window.__tideHmrRefreshListeners&&(window.__tideHmrRefreshListeners=new Set);function AM(){console.log("[Tide HMR] Manual scene refresh triggered");const s=fm();if(s){try{s.dispose()}catch(t){console.warn("[Tide HMR] Error disposing scene:",t)}cd(null)}Ip(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=AM);function HB({canvasRef:s,selectionBoxRef:e,showToast:t,showAgentNotification:n,toolboxModal:a,contextMenu:i,setHoveredAgentPopup:o,setBuildingPopup:l,getBuildingPopup:c,openBuildingModal:d,openPM2LogsModal:m,openBossLogsModal:p,openDatabasePanel:f}){const b=y.useRef(null),x=y.useRef(null),w=y.useRef(null);return y.useEffect(()=>{if(!s.current||!e.current)return;let k=!1;const j=fm(),C=jM()===s.current;function A(){var _,T,P,M,D,R,L,O;(_=b.current)==null||_.setOnToast(t),(T=b.current)==null||T.setOnBuildingClick((I,B)=>{z.selectBuilding(I);const G=z.getState().buildings.get(I);(G==null?void 0:G.type)==="folder"&&G.folderPath?z.openFileExplorer(G.folderPath):(G==null?void 0:G.type)==="server"||(G==null?void 0:G.type)==="boss"||(G==null?void 0:G.type)==="database"?(x.current&&clearTimeout(x.current),x.current=setTimeout(()=>{l({buildingId:I,screenPos:B,fromClick:!0}),x.current=null},150)):d(I)}),(P=b.current)==null||P.setOnContextMenu((I,B,G)=>{i.open(I,B,G)}),(M=b.current)==null||M.setOnAgentHover(()=>{}),(D=b.current)==null||D.setOnBuildingHover((I,B)=>{const G=c();if(I&&B){const $=z.getState().buildings.get(I);(($==null?void 0:$.type)==="server"||($==null?void 0:$.type)==="boss"||($==null?void 0:$.type)==="database")&&!(G!=null&&G.fromClick)&&l({buildingId:I,screenPos:B,fromClick:!1})}else G!=null&&G.fromClick||l(null)}),(R=b.current)==null||R.setOnGroundClick(()=>{l(null)}),(L=b.current)==null||L.setOnAreaDoubleClick(I=>{z.selectArea(I),a.open()}),(O=b.current)==null||O.setOnBuildingDoubleClick(I=>{var G;x.current&&(clearTimeout(x.current),x.current=null),l(null);const B=z.getState().buildings.get(I);(B==null?void 0:B.type)==="server"&&((G=B.pm2)!=null&&G.enabled)?m==null||m(I):(B==null?void 0:B.type)==="boss"?p==null||p(I):(B==null?void 0:B.type)==="database"?f==null||f(I):(B==null?void 0:B.type)==="folder"&&B.folderPath?z.openFileExplorer(B.folderPath):d(I)})}if(j&&C){b.current=j,console.log("[Tide] Reusing existing scene (StrictMode remount)");const _=z.getState();j.syncAreas(),j.syncBuildings(),_.agents.size>0&&(console.log("[Tide] Re-syncing agents from store after remount:",_.agents.size),j.syncAgents(Array.from(_.agents.values()))),A()}else{const _=s.current,T=e.current,P=()=>{if(k){console.log("[Tide] Effect cleaned up before scene init, skipping");return}if(!_.isConnected||!T.isConnected){console.warn("[Tide] Canvas disconnected before initialization");return}(!_.clientWidth||!_.clientHeight)&&(console.log("[Tide] Canvas has no CSS dimensions, using window fallback"),_.style.width="100%",_.style.height="100%",_.offsetHeight),(!_.clientWidth||!_.clientHeight)&&(_.width=window.innerWidth,_.height=window.innerHeight),IB();try{const M=new PB(_,T);b.current=M,cd(M),Ip(_);const D=NM();M.setCharacterScale(D.characterScale),M.setIndicatorScale(D.indicatorScale),M.setGridVisible(D.gridVisible),M.setTimeMode(D.timeMode),M.setTerrainConfig(D.terrain),M.setFloorStyle(D.terrain.floorStyle,!0),M.setAgentModelStyle(D.modelStyle),M.setIdleAnimation(D.animations.idleAnimation),M.setWorkingAnimation(D.animations.workingAnimation),M.setFpsLimit(D.fpsLimit),M.syncAreas(),M.syncBuildings(),M.loadCharacterModels().then(()=>{console.log("[Tide] Character models ready");const R=z.getState();R.customAgentClasses.size>0&&(console.log("[Tide] Applying custom classes from store:",R.customAgentClasses.size),M.setCustomAgentClasses(R.customAgentClasses)),R.agents.size>0&&(console.log("[Tide] Syncing agents from store:",R.agents.size),M.syncAgents(Array.from(R.agents.values()))),M.upgradeAgentModels()}).catch(R=>{console.warn("[Tide] Some models failed to load, using fallback:",R)}),A()}catch(M){console.error("[Tide] Failed to initialize 3D scene:",M)}};w.current=requestAnimationFrame(P)}return rM({onAgentCreated:_=>{var T,P;(T=b.current)==null||T.addAgent(_),(P=window.__spawnModalSuccess)==null||P.call(window)},onAgentUpdated:(_,T)=>{var P;(P=b.current)==null||P.updateAgent(_,T)},onAgentDeleted:_=>{var T;(T=b.current)==null||T.removeAgent(_)},onAgentsSync:_=>{var T;(T=b.current)==null||T.syncAgents(_)},onAreasSync:()=>{var T,P;(T=b.current)==null||T.syncAreas();const _=Array.from(z.getState().agents.values());(P=b.current)==null||P.syncAgents(_)},onSpawnError:()=>{var _;(_=window.__spawnModalError)==null||_.call(window)},onSpawnSuccess:()=>{var _;(_=window.__spawnModalSuccess)==null||_.call(window)},onDirectoryNotFound:_=>{var T;(T=window.__spawnModalDirNotFound)==null||T.call(window,_)},onToolUse:(_,T,P)=>{var M;(M=b.current)==null||M.showToolBubble(_,T,P)},onDelegation:(_,T)=>{var P;(P=b.current)==null||P.showDelegationEffect(_,T)},onCustomClassesSync:_=>{var T,P;(T=b.current)==null||T.setCustomAgentClasses(_),(P=b.current)==null||P.upgradeAgentModels()},onBuildingUpdated:_=>{var T;(T=b.current)==null||T.updateBuilding(_)},onSubagentStarted:_=>{var T;(T=b.current)==null||T.addSubagentEffect(_.id,_.parentAgentId,_.name,_.subagentType)},onSubagentCompleted:_=>{var M;const T=z.getSubagent(_)||z.getSubagentByToolUseId(_),P=(T==null?void 0:T.id)||_;(M=b.current)==null||M.completeSubagentEffect(P),setTimeout(()=>{var D;(D=b.current)==null||D.removeSubagentEffect(P)},3e4)}}),()=>{k=!0,w.current!==null&&(cancelAnimationFrame(w.current),w.current=null),z.getState().viewMode!=="3d"&&b.current&&(console.log("[Tide] 3D canvas unmounted - disposing scene to free memory"),EL(),b.current.dispose(),b.current=null,cd(null),Ip(null))}},[s.current,e.current]),b}function UB({showToast:s,showAgentNotification:e}){const t=y.useRef(!1);y.useEffect(()=>{if(t.current||LB())return;t.current=!0,rM({onToast:s,onReconnect:()=>{z.triggerReconnect()},onAgentNotification:i=>{e(i)}}),ld(),CM(!0),wL();let n;SL(i=>{i.type==="agent_notification"&&typeof i.agentId=="string"&&nM(i.agentId)}).then(i=>{n=i});const a=()=>{console.log("[Tide] App resumed from background, reconnecting..."),setTimeout(()=>ld(),100)};return window.addEventListener("tideAppResume",a),()=>{window.removeEventListener("tideAppResume",a),n==null||n()}},[s,e])}function GB(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 WB(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 qB(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 YB(s,e){y.useEffect(()=>{var t;(t=s.current)==null||t.highlightArea(e)},[s,e])}function VB(s,e){y.useEffect(()=>{var t;(t=s.current)==null||t.setPowerSaving(e)},[s,e])}function KB({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 R,L,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(yt(p,w)){if(my()){p.preventDefault();return}const B=z.getState();if(B.activeTool==="rectangle"||B.activeTool==="circle"){(R=s.current)==null||R.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(),(L=s.current)==null||L.refreshSelectionVisuals())}for(let B=1;B<=9;B++){const G=f.find($=>$.id===`select-agent-${B}`);if(yt(p,G)){p.preventDefault();const $=z.getState(),Y=B-1,K=Array.from($.agents.keys());Y<K.length&&(z.selectAgent(K[Y]),(O=s.current)==null||O.refreshSelectionVisuals());return}}const k=f.find(B=>B.id==="spawn-agent");if(yt(p,k)){p.preventDefault(),e.open();return}const j=f.find(B=>B.id==="toggle-commander-tab");if(yt(p,j)&&!x){p.preventDefault(),t.toggle();return}const S=f.find(B=>B.id==="toggle-commander");if(yt(p,S)){p.preventDefault(),t.toggle();return}const C=f.find(B=>B.id==="toggle-file-explorer");if(yt(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 Y=Array.from(B.areas.values()).filter(K=>K.directories&&K.directories.length>0);Y.length>0&&n.open(Y[0].id)}else{const Y=Array.from(B.areas.values()).filter(K=>K.directories&&K.directories.length>0);Y.length>0&&n.open(Y[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"),G=z.getState();if(B){const $=G.buildings.get(B);if(($==null?void 0:$.type)==="database"){l(B);return}}for(const[$,Y]of G.buildings)if(Y.type==="database"){l($);return}return}const A=f.find(B=>B.id==="toggle-spotlight");if(yt(p,A)||p.altKey&&!p.ctrlKey&&!p.metaKey&&p.code==="KeyP"){console.log("[useKeyboardShortcuts] Spotlight shortcut matched!",{spotlightShortcut:A,altKey:p.altKey,code:p.code}),p.preventDefault(),a.toggle();return}const _=f.find(B=>B.id==="toggle-2d-view");if(yt(p,_)){p.preventDefault();const B=z.getState().viewMode,G=B==="3d"?"2d":B==="2d"?"dashboard":"3d";z.setViewMode(G);return}const T=f.find(B=>B.id==="next-working-agent"),P=f.find(B=>B.id==="prev-working-agent");if((yt(p,T)||yt(p,P))&&!x){const B=z.getState();if(B.terminalOpen)return;const G=Array.from(B.agents.values());let $=G.filter(H=>B.agentsWithUnseenOutput.has(H.id));if($.length===0&&($=G.filter(H=>H.status==="working")),$.length===0)return;p.preventDefault();const Y=B.selectedAgentIds.size===1?Array.from(B.selectedAgentIds)[0]:null,K=Y?$.findIndex(H=>H.id===Y):-1;let Q;yt(p,T)?Q=K===-1?0:(K+1)%$.length:Q=K===-1?$.length-1:(K-1+$.length)%$.length,z.selectAgent($[Q].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((yt(p,M)||yt(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 XB(){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",my()||(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),my()||(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 cb="agent-order-change";function MM(s){const e=y.useMemo(()=>new Set(s.map(c=>c.id)),[s]),[t,n]=y.useState(()=>Ja(mt.AGENT_ORDER,[]));y.useEffect(()=>{const c=d=>{n(d.detail)};return window.addEventListener(cb,c),()=>{window.removeEventListener(cb,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),Ci(mt.AGENT_ORDER,c),window.dispatchEvent(new CustomEvent(cb,{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([]),Ci(mt.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 jx="deivid11/tide-commander",ZB=`https://api.github.com/repos/${jx}/releases/latest`,QB=`https://api.github.com/repos/${jx}/releases?per_page=3`,JB=3600*1e3,$j="app_update_dismissed_version",Hj="0.78.0";function ez(){var m;const[s,e]=y.useState({isChecking:!1,updateAvailable:!1,updateInfo:null,recentReleases:[],error:null,currentVersion:Hj}),t=((m=ka==null?void 0:ka.getPlatform)==null?void 0:m.call(ka))==="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 j=b[k]||0,S=x[k]||0;if(j>S)return 1;if(j<S)return-1}return 0},i=async p=>{var b;if(ka&&tj&&((b=ka.isNativePlatform)==null?void 0:b.call(ka))===!0){const x=await tj.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(ZB),i(QB)]);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(_=>({version:_.tag_name,name:_.name,publishedAt:_.published_at,releaseUrl:_.html_url})));const j=localStorage.getItem($j);if(!p&&j===w)return e(_=>({..._,isChecking:!1,updateAvailable:!1,recentReleases:k})),null;if(!(a(w,Hj)>0))return e(_=>({..._,isChecking:!1,updateAvailable:!1,recentReleases:k})),null;const C=x.assets.find(_=>_.name.endsWith(".apk")&&_.content_type==="application/vnd.android.package-archive"),A={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(_=>({..._,isChecking:!1,updateAvailable:!0,updateInfo:A,recentReleases:k})),A}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($j,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/${jx}/releases`,"_blank")},[s.updateInfo]);return y.useEffect(()=>{if(!t)return;const p=setTimeout(()=>{o()},5e3),f=setInterval(()=>{o()},JB);return()=>{clearTimeout(p),clearInterval(f)}},[t,o]),{...s,isAndroid:t,checkForUpdate:o,downloadAndInstall:l,dismissUpdate:c,openReleasePage:d}}function Ts(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 tz=3e4;function nz(){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 ft(at(`/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 ft(at(`/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:j,count:S}of b)w[j]!==S&&(w[j]=S,k=!0);k&&z.updateAreaLocal(f,{directoryGitCounts:w})}}catch{}};return e(),s.current=setInterval(e,tz),()=>{s.current&&(clearInterval(s.current),s.current=null)}},[])}const Uj={historyLimit:500,hideCost:!0,showFPS:!1,powerSaving:!1,customAgentNames:[],experimental2DView:!1,experimentalVoiceAssistant:!1,experimentalTTS:!1,experimentalEchoPrompt:!1,externalEditorCommand:""},Bp=90,ub=["simple","chat","advanced"],Gj=55,Wj=20,qj=85,sz=200,az=12e4,iz=5,za=new Map;function rz(s){const e=za.get(s);e&&(za.delete(s),za.set(s,e))}function oz(){for(;za.size>iz;){const s=za.keys().next().value;if(s!==void 0)za.delete(s);else break}}function lz(s){za.delete(s)}function cz(s){return s.trim().replace(/\r\n/g,`
|
|
148
|
+
`,side:DA});a.add(new Re(i,o)),a.add(new dx(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,x=Math.max(l?1.35:1.1,Math.min(l?1.65:1.35,p)),w=typeof d.userData.aspectRatio=="number"?d.userData.aspectRatio:1024/4096;d.scale.set(x*o,x*w*o,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 xt(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:ec.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 Op="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 fm(){return typeof window<"u"?window.__tidePersistedScene??null:null}function jM(){return typeof window<"u"?window.__tidePersistedCanvas??null:null}function LB(){return typeof window<"u"?window.__tideWsConnected??!1:!1}function cd(s){typeof window<"u"&&(window.__tidePersistedScene=s)}function Ip(s){typeof window<"u"&&(window.__tidePersistedCanvas=s)}function CM(s){typeof window<"u"&&(window.__tideWsConnected=s)}function OB(s){typeof window<"u"&&(window.__tideIsPageUnloading=s)}function IB(){sessionStorage.setItem(Op,"true")}function Vh(s){OB(!0),sessionStorage.removeItem(Op),uM(),TL(),window.__tideScene&&(window.__tideScene=null);const e=fm();e?(console.log("[App] Calling persistedScene.dispose()"),e.dispose(),cd(null)):console.log("[App] No persistedScene to dispose"),Ip(null),CM(!1);const t=document.getElementById("battlefield");t&&t.remove();const n=document.getElementById("app");n&&(n.innerHTML="")}function BB(){var a,i;if(window.__tideAppInitialized)return;if(window.__tideAppInitialized=!0,sessionStorage.getItem(Op)==="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=fm();if(e){console.log("[App] Cleaning up stale persistedScene");try{e.dispose()}catch{}cd(null)}const t=document.getElementById("battlefield"),n=jM();t&&t!==n&&t.remove(),sessionStorage.removeItem(Op)}function zB(){typeof window>"u"||(BB(),window.addEventListener("pageshow",s=>{s.persisted&&(console.log("[App] Page restored from bfcache - cleaning up"),Vh(),window.location.reload())}),window.onunload=()=>Vh(),window.onbeforeunload=s=>{Vh()},window.addEventListener("pagehide",s=>{Vh(`pagehide (persisted=${s.persisted})`)}))}zB();const Bj={showTrees:!0,showBushes:!0,showHouse:!0,showLamps:!0,showGrass:!0,showClouds:!0,fogDensity:1,floorStyle:"metal",brightness:1,skyColor:null},zj={saturation:2,roughness:.5,metalness:-1,emissiveBoost:0,envMapIntensity:1,wireframe:!1,colorMode:"normal"},Fj={idleAnimation:"sit",workingAnimation:"sprint"},FB=0;function NM(){const s={characterScale:2,indicatorScale:1,gridVisible:!1,timeMode:"day",terrain:Bj,modelStyle:zj,animations:Fj,fpsLimit:FB},e=Ja(mt.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:{...Bj,...e.terrain},modelStyle:{...zj,...e.modelStyle},animations:{...Fj,...e.animations},fpsLimit:e.fpsLimit??s.fpsLimit}:s}function $B(s){Ci(mt.CONFIG,s)}typeof window<"u"&&!window.__tideHmrRefreshListeners&&(window.__tideHmrRefreshListeners=new Set);function AM(){console.log("[Tide HMR] Manual scene refresh triggered");const s=fm();if(s){try{s.dispose()}catch(t){console.warn("[Tide HMR] Error disposing scene:",t)}cd(null)}Ip(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=AM);function HB({canvasRef:s,selectionBoxRef:e,showToast:t,showAgentNotification:n,toolboxModal:a,contextMenu:i,setHoveredAgentPopup:o,setBuildingPopup:l,getBuildingPopup:c,openBuildingModal:d,openPM2LogsModal:m,openBossLogsModal:p,openDatabasePanel:f}){const b=y.useRef(null),x=y.useRef(null),w=y.useRef(null);return y.useEffect(()=>{if(!s.current||!e.current)return;let k=!1;const j=fm(),C=jM()===s.current;function A(){var _,T,P,M,D,R,L,O;(_=b.current)==null||_.setOnToast(t),(T=b.current)==null||T.setOnBuildingClick((I,B)=>{z.selectBuilding(I);const G=z.getState().buildings.get(I);(G==null?void 0:G.type)==="folder"&&G.folderPath?z.openFileExplorer(G.folderPath):(G==null?void 0:G.type)==="server"||(G==null?void 0:G.type)==="boss"||(G==null?void 0:G.type)==="database"?(x.current&&clearTimeout(x.current),x.current=setTimeout(()=>{l({buildingId:I,screenPos:B,fromClick:!0}),x.current=null},150)):d(I)}),(P=b.current)==null||P.setOnContextMenu((I,B,G)=>{i.open(I,B,G)}),(M=b.current)==null||M.setOnAgentHover(()=>{}),(D=b.current)==null||D.setOnBuildingHover((I,B)=>{const G=c();if(I&&B){const $=z.getState().buildings.get(I);(($==null?void 0:$.type)==="server"||($==null?void 0:$.type)==="boss"||($==null?void 0:$.type)==="database")&&!(G!=null&&G.fromClick)&&l({buildingId:I,screenPos:B,fromClick:!1})}else G!=null&&G.fromClick||l(null)}),(R=b.current)==null||R.setOnGroundClick(()=>{l(null)}),(L=b.current)==null||L.setOnAreaDoubleClick(I=>{z.selectArea(I),a.open()}),(O=b.current)==null||O.setOnBuildingDoubleClick(I=>{var G;x.current&&(clearTimeout(x.current),x.current=null),l(null);const B=z.getState().buildings.get(I);(B==null?void 0:B.type)==="server"&&((G=B.pm2)!=null&&G.enabled)?m==null||m(I):(B==null?void 0:B.type)==="boss"?p==null||p(I):(B==null?void 0:B.type)==="database"?f==null||f(I):(B==null?void 0:B.type)==="folder"&&B.folderPath?z.openFileExplorer(B.folderPath):d(I)})}if(j&&C){b.current=j,console.log("[Tide] Reusing existing scene (StrictMode remount)");const _=z.getState();j.syncAreas(),j.syncBuildings(),_.agents.size>0&&(console.log("[Tide] Re-syncing agents from store after remount:",_.agents.size),j.syncAgents(Array.from(_.agents.values()))),A()}else{const _=s.current,T=e.current,P=()=>{if(k){console.log("[Tide] Effect cleaned up before scene init, skipping");return}if(!_.isConnected||!T.isConnected){console.warn("[Tide] Canvas disconnected before initialization");return}(!_.clientWidth||!_.clientHeight)&&(console.log("[Tide] Canvas has no CSS dimensions, using window fallback"),_.style.width="100%",_.style.height="100%",_.offsetHeight),(!_.clientWidth||!_.clientHeight)&&(_.width=window.innerWidth,_.height=window.innerHeight),IB();try{const M=new PB(_,T);b.current=M,cd(M),Ip(_);const D=NM();M.setCharacterScale(D.characterScale),M.setIndicatorScale(D.indicatorScale),M.setGridVisible(D.gridVisible),M.setTimeMode(D.timeMode),M.setTerrainConfig(D.terrain),M.setFloorStyle(D.terrain.floorStyle,!0),M.setAgentModelStyle(D.modelStyle),M.setIdleAnimation(D.animations.idleAnimation),M.setWorkingAnimation(D.animations.workingAnimation),M.setFpsLimit(D.fpsLimit),M.syncAreas(),M.syncBuildings(),M.loadCharacterModels().then(()=>{console.log("[Tide] Character models ready");const R=z.getState();R.customAgentClasses.size>0&&(console.log("[Tide] Applying custom classes from store:",R.customAgentClasses.size),M.setCustomAgentClasses(R.customAgentClasses)),R.agents.size>0&&(console.log("[Tide] Syncing agents from store:",R.agents.size),M.syncAgents(Array.from(R.agents.values()))),M.upgradeAgentModels()}).catch(R=>{console.warn("[Tide] Some models failed to load, using fallback:",R)}),A()}catch(M){console.error("[Tide] Failed to initialize 3D scene:",M)}};w.current=requestAnimationFrame(P)}return rM({onAgentCreated:_=>{var T,P;(T=b.current)==null||T.addAgent(_),(P=window.__spawnModalSuccess)==null||P.call(window)},onAgentUpdated:(_,T)=>{var P;(P=b.current)==null||P.updateAgent(_,T)},onAgentDeleted:_=>{var T;(T=b.current)==null||T.removeAgent(_)},onAgentsSync:_=>{var T;(T=b.current)==null||T.syncAgents(_)},onAreasSync:()=>{var T,P;(T=b.current)==null||T.syncAreas();const _=Array.from(z.getState().agents.values());(P=b.current)==null||P.syncAgents(_)},onSpawnError:()=>{var _;(_=window.__spawnModalError)==null||_.call(window)},onSpawnSuccess:()=>{var _;(_=window.__spawnModalSuccess)==null||_.call(window)},onDirectoryNotFound:_=>{var T;(T=window.__spawnModalDirNotFound)==null||T.call(window,_)},onToolUse:(_,T,P)=>{var M;(M=b.current)==null||M.showToolBubble(_,T,P)},onDelegation:(_,T)=>{var P;(P=b.current)==null||P.showDelegationEffect(_,T)},onCustomClassesSync:_=>{var T,P;(T=b.current)==null||T.setCustomAgentClasses(_),(P=b.current)==null||P.upgradeAgentModels()},onBuildingUpdated:_=>{var T;(T=b.current)==null||T.updateBuilding(_)},onSubagentStarted:_=>{var T;(T=b.current)==null||T.addSubagentEffect(_.id,_.parentAgentId,_.name,_.subagentType)},onSubagentCompleted:_=>{var M;const T=z.getSubagent(_)||z.getSubagentByToolUseId(_),P=(T==null?void 0:T.id)||_;(M=b.current)==null||M.completeSubagentEffect(P),setTimeout(()=>{var D;(D=b.current)==null||D.removeSubagentEffect(P)},3e4)}}),()=>{k=!0,w.current!==null&&(cancelAnimationFrame(w.current),w.current=null),z.getState().viewMode!=="3d"&&b.current&&(console.log("[Tide] 3D canvas unmounted - disposing scene to free memory"),EL(),b.current.dispose(),b.current=null,cd(null),Ip(null))}},[s.current,e.current]),b}function UB({showToast:s,showAgentNotification:e}){const t=y.useRef(!1);y.useEffect(()=>{if(t.current||LB())return;t.current=!0,rM({onToast:s,onReconnect:()=>{z.triggerReconnect()},onAgentNotification:i=>{e(i)}}),ld(),CM(!0),wL();let n;SL(i=>{i.type==="agent_notification"&&typeof i.agentId=="string"&&nM(i.agentId)}).then(i=>{n=i});const a=()=>{console.log("[Tide] App resumed from background, reconnecting..."),setTimeout(()=>ld(),100)};return window.addEventListener("tideAppResume",a),()=>{window.removeEventListener("tideAppResume",a),n==null||n()}},[s,e])}function GB(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 WB(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 qB(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 YB(s,e){y.useEffect(()=>{var t;(t=s.current)==null||t.highlightArea(e)},[s,e])}function VB(s,e){y.useEffect(()=>{var t;(t=s.current)==null||t.setPowerSaving(e)},[s,e])}function KB({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 R,L,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(yt(p,w)){if(my()){p.preventDefault();return}const B=z.getState();if(B.activeTool==="rectangle"||B.activeTool==="circle"){(R=s.current)==null||R.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(),(L=s.current)==null||L.refreshSelectionVisuals())}for(let B=1;B<=9;B++){const G=f.find($=>$.id===`select-agent-${B}`);if(yt(p,G)){p.preventDefault();const $=z.getState(),Y=B-1,K=Array.from($.agents.keys());Y<K.length&&(z.selectAgent(K[Y]),(O=s.current)==null||O.refreshSelectionVisuals());return}}const k=f.find(B=>B.id==="spawn-agent");if(yt(p,k)){p.preventDefault(),e.open();return}const j=f.find(B=>B.id==="toggle-commander-tab");if(yt(p,j)&&!x){p.preventDefault(),t.toggle();return}const S=f.find(B=>B.id==="toggle-commander");if(yt(p,S)){p.preventDefault(),t.toggle();return}const C=f.find(B=>B.id==="toggle-file-explorer");if(yt(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 Y=Array.from(B.areas.values()).filter(K=>K.directories&&K.directories.length>0);Y.length>0&&n.open(Y[0].id)}else{const Y=Array.from(B.areas.values()).filter(K=>K.directories&&K.directories.length>0);Y.length>0&&n.open(Y[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"),G=z.getState();if(B){const $=G.buildings.get(B);if(($==null?void 0:$.type)==="database"){l(B);return}}for(const[$,Y]of G.buildings)if(Y.type==="database"){l($);return}return}const A=f.find(B=>B.id==="toggle-spotlight");if(yt(p,A)||p.altKey&&!p.ctrlKey&&!p.metaKey&&p.code==="KeyP"){console.log("[useKeyboardShortcuts] Spotlight shortcut matched!",{spotlightShortcut:A,altKey:p.altKey,code:p.code}),p.preventDefault(),a.toggle();return}const _=f.find(B=>B.id==="toggle-2d-view");if(yt(p,_)){p.preventDefault();const B=z.getState().viewMode,G=B==="3d"?"2d":B==="2d"?"dashboard":"3d";z.setViewMode(G);return}const T=f.find(B=>B.id==="next-working-agent"),P=f.find(B=>B.id==="prev-working-agent");if((yt(p,T)||yt(p,P))&&!x){const B=z.getState();if(B.terminalOpen)return;const G=Array.from(B.agents.values());let $=G.filter(H=>B.agentsWithUnseenOutput.has(H.id));if($.length===0&&($=G.filter(H=>H.status==="working")),$.length===0)return;p.preventDefault();const Y=B.selectedAgentIds.size===1?Array.from(B.selectedAgentIds)[0]:null,K=Y?$.findIndex(H=>H.id===Y):-1;let Q;yt(p,T)?Q=K===-1?0:(K+1)%$.length:Q=K===-1?$.length-1:(K-1+$.length)%$.length,z.selectAgent($[Q].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((yt(p,M)||yt(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 XB(){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",my()||(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),my()||(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 cb="agent-order-change";function MM(s){const e=y.useMemo(()=>new Set(s.map(c=>c.id)),[s]),[t,n]=y.useState(()=>Ja(mt.AGENT_ORDER,[]));y.useEffect(()=>{const c=d=>{n(d.detail)};return window.addEventListener(cb,c),()=>{window.removeEventListener(cb,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),Ci(mt.AGENT_ORDER,c),window.dispatchEvent(new CustomEvent(cb,{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([]),Ci(mt.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 jx="deivid11/tide-commander",ZB=`https://api.github.com/repos/${jx}/releases/latest`,QB=`https://api.github.com/repos/${jx}/releases?per_page=3`,JB=3600*1e3,$j="app_update_dismissed_version",Hj="0.78.1";function ez(){var m;const[s,e]=y.useState({isChecking:!1,updateAvailable:!1,updateInfo:null,recentReleases:[],error:null,currentVersion:Hj}),t=((m=ka==null?void 0:ka.getPlatform)==null?void 0:m.call(ka))==="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 j=b[k]||0,S=x[k]||0;if(j>S)return 1;if(j<S)return-1}return 0},i=async p=>{var b;if(ka&&tj&&((b=ka.isNativePlatform)==null?void 0:b.call(ka))===!0){const x=await tj.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(ZB),i(QB)]);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(_=>({version:_.tag_name,name:_.name,publishedAt:_.published_at,releaseUrl:_.html_url})));const j=localStorage.getItem($j);if(!p&&j===w)return e(_=>({..._,isChecking:!1,updateAvailable:!1,recentReleases:k})),null;if(!(a(w,Hj)>0))return e(_=>({..._,isChecking:!1,updateAvailable:!1,recentReleases:k})),null;const C=x.assets.find(_=>_.name.endsWith(".apk")&&_.content_type==="application/vnd.android.package-archive"),A={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(_=>({..._,isChecking:!1,updateAvailable:!0,updateInfo:A,recentReleases:k})),A}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($j,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/${jx}/releases`,"_blank")},[s.updateInfo]);return y.useEffect(()=>{if(!t)return;const p=setTimeout(()=>{o()},5e3),f=setInterval(()=>{o()},JB);return()=>{clearTimeout(p),clearInterval(f)}},[t,o]),{...s,isAndroid:t,checkForUpdate:o,downloadAndInstall:l,dismissUpdate:c,openReleasePage:d}}function Ts(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 tz=3e4;function nz(){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 ft(at(`/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 ft(at(`/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:j,count:S}of b)w[j]!==S&&(w[j]=S,k=!0);k&&z.updateAreaLocal(f,{directoryGitCounts:w})}}catch{}};return e(),s.current=setInterval(e,tz),()=>{s.current&&(clearInterval(s.current),s.current=null)}},[])}const Uj={historyLimit:500,hideCost:!0,showFPS:!1,powerSaving:!1,customAgentNames:[],experimental2DView:!1,experimentalVoiceAssistant:!1,experimentalTTS:!1,experimentalEchoPrompt:!1,externalEditorCommand:""},Bp=90,ub=["simple","chat","advanced"],Gj=55,Wj=20,qj=85,sz=200,az=12e4,iz=5,za=new Map;function rz(s){const e=za.get(s);e&&(za.delete(s),za.set(s,e))}function oz(){for(;za.size>iz;){const s=za.keys().next().value;if(s!==void 0)za.delete(s);else break}}function lz(s){za.delete(s)}function cz(s){return s.trim().replace(/\r\n/g,`
|
|
149
149
|
`)}function My(s,e){return`${s}:${cz(e)}`}function Yj(s,e,t,n){if(s.uuid&&e.has(s.uuid))return!1;const a=s.isUserPrompt?"user":"assistant",i=My(a,s.text),o=s.timestamp||0,l=t.get(i);return l!==void 0&&Math.abs(o-l)<=az?!1:o>n}function TM({selectedAgentId:s,hasSessionId:e,reconnectCount:t,lastPrompts:n,outputScrollRef:a}){const[i,o]=y.useState([]),[l,c]=y.useState(!1),[d,m]=y.useState(!1),[p,f]=y.useState(0),[b,x]=y.useState(!1),[w,k]=y.useState(!1),[j,S]=y.useState(0),C=y.useRef(!0),A=y.useRef(0),_=y.useRef(0),T=y.useRef(!1),P=y.useRef(!1),M=y.useRef(null),D=y.useRef(!1),R=y.useRef(null),L=y.useRef(null);y.useEffect(()=>(C.current=!0,()=>{C.current=!1}),[]),y.useEffect(()=>{if(!s||!e){o([]),_.current=0,k(!1),P.current=!1,S(0),c(!1),m(!1),f(F=>F+1),D.current=!1,R.current=null;return}const G=`${s}:${t}`;if(R.current===G)return;const $=M.current!==null&&M.current!==s,Y=t>0,K=$||Y,Q=!$&&!D.current&&e;M.current=s,D.current=e,R.current=G;let H;if(Y){const F=z.getOutputs(s);F.length>0&&(H=F.map(V=>({...V})))}L.current&&(clearTimeout(L.current),L.current=null),Y&&za.delete(s),A.current+=1;const re=A.current;m(!0);const de=za.get(s);de?(rz(s),o(de.messages),_.current=de.messages.length,k(de.hasMore),P.current=de.hasMore,S(de.totalCount)):(o([]),_.current=0,k(!1),P.current=!1,S(0)),Q||(L.current=setTimeout(()=>{c(!0)},150)),ft(at(`/api/agents/${s}/history?limit=${Bp}&offset=0`)).then(F=>{if(!F.ok)throw new Error(`HTTP ${F.status}: ${F.statusText}`);return F.json()}).then(F=>{if(re!==A.current)return;const V=Array.isArray(F.messages)?F.messages:[];o(V),_.current=V.length;const J=F.hasMore||!1;if(k(J),P.current=J,S(F.totalCount||0),za.set(s,{messages:V,hasMore:J,totalCount:F.totalCount||0}),oz(),H&&H.length>0){const ie=V.length>0?Math.max(...V.map(se=>se.timestamp?new Date(se.timestamp).getTime():0)):0,Z=new Set(V.map(se=>se.uuid).filter(se=>typeof se=="string"&&se.length>0)),X=new Map;for(const se of V){if(se.type!=="user"&&se.type!=="assistant")continue;const pe=My(se.type,se.content),Se=se.timestamp?new Date(se.timestamp).getTime():0,Te=X.get(pe)??0;Se>Te&&X.set(pe,Se)}const q=H.filter(se=>Yj(se,Z,X,ie));z.clearOutputs(s);for(const se of q)z.addOutput(s,se)}else if(V.length>0){const ie=Math.max(...V.map(pe=>pe.timestamp?new Date(pe.timestamp).getTime():0)),Z=new Set(V.map(pe=>pe.uuid).filter(pe=>typeof pe=="string"&&pe.length>0)),X=new Map;for(const pe of V){if(pe.type!=="user"&&pe.type!=="assistant")continue;const Se=My(pe.type,pe.content),Te=pe.timestamp?new Date(pe.timestamp).getTime():0,xe=X.get(Se)??0;Te>xe&&X.set(Se,Te)}const q=z.getOutputs(s),se=q.filter(pe=>{const Se=Yj(pe,Z,X,ie);return Se||console.warn(`[HISTORY-DEDUP] Removing live output: uuid=${pe.uuid||"none"} ts=${pe.timestamp} lastHistTs=${ie} text="${pe.text.slice(0,80)}"`),Se});if(q.length!==se.length){console.warn(`[HISTORY-DEDUP] Cleared ${q.length-se.length}/${q.length} overlapping outputs for agent ${s}`),z.clearOutputs(s);for(const pe of se)z.addOutput(s,pe)}}if(!n.get(s)){for(let ie=V.length-1;ie>=0;ie--)if(V[ie].type==="user"){z.setLastPrompt(s,V[ie].content);break}}}).catch(F=>{if(console.error("Failed to load history:",F),o([]),_.current=0,k(!1),P.current=!1,S(0),K&&H&&H.length>0){z.clearOutputs(s);for(const V of H)z.addOutput(s,V)}}).finally(()=>{C.current&&re===A.current&&(L.current&&(clearTimeout(L.current),L.current=null),c(!1),m(!1),f(F=>F+1))})},[s,e,t]);const O=y.useCallback(async()=>{if(!s||T.current||!P.current)return;const G=a.current;if(!G){console.warn("loadMoreHistory: outputScrollRef not connected");return}const $=G.scrollHeight-G.scrollTop;T.current=!0,x(!0);const Y=_.current;try{const Q=await(await ft(at(`/api/agents/${s}/history?limit=${Bp}&offset=${Y}`))).json();if(Q.messages&&Q.messages.length>0){if(!C.current)return;o(re=>{const de=[...Q.messages,...re];return _.current=de.length,de});const H=Q.hasMore||!1;P.current=H,k(H),requestAnimationFrame(()=>{requestAnimationFrame(()=>{C.current&&(a.current&&(a.current.scrollTop=a.current.scrollHeight-$),T.current=!1,x(!1))})})}else{if(!C.current)return;T.current=!1,x(!1)}}catch(K){if(console.error("Failed to load more history:",K),!C.current)return;T.current=!1,x(!1)}},[s,a]),I=y.useCallback(G=>{if(!a.current||G.current)return;const{scrollTop:$}=a.current;!T.current&&P.current&&$<sz&&O()},[O,a]),B=y.useCallback(()=>{o([]),_.current=0,s&&za.delete(s)},[s]);return{history:i,loadingHistory:l,fetchingHistory:d,historyLoadVersion:p,loadingMore:b,hasMore:w,totalCount:j,isMountedRef:C,loadMoreHistory:O,handleScroll:I,clearHistory:B,hasCachedHistory:y.useCallback(G=>za.has(G),[])}}function Mu(...s){}function uz(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)&&Mu("[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&&Mu(`[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),Mu(`[Store] Agent ${i.name} completed work - marked as unseen`),d=!0))}),d&&a&&a(),t(),c&&Mu(`[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)}),lz(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,j){Mu("[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:j?`${j.length} chars`:void 0});const S=c?{x:c.x,y:0,z:c.z}:void 0,C={type:"spawn_agent",payload:{name:i,class:o,cwd:l,position:S,sessionId:d,useChrome:m,permissionMode:p,initialSkillIds:f,provider:b,codexConfig:x,codexModel:w,model:k,customInstructions:j}},A=n();if(!A){console.error("[Store] sendMessage is not defined! WebSocket may not be connected");return}A(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=new Map(l.agentOutputs);c.delete(i),l.agentOutputs=c}),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 ft(at("/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 Vj=200,dz=1024*1024,Kj=64*1024,Xj=`
|
|
150
150
|
|
|
151
151
|
[output truncated]`;function ud(s){return s.length*2}function hz(s,e){if(ud(s)<=e)return s;const t=ud(Xj),n=Math.max(0,e-t),a=Math.floor(n/2);return`${s.slice(0,a)}${Xj}`}function Zj(s){return ud(s.text)<=Kj?s:{...s,text:hz(s.text,Kj)}}function Qj(s){let e=s;e.length>Vj&&(e=e.slice(-Vj));let t=e.reduce((n,a)=>n+ud(a.text),0);for(;e.length>1&&t>dz;)t-=ud(e[0].text),e=e.slice(1);return e}function pz(s,e,t,n){return{addOutput(a,i){const o=n();e(l=>{const c=l.agentOutputs.get(a)||[],d=Zj(i);if(d.uuid&&c.some(b=>b.uuid===d.uuid))return;const m=Qj([...c,d]);od.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(Zj);return l.sort((c,d)=>c.timestamp-d.timestamp),l=Qj(l),e(c=>{const d=new Map(c.agentOutputs);d.set(a,l),c.agentOutputs=d}),t(),l}}}function mz(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 fz(s,e,t,n){const a=()=>{var o;const i=Array.from(s().areas.values());(o=n())==null||o({type:"sync_areas",payload:i})};return{setActiveTool(i){e(o=>{o.activeTool=i,i!=="select"&&(o.selectedAreaId=null)}),t()},selectArea(i){e(o=>{o.selectedAreaId=i}),t()},addArea(i){if(i.zIndex===void 0||i.zIndex===null){const o=Array.from(s().areas.values()),l=o.length===0?-1:Math.max(...o.map(c=>c.zIndex??0));i.zIndex=l+1}e(o=>{o.areas.set(i.id,i)}),a(),t()},updateArea(i,o){s().areas.get(i)&&(e(d=>{Object.assign(d.areas.get(i),o)}),a(),t())},updateAreaLocal(i,o){s().areas.get(i)&&(e(d=>{Object.assign(d.areas.get(i),o)}),t())},deleteArea(i){e(o=>{o.areas.delete(i),o.selectedAreaId===i&&(o.selectedAreaId=null)}),a(),t()},assignAgentToArea(i,o){const c=s().areas.get(o);c&&!c.assignedAgentIds.includes(i)&&(e(d=>{for(const m of d.areas.values()){const p=m.assignedAgentIds.indexOf(i);p!==-1&&m.assignedAgentIds.splice(p,1)}d.areas.get(o).assignedAgentIds.push(i)}),a(),t())},unassignAgentFromArea(i,o){const c=s().areas.get(o);if(c){const d=c.assignedAgentIds.indexOf(i);d!==-1&&(e(m=>{m.areas.get(o).assignedAgentIds.splice(d,1)}),a(),t())}},addDirectoryToArea(i,o){const c=s().areas.get(i);c&&!c.directories.includes(o)&&(e(d=>{d.areas.get(i).directories.push(o)}),a(),t())},removeDirectoryFromArea(i,o){const c=s().areas.get(i);if(c){const d=c.directories.indexOf(o);d!==-1&&(e(m=>{m.areas.get(i).directories.splice(d,1)}),a(),t())}},getAreaDirectories(i){const o=s().areas.get(i);return(o==null?void 0:o.directories)||[]},isPositionInArea(i,o){if(o.type==="rectangle"&&o.width&&o.height){const l=o.width/2,c=o.height/2;return i.x>=o.center.x-l&&i.x<=o.center.x+l&&i.z>=o.center.z-c&&i.z<=o.center.z+c}else if(o.type==="circle"&&o.radius){const l=i.x-o.center.x,c=i.z-o.center.z;return l*l+c*c<=o.radius*o.radius}return!1},getAreaForAgent(i){const o=s(),l=o.agents.get(i);if(!l)return null;for(const c of o.areas.values())if(this.isPositionInArea({x:l.position.x,z:l.position.z},c))return c;return null},setAreasFromServer(i){e(o=>{const l=new Map;for(let c=0;c<i.length;c++){const d=i[c];d.directories||(d.directories=[]),(d.zIndex===void 0||d.zIndex===null)&&(d.zIndex=c),d.archived===void 0&&(d.archived=!1),l.set(d.id,d)}o.areas=l}),t()},getAreasInZOrder(){return Array.from(s().areas.values()).sort((o,l)=>(o.zIndex??0)-(l.zIndex??0))},getNextZIndex(){const i=Array.from(s().areas.values());return i.length===0?0:Math.max(...i.map(l=>l.zIndex??0))+1},bringAreaToFront(i){const o=s(),l=o.areas.get(i);if(!l)return;const c=Array.from(o.areas.values()),d=c.length===0?-1:Math.max(...c.map(b=>b.zIndex??0)),m=d+1,p=l.zIndex??0,f=c.filter(b=>(b.zIndex??0)===d);p===d&&f.length===1||(e(b=>{b.areas.get(i).zIndex=m}),a(),t())},sendAreaToBack(i){const o=s(),l=o.areas.get(i);if(!l)return;const c=Array.from(o.areas.values()),d=Math.min(...c.map(f=>f.zIndex??0)),m=l.zIndex??0,p=c.filter(f=>(f.zIndex??0)===d);m===d&&p.length===1||(e(f=>{for(const b of f.areas.values())b.id!==i&&(b.zIndex=(b.zIndex??0)+1);f.areas.get(i).zIndex=0}),a(),t())},setAreaZIndex(i,o){s().areas.get(i)&&(e(d=>{d.areas.get(i).zIndex=o}),a(),t())},archiveArea(i,o){const c=s().areas.get(i);if(!(!c||c.archived)){if(o)for(const d of c.assignedAgentIds)o(d);e(d=>{const m=d.areas.get(i);m.archived=!0,m.archivedAt=Date.now(),m.originalCenter={...m.center},d.selectedAreaId===i&&(d.selectedAreaId=null)}),a(),t()}},restoreArchivedArea(i,o){const l=s(),c=l.areas.get(i);if(!c||!c.archived)return;const d=c.center,m=o||c.originalCenter||c.center,p=m.x-d.x,f=m.z-d.z,b=Array.from(l.areas.values()),w=(b.length===0?-1:Math.max(...b.map(k=>k.zIndex??0)))+1;e(k=>{const j=k.areas.get(i);if(j.archived=!1,j.archivedAt=void 0,j.center=m,j.zIndex=w,p!==0||f!==0)for(const S of j.assignedAgentIds){const C=k.agents.get(S);C&&(C.position={x:C.position.x+p,y:C.position.y,z:C.position.z+f})}}),a(),t()},getArchivedAreas(){return Array.from(s().areas.values()).filter(i=>i.archived===!0)},getVisibleAreas(){return Array.from(s().areas.values()).filter(i=>!i.archived)},isAgentInArchivedArea(i){const o=s();for(const l of o.areas.values())if(l.archived&&l.assignedAgentIds.includes(i))return!0;return!1}}}function gz(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(`
|
|
@@ -230,7 +230,7 @@ ${oe}`:ve=oe}z.sendCommand(t,ve),i(""),l(!1),k(new Map),m([]),j(),window.innerWi
|
|
|
230
230
|
`),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(`
|
|
231
231
|
`)[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:Rp(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,j)=>{var C,A;const S=k.toolInput&&(k.toolInput.file_path||((C=k.toolInput.command)==null?void 0:C.slice(0,40))||k.toolInput.pattern||k.toolInput.description||((A=k.toolInput.prompt)==null?void 0:A.slice(0,50)))||"";return r.jsxs("div",{className:"aop-timeline-entry",children:[r.jsx("span",{className:"tl-time",children:Rp(k.timestamp)}),r.jsx("span",{className:"tl-icon",children:es[k.toolName]||es.default}),r.jsx("span",{className:"tl-tool",children:k.toolName}),S&&r.jsx("span",{className:"tl-param",children:S})]},`${k.timestamp}-${j}`)})]}),n.length===0&&a.length===0&&r.jsx("div",{className:"aop-no-activity",children:c("terminal:overview.noToolActivity")})]})]})}function zH({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}=Ue(["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),j=w%60;return`${k}m ${j}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(FH,{output:s.output,agentId:s.agentId,maxHeight:200})})]})]})}function FH({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=ev({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(lv,{output:o,agentId:e},`progress-${l}`))})}const $H={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"}},vE={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"}},HH={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"}},UH={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"}},GH={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"}},WH={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"}},qH={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"}},YH={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"}},VH={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"}},KH={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"}},XH={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"}},ZH={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"}},QH={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"}},JH={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"}},eU={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"}},wa=[eU,XH,$H,vE,HH,UH,GH,WH,qH,YH,VH,KH,ZH,QH,JH];function nd(s){return wa.find(e=>e.id===s)||vE}const tU="classic";function Yp(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 cv(){try{const s=localStorage.getItem("tide-theme");if(s&&wa.some(e=>e.id===s))return s}catch{}return tU}function nU(){const s=cv(),e=nd(s);Yp(e)}const sU=y.memo(function(){const{t:e}=Ue(["terminal"]),[t,n]=y.useState(!1),[a,i]=y.useState(()=>cv()),[o,l]=y.useState(-1),c=y.useRef(null),d=y.useRef(null),m=wa.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)%wa.length:(m-1+wa.length)%wa.length,j=wa[k],S=nd(j.id);Yp(S),i(j.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 j,S;k.key==="Escape"?(n(!1),(j=d.current)==null||j.focus()):k.key==="ArrowDown"?(k.preventDefault(),l(C=>(C+1)%wa.length)):k.key==="ArrowUp"?(k.preventDefault(),l(C=>(C-1+wa.length)%wa.length)):k.key==="Enter"&&o>=0&&(k.preventDefault(),b(wa[o].id),(S=d.current)==null||S.focus())};return document.addEventListener("keydown",w),()=>document.removeEventListener("keydown",w)},[t,o]);const b=w=>{const k=nd(w);Yp(k),i(w),n(!1)},x=nd(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:wa.map((w,k)=>r.jsxs("button",{className:`theme-selector-option ${w.id===a?"active":""} ${k===o?"highlighted":""}`,onClick:j=>{j.stopPropagation(),b(w.id)},onMouseDown:j=>j.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))})]})]})}),D1=1e4,aU=3e4,iU=12e4;function Db(s){const e=nv(s);return sv(e.userMessage).userMessage.trim().replace(/\r\n/g,`
|
|
232
232
|
`)}function tp(s){return s.trim().replace(/\r\n/g,`
|
|
233
|
-
`)}function rU(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 oU=y.memo(function({onSaveSnapshot:e}={}){var is,Bs,Wa,ca,qs;const{t}=Ue(["terminal","common"]),n=ui(),a=bm(),i=DM(),o=Tx(),l=Rx(),c=RM(),d=_x(),m=Dx(),p=sF(),f=!!p,b=y.useMemo(()=>p?{id:p.agentId,name:p.agentName,class:p.agentClass,status:"idle",provider:"claude",position:{x:0,y:0,z:0},cwd:p.cwd,permissionMode:"interactive",tokensUsed:0,contextUsed:0,contextLimit:2e5,taskCount:0,createdAt:p.createdAt,lastActivity:p.createdAt}:null,[p]),x=Array.from(a),k=x.length===1?x[0]:null,S=(Nx(k)||null)??(f?b:null),C=k??(f?(p==null?void 0:p.agentId)??null:null),A=!!(S!=null&&S.sessionId)&&!f,{terminalHeight:_,terminalRef:T,handleResizeStart:P}=O9(),M=L9(),D=Ax(C),R=y.useMemo(()=>f&&p?p.outputs.map(Ze=>({text:Ze.text||"",timestamp:Ze.timestamp,isStreaming:!1,isUserPrompt:!1})):D,[f,p,D]),L=y.useRef(null),O=y.useRef(null),I=y.useRef(null),[B,G]=y.useState(()=>{const Ze=Ms(mt.VIEW_MODE);return Ze==="simple"||Ze==="chat"||Ze==="advanced"?Ze:Ms(mt.ADVANCED_VIEW)==="true"?"advanced":"simple"}),[$,Y]=y.useState(null),[K,Q]=y.useState(null),[H,re]=y.useState(null),[de,F]=y.useState(null),[V,J]=y.useState(!1);Sn("guake-image-modal",$!==null,()=>Y(null)),Sn("guake-bash-modal",K!==null,()=>Q(null)),Sn("guake-response-modal",de!==null,()=>F(null)),Sn("guake-context-confirm",H!==null,()=>re(null)),Sn("guake-agent-info",V,()=>J(!1));const[ie,Z]=y.useState(!1),[X,q]=y.useState(()=>ws.isEnabled()),se=cF(),pe=y.useCallback(Ze=>z.setOverviewPanelOpen(Ze),[]),[Se,Te]=y.useState(!1),[xe,$e]=y.useState(null),Pe=y.useRef(null),ve=y.useRef(null),[ee,fe]=y.useState(!1),[le,oe]=y.useState(!1),[ae,we]=y.useState(!1),he=i&&S!==null,Ee=TM({selectedAgentId:C,hasSessionId:A,reconnectCount:l,lastPrompts:o,outputScrollRef:L}),ce=B9({selectedAgentId:C,isOpen:he}),ne=I9({agents:n,selectedAgentId:C,isOpen:he,loadingHistory:Ee.fetchingHistory,hasModalOpen:!!($||K||de||d||m),outputRef:L}),ge=QT({selectedAgentId:k}),ue=Lz(),Me=y.useMemo(()=>f||!C?[]:Array.from(ue.values()).filter(Ze=>Ze.agentId===C&&Ze.status==="pending"),[f,C,ue]),Ce=(S==null?void 0:S.class)==="boss"||(S==null?void 0:S.isBoss),We=Vz(!f&&Ce?C:null),nt=Kz(f?null:C),Je=lF(f?null:C);y.useEffect(()=>{ie&&!X&&(q(!0),ws.setEnabled(!0))},[ie,X]),y.useEffect(()=>{he||J(!1)},[he]),y.useEffect(()=>{const Ze=S==null?void 0:S.status;if(Pe.current==="working"&&Ze==="idle"){ve.current&&clearTimeout(ve.current);const me=C?o.get(C):void 0;$e(me!=null&&me.timestamp?Date.now()-me.timestamp:null),Te(!0),ve.current=setTimeout(()=>{Te(!1),$e(null),ve.current=null},4e3)}else Ze==="working"&&(ve.current&&(clearTimeout(ve.current),ve.current=null),Te(!1),$e(null));return Pe.current=Ze||null,()=>{ve.current&&clearTimeout(ve.current)}},[S==null?void 0:S.status]);const ct=y.useMemo(()=>{const{history:Ze}=Ee,dt=new Map;for(const ze of Ze)ze.type==="tool_result"&&ze.toolUseId&&dt.set(ze.toolUseId,ze.content);return(ze=>ze.map(Xe=>{if(Xe.type==="tool_use"&&Xe.toolName==="Bash"&&Xe.toolUseId){const ht=dt.get(Xe.toolUseId);let lt;try{lt=(Xe.toolInput||(Xe.content?JSON.parse(Xe.content):{})).command}catch{}return{...Xe,_bashOutput:ht,_bashCommand:lt}}return Xe}))(Ze)},[Ee.history,B]),et=JT({outputs:R,viewMode:B}),gt=y.useMemo(()=>{const Ze=[],dt=new Set,me=new Set;let ze=null,Xe=0;for(const ht of ct){if(ht.type==="assistant"){const Gt=ht.uuid?`uuid:${ht.uuid}:${tp(ht.content)}`:`sig:${ht.timestamp}:${tp(ht.content)}`;if(dt.has(Gt))continue;dt.add(Gt),Ze.push(ht);continue}if(ht.type!=="user"){Ze.push(ht);continue}const lt=Db(ht.content),Nt=ht.uuid?`uuid:${ht.uuid}:${lt}`:null;if(Nt&&me.has(Nt))continue;const Dt=ht.timestamp?new Date(ht.timestamp).getTime():0;ze===lt&&Math.abs(Dt-Xe)<=D1||(Ze.push(ht),Nt&&me.add(Nt),ze=lt,Xe=Dt)}return Ze},[ct]),Mt=y.useMemo(()=>{const Ze=new Map,dt=new Set,me=new Map;for(const lt of gt){const Nt=lt.timestamp?new Date(lt.timestamp).getTime():0;if(lt.type==="user"){const Pn=Db(lt.content),Ln=Ze.get(Pn)??0;Nt>Ln&&Ze.set(Pn,Nt);continue}if(lt.type!=="assistant")continue;lt.uuid&&dt.add(lt.uuid);const Dt=tp(lt.content),Gt=me.get(Dt)??0;Nt>Gt&&me.set(Dt,Nt)}const ze=[];let Xe=null,ht=0;for(const lt of et){if(!lt.isUserPrompt){if(!lt.isStreaming&&!rU(lt.text)){if(lt.uuid&&dt.has(lt.uuid))continue;const Pn=tp(lt.text),Ln=lt.timestamp||0,Un=me.get(Pn);if(Un&&Math.abs(Ln-Un)<=iU)continue}ze.push(lt);continue}const Nt=Db(lt.text),Dt=lt.timestamp||0,Gt=Ze.get(Nt);Gt&&Dt>=Gt&&Dt-Gt<=aU||Xe===Nt&&Math.abs(Dt-ht)<=D1||(ze.push(lt),Xe=Nt,ht=Dt)}return ze},[et,gt]),Ft=gt.length+Mt.length,An=$9({totalMessages:Ft,isOpen:he,hasModalOpen:!!($||K||de||d),scrollContainerRef:L,selectedAgentId:C,inputRef:O,textareaRef:I,useTextarea:ge.useTextarea});y.useEffect(()=>{if(!(!(K!=null&&K.isLive)||!K.command)){for(const Ze of Mt)if(Ze._bashCommand===K.command&&Ze._bashOutput){Q({command:K.command,output:Ze._bashOutput,isLive:!1});return}}},[K,Mt]);const Ne=y.useCallback((Ze,dt)=>{Y({url:Ze,name:dt})},[]),be=y.useCallback((Ze,dt)=>{const me=Nd(Ze,S==null?void 0:S.cwd),ze=me.line?{...dt||{},targetLine:me.line}:dt;z.setFileViewerPath(me.path,ze,S==null?void 0:S.cwd)},[S==null?void 0:S.cwd]),De=y.useCallback((Ze,dt)=>{Q({command:Ze,output:dt,isLive:dt==="Running..."})},[]),it=y.useCallback(Ze=>{F(Ze)},[]),ot=y.useCallback(()=>{J(Ze=>!Ze)},[]),[$t,tn]=y.useState(!0),Ut=y.useRef(!1),st=y.useRef(!1),Et=y.useCallback(()=>{st.current||(Ut.current=!0,tn(!1))},[]),un=y.useCallback(()=>oe(!1),[]);y.useEffect(()=>{tn(!0),Ut.current=!1,st.current=!0;const Ze=setTimeout(()=>{st.current=!1},3e3);return()=>clearTimeout(Ze)},[C]);const Pt=y.useRef(Ee.handleScroll);Pt.current=Ee.handleScroll;const gs=y.useCallback(()=>{if(!L.current||M.keyboardScrollLockRef.current)return;const{scrollTop:Ze,scrollHeight:dt,clientHeight:me}=L.current,ze=dt-Ze-me<150;st.current||(Ut.current=!ze,ze&&tn(!0)),Pt.current(M.keyboardScrollLockRef)},[L,M.keyboardScrollLockRef]),Dn=D.length>0&&((Bs=(is=D[D.length-1])==null?void 0:is.text)==null?void 0:Bs.length)||0;y.useEffect(()=>{M.keyboardScrollLockRef.current||Ut.current||requestAnimationFrame(()=>{if(L.current){const{scrollTop:Ze,scrollHeight:dt,clientHeight:me}=L.current;dt-Ze-me<150&&(L.current.scrollTop=dt)}})},[D.length,Dn,M.keyboardScrollLockRef,L]);const Zn=y.useRef(null);y.useLayoutEffect(()=>{const Ze=Zn.current;Ze!==null&&Ze!==k?(k&&Ee.hasCachedHistory(k)||(we(!0),fe(!1)),z.getState().currentSnapshot&&z.setCurrentSnapshot(null)):k||fe(!1),Zn.current=k},[k]),y.useEffect(()=>{if(!ae||Ee.fetchingHistory)return;const Ze=requestAnimationFrame(()=>{L.current&&(L.current.scrollTop=L.current.scrollHeight),we(!1)});return()=>cancelAnimationFrame(Ze)},[ae,Ee.fetchingHistory,Ee.historyLoadVersion]);const as=y.useRef(!1);y.useEffect(()=>{he&&k&&z.clearUnseenForAgent(k)},[he,k]),y.useEffect(()=>{as.current=!0,oe(!0)},[C,l]),y.useEffect(()=>{Ee.fetchingHistory&&(as.current=!0,oe(!0))},[Ee.fetchingHistory]),y.useEffect(()=>{if(!le||!he||Ee.fetchingHistory)return;const Ze=L.current;if(!Ze)return;let dt=null;const me=performance.now();let ze=0,Xe=-1;const ht=()=>{const{scrollTop:Nt,scrollHeight:Dt,clientHeight:Gt}=Ze;return Dt-Nt-Gt<=2},lt=()=>{const Nt=performance.now(),Dt=Ze.scrollHeight,Gt=Math.abs(Dt-Xe)<=1,Pn=ht();if(Gt&&Pn?ze+=1:ze=0,Xe=Dt,ze>=8){oe(!1),dt=null;return}if(Nt-me>8e3){oe(!1),dt=null;return}dt=requestAnimationFrame(lt)};return dt=requestAnimationFrame(lt),()=>{dt!==null&&cancelAnimationFrame(dt)}},[le,he,Ee.fetchingHistory,Ee.historyLoadVersion]);const _s=y.useRef(!1);y.useEffect(()=>{_s.current&&!le&&as.current&&(as.current=!1,fe(!0)),_s.current=le},[le]),y.useEffect(()=>{if(!he||!as.current||le||Ee.fetchingHistory)return;const Ze=requestAnimationFrame(()=>{as.current&&(as.current=!1,fe(!0))});return()=>cancelAnimationFrame(Ze)},[Ee.historyLoadVersion,he,le,Ee.fetchingHistory]),y.useEffect(()=>{const Ze=dt=>{if(dt.key==="`"&&!dt.ctrlKey&&!dt.altKey&&S){const me=dt.target;me.tagName!=="INPUT"&&me.tagName!=="TEXTAREA"&&(dt.preventDefault(),z.toggleTerminal())}};return document.addEventListener("keydown",Ze),()=>document.removeEventListener("keydown",Ze)},[S]),y.useEffect(()=>{const Ze=dt=>{dt.key==="Escape"&&(d?(dt.stopImmediatePropagation(),z.clearFileViewerPath()):m?(dt.stopImmediatePropagation(),z.closeContextModal()):de?(dt.stopImmediatePropagation(),F(null)):K?(dt.stopImmediatePropagation(),Q(null)):$?(dt.stopImmediatePropagation(),Y(null)):ce.searchMode&&(dt.stopImmediatePropagation(),ce.closeSearch()))};return document.addEventListener("keydown",Ze,!0),()=>document.removeEventListener("keydown",Ze,!0)},[$,K,de,ce,d,m]);const ds=y.useRef(he),mn=y.useRef(!1);y.useEffect(()=>{ds.current=he},[he]),y.useEffect(()=>{if(window.innerWidth<=768)return;const dt=Xe=>{var Dt;if(!(Xe instanceof Element))return!1;const ht=(Dt=T.current)==null?void 0:Dt.contains(Xe),lt=Xe.closest(".agent-bar"),Nt=!!Xe.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!!ht||!!lt||Nt},me=Xe=>{if(!ds.current){mn.current=!1;return}mn.current=!dt(Xe.target)},ze=Xe=>{mn.current&&(dt(Xe.target)||z.setTerminalOpen(!1),mn.current=!1)};return document.addEventListener("mousedown",me,!0),document.addEventListener("mouseup",ze,!0),()=>{document.removeEventListener("mousedown",me,!0),document.removeEventListener("mouseup",ze,!0)}},[]),y.useEffect(()=>{const Ze=()=>{document.hidden&&M.cleanup()};return document.addEventListener("visibilitychange",Ze),()=>document.removeEventListener("visibilitychange",Ze)},[M]);const Rn=typeof window<"u"&&window.innerWidth<=768;return S?C?r.jsxs("div",{ref:T,className:`guake-terminal ${he?"open":"collapsed"} ${ie&&he?"with-debug-panel":""} ${se&&he?"with-overview-panel":""}`,style:{"--terminal-height":`${_}%`},children:[!f&&ie&&he&&C&&r.jsx(RH,{agentId:C,onClose:()=>Z(!1)}),!f&&se&&he&&C&&r.jsx(IH,{activeAgentId:C,onClose:()=>pe(!1),onSelectAgent:Ze=>{z.selectAgent(Ze)}}),r.jsxs("div",{className:"guake-content",children:[r.jsx(Z9,{selectedAgent:S,selectedAgentId:C,sortedAgents:ne.sortedAgents,swipeOffset:ne.swipeOffset,viewMode:B,setViewMode:G,searchMode:ce.searchMode,toggleSearch:ce.toggleSearch,closeSearch:ce.closeSearch,debugPanelOpen:ie,setDebugPanelOpen:Z,debuggerEnabled:X,setDebuggerEnabled:q,overviewPanelOpen:se,setOverviewPanelOpen:pe,agentInfoOpen:V,onToggleAgentInfo:ot,outputsLength:gt.length+Mt.length,setContextConfirm:re,headerRef:ne.headerRef,onSaveSnapshot:f?void 0:e,isSnapshotView:f}),ce.searchMode&&r.jsx(Q9,{searchInputRef:ce.searchInputRef,searchQuery:ce.searchQuery,setSearchQuery:ce.setSearchQuery,handleSearch:ce.handleSearch,closeSearch:ce.closeSearch,searchLoading:ce.searchLoading,searchResultsCount:ce.searchResults.length}),r.jsxs("div",{className:`guake-swipe-container ${ne.swipeAnimationClass}`,style:ne.swipeOffset!==0?{transform:`translateX(${ne.swipeOffset*40}%)`}:void 0,children:[ne.sortedAgents.length>1&&ne.swipeOffset!==0&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:`swipe-indicator left ${ne.swipeOffset>.3?"visible":""}`,children:[r.jsx("span",{className:"indicator-icon",children:"←"}),r.jsx("span",{className:"indicator-name",children:(Wa=ne.prevAgent)==null?void 0:Wa.name})]}),r.jsxs("div",{className:`swipe-indicator right ${ne.swipeOffset<-.3?"visible":""}`,children:[r.jsx("span",{className:"indicator-name",children:(ca=ne.nextAgent)==null?void 0:ca.name}),r.jsx("span",{className:"indicator-icon",children:"→"})]})]}),ne.sortedAgents.length>1&&ne.sortedAgents.length<=8&&ne.swipeOffset!==0&&r.jsx("div",{className:`swipe-dots ${Math.abs(ne.swipeOffset)>.1?"visible":""}`,children:ne.sortedAgents.map((Ze,dt)=>r.jsx("div",{className:`swipe-dot ${dt===ne.currentAgentIndex?"active":""}`},Ze.id))}),r.jsx("div",{className:"guake-output",ref:L,onScroll:gs,children:ce.searchMode&&ce.searchResults.length>0?r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"guake-search-header",children:t("terminal:header.searchResultsTitle")}),ce.searchResults.map((Ze,dt)=>r.jsx(ov,{message:Ze,agentId:C,highlight:ce.searchQuery,onImageClick:Ne,onFileClick:be,onBashClick:De,onViewMarkdown:it},`s-${dt}`))]}):r.jsxs("div",{className:`guake-history-content ${ee?"fade-in":""}`,children:[ae&&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",{})]})]}),!ae&&Ee.loadingHistory&&Ee.history.length===0&&D.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",{})]})]}),!ae&&!Ee.loadingHistory&&Ee.history.length===0&&R.length===0&&S.status!=="working"&&r.jsx("div",{className:"guake-empty",children:t("terminal:empty.noOutput")}),!ae&&Ee.hasMore&&!ce.searchMode&&r.jsx("div",{className:"guake-load-more",children:Ee.loadingMore?r.jsx("span",{children:t("terminal:empty.loadingOlder")}):r.jsx("button",{onClick:Ee.loadMoreHistory,children:t("terminal:empty.loadMore",{count:Ee.totalCount-Ee.history.length})})}),!ae&&r.jsx(xE,{historyMessages:gt,liveOutputs:Mt,agentId:C,execTasks:nt,subagents:Je,viewMode:B,selectedMessageIndex:An.selectedIndex,isMessageSelected:An.isSelected,onImageClick:Ne,onFileClick:be,onBashClick:De,onViewMarkdown:it,scrollContainerRef:L,onScrollTopReached:Ee.loadMoreHistory,isLoadingMore:Ee.loadingMore,hasMore:Ee.hasMore,shouldAutoScroll:$t,onUserScroll:Et,pinToBottom:le,onPinCancel:un,isLoadingHistory:Ee.fetchingHistory},C),!ae&&Ce&&We.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:We.size})})]}),Array.from(We.values()).map(Ze=>r.jsx(zH,{progress:Ze,defaultExpanded:Ze.status==="working",onAgentClick:z.selectAgent},Ze.agentId))]})]})})]}),r.jsx(iH,{selectedAgent:S,selectedAgentId:C,isOpen:he,command:ge.command,setCommand:ge.setCommand,forceTextarea:ge.forceTextarea,setForceTextarea:ge.setForceTextarea,useTextarea:ge.useTextarea,attachedFiles:ge.attachedFiles,setAttachedFiles:ge.setAttachedFiles,removeAttachedFile:ge.removeAttachedFile,uploadFile:ge.uploadFile,pastedTexts:ge.pastedTexts,expandPastedTexts:ge.expandPastedTexts,incrementPastedCount:ge.incrementPastedCount,setPastedTexts:ge.setPastedTexts,resetPastedCount:ge.resetPastedCount,handleInputFocus:M.handleInputFocus,handleInputBlur:M.handleInputBlur,pendingPermissions:Me,showCompletion:Se,completionElapsed:xe,onImageClick:Ne,inputRef:O,textareaRef:I,isSnapshotView:f,onClearHistory:Ee.clearHistory}),r.jsxs("div",{className:"guake-agent-status-bar",children:[!f&&(S==null?void 0:S.isDetached)&&r.jsx(Gp,{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")]})}),(S==null?void 0:S.cwd)&&r.jsxs("span",{className:"guake-agent-cwd",children:["📁 ",S.cwd.split("/").filter(Boolean).slice(-2).join("/")||S.cwd]}),!f&&S&&(()=>{const Ze=S.contextStats,dt=!!Ze,me=Ze?Ze.totalTokens:S.contextUsed||0,ze=Ze?Ze.contextWindow:S.contextLimit||2e5,Xe=Ze?Ze.usedPercent:Math.round(me/ze*100),ht=Math.round(100-Xe),lt=Xe>=80?"#ff4a4a":Xe>=60?"#ff9e4a":Xe>=40?"#ffd700":"#4aff9e",Nt=(me/1e3).toFixed(1),Dt=(ze/1e3).toFixed(1);return r.jsxs("span",{className:"guake-agent-context",onClick:()=>z.setContextModalAgentId(C),title:t(dt?"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,Xe)}%`,backgroundColor:lt}})}),r.jsxs("span",{className:"context-tokens",style:{color:lt},children:[Nt,"k/",Dt,"k"]}),r.jsxs("span",{className:"context-free",children:["(",t("terminal:context.percentFree",{percent:ht}),")"]}),!dt&&r.jsx("span",{className:"context-warning",title:t("terminal:context.clickToFetchStats"),children:"⚠️"})]})})(),r.jsx(sU,{})]})]}),he&&r.jsx("div",{className:"guake-resize-handle",onMouseDown:P,title:t("common:rightPanel.dragToResize")}),r.jsxs("div",{className:"guake-handle",onClick:()=>{he&&z.toggleTerminal()},onDoubleClick:()=>{he||z.toggleTerminal()},style:{top:he?`min(${_}%, calc(100vh - 72px))`:"0"},children:[r.jsx("span",{className:"guake-handle-icon",children:he?"▲":"▼"}),r.jsx("span",{className:"guake-handle-text",children:S.name})]}),$&&r.jsx(lE,{url:$.url,name:$.name,onClose:()=>Y(null)}),K&&r.jsx(cE,{state:K,onClose:()=>Q(null)}),H&&r.jsx(lH,{action:H,selectedAgentId:C,subordinateCount:((qs=S==null?void 0:S.subordinateIds)==null?void 0:qs.length)||0,onClose:()=>re(null),onClearHistory:Ee.clearHistory}),r.jsx(cH,{}),r.jsx(uH,{}),r.jsx(dH,{agent:S,isOpen:V,onClose:()=>J(!1)}),!f&&r.jsx(uE,{agent:S,content:de,onClose:()=>F(null)})]}):null:Rn&&c==="terminal"&&a.size===0?r.jsx("div",{ref:T,className:"guake-terminal open",style:{"--terminal-height":`${_}%`},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")})]})})})}):Rn&&c==="terminal"&&a.size>0?r.jsx("div",{ref:T,className:"guake-terminal open",style:{"--terminal-height":`${_}%`},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});function lU(s){return s.trim().replace(/^v/i,"")}function R1(s){const t=lU(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 cU(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 uU(s,e){const t=R1(s),n=R1(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 cU(t.prerelease,n.prerelease)}function dU(s,e){const t=uU(s,e);return t===null?"unknown":t<0?"behind":t>0?"ahead":"equal"}async function hU(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 pU(s,e,t={}){const n=await hU(s,t);return n?{currentVersion:e,latestVersion:n,relation:dU(e,n)}:{currentVersion:e,latestVersion:null,relation:"unknown"}}const mU="tide-commander",Rb="0.78.0";function fU(){const[s,e]=y.useState({currentVersion:Rb,latestVersion:null,relation:"unknown",isChecking:!1}),t=y.useCallback(async()=>{e(a=>({...a,isChecking:!0}));const n=await pU(mU,Rb);e({currentVersion:Rb,latestVersion:n.latestVersion,relation:n.relation,isChecking:!1})},[]);return y.useEffect(()=>{t()},[t]),{...s,refresh:t}}const gU=y.memo(function({agent:e,currentIndex:t,agentIndex:n,isSelected:a,hasUnseenOutput:i,isDragging:o,isDragOver:l,customClasses:c,onDragStart:d,onDragEnd:m,onDragOver:p,onDragEnter:f,onDragLeave:b,onDrop:x,onAgentClick:w,onAgentDoubleClick:k,onHoverEnter:j,onHoverLeave:S,onItemRef:C}){const A=y.useMemo(()=>co(e.class,c),[e.class,c]),_=y.useCallback(T=>{C(e.id,T)},[e.id,C]);return r.jsxs("div",{ref:_,className:`agent-bar-item ${a?"selected":""} ${e.status} ${e.isBoss?"is-boss":""} ${o?"dragging":""} ${l?"drag-over":""}`,draggable:!0,onDragStart:T=>d(T,e),onDragEnd:m,onDragOver:T=>p(T,n),onDragEnter:T=>f(T,n),onDragLeave:b,onDrop:T=>x(T,n),onClick:T=>w(e,T),onDoubleClick:()=>k(e),onMouseEnter:()=>j(e),onMouseLeave:S,title:`${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:A.icon}),r.jsx("span",{className:"agent-bar-status",style:{backgroundColor:px(e.status)}}),i&&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:hm(e.lastActivity)},title:pm(e.lastActivity),children:"⏱"})]}),r.jsxs("span",{className:"agent-bar-hotkey",title:`Ctrl+${t+1}`,children:["^",t+1]})]})}),bU=y.memo(function({onFocusAgent:e,onSpawnClick:t,onSpawnBossClick:n,onNewBuildingClick:a,onNewAreaClick:i}){const{t:o}=Ue(["common"]),l=ui(),c=cl(),d=bm(),m=Az(),p=Tx(),f=lo(),b=di(),x=Px(),[w,k]=y.useState(!1);oM("AgentBar");const j=y.useRef(null),S=y.useRef(null),C=y.useRef(null),A=y.useRef(new Map);y.useEffect(()=>{{k(!1);return}},[f.experimental2DView]),y.useEffect(()=>{const ae=S.current;if(!ae)return;const we=he=>{ae.scrollWidth<=ae.clientWidth||(he.preventDefault(),ae.scrollLeft+=he.deltaY)};return ae.addEventListener("wheel",we,{passive:!1}),()=>ae.removeEventListener("wheel",we)},[]);const[_,T]=y.useState(null),[P,M]=y.useState(new Map),[D,R]=y.useState(null),[L,O]=y.useState(null),I=y.useRef(0),B=y.useMemo(()=>Array.from(l.values()).filter(ae=>!z.isAgentInArchivedArea(ae.id)).sort((ae,we)=>(ae.createdAt||0)-(we.createdAt||0)),[l,c]),{orderedAgents:G,moveAgent:$}=MM(B),Y=G,K=y.useMemo(()=>{const ae=new Map;for(const we of Y)ae.set(we.id,z.getAreaForAgent(we.id));return ae},[Y,c]),Q=y.useMemo(()=>{const ae=new Map;for(const he of Y){const Ee=K.get(he.id)||null,ce=(Ee==null?void 0:Ee.id)||null;ae.has(ce)||ae.set(ce,{area:Ee,agents:[]}),ae.get(ce).agents.push(he)}const we=Array.from(ae.values());return we.sort((he,Ee)=>{var ce,ne;return!he.area&&Ee.area?1:he.area&&!Ee.area?-1:!he.area&&!Ee.area?0:(((ce=he.area)==null?void 0:ce.name)||"").localeCompare(((ne=Ee.area)==null?void 0:ne.name)||"")}),we},[Y,K]),H=y.useRef(e);H.current=e;const re=y.useRef(D);re.current=D;const de=y.useRef(Y);de.current=Y;const F=y.useRef(K);F.current=K;const V=y.useRef($);V.current=$,y.useEffect(()=>{const ae=new Map(P);let we=!1;for(const he of Y){const Ee=P.get(he.id);he.currentTool?(!Ee||Ee.tool!==he.currentTool)&&(ae.set(he.id,{tool:he.currentTool,key:Date.now()}),we=!0):Ee&&setTimeout(()=>{M(ce=>{const ne=new Map(ce);return ne.delete(he.id),ne})},1500)}we&&M(ae)},[Y.map(ae=>ae.currentTool).join(",")]),y.useEffect(()=>{const ae=m;if(!ae)return;const we=A.current.get(ae),he=S.current;we&&he&&requestAnimationFrame(()=>{const Ee=we.getBoundingClientRect(),ce=he.getBoundingClientRect(),ge=Ee.left-ce.left+he.scrollLeft+Ee.width/2,ue=he.clientWidth;he.scrollTo({left:ge-ue/2,behavior:"smooth"})})},[m]);const J=y.useCallback((ae,we)=>{z.setLastSelectionViaDirectClick(!0),we.shiftKey?z.addToSelection(ae.id):z.selectAgent(ae.id),z.setTerminalOpen(!0)},[]),ie=y.useCallback(ae=>{var we;(we=H.current)==null||we.call(H,ae.id),z.setTerminalOpen(!0)},[]),Z=y.useCallback(()=>T(null),[]),X=y.useCallback((ae,we)=>{we?A.current.set(ae,we):A.current.delete(ae)},[]),q=y.useCallback((ae,we)=>{R(we),ae.dataTransfer.effectAllowed="move",ae.dataTransfer.setData("text/plain",we.id),requestAnimationFrame(()=>{ae.target.classList.add("dragging")})},[]),se=y.useCallback(ae=>{R(null),O(null),I.current=0,ae.target.classList.remove("dragging")},[]),pe=y.useCallback((ae,we)=>{ae.preventDefault();const he=re.current;if(he){const Ee=F.current.get(he.id),ce=de.current[we],ne=ce?F.current.get(ce.id):null,ge=(Ee==null?void 0:Ee.id)??null,ue=(ne==null?void 0:ne.id)??null;ae.dataTransfer.dropEffect=ge===ue?"move":"none"}else ae.dataTransfer.dropEffect="move"},[]),Se=y.useCallback((ae,we)=>{ae.preventDefault(),I.current++;const he=re.current;if(he){const Ee=F.current.get(he.id),ce=de.current[we],ne=ce?F.current.get(ce.id):null,ge=(Ee==null?void 0:Ee.id)??null,ue=(ne==null?void 0:ne.id)??null;O(ge===ue?we:null)}else O(we)},[]),Te=y.useCallback(ae=>{I.current--,I.current===0&&O(null)},[]),xe=y.useCallback((ae,we)=>{ae.preventDefault();const he=re.current;if(!he)return;const Ee=de.current,ce=F.current,ne=Ee.findIndex(ge=>ge.id===he.id);if(ne!==-1&&ne!==we){const ge=ce.get(he.id),ue=Ee[we],Me=ue?ce.get(ue.id):null,Ce=(ge==null?void 0:ge.id)??null,We=(Me==null?void 0:Me.id)??null;Ce===We&&V.current(ne,we)}R(null),O(null),I.current=0},[]),$e=ae=>{const we=`common:status.${ae}`;return o(we,{defaultValue:o("common:status.unknown")})},{currentVersion:Pe,latestVersion:ve,relation:ee,isChecking:fe}=fU(),le=Pe;let oe=0;return r.jsxs("div",{className:"agent-bar",ref:j,children:[r.jsxs("div",{className:"agent-bar-scroll",ref:S,children:[r.jsxs("div",{className:"agent-bar-version",title:ve?`Tide Commander v${le} (npm: v${ve})`:`Tide Commander v${le}`,children:[r.jsxs("span",{children:["v",le]}),ee==="behind"&&ve?r.jsxs("span",{className:"agent-bar-version-badge agent-bar-version-badge-behind",title:`Behind npm latest v${ve}`,children:["npm v",ve]}):ee==="ahead"&&ve?r.jsxs("span",{className:"agent-bar-version-badge agent-bar-version-badge-ahead",title:`Ahead of npm latest v${ve}`,children:["npm v",ve]}):null,ee==="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)"})}):ee==="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)"})}):ee==="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")}):fe?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:AM,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")})]}),Q.map(ae=>{var Ee,ce,ne,ge,ue;const we=ae.agents,he=!ae.area;return r.jsxs("div",{className:`agent-bar-group ${he?"unassigned":""}`,style:{borderColor:((Ee=ae.area)==null?void 0:Ee.color)||void 0,background:ae.area?`${ae.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:((ce=ae.area)==null?void 0:ce.color)||"#888"},children:((ne=ae.area)==null?void 0:ne.name)||o("common:agentBar.unassigned")})}),((ge=ae.area)==null?void 0:ge.directories)&&ae.area.directories.length>0&&r.jsx("div",{className:"agent-bar-folders",children:ae.area.directories.map((Me,Ce)=>r.jsxs("div",{className:"agent-bar-folder-item",onClick:We=>{We.stopPropagation(),z.openFileExplorer(Me)},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:Me}),r.jsx("div",{className:"agent-bar-folder-tooltip-hint",children:o("common:agentBar.clickToOpen")})]})]},Ce))}),we.map(Me=>{const Ce=oe++,We=Y.findIndex(nt=>nt.id===Me.id);return r.jsx(gU,{agent:Me,currentIndex:Ce,agentIndex:We,isSelected:d.has(Me.id),hasUnseenOutput:x.has(Me.id),isDragging:(D==null?void 0:D.id)===Me.id,isDragOver:L===We,customClasses:b,onDragStart:q,onDragEnd:se,onDragOver:pe,onDragEnter:Se,onDragLeave:Te,onDrop:xe,onAgentClick:J,onAgentDoubleClick:ie,onHoverEnter:T,onHoverLeave:Z,onItemRef:X},Me.id)})]},((ue=ae.area)==null?void 0:ue.id)||"unassigned")})]})]}),Array.from(P.entries()).map(([ae,we])=>{const he=A.current.get(ae);if(!he)return null;const Ee=he.getBoundingClientRect(),ce=es[we.tool]||es.default;return r.jsxs("div",{className:"agent-bar-tool-bubble",title:we.tool,style:{position:"fixed",left:Ee.left+Ee.width/2,bottom:window.innerHeight-Ee.top+8},children:[r.jsx("span",{className:"agent-bar-tool-icon",children:ce}),r.jsx("span",{className:"agent-bar-tool-name",children:we.tool})]},`tool-${ae}-${we.key}`)}),_&&(()=>{const ae=z.getAreaForAgent(_.id),we=p.get(_.id),he=co(_.class,b),Ee=z.getAgentSupervisorHistory(_.id),ce=Ee.length>0?Ee[Ee.length-1]:void 0,ne=Date.now()-(_.createdAt||Date.now()),ge=Math.floor(ne/6e4),ue=Math.floor(ge/60),Me=ue>0?`${ue}h ${ge%60}m`:`${ge}m`,Ce=et=>et>=1e6?`${(et/1e6).toFixed(1)}M`:et>=1e3?`${(et/1e3).toFixed(1)}K`:et.toString(),We=_.contextLimit>0?Math.round(_.contextUsed/_.contextLimit*100):0,nt=et=>{switch(et){case"on_track":return"#4aff9e";case"completed":return"#4a9eff";case"stalled":return"#ff9e4a";case"blocked":return"#ff4a4a";case"idle":return"#888888";default:return"#888888"}},Je=A.current.get(_.id),ct={};if(Je){const et=Je.getBoundingClientRect();ct.position="fixed",ct.left=et.left+et.width/2,ct.bottom=window.innerHeight-et.top+12}return r.jsxs("div",{className:"agent-bar-tooltip",style:ct,children:[r.jsxs("div",{className:"agent-bar-tooltip-header",children:[r.jsx("span",{className:"agent-bar-tooltip-icon",children:he.icon}),r.jsxs("span",{className:"agent-bar-tooltip-name",children:[r.jsx("img",{src:_.provider==="codex"?"/assets/codex.png":"/assets/claude.png",alt:_.provider,className:"agent-bar-provider-icon",title:_.provider==="codex"?"Codex Agent":"Claude Agent"}),_.name]}),r.jsx("span",{className:"agent-bar-tooltip-status",style:{color:px(_.status)},children:$e(_.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:[_.class," — ",he.description]})]}),ae&&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:ae.color},children:ae.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:_.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:Me})]}),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:[Ce(_.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:We>80?"#ff4a4a":We>60?"#ff9e4a":void 0},children:[Ce(_.contextUsed)," / ",Ce(_.contextLimit)," (",We,"%)"]})]}),_.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:[es[_.currentTool]||es.default," ",_.currentTool]})]}),_.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:[_.currentTask.substring(0,150),_.currentTask.length>150?"...":""]})]}),_.lastAssignedTask&&!_.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:[_.lastAssignedTask.substring(0,200),_.lastAssignedTask.length>200?"...":""]})]}),we&&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:[we.text.substring(0,300),we.text.length>300?"...":""]})]}),ce&&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:nt(ce.analysis.progress)},children:ce.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:ce.analysis.statusDescription})]}),ce.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:[ce.analysis.recentWorkSummary.substring(0,300),ce.analysis.recentWorkSummary.length>300?"...":""]})]}),ce.analysis.concerns&&ce.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:ce.analysis.concerns.join("; ")})]})]})]})]})})()]})});function yU({activeTool:s,onExit:e}){const{t}=Ue(["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 xU={idle:"common:status.idle",working:"common:status.working",waiting:"common:status.waiting",error:"common:status.error",offline:"common:status.offline"},Pb=s=>s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(1)}K`:s.toString(),vU=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"}},wU=y.memo(function({agent:e,screenPos:t,onClose:n}){const{t:a}=Ue(["common"]),i=di(),o=z.getAreaForAgent(e.id),l=z.getState().lastPrompts.get(e.id),c=co(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,A=t.y-320-10;return typeof window<"u"&&(C<10?C=10:C+300>window.innerWidth-10&&(C=window.innerWidth-300-10),A<10&&(A=t.y+10)),{position:"fixed",left:C,top:A,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:px(e.status)},children:a(xU[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:[Pb(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:[Pb(e.contextUsed)," / ",Pb(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:[es[e.currentTool]||es.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:vU(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 P1(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 L1(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 O1={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 kU(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:O1[l]&&(a=O1[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 SU=y.memo(function({building:e,screenPos:t,onClose:n,onOpenSettings:a,onOpenLogsModal:i,onOpenUrlInModal:o}){var $,Y,K,Q,H,re,de,F,V,J,ie,Z,X,q,se,pe,Se,Te,xe,$e;const{t:l}=Ue(["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}=$n(),j=z.getBuildingLogs(e.id),S=($=e.pm2)==null?void 0:$.enabled,C=(Y=e.docker)==null?void 0:Y.enabled,A=y.useRef(null),_=y.useRef(null),T=y.useCallback(Pe=>{Pe.preventDefault();const ve=w.current?w.current.x:0,ee=w.current?w.current.y:0;x.current={mouseX:Pe.clientX,mouseY:Pe.clientY,popupX:ve,popupY:ee},b(!0),A.current=fe=>{if(!x.current)return;const le=fe.clientX-x.current.mouseX,oe=fe.clientY-x.current.mouseY;p({x:x.current.popupX+le,y:x.current.popupY+oe})},_.current=()=>{b(!1),x.current=null,A.current&&document.removeEventListener("mousemove",A.current),_.current&&document.removeEventListener("mouseup",_.current)},document.addEventListener("mousemove",A.current),document.addEventListener("mouseup",_.current)},[]);y.useEffect(()=>()=>{A.current&&document.removeEventListener("mousemove",A.current),_.current&&document.removeEventListener("mouseup",_.current)},[]);const P=Pe=>{if(Pe==="logs"){if((S||C)&&i){i();return}z.sendBuildingCommand(e.id,Pe),d(!0)}else z.sendBuildingCommand(e.id,Pe)},M=(Pe,ve)=>{if(Pe){const ee=`http://localhost:${Pe}`;ve&&o?o(ee):window.open(ee,"_blank")}},D=((K=e.pm2Status)==null?void 0:K.ports)||[],R=((H=(Q=e.dockerStatus)==null?void 0:Q.ports)==null?void 0:H.map(Pe=>Pe.host))||[],L=S?D:C?R:[],O=S?!!((re=e.pm2)!=null&&re.script):C?!!((de=e.docker)!=null&&de.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=S?!!((ie=e.pm2)!=null&&ie.script):C?!0:!!((Z=e.commands)!=null&&Z.stop),B=S?!!((X=e.pm2)!=null&&X.script):C?!0:!!((q=e.commands)!=null&&q.restart),G=y.useMemo(()=>{const ve=c?400:250;let ee=t.x+20,fe=t.y-80;return typeof window<"u"&&!m&&(t.x+20+280>window.innerWidth&&(ee=t.x-280-20),t.y-80<0?fe=10:t.y-80+ve>window.innerHeight&&(fe=window.innerHeight-ve-10)),{position:"fixed",left:ee+((m==null?void 0:m.x)||0),top:fe+((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:G,onClick:Pe=>Pe.stopPropagation(),children:[r.jsxs("div",{className:`building-popup-header ${f?"dragging":""}`,onMouseDown:T,children:[r.jsx("span",{className:"building-popup-name",children:e.name}),L.length>0&&r.jsx("span",{className:"building-popup-ports",children:L.map(Pe=>r.jsxs("a",{href:`http://localhost:${Pe}`,className:"building-popup-port-link",onClick:ve=>{ve.preventDefault(),ve.stopPropagation(),M(Pe,ve.altKey)},onMouseDown:ve=>ve.stopPropagation(),title:`Open http://localhost:${Pe} (Alt+Click for modal)`,children:[":",Pe]},Pe))}),r.jsx("span",{className:"building-popup-status",style:{backgroundColor:ao[e.status]},children:e.status}),r.jsx("button",{className:"building-popup-close",onClick:n,children:"x"})]}),S&&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:[((se=e.pm2Status.cpu)==null?void 0:se.toFixed(1))||"0","%"]})]}),r.jsxs("span",{className:"metric",children:[r.jsx("span",{className:"label",children:"MEM"}),r.jsx("span",{className:"value",children:P1(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:L1(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:P1(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:L1(e.dockerStatus.startedAt)})]})]}),C&&((pe=e.dockerStatus)==null?void 0:pe.services)&&e.dockerStatus.services.length>0&&r.jsx("div",{className:"building-popup-services",children:e.dockerStatus.services.map((Pe,ve)=>r.jsxs("span",{className:"service-item",title:`${Pe.name}: ${Pe.status}`,children:[r.jsx("span",{className:"service-indicator",style:{backgroundColor:Pe.status==="running"?"#4ade80":"#f87171"}}),r.jsx("span",{className:"service-name",children:Pe.name})]},ve))}),(e.lastError||S&&((Se=e.pm2Status)==null?void 0:Se.status)==="errored"||C&&((Te=e.dockerStatus)==null?void 0:Te.status)==="dead")&&r.jsxs("div",{className:"building-popup-error",children:[e.lastError||l("terminal:building.processFailedToStart"),S&&((xe=e.pm2Status)==null?void 0:xe.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:()=>P("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:()=>P("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:()=>P("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:()=>P("logs"),title:l("terminal:buildingAction.viewLogs"),children:[r.jsx("span",{className:"icon",children:"📄"}),l("terminal:logs.title")]}),L.length===1&&r.jsxs("button",{className:"action-btn open-url",onClick:Pe=>M(L[0],Pe.altKey),title:`Open http://localhost:${L[0]} (Alt+Click for modal)`,children:[r.jsx("span",{className:"icon",children:"🔗"}),l("terminal:buildingAction.openInBrowser")]}),L.length>1&&r.jsxs("div",{className:"action-btn-group",children:[r.jsxs("span",{className:"action-btn-label",children:[l("terminal:buildingAction.openInBrowser"),":"]}),L.map(Pe=>r.jsxs("button",{className:"action-btn open-url port-btn",onClick:ve=>M(Pe,ve.altKey),title:`Open http://localhost:${Pe} (Alt+Click for modal)`,children:[":",Pe]},Pe))]})]}),c&&j.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:j.slice(-50).map((Pe,ve)=>r.jsx("pre",{children:kU(Pe)},ve))})]}),r.jsx("button",{className:"building-popup-settings",onClick:a,children:l("terminal:buildingAction.fullSettings")})]})});function jU(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 CU(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 NU=y.memo(function({building:e,screenPos:t,onClose:n,onOpenSettings:a,onOpenLogsModal:i,onOpenUrlInModal:o}){const{t:l}=Ue(["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}=$n(),k=(e.subordinateBuildingIds||[]).map(D=>x.get(D)).filter(D=>D!==void 0),j=y.useRef(null),S=y.useRef(null),C=y.useCallback(D=>{D.preventDefault();const R=b.current?b.current.x:0,L=b.current?b.current.y:0;f.current={mouseX:D.clientX,mouseY:D.clientY,popupX:R,popupY:L},p(!0),j.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})},S.current=()=>{p(!1),f.current=null,j.current&&document.removeEventListener("mousemove",j.current),S.current&&document.removeEventListener("mouseup",S.current)},document.addEventListener("mousemove",j.current),document.addEventListener("mouseup",S.current)},[]);y.useEffect(()=>()=>{j.current&&document.removeEventListener("mousemove",j.current),S.current&&document.removeEventListener("mouseup",S.current)},[]);const A=D=>{z.sendBossBuildingCommand(e.id,D)},_=k.reduce((D,R)=>(D[R.status]=(D[R.status]||0)+1,D),{}),T=k.some(D=>{var R;return(R=D.pm2)==null?void 0:R.enabled}),P=(D,R)=>{const L=`http://localhost:${D}`;R&&o?o(L):window.open(L,"_blank")},M=y.useMemo(()=>{let L=t.x+20,O=t.y-80;return typeof window<"u"&&!c&&(t.x+20+340>window.innerWidth&&(L=t.x-340-20),t.y-80<0?O=10:t.y-80+350>window.innerHeight&&(O=window.innerHeight-350-10)),{position:"fixed",left:L+((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(_).map(([D,R])=>r.jsxs("span",{className:"status-badge",style:{backgroundColor:ao[D]||"#666"},children:[R," ",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 R,L,O;return r.jsxs("div",{className:"subordinate-item",children:[r.jsx("span",{className:"sub-status-dot",style:{backgroundColor:ao[D.status]}}),r.jsx("span",{className:"sub-name",children:D.name}),((R=D.pm2Status)==null?void 0:R.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(),P(I,B.altKey)},title:`Open http://localhost:${I} (Alt+Click for modal)`,children:[":",I]},I))}),D.pm2Status&&r.jsxs("span",{className:"sub-metrics",children:[(L=D.pm2Status.cpu)==null?void 0:L.toFixed(0),"% | ",jU(D.pm2Status.memory||0)]}),((O=D.pm2Status)==null?void 0:O.uptime)&&r.jsx("span",{className:"sub-uptime",children:CU(D.pm2Status.uptime)})]},D.id)})}),r.jsxs("div",{className:"building-popup-actions boss-actions",children:[r.jsxs("button",{className:"action-btn start",onClick:()=>A("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:()=>A("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:()=>A("restart_all"),disabled:k.length===0,title:l("terminal:building.restartAllSubs"),children:[r.jsx("span",{className:"icon",children:"↺"}),l("terminal:building.restartAll")]}),T&&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")})]})}),AU=y.memo(function({building:e,screenPos:t,onClose:n,onOpenSettings:a,onOpenDatabasePanel:i}){var _;const{t:o}=Ue(["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=xm(e.id),x=((_=e.database)==null?void 0:_.connections)??[],w=y.useRef(null),k=y.useRef(null),j=y.useCallback(T=>{T.preventDefault();const P=f.current?f.current.x:0,M=f.current?f.current.y:0;p.current={mouseX:T.clientX,mouseY:T.clientY,popupX:P,popupY:M},m(!0),w.current=D=>{if(!p.current)return;const R=D.clientX-p.current.mouseX,L=D.clientY-p.current.mouseY;c({x:p.current.popupX+R,y:p.current.popupY+L})},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 S=T=>{z.testDatabaseConnection(e.id,T)},C=T=>b.connectionStatus.get(T),A=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:A,onClick:T=>T.stopPropagation(),children:[r.jsxs("div",{className:`building-popup-header database-header ${d?"dragging":""}`,onMouseDown:j,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(T=>{const P=C(T.id);return r.jsxs("div",{className:"database-connection-item",children:[r.jsx("span",{className:"conn-engine",children:T.engine==="mysql"?"🐬":"🐘"}),r.jsx("span",{className:"conn-name",children:T.name}),r.jsxs("span",{className:"conn-host",children:[T.host,":",T.port]}),P&&r.jsx("span",{className:`conn-status ${P.connected?"connected":"disconnected"}`,children:P.connected?"●":"○"}),r.jsx("button",{className:"conn-test-btn",onClick:()=>S(T.id),title:o("terminal:building.testConnection"),children:"↻"})]},T.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(T=>S(T.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")})]})}),MU=({building:s,connections:e,activeConnectionId:t,activeDatabase:n,collapsed:a,onToggleCollapse:i,onConnectionChange:o,onDatabaseChange:l,onInsertTable:c,onSelectTableQuery:d})=>{const{t:m}=Ue(["terminal"]),p=xm(s.id),[f,b]=y.useState(new Set),[x,w]=y.useState(""),[k,j]=y.useState(!1),[S,C]=y.useState(null),A=y.useRef(null),_=y.useRef(null),T=t?p.databases.get(t)??[]:[],P=t&&n?`${t}:${n}`:"",M=P?p.tables.get(P)??[]:[],D=t?p.connectionStatus.get(t):void 0,R=y.useMemo(()=>{if(!x.trim())return T;const I=x.toLowerCase();return T.filter(B=>B.toLowerCase().includes(I))},[T,x]);y.useEffect(()=>{const I=B=>{_.current&&!_.current.contains(B.target)&&j(!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)&&T.length===0&&z.listDatabases(s.id,t)},[s.id,t,D==null?void 0:D.connected,T.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 L=y.useCallback(I=>{b(B=>{const G=new Set(B);if(G.has(I))G.delete(I);else if(G.add(I),t&&n){const $=`${t}:${n}:${I}`;p.tableSchemas.has($)||z.getTableSchema(s.id,t,n,I)}return G})},[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")]})})]}),T.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:_,children:[r.jsx("input",{ref:A,className:"database-sidebar__search-input",type:"text",value:k?x:n||"",placeholder:m("terminal:database.selectDatabase"),onChange:I=>{w(I.target.value),k||j(!0)},onFocus:()=>{j(!0),w("")},onKeyDown:I=>{var B,G;I.key==="Escape"?(j(!1),w(""),(B=A.current)==null||B.blur()):I.key==="Enter"&&R.length===1&&(l(R[0]),j(!1),w(""),(G=A.current)==null||G.blur())}}),k&&r.jsx("div",{className:"database-sidebar__dropdown",children:R.length===0?r.jsx("div",{className:"database-sidebar__dropdown-empty",children:"No matches"}):R.map(I=>r.jsx("div",{className:`database-sidebar__dropdown-item ${I===n?"database-sidebar__dropdown-item--active":""}`,onMouseDown:B=>{B.preventDefault(),l(I),j(!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),G=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:()=>L(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 ${S===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&&G&&r.jsx("div",{className:"database-sidebar__table-columns",children:G.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 uv(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===`
|
|
233
|
+
`)}function rU(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 oU=y.memo(function({onSaveSnapshot:e}={}){var is,Bs,Wa,ca,qs;const{t}=Ue(["terminal","common"]),n=ui(),a=bm(),i=DM(),o=Tx(),l=Rx(),c=RM(),d=_x(),m=Dx(),p=sF(),f=!!p,b=y.useMemo(()=>p?{id:p.agentId,name:p.agentName,class:p.agentClass,status:"idle",provider:"claude",position:{x:0,y:0,z:0},cwd:p.cwd,permissionMode:"interactive",tokensUsed:0,contextUsed:0,contextLimit:2e5,taskCount:0,createdAt:p.createdAt,lastActivity:p.createdAt}:null,[p]),x=Array.from(a),k=x.length===1?x[0]:null,S=(Nx(k)||null)??(f?b:null),C=k??(f?(p==null?void 0:p.agentId)??null:null),A=!!(S!=null&&S.sessionId)&&!f,{terminalHeight:_,terminalRef:T,handleResizeStart:P}=O9(),M=L9(),D=Ax(C),R=y.useMemo(()=>f&&p?p.outputs.map(Ze=>({text:Ze.text||"",timestamp:Ze.timestamp,isStreaming:!1,isUserPrompt:!1})):D,[f,p,D]),L=y.useRef(null),O=y.useRef(null),I=y.useRef(null),[B,G]=y.useState(()=>{const Ze=Ms(mt.VIEW_MODE);return Ze==="simple"||Ze==="chat"||Ze==="advanced"?Ze:Ms(mt.ADVANCED_VIEW)==="true"?"advanced":"simple"}),[$,Y]=y.useState(null),[K,Q]=y.useState(null),[H,re]=y.useState(null),[de,F]=y.useState(null),[V,J]=y.useState(!1);Sn("guake-image-modal",$!==null,()=>Y(null)),Sn("guake-bash-modal",K!==null,()=>Q(null)),Sn("guake-response-modal",de!==null,()=>F(null)),Sn("guake-context-confirm",H!==null,()=>re(null)),Sn("guake-agent-info",V,()=>J(!1));const[ie,Z]=y.useState(!1),[X,q]=y.useState(()=>ws.isEnabled()),se=cF(),pe=y.useCallback(Ze=>z.setOverviewPanelOpen(Ze),[]),[Se,Te]=y.useState(!1),[xe,$e]=y.useState(null),Pe=y.useRef(null),ve=y.useRef(null),[ee,fe]=y.useState(!1),[le,oe]=y.useState(!1),[ae,we]=y.useState(!1),he=i&&S!==null,Ee=TM({selectedAgentId:C,hasSessionId:A,reconnectCount:l,lastPrompts:o,outputScrollRef:L}),ce=B9({selectedAgentId:C,isOpen:he}),ne=I9({agents:n,selectedAgentId:C,isOpen:he,loadingHistory:Ee.fetchingHistory,hasModalOpen:!!($||K||de||d||m),outputRef:L}),ge=QT({selectedAgentId:k}),ue=Lz(),Me=y.useMemo(()=>f||!C?[]:Array.from(ue.values()).filter(Ze=>Ze.agentId===C&&Ze.status==="pending"),[f,C,ue]),Ce=(S==null?void 0:S.class)==="boss"||(S==null?void 0:S.isBoss),We=Vz(!f&&Ce?C:null),nt=Kz(f?null:C),Je=lF(f?null:C);y.useEffect(()=>{ie&&!X&&(q(!0),ws.setEnabled(!0))},[ie,X]),y.useEffect(()=>{he||J(!1)},[he]),y.useEffect(()=>{const Ze=S==null?void 0:S.status;if(Pe.current==="working"&&Ze==="idle"){ve.current&&clearTimeout(ve.current);const me=C?o.get(C):void 0;$e(me!=null&&me.timestamp?Date.now()-me.timestamp:null),Te(!0),ve.current=setTimeout(()=>{Te(!1),$e(null),ve.current=null},4e3)}else Ze==="working"&&(ve.current&&(clearTimeout(ve.current),ve.current=null),Te(!1),$e(null));return Pe.current=Ze||null,()=>{ve.current&&clearTimeout(ve.current)}},[S==null?void 0:S.status]);const ct=y.useMemo(()=>{const{history:Ze}=Ee,dt=new Map;for(const ze of Ze)ze.type==="tool_result"&&ze.toolUseId&&dt.set(ze.toolUseId,ze.content);return(ze=>ze.map(Xe=>{if(Xe.type==="tool_use"&&Xe.toolName==="Bash"&&Xe.toolUseId){const ht=dt.get(Xe.toolUseId);let lt;try{lt=(Xe.toolInput||(Xe.content?JSON.parse(Xe.content):{})).command}catch{}return{...Xe,_bashOutput:ht,_bashCommand:lt}}return Xe}))(Ze)},[Ee.history,B]),et=JT({outputs:R,viewMode:B}),gt=y.useMemo(()=>{const Ze=[],dt=new Set,me=new Set;let ze=null,Xe=0;for(const ht of ct){if(ht.type==="assistant"){const Gt=ht.uuid?`uuid:${ht.uuid}:${tp(ht.content)}`:`sig:${ht.timestamp}:${tp(ht.content)}`;if(dt.has(Gt))continue;dt.add(Gt),Ze.push(ht);continue}if(ht.type!=="user"){Ze.push(ht);continue}const lt=Db(ht.content),Nt=ht.uuid?`uuid:${ht.uuid}:${lt}`:null;if(Nt&&me.has(Nt))continue;const Dt=ht.timestamp?new Date(ht.timestamp).getTime():0;ze===lt&&Math.abs(Dt-Xe)<=D1||(Ze.push(ht),Nt&&me.add(Nt),ze=lt,Xe=Dt)}return Ze},[ct]),Mt=y.useMemo(()=>{const Ze=new Map,dt=new Set,me=new Map;for(const lt of gt){const Nt=lt.timestamp?new Date(lt.timestamp).getTime():0;if(lt.type==="user"){const Pn=Db(lt.content),Ln=Ze.get(Pn)??0;Nt>Ln&&Ze.set(Pn,Nt);continue}if(lt.type!=="assistant")continue;lt.uuid&&dt.add(lt.uuid);const Dt=tp(lt.content),Gt=me.get(Dt)??0;Nt>Gt&&me.set(Dt,Nt)}const ze=[];let Xe=null,ht=0;for(const lt of et){if(!lt.isUserPrompt){if(!lt.isStreaming&&!rU(lt.text)){if(lt.uuid&&dt.has(lt.uuid))continue;const Pn=tp(lt.text),Ln=lt.timestamp||0,Un=me.get(Pn);if(Un&&Math.abs(Ln-Un)<=iU)continue}ze.push(lt);continue}const Nt=Db(lt.text),Dt=lt.timestamp||0,Gt=Ze.get(Nt);Gt&&Dt>=Gt&&Dt-Gt<=aU||Xe===Nt&&Math.abs(Dt-ht)<=D1||(ze.push(lt),Xe=Nt,ht=Dt)}return ze},[et,gt]),Ft=gt.length+Mt.length,An=$9({totalMessages:Ft,isOpen:he,hasModalOpen:!!($||K||de||d),scrollContainerRef:L,selectedAgentId:C,inputRef:O,textareaRef:I,useTextarea:ge.useTextarea});y.useEffect(()=>{if(!(!(K!=null&&K.isLive)||!K.command)){for(const Ze of Mt)if(Ze._bashCommand===K.command&&Ze._bashOutput){Q({command:K.command,output:Ze._bashOutput,isLive:!1});return}}},[K,Mt]);const Ne=y.useCallback((Ze,dt)=>{Y({url:Ze,name:dt})},[]),be=y.useCallback((Ze,dt)=>{const me=Nd(Ze,S==null?void 0:S.cwd),ze=me.line?{...dt||{},targetLine:me.line}:dt;z.setFileViewerPath(me.path,ze,S==null?void 0:S.cwd)},[S==null?void 0:S.cwd]),De=y.useCallback((Ze,dt)=>{Q({command:Ze,output:dt,isLive:dt==="Running..."})},[]),it=y.useCallback(Ze=>{F(Ze)},[]),ot=y.useCallback(()=>{J(Ze=>!Ze)},[]),[$t,tn]=y.useState(!0),Ut=y.useRef(!1),st=y.useRef(!1),Et=y.useCallback(()=>{st.current||(Ut.current=!0,tn(!1))},[]),un=y.useCallback(()=>oe(!1),[]);y.useEffect(()=>{tn(!0),Ut.current=!1,st.current=!0;const Ze=setTimeout(()=>{st.current=!1},3e3);return()=>clearTimeout(Ze)},[C]);const Pt=y.useRef(Ee.handleScroll);Pt.current=Ee.handleScroll;const gs=y.useCallback(()=>{if(!L.current||M.keyboardScrollLockRef.current)return;const{scrollTop:Ze,scrollHeight:dt,clientHeight:me}=L.current,ze=dt-Ze-me<150;st.current||(Ut.current=!ze,ze&&tn(!0)),Pt.current(M.keyboardScrollLockRef)},[L,M.keyboardScrollLockRef]),Dn=D.length>0&&((Bs=(is=D[D.length-1])==null?void 0:is.text)==null?void 0:Bs.length)||0;y.useEffect(()=>{M.keyboardScrollLockRef.current||Ut.current||requestAnimationFrame(()=>{if(L.current){const{scrollTop:Ze,scrollHeight:dt,clientHeight:me}=L.current;dt-Ze-me<150&&(L.current.scrollTop=dt)}})},[D.length,Dn,M.keyboardScrollLockRef,L]);const Zn=y.useRef(null);y.useLayoutEffect(()=>{const Ze=Zn.current;Ze!==null&&Ze!==k?(k&&Ee.hasCachedHistory(k)||(we(!0),fe(!1)),z.getState().currentSnapshot&&z.setCurrentSnapshot(null)):k||fe(!1),Zn.current=k},[k]),y.useEffect(()=>{if(!ae||Ee.fetchingHistory)return;const Ze=requestAnimationFrame(()=>{L.current&&(L.current.scrollTop=L.current.scrollHeight),we(!1)});return()=>cancelAnimationFrame(Ze)},[ae,Ee.fetchingHistory,Ee.historyLoadVersion]);const as=y.useRef(!1);y.useEffect(()=>{he&&k&&z.clearUnseenForAgent(k)},[he,k]),y.useEffect(()=>{as.current=!0,oe(!0)},[C,l]),y.useEffect(()=>{Ee.fetchingHistory&&(as.current=!0,oe(!0))},[Ee.fetchingHistory]),y.useEffect(()=>{if(!le||!he||Ee.fetchingHistory)return;const Ze=L.current;if(!Ze)return;let dt=null;const me=performance.now();let ze=0,Xe=-1;const ht=()=>{const{scrollTop:Nt,scrollHeight:Dt,clientHeight:Gt}=Ze;return Dt-Nt-Gt<=2},lt=()=>{const Nt=performance.now(),Dt=Ze.scrollHeight,Gt=Math.abs(Dt-Xe)<=1,Pn=ht();if(Gt&&Pn?ze+=1:ze=0,Xe=Dt,ze>=8){oe(!1),dt=null;return}if(Nt-me>8e3){oe(!1),dt=null;return}dt=requestAnimationFrame(lt)};return dt=requestAnimationFrame(lt),()=>{dt!==null&&cancelAnimationFrame(dt)}},[le,he,Ee.fetchingHistory,Ee.historyLoadVersion]);const _s=y.useRef(!1);y.useEffect(()=>{_s.current&&!le&&as.current&&(as.current=!1,fe(!0)),_s.current=le},[le]),y.useEffect(()=>{if(!he||!as.current||le||Ee.fetchingHistory)return;const Ze=requestAnimationFrame(()=>{as.current&&(as.current=!1,fe(!0))});return()=>cancelAnimationFrame(Ze)},[Ee.historyLoadVersion,he,le,Ee.fetchingHistory]),y.useEffect(()=>{const Ze=dt=>{if(dt.key==="`"&&!dt.ctrlKey&&!dt.altKey&&S){const me=dt.target;me.tagName!=="INPUT"&&me.tagName!=="TEXTAREA"&&(dt.preventDefault(),z.toggleTerminal())}};return document.addEventListener("keydown",Ze),()=>document.removeEventListener("keydown",Ze)},[S]),y.useEffect(()=>{const Ze=dt=>{dt.key==="Escape"&&(d?(dt.stopImmediatePropagation(),z.clearFileViewerPath()):m?(dt.stopImmediatePropagation(),z.closeContextModal()):de?(dt.stopImmediatePropagation(),F(null)):K?(dt.stopImmediatePropagation(),Q(null)):$?(dt.stopImmediatePropagation(),Y(null)):ce.searchMode&&(dt.stopImmediatePropagation(),ce.closeSearch()))};return document.addEventListener("keydown",Ze,!0),()=>document.removeEventListener("keydown",Ze,!0)},[$,K,de,ce,d,m]);const ds=y.useRef(he),mn=y.useRef(!1);y.useEffect(()=>{ds.current=he},[he]),y.useEffect(()=>{if(window.innerWidth<=768)return;const dt=Xe=>{var Dt;if(!(Xe instanceof Element))return!1;const ht=(Dt=T.current)==null?void 0:Dt.contains(Xe),lt=Xe.closest(".agent-bar"),Nt=!!Xe.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!!ht||!!lt||Nt},me=Xe=>{if(!ds.current){mn.current=!1;return}mn.current=!dt(Xe.target)},ze=Xe=>{mn.current&&(dt(Xe.target)||z.setTerminalOpen(!1),mn.current=!1)};return document.addEventListener("mousedown",me,!0),document.addEventListener("mouseup",ze,!0),()=>{document.removeEventListener("mousedown",me,!0),document.removeEventListener("mouseup",ze,!0)}},[]),y.useEffect(()=>{const Ze=()=>{document.hidden&&M.cleanup()};return document.addEventListener("visibilitychange",Ze),()=>document.removeEventListener("visibilitychange",Ze)},[M]);const Rn=typeof window<"u"&&window.innerWidth<=768;return S?C?r.jsxs("div",{ref:T,className:`guake-terminal ${he?"open":"collapsed"} ${ie&&he?"with-debug-panel":""} ${se&&he?"with-overview-panel":""}`,style:{"--terminal-height":`${_}%`},children:[!f&&ie&&he&&C&&r.jsx(RH,{agentId:C,onClose:()=>Z(!1)}),!f&&se&&he&&C&&r.jsx(IH,{activeAgentId:C,onClose:()=>pe(!1),onSelectAgent:Ze=>{z.selectAgent(Ze)}}),r.jsxs("div",{className:"guake-content",children:[r.jsx(Z9,{selectedAgent:S,selectedAgentId:C,sortedAgents:ne.sortedAgents,swipeOffset:ne.swipeOffset,viewMode:B,setViewMode:G,searchMode:ce.searchMode,toggleSearch:ce.toggleSearch,closeSearch:ce.closeSearch,debugPanelOpen:ie,setDebugPanelOpen:Z,debuggerEnabled:X,setDebuggerEnabled:q,overviewPanelOpen:se,setOverviewPanelOpen:pe,agentInfoOpen:V,onToggleAgentInfo:ot,outputsLength:gt.length+Mt.length,setContextConfirm:re,headerRef:ne.headerRef,onSaveSnapshot:f?void 0:e,isSnapshotView:f}),ce.searchMode&&r.jsx(Q9,{searchInputRef:ce.searchInputRef,searchQuery:ce.searchQuery,setSearchQuery:ce.setSearchQuery,handleSearch:ce.handleSearch,closeSearch:ce.closeSearch,searchLoading:ce.searchLoading,searchResultsCount:ce.searchResults.length}),r.jsxs("div",{className:`guake-swipe-container ${ne.swipeAnimationClass}`,style:ne.swipeOffset!==0?{transform:`translateX(${ne.swipeOffset*40}%)`}:void 0,children:[ne.sortedAgents.length>1&&ne.swipeOffset!==0&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:`swipe-indicator left ${ne.swipeOffset>.3?"visible":""}`,children:[r.jsx("span",{className:"indicator-icon",children:"←"}),r.jsx("span",{className:"indicator-name",children:(Wa=ne.prevAgent)==null?void 0:Wa.name})]}),r.jsxs("div",{className:`swipe-indicator right ${ne.swipeOffset<-.3?"visible":""}`,children:[r.jsx("span",{className:"indicator-name",children:(ca=ne.nextAgent)==null?void 0:ca.name}),r.jsx("span",{className:"indicator-icon",children:"→"})]})]}),ne.sortedAgents.length>1&&ne.sortedAgents.length<=8&&ne.swipeOffset!==0&&r.jsx("div",{className:`swipe-dots ${Math.abs(ne.swipeOffset)>.1?"visible":""}`,children:ne.sortedAgents.map((Ze,dt)=>r.jsx("div",{className:`swipe-dot ${dt===ne.currentAgentIndex?"active":""}`},Ze.id))}),r.jsx("div",{className:"guake-output",ref:L,onScroll:gs,children:ce.searchMode&&ce.searchResults.length>0?r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"guake-search-header",children:t("terminal:header.searchResultsTitle")}),ce.searchResults.map((Ze,dt)=>r.jsx(ov,{message:Ze,agentId:C,highlight:ce.searchQuery,onImageClick:Ne,onFileClick:be,onBashClick:De,onViewMarkdown:it},`s-${dt}`))]}):r.jsxs("div",{className:`guake-history-content ${ee?"fade-in":""}`,children:[ae&&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",{})]})]}),!ae&&Ee.loadingHistory&&Ee.history.length===0&&D.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",{})]})]}),!ae&&!Ee.loadingHistory&&Ee.history.length===0&&R.length===0&&S.status!=="working"&&r.jsx("div",{className:"guake-empty",children:t("terminal:empty.noOutput")}),!ae&&Ee.hasMore&&!ce.searchMode&&r.jsx("div",{className:"guake-load-more",children:Ee.loadingMore?r.jsx("span",{children:t("terminal:empty.loadingOlder")}):r.jsx("button",{onClick:Ee.loadMoreHistory,children:t("terminal:empty.loadMore",{count:Ee.totalCount-Ee.history.length})})}),!ae&&r.jsx(xE,{historyMessages:gt,liveOutputs:Mt,agentId:C,execTasks:nt,subagents:Je,viewMode:B,selectedMessageIndex:An.selectedIndex,isMessageSelected:An.isSelected,onImageClick:Ne,onFileClick:be,onBashClick:De,onViewMarkdown:it,scrollContainerRef:L,onScrollTopReached:Ee.loadMoreHistory,isLoadingMore:Ee.loadingMore,hasMore:Ee.hasMore,shouldAutoScroll:$t,onUserScroll:Et,pinToBottom:le,onPinCancel:un,isLoadingHistory:Ee.fetchingHistory},C),!ae&&Ce&&We.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:We.size})})]}),Array.from(We.values()).map(Ze=>r.jsx(zH,{progress:Ze,defaultExpanded:Ze.status==="working",onAgentClick:z.selectAgent},Ze.agentId))]})]})})]}),r.jsx(iH,{selectedAgent:S,selectedAgentId:C,isOpen:he,command:ge.command,setCommand:ge.setCommand,forceTextarea:ge.forceTextarea,setForceTextarea:ge.setForceTextarea,useTextarea:ge.useTextarea,attachedFiles:ge.attachedFiles,setAttachedFiles:ge.setAttachedFiles,removeAttachedFile:ge.removeAttachedFile,uploadFile:ge.uploadFile,pastedTexts:ge.pastedTexts,expandPastedTexts:ge.expandPastedTexts,incrementPastedCount:ge.incrementPastedCount,setPastedTexts:ge.setPastedTexts,resetPastedCount:ge.resetPastedCount,handleInputFocus:M.handleInputFocus,handleInputBlur:M.handleInputBlur,pendingPermissions:Me,showCompletion:Se,completionElapsed:xe,onImageClick:Ne,inputRef:O,textareaRef:I,isSnapshotView:f,onClearHistory:Ee.clearHistory}),r.jsxs("div",{className:"guake-agent-status-bar",children:[!f&&(S==null?void 0:S.isDetached)&&r.jsx(Gp,{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")]})}),(S==null?void 0:S.cwd)&&r.jsxs("span",{className:"guake-agent-cwd",children:["📁 ",S.cwd.split("/").filter(Boolean).slice(-2).join("/")||S.cwd]}),!f&&S&&(()=>{const Ze=S.contextStats,dt=!!Ze,me=Ze?Ze.totalTokens:S.contextUsed||0,ze=Ze?Ze.contextWindow:S.contextLimit||2e5,Xe=Ze?Ze.usedPercent:Math.round(me/ze*100),ht=Math.round(100-Xe),lt=Xe>=80?"#ff4a4a":Xe>=60?"#ff9e4a":Xe>=40?"#ffd700":"#4aff9e",Nt=(me/1e3).toFixed(1),Dt=(ze/1e3).toFixed(1);return r.jsxs("span",{className:"guake-agent-context",onClick:()=>z.setContextModalAgentId(C),title:t(dt?"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,Xe)}%`,backgroundColor:lt}})}),r.jsxs("span",{className:"context-tokens",style:{color:lt},children:[Nt,"k/",Dt,"k"]}),r.jsxs("span",{className:"context-free",children:["(",t("terminal:context.percentFree",{percent:ht}),")"]}),!dt&&r.jsx("span",{className:"context-warning",title:t("terminal:context.clickToFetchStats"),children:"⚠️"})]})})(),r.jsx(sU,{})]})]}),he&&r.jsx("div",{className:"guake-resize-handle",onMouseDown:P,title:t("common:rightPanel.dragToResize")}),r.jsxs("div",{className:"guake-handle",onClick:()=>{he&&z.toggleTerminal()},onDoubleClick:()=>{he||z.toggleTerminal()},style:{top:he?`min(${_}%, calc(100vh - 72px))`:"0"},children:[r.jsx("span",{className:"guake-handle-icon",children:he?"▲":"▼"}),r.jsx("span",{className:"guake-handle-text",children:S.name})]}),$&&r.jsx(lE,{url:$.url,name:$.name,onClose:()=>Y(null)}),K&&r.jsx(cE,{state:K,onClose:()=>Q(null)}),H&&r.jsx(lH,{action:H,selectedAgentId:C,subordinateCount:((qs=S==null?void 0:S.subordinateIds)==null?void 0:qs.length)||0,onClose:()=>re(null),onClearHistory:Ee.clearHistory}),r.jsx(cH,{}),r.jsx(uH,{}),r.jsx(dH,{agent:S,isOpen:V,onClose:()=>J(!1)}),!f&&r.jsx(uE,{agent:S,content:de,onClose:()=>F(null)})]}):null:Rn&&c==="terminal"&&a.size===0?r.jsx("div",{ref:T,className:"guake-terminal open",style:{"--terminal-height":`${_}%`},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")})]})})})}):Rn&&c==="terminal"&&a.size>0?r.jsx("div",{ref:T,className:"guake-terminal open",style:{"--terminal-height":`${_}%`},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});function lU(s){return s.trim().replace(/^v/i,"")}function R1(s){const t=lU(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 cU(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 uU(s,e){const t=R1(s),n=R1(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 cU(t.prerelease,n.prerelease)}function dU(s,e){const t=uU(s,e);return t===null?"unknown":t<0?"behind":t>0?"ahead":"equal"}async function hU(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 pU(s,e,t={}){const n=await hU(s,t);return n?{currentVersion:e,latestVersion:n,relation:dU(e,n)}:{currentVersion:e,latestVersion:null,relation:"unknown"}}const mU="tide-commander",Rb="0.78.1";function fU(){const[s,e]=y.useState({currentVersion:Rb,latestVersion:null,relation:"unknown",isChecking:!1}),t=y.useCallback(async()=>{e(a=>({...a,isChecking:!0}));const n=await pU(mU,Rb);e({currentVersion:Rb,latestVersion:n.latestVersion,relation:n.relation,isChecking:!1})},[]);return y.useEffect(()=>{t()},[t]),{...s,refresh:t}}const gU=y.memo(function({agent:e,currentIndex:t,agentIndex:n,isSelected:a,hasUnseenOutput:i,isDragging:o,isDragOver:l,customClasses:c,onDragStart:d,onDragEnd:m,onDragOver:p,onDragEnter:f,onDragLeave:b,onDrop:x,onAgentClick:w,onAgentDoubleClick:k,onHoverEnter:j,onHoverLeave:S,onItemRef:C}){const A=y.useMemo(()=>co(e.class,c),[e.class,c]),_=y.useCallback(T=>{C(e.id,T)},[e.id,C]);return r.jsxs("div",{ref:_,className:`agent-bar-item ${a?"selected":""} ${e.status} ${e.isBoss?"is-boss":""} ${o?"dragging":""} ${l?"drag-over":""}`,draggable:!0,onDragStart:T=>d(T,e),onDragEnd:m,onDragOver:T=>p(T,n),onDragEnter:T=>f(T,n),onDragLeave:b,onDrop:T=>x(T,n),onClick:T=>w(e,T),onDoubleClick:()=>k(e),onMouseEnter:()=>j(e),onMouseLeave:S,title:`${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:A.icon}),r.jsx("span",{className:"agent-bar-status",style:{backgroundColor:px(e.status)}}),i&&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:hm(e.lastActivity)},title:pm(e.lastActivity),children:"⏱"})]}),r.jsxs("span",{className:"agent-bar-hotkey",title:`Ctrl+${t+1}`,children:["^",t+1]})]})}),bU=y.memo(function({onFocusAgent:e,onSpawnClick:t,onSpawnBossClick:n,onNewBuildingClick:a,onNewAreaClick:i}){const{t:o}=Ue(["common"]),l=ui(),c=cl(),d=bm(),m=Az(),p=Tx(),f=lo(),b=di(),x=Px(),[w,k]=y.useState(!1);oM("AgentBar");const j=y.useRef(null),S=y.useRef(null),C=y.useRef(null),A=y.useRef(new Map);y.useEffect(()=>{{k(!1);return}},[f.experimental2DView]),y.useEffect(()=>{const ae=S.current;if(!ae)return;const we=he=>{ae.scrollWidth<=ae.clientWidth||(he.preventDefault(),ae.scrollLeft+=he.deltaY)};return ae.addEventListener("wheel",we,{passive:!1}),()=>ae.removeEventListener("wheel",we)},[]);const[_,T]=y.useState(null),[P,M]=y.useState(new Map),[D,R]=y.useState(null),[L,O]=y.useState(null),I=y.useRef(0),B=y.useMemo(()=>Array.from(l.values()).filter(ae=>!z.isAgentInArchivedArea(ae.id)).sort((ae,we)=>(ae.createdAt||0)-(we.createdAt||0)),[l,c]),{orderedAgents:G,moveAgent:$}=MM(B),Y=G,K=y.useMemo(()=>{const ae=new Map;for(const we of Y)ae.set(we.id,z.getAreaForAgent(we.id));return ae},[Y,c]),Q=y.useMemo(()=>{const ae=new Map;for(const he of Y){const Ee=K.get(he.id)||null,ce=(Ee==null?void 0:Ee.id)||null;ae.has(ce)||ae.set(ce,{area:Ee,agents:[]}),ae.get(ce).agents.push(he)}const we=Array.from(ae.values());return we.sort((he,Ee)=>{var ce,ne;return!he.area&&Ee.area?1:he.area&&!Ee.area?-1:!he.area&&!Ee.area?0:(((ce=he.area)==null?void 0:ce.name)||"").localeCompare(((ne=Ee.area)==null?void 0:ne.name)||"")}),we},[Y,K]),H=y.useRef(e);H.current=e;const re=y.useRef(D);re.current=D;const de=y.useRef(Y);de.current=Y;const F=y.useRef(K);F.current=K;const V=y.useRef($);V.current=$,y.useEffect(()=>{const ae=new Map(P);let we=!1;for(const he of Y){const Ee=P.get(he.id);he.currentTool?(!Ee||Ee.tool!==he.currentTool)&&(ae.set(he.id,{tool:he.currentTool,key:Date.now()}),we=!0):Ee&&setTimeout(()=>{M(ce=>{const ne=new Map(ce);return ne.delete(he.id),ne})},1500)}we&&M(ae)},[Y.map(ae=>ae.currentTool).join(",")]),y.useEffect(()=>{const ae=m;if(!ae)return;const we=A.current.get(ae),he=S.current;we&&he&&requestAnimationFrame(()=>{const Ee=we.getBoundingClientRect(),ce=he.getBoundingClientRect(),ge=Ee.left-ce.left+he.scrollLeft+Ee.width/2,ue=he.clientWidth;he.scrollTo({left:ge-ue/2,behavior:"smooth"})})},[m]);const J=y.useCallback((ae,we)=>{z.setLastSelectionViaDirectClick(!0),we.shiftKey?z.addToSelection(ae.id):z.selectAgent(ae.id),z.setTerminalOpen(!0)},[]),ie=y.useCallback(ae=>{var we;(we=H.current)==null||we.call(H,ae.id),z.setTerminalOpen(!0)},[]),Z=y.useCallback(()=>T(null),[]),X=y.useCallback((ae,we)=>{we?A.current.set(ae,we):A.current.delete(ae)},[]),q=y.useCallback((ae,we)=>{R(we),ae.dataTransfer.effectAllowed="move",ae.dataTransfer.setData("text/plain",we.id),requestAnimationFrame(()=>{ae.target.classList.add("dragging")})},[]),se=y.useCallback(ae=>{R(null),O(null),I.current=0,ae.target.classList.remove("dragging")},[]),pe=y.useCallback((ae,we)=>{ae.preventDefault();const he=re.current;if(he){const Ee=F.current.get(he.id),ce=de.current[we],ne=ce?F.current.get(ce.id):null,ge=(Ee==null?void 0:Ee.id)??null,ue=(ne==null?void 0:ne.id)??null;ae.dataTransfer.dropEffect=ge===ue?"move":"none"}else ae.dataTransfer.dropEffect="move"},[]),Se=y.useCallback((ae,we)=>{ae.preventDefault(),I.current++;const he=re.current;if(he){const Ee=F.current.get(he.id),ce=de.current[we],ne=ce?F.current.get(ce.id):null,ge=(Ee==null?void 0:Ee.id)??null,ue=(ne==null?void 0:ne.id)??null;O(ge===ue?we:null)}else O(we)},[]),Te=y.useCallback(ae=>{I.current--,I.current===0&&O(null)},[]),xe=y.useCallback((ae,we)=>{ae.preventDefault();const he=re.current;if(!he)return;const Ee=de.current,ce=F.current,ne=Ee.findIndex(ge=>ge.id===he.id);if(ne!==-1&&ne!==we){const ge=ce.get(he.id),ue=Ee[we],Me=ue?ce.get(ue.id):null,Ce=(ge==null?void 0:ge.id)??null,We=(Me==null?void 0:Me.id)??null;Ce===We&&V.current(ne,we)}R(null),O(null),I.current=0},[]),$e=ae=>{const we=`common:status.${ae}`;return o(we,{defaultValue:o("common:status.unknown")})},{currentVersion:Pe,latestVersion:ve,relation:ee,isChecking:fe}=fU(),le=Pe;let oe=0;return r.jsxs("div",{className:"agent-bar",ref:j,children:[r.jsxs("div",{className:"agent-bar-scroll",ref:S,children:[r.jsxs("div",{className:"agent-bar-version",title:ve?`Tide Commander v${le} (npm: v${ve})`:`Tide Commander v${le}`,children:[r.jsxs("span",{children:["v",le]}),ee==="behind"&&ve?r.jsxs("span",{className:"agent-bar-version-badge agent-bar-version-badge-behind",title:`Behind npm latest v${ve}`,children:["npm v",ve]}):ee==="ahead"&&ve?r.jsxs("span",{className:"agent-bar-version-badge agent-bar-version-badge-ahead",title:`Ahead of npm latest v${ve}`,children:["npm v",ve]}):null,ee==="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)"})}):ee==="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)"})}):ee==="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")}):fe?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:AM,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")})]}),Q.map(ae=>{var Ee,ce,ne,ge,ue;const we=ae.agents,he=!ae.area;return r.jsxs("div",{className:`agent-bar-group ${he?"unassigned":""}`,style:{borderColor:((Ee=ae.area)==null?void 0:Ee.color)||void 0,background:ae.area?`${ae.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:((ce=ae.area)==null?void 0:ce.color)||"#888"},children:((ne=ae.area)==null?void 0:ne.name)||o("common:agentBar.unassigned")})}),((ge=ae.area)==null?void 0:ge.directories)&&ae.area.directories.length>0&&r.jsx("div",{className:"agent-bar-folders",children:ae.area.directories.map((Me,Ce)=>r.jsxs("div",{className:"agent-bar-folder-item",onClick:We=>{We.stopPropagation(),z.openFileExplorer(Me)},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:Me}),r.jsx("div",{className:"agent-bar-folder-tooltip-hint",children:o("common:agentBar.clickToOpen")})]})]},Ce))}),we.map(Me=>{const Ce=oe++,We=Y.findIndex(nt=>nt.id===Me.id);return r.jsx(gU,{agent:Me,currentIndex:Ce,agentIndex:We,isSelected:d.has(Me.id),hasUnseenOutput:x.has(Me.id),isDragging:(D==null?void 0:D.id)===Me.id,isDragOver:L===We,customClasses:b,onDragStart:q,onDragEnd:se,onDragOver:pe,onDragEnter:Se,onDragLeave:Te,onDrop:xe,onAgentClick:J,onAgentDoubleClick:ie,onHoverEnter:T,onHoverLeave:Z,onItemRef:X},Me.id)})]},((ue=ae.area)==null?void 0:ue.id)||"unassigned")})]})]}),Array.from(P.entries()).map(([ae,we])=>{const he=A.current.get(ae);if(!he)return null;const Ee=he.getBoundingClientRect(),ce=es[we.tool]||es.default;return r.jsxs("div",{className:"agent-bar-tool-bubble",title:we.tool,style:{position:"fixed",left:Ee.left+Ee.width/2,bottom:window.innerHeight-Ee.top+8},children:[r.jsx("span",{className:"agent-bar-tool-icon",children:ce}),r.jsx("span",{className:"agent-bar-tool-name",children:we.tool})]},`tool-${ae}-${we.key}`)}),_&&(()=>{const ae=z.getAreaForAgent(_.id),we=p.get(_.id),he=co(_.class,b),Ee=z.getAgentSupervisorHistory(_.id),ce=Ee.length>0?Ee[Ee.length-1]:void 0,ne=Date.now()-(_.createdAt||Date.now()),ge=Math.floor(ne/6e4),ue=Math.floor(ge/60),Me=ue>0?`${ue}h ${ge%60}m`:`${ge}m`,Ce=et=>et>=1e6?`${(et/1e6).toFixed(1)}M`:et>=1e3?`${(et/1e3).toFixed(1)}K`:et.toString(),We=_.contextLimit>0?Math.round(_.contextUsed/_.contextLimit*100):0,nt=et=>{switch(et){case"on_track":return"#4aff9e";case"completed":return"#4a9eff";case"stalled":return"#ff9e4a";case"blocked":return"#ff4a4a";case"idle":return"#888888";default:return"#888888"}},Je=A.current.get(_.id),ct={};if(Je){const et=Je.getBoundingClientRect();ct.position="fixed",ct.left=et.left+et.width/2,ct.bottom=window.innerHeight-et.top+12}return r.jsxs("div",{className:"agent-bar-tooltip",style:ct,children:[r.jsxs("div",{className:"agent-bar-tooltip-header",children:[r.jsx("span",{className:"agent-bar-tooltip-icon",children:he.icon}),r.jsxs("span",{className:"agent-bar-tooltip-name",children:[r.jsx("img",{src:_.provider==="codex"?"/assets/codex.png":"/assets/claude.png",alt:_.provider,className:"agent-bar-provider-icon",title:_.provider==="codex"?"Codex Agent":"Claude Agent"}),_.name]}),r.jsx("span",{className:"agent-bar-tooltip-status",style:{color:px(_.status)},children:$e(_.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:[_.class," — ",he.description]})]}),ae&&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:ae.color},children:ae.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:_.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:Me})]}),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:[Ce(_.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:We>80?"#ff4a4a":We>60?"#ff9e4a":void 0},children:[Ce(_.contextUsed)," / ",Ce(_.contextLimit)," (",We,"%)"]})]}),_.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:[es[_.currentTool]||es.default," ",_.currentTool]})]}),_.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:[_.currentTask.substring(0,150),_.currentTask.length>150?"...":""]})]}),_.lastAssignedTask&&!_.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:[_.lastAssignedTask.substring(0,200),_.lastAssignedTask.length>200?"...":""]})]}),we&&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:[we.text.substring(0,300),we.text.length>300?"...":""]})]}),ce&&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:nt(ce.analysis.progress)},children:ce.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:ce.analysis.statusDescription})]}),ce.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:[ce.analysis.recentWorkSummary.substring(0,300),ce.analysis.recentWorkSummary.length>300?"...":""]})]}),ce.analysis.concerns&&ce.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:ce.analysis.concerns.join("; ")})]})]})]})]})})()]})});function yU({activeTool:s,onExit:e}){const{t}=Ue(["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 xU={idle:"common:status.idle",working:"common:status.working",waiting:"common:status.waiting",error:"common:status.error",offline:"common:status.offline"},Pb=s=>s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(1)}K`:s.toString(),vU=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"}},wU=y.memo(function({agent:e,screenPos:t,onClose:n}){const{t:a}=Ue(["common"]),i=di(),o=z.getAreaForAgent(e.id),l=z.getState().lastPrompts.get(e.id),c=co(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,A=t.y-320-10;return typeof window<"u"&&(C<10?C=10:C+300>window.innerWidth-10&&(C=window.innerWidth-300-10),A<10&&(A=t.y+10)),{position:"fixed",left:C,top:A,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:px(e.status)},children:a(xU[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:[Pb(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:[Pb(e.contextUsed)," / ",Pb(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:[es[e.currentTool]||es.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:vU(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 P1(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 L1(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 O1={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 kU(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:O1[l]&&(a=O1[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 SU=y.memo(function({building:e,screenPos:t,onClose:n,onOpenSettings:a,onOpenLogsModal:i,onOpenUrlInModal:o}){var $,Y,K,Q,H,re,de,F,V,J,ie,Z,X,q,se,pe,Se,Te,xe,$e;const{t:l}=Ue(["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}=$n(),j=z.getBuildingLogs(e.id),S=($=e.pm2)==null?void 0:$.enabled,C=(Y=e.docker)==null?void 0:Y.enabled,A=y.useRef(null),_=y.useRef(null),T=y.useCallback(Pe=>{Pe.preventDefault();const ve=w.current?w.current.x:0,ee=w.current?w.current.y:0;x.current={mouseX:Pe.clientX,mouseY:Pe.clientY,popupX:ve,popupY:ee},b(!0),A.current=fe=>{if(!x.current)return;const le=fe.clientX-x.current.mouseX,oe=fe.clientY-x.current.mouseY;p({x:x.current.popupX+le,y:x.current.popupY+oe})},_.current=()=>{b(!1),x.current=null,A.current&&document.removeEventListener("mousemove",A.current),_.current&&document.removeEventListener("mouseup",_.current)},document.addEventListener("mousemove",A.current),document.addEventListener("mouseup",_.current)},[]);y.useEffect(()=>()=>{A.current&&document.removeEventListener("mousemove",A.current),_.current&&document.removeEventListener("mouseup",_.current)},[]);const P=Pe=>{if(Pe==="logs"){if((S||C)&&i){i();return}z.sendBuildingCommand(e.id,Pe),d(!0)}else z.sendBuildingCommand(e.id,Pe)},M=(Pe,ve)=>{if(Pe){const ee=`http://localhost:${Pe}`;ve&&o?o(ee):window.open(ee,"_blank")}},D=((K=e.pm2Status)==null?void 0:K.ports)||[],R=((H=(Q=e.dockerStatus)==null?void 0:Q.ports)==null?void 0:H.map(Pe=>Pe.host))||[],L=S?D:C?R:[],O=S?!!((re=e.pm2)!=null&&re.script):C?!!((de=e.docker)!=null&&de.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=S?!!((ie=e.pm2)!=null&&ie.script):C?!0:!!((Z=e.commands)!=null&&Z.stop),B=S?!!((X=e.pm2)!=null&&X.script):C?!0:!!((q=e.commands)!=null&&q.restart),G=y.useMemo(()=>{const ve=c?400:250;let ee=t.x+20,fe=t.y-80;return typeof window<"u"&&!m&&(t.x+20+280>window.innerWidth&&(ee=t.x-280-20),t.y-80<0?fe=10:t.y-80+ve>window.innerHeight&&(fe=window.innerHeight-ve-10)),{position:"fixed",left:ee+((m==null?void 0:m.x)||0),top:fe+((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:G,onClick:Pe=>Pe.stopPropagation(),children:[r.jsxs("div",{className:`building-popup-header ${f?"dragging":""}`,onMouseDown:T,children:[r.jsx("span",{className:"building-popup-name",children:e.name}),L.length>0&&r.jsx("span",{className:"building-popup-ports",children:L.map(Pe=>r.jsxs("a",{href:`http://localhost:${Pe}`,className:"building-popup-port-link",onClick:ve=>{ve.preventDefault(),ve.stopPropagation(),M(Pe,ve.altKey)},onMouseDown:ve=>ve.stopPropagation(),title:`Open http://localhost:${Pe} (Alt+Click for modal)`,children:[":",Pe]},Pe))}),r.jsx("span",{className:"building-popup-status",style:{backgroundColor:ao[e.status]},children:e.status}),r.jsx("button",{className:"building-popup-close",onClick:n,children:"x"})]}),S&&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:[((se=e.pm2Status.cpu)==null?void 0:se.toFixed(1))||"0","%"]})]}),r.jsxs("span",{className:"metric",children:[r.jsx("span",{className:"label",children:"MEM"}),r.jsx("span",{className:"value",children:P1(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:L1(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:P1(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:L1(e.dockerStatus.startedAt)})]})]}),C&&((pe=e.dockerStatus)==null?void 0:pe.services)&&e.dockerStatus.services.length>0&&r.jsx("div",{className:"building-popup-services",children:e.dockerStatus.services.map((Pe,ve)=>r.jsxs("span",{className:"service-item",title:`${Pe.name}: ${Pe.status}`,children:[r.jsx("span",{className:"service-indicator",style:{backgroundColor:Pe.status==="running"?"#4ade80":"#f87171"}}),r.jsx("span",{className:"service-name",children:Pe.name})]},ve))}),(e.lastError||S&&((Se=e.pm2Status)==null?void 0:Se.status)==="errored"||C&&((Te=e.dockerStatus)==null?void 0:Te.status)==="dead")&&r.jsxs("div",{className:"building-popup-error",children:[e.lastError||l("terminal:building.processFailedToStart"),S&&((xe=e.pm2Status)==null?void 0:xe.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:()=>P("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:()=>P("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:()=>P("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:()=>P("logs"),title:l("terminal:buildingAction.viewLogs"),children:[r.jsx("span",{className:"icon",children:"📄"}),l("terminal:logs.title")]}),L.length===1&&r.jsxs("button",{className:"action-btn open-url",onClick:Pe=>M(L[0],Pe.altKey),title:`Open http://localhost:${L[0]} (Alt+Click for modal)`,children:[r.jsx("span",{className:"icon",children:"🔗"}),l("terminal:buildingAction.openInBrowser")]}),L.length>1&&r.jsxs("div",{className:"action-btn-group",children:[r.jsxs("span",{className:"action-btn-label",children:[l("terminal:buildingAction.openInBrowser"),":"]}),L.map(Pe=>r.jsxs("button",{className:"action-btn open-url port-btn",onClick:ve=>M(Pe,ve.altKey),title:`Open http://localhost:${Pe} (Alt+Click for modal)`,children:[":",Pe]},Pe))]})]}),c&&j.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:j.slice(-50).map((Pe,ve)=>r.jsx("pre",{children:kU(Pe)},ve))})]}),r.jsx("button",{className:"building-popup-settings",onClick:a,children:l("terminal:buildingAction.fullSettings")})]})});function jU(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 CU(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 NU=y.memo(function({building:e,screenPos:t,onClose:n,onOpenSettings:a,onOpenLogsModal:i,onOpenUrlInModal:o}){const{t:l}=Ue(["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}=$n(),k=(e.subordinateBuildingIds||[]).map(D=>x.get(D)).filter(D=>D!==void 0),j=y.useRef(null),S=y.useRef(null),C=y.useCallback(D=>{D.preventDefault();const R=b.current?b.current.x:0,L=b.current?b.current.y:0;f.current={mouseX:D.clientX,mouseY:D.clientY,popupX:R,popupY:L},p(!0),j.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})},S.current=()=>{p(!1),f.current=null,j.current&&document.removeEventListener("mousemove",j.current),S.current&&document.removeEventListener("mouseup",S.current)},document.addEventListener("mousemove",j.current),document.addEventListener("mouseup",S.current)},[]);y.useEffect(()=>()=>{j.current&&document.removeEventListener("mousemove",j.current),S.current&&document.removeEventListener("mouseup",S.current)},[]);const A=D=>{z.sendBossBuildingCommand(e.id,D)},_=k.reduce((D,R)=>(D[R.status]=(D[R.status]||0)+1,D),{}),T=k.some(D=>{var R;return(R=D.pm2)==null?void 0:R.enabled}),P=(D,R)=>{const L=`http://localhost:${D}`;R&&o?o(L):window.open(L,"_blank")},M=y.useMemo(()=>{let L=t.x+20,O=t.y-80;return typeof window<"u"&&!c&&(t.x+20+340>window.innerWidth&&(L=t.x-340-20),t.y-80<0?O=10:t.y-80+350>window.innerHeight&&(O=window.innerHeight-350-10)),{position:"fixed",left:L+((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(_).map(([D,R])=>r.jsxs("span",{className:"status-badge",style:{backgroundColor:ao[D]||"#666"},children:[R," ",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 R,L,O;return r.jsxs("div",{className:"subordinate-item",children:[r.jsx("span",{className:"sub-status-dot",style:{backgroundColor:ao[D.status]}}),r.jsx("span",{className:"sub-name",children:D.name}),((R=D.pm2Status)==null?void 0:R.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(),P(I,B.altKey)},title:`Open http://localhost:${I} (Alt+Click for modal)`,children:[":",I]},I))}),D.pm2Status&&r.jsxs("span",{className:"sub-metrics",children:[(L=D.pm2Status.cpu)==null?void 0:L.toFixed(0),"% | ",jU(D.pm2Status.memory||0)]}),((O=D.pm2Status)==null?void 0:O.uptime)&&r.jsx("span",{className:"sub-uptime",children:CU(D.pm2Status.uptime)})]},D.id)})}),r.jsxs("div",{className:"building-popup-actions boss-actions",children:[r.jsxs("button",{className:"action-btn start",onClick:()=>A("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:()=>A("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:()=>A("restart_all"),disabled:k.length===0,title:l("terminal:building.restartAllSubs"),children:[r.jsx("span",{className:"icon",children:"↺"}),l("terminal:building.restartAll")]}),T&&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")})]})}),AU=y.memo(function({building:e,screenPos:t,onClose:n,onOpenSettings:a,onOpenDatabasePanel:i}){var _;const{t:o}=Ue(["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=xm(e.id),x=((_=e.database)==null?void 0:_.connections)??[],w=y.useRef(null),k=y.useRef(null),j=y.useCallback(T=>{T.preventDefault();const P=f.current?f.current.x:0,M=f.current?f.current.y:0;p.current={mouseX:T.clientX,mouseY:T.clientY,popupX:P,popupY:M},m(!0),w.current=D=>{if(!p.current)return;const R=D.clientX-p.current.mouseX,L=D.clientY-p.current.mouseY;c({x:p.current.popupX+R,y:p.current.popupY+L})},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 S=T=>{z.testDatabaseConnection(e.id,T)},C=T=>b.connectionStatus.get(T),A=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:A,onClick:T=>T.stopPropagation(),children:[r.jsxs("div",{className:`building-popup-header database-header ${d?"dragging":""}`,onMouseDown:j,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(T=>{const P=C(T.id);return r.jsxs("div",{className:"database-connection-item",children:[r.jsx("span",{className:"conn-engine",children:T.engine==="mysql"?"🐬":"🐘"}),r.jsx("span",{className:"conn-name",children:T.name}),r.jsxs("span",{className:"conn-host",children:[T.host,":",T.port]}),P&&r.jsx("span",{className:`conn-status ${P.connected?"connected":"disconnected"}`,children:P.connected?"●":"○"}),r.jsx("button",{className:"conn-test-btn",onClick:()=>S(T.id),title:o("terminal:building.testConnection"),children:"↻"})]},T.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(T=>S(T.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")})]})}),MU=({building:s,connections:e,activeConnectionId:t,activeDatabase:n,collapsed:a,onToggleCollapse:i,onConnectionChange:o,onDatabaseChange:l,onInsertTable:c,onSelectTableQuery:d})=>{const{t:m}=Ue(["terminal"]),p=xm(s.id),[f,b]=y.useState(new Set),[x,w]=y.useState(""),[k,j]=y.useState(!1),[S,C]=y.useState(null),A=y.useRef(null),_=y.useRef(null),T=t?p.databases.get(t)??[]:[],P=t&&n?`${t}:${n}`:"",M=P?p.tables.get(P)??[]:[],D=t?p.connectionStatus.get(t):void 0,R=y.useMemo(()=>{if(!x.trim())return T;const I=x.toLowerCase();return T.filter(B=>B.toLowerCase().includes(I))},[T,x]);y.useEffect(()=>{const I=B=>{_.current&&!_.current.contains(B.target)&&j(!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)&&T.length===0&&z.listDatabases(s.id,t)},[s.id,t,D==null?void 0:D.connected,T.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 L=y.useCallback(I=>{b(B=>{const G=new Set(B);if(G.has(I))G.delete(I);else if(G.add(I),t&&n){const $=`${t}:${n}:${I}`;p.tableSchemas.has($)||z.getTableSchema(s.id,t,n,I)}return G})},[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")]})})]}),T.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:_,children:[r.jsx("input",{ref:A,className:"database-sidebar__search-input",type:"text",value:k?x:n||"",placeholder:m("terminal:database.selectDatabase"),onChange:I=>{w(I.target.value),k||j(!0)},onFocus:()=>{j(!0),w("")},onKeyDown:I=>{var B,G;I.key==="Escape"?(j(!1),w(""),(B=A.current)==null||B.blur()):I.key==="Enter"&&R.length===1&&(l(R[0]),j(!1),w(""),(G=A.current)==null||G.blur())}}),k&&r.jsx("div",{className:"database-sidebar__dropdown",children:R.length===0?r.jsx("div",{className:"database-sidebar__dropdown-empty",children:"No matches"}):R.map(I=>r.jsx("div",{className:`database-sidebar__dropdown-item ${I===n?"database-sidebar__dropdown-item--active":""}`,onMouseDown:B=>{B.preventDefault(),l(I),j(!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),G=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:()=>L(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 ${S===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&&G&&r.jsx("div",{className:"database-sidebar__table-columns",children:G.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 uv(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===`
|
|
234
234
|
`&&(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 TU(s,e){const t=uv(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 EU=({query:s,onChange:e,onExecute:t,isExecuting:n,disabled:a,autoFocus:i=!0})=>{const{t:o}=Ue(["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 P=localStorage.getItem(m);if(P){const M=Number(P);if(M>=p&&M<=f)return M}}catch{}return 150}),w=y.useCallback(P=>{try{localStorage.setItem(m,String(P))}catch{}},[]),k=y.useCallback(P=>{P.preventDefault(),d.current=!0;const M=P.clientY,D=b,R=O=>{const I=O.clientY-M,B=Math.max(p,Math.min(f,D+I));x(B)},L=()=>{var I;d.current=!1,document.removeEventListener("mousemove",R),document.removeEventListener("mouseup",L),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",R),document.addEventListener("mouseup",L),document.body.style.cursor="row-resize",document.body.style.userSelect="none"},[b,w]);y.useEffect(()=>{if(i&&!a&&l.current){const P=setTimeout(()=>{var M;(M=l.current)==null||M.focus()},100);return()=>clearTimeout(P)}},[i,a]);const j=y.useCallback(P=>{const M=P.currentTarget;c.current&&(c.current.scrollLeft=M.scrollLeft,c.current.scrollTop=M.scrollTop)},[]),S=y.useMemo(()=>uv(s).length>1,[s]),C=y.useCallback(P=>{if((P.ctrlKey||P.metaKey)&&P.shiftKey&&P.key==="Enter"){P.preventDefault(),!a&&!n&&t("all");return}if((P.ctrlKey||P.metaKey)&&P.key==="Enter"&&(P.preventDefault(),!a&&!n&&t("cursor")),P.key==="Tab"){P.preventDefault();const M=P.currentTarget,D=M.selectionStart,R=M.selectionEnd,L=s.substring(0,D)+" "+s.substring(R);e(L),setTimeout(()=>{M.selectionStart=M.selectionEnd=D+2},0)}},[s,e,t,a,n]),A=y.useMemo(()=>{if(!s)return"";try{return rl.highlight(s,rl.languages.sql,"sql")}catch{return s}},[s]),_=y.useMemo(()=>s.split(`
|
|
235
235
|
`).map((M,D)=>D+1),[s]),T=y.useCallback(()=>{var P;return((P=l.current)==null?void 0:P.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(S?"terminal:database.runAtCursor":"terminal:database.runQuery")]})}),S&&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(S?"terminal:database.pressCtrlEnterMulti":"terminal:database.pressCtrlEnter")})]}),r.jsxs("div",{className:"query-editor__input-wrapper",children:[r.jsx("div",{className:"query-editor__line-numbers",children:_.map(P=>r.jsx("span",{children:P},P))}),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:A+`
|
|
236
236
|
`}}),r.jsx("textarea",{ref:l,className:"query-editor__textarea",value:s,onChange:P=>e(P.target.value),onKeyDown:C,onScroll:j,placeholder:o(a?"terminal:database.selectDbPlaceholder":"terminal:database.enterQueryPlaceholder"),disabled:a,spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off","data-cursor-pos":T()})]})]}),r.jsx("div",{className:"query-editor__resize-handle",onMouseDown:k})]})};function wE(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=wE(s[e]))&&(n&&(n+=" "),n+=t)}else for(t in s)s[t]&&(n&&(n+=" "),n+=t);return n}function fs(){for(var s,e,t=0,n="",a=arguments.length;t<a;t++)(s=arguments[t])&&(e=wE(s))&&(n&&(n+=" "),n+=e);return n}const kE=6048e5,_U=864e5,Am=6e4,Mm=36e5,DU=1e3,I1=Symbol.for("constructDateFrom");function xn(s,e){return typeof s=="function"?s(e):s&&typeof s=="object"&&I1 in s?s[I1](e):s instanceof Date?new s.constructor(e):new Date(e)}function vt(s,e){return xn(e||s,s)}function ai(s,e,t){const n=vt(s,t==null?void 0:t.in);return isNaN(e)?xn((t==null?void 0:t.in)||s,NaN):(e&&n.setDate(n.getDate()+e),n)}function ri(s,e,t){const n=vt(s,t==null?void 0:t.in);if(isNaN(e))return xn(s,NaN);if(!e)return n;const a=n.getDate(),i=xn(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 SE(s,e,t){return xn(s,+vt(s)+e)}function RU(s,e,t){return SE(s,e*Mm)}let PU={};function dl(){return PU}function pr(s,e){var l,c,d,m;const t=dl(),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=vt(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 wc(s,e){return pr(s,{...e,weekStartsOn:1})}function jE(s,e){const t=vt(s,e==null?void 0:e.in),n=t.getFullYear(),a=xn(t,0);a.setFullYear(n+1,0,4),a.setHours(0,0,0,0);const i=wc(a),o=xn(t,0);o.setFullYear(n,0,4),o.setHours(0,0,0,0);const l=wc(o);return t.getTime()>=i.getTime()?n+1:t.getTime()>=l.getTime()?n:n-1}function Vp(s){const e=vt(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 gr(s,...e){const t=xn.bind(null,e.find(n=>typeof n=="object"));return e.map(t)}function ol(s,e){const t=vt(s,e==null?void 0:e.in);return t.setHours(0,0,0,0),t}function kc(s,e,t){const[n,a]=gr(t==null?void 0:t.in,s,e),i=ol(n),o=ol(a),l=+i-Vp(i),c=+o-Vp(o);return Math.round((l-c)/_U)}function LU(s,e){const t=jE(s,e),n=xn(s,0);return n.setFullYear(t,0,4),n.setHours(0,0,0,0),wc(n)}function md(s,e,t){const n=vt(s,t==null?void 0:t.in);return n.setTime(n.getTime()+e*Am),n}function dv(s,e,t){return ri(s,e*3,t)}function OU(s,e,t){return SE(s,e*1e3)}function Kp(s,e,t){return ai(s,e*7,t)}function ii(s,e,t){return ri(s,e*12,t)}function B1(s,e){let t,n=e==null?void 0:e.in;return s.forEach(a=>{!n&&typeof a=="object"&&(n=xn.bind(null,a));const i=vt(a,n);(!t||t<i||isNaN(+i))&&(t=i)}),xn(n,t||NaN)}function z1(s,e){let t,n=e==null?void 0:e.in;return s.forEach(a=>{!n&&typeof a=="object"&&(n=xn.bind(null,a));const i=vt(a,n);(!t||t>i||isNaN(+i))&&(t=i)}),xn(n,t||NaN)}function IU(s,e,t){const[n,a]=gr(t==null?void 0:t.in,s,e);return+ol(n)==+ol(a)}function Ei(s){return s instanceof Date||typeof s=="object"&&Object.prototype.toString.call(s)==="[object Date]"}function Sc(s){return!(!Ei(s)&&typeof s!="number"||isNaN(+vt(s)))}function Xp(s,e,t){const[n,a]=gr(t==null?void 0:t.in,s,e),i=n.getFullYear()-a.getFullYear(),o=n.getMonth()-a.getMonth();return i*12+o}function Xr(s,e){const t=vt(s,e==null?void 0:e.in);return Math.trunc(t.getMonth()/3)+1}function Zp(s,e,t){const[n,a]=gr(t==null?void 0:t.in,s,e),i=n.getFullYear()-a.getFullYear(),o=Xr(n)-Xr(a);return i*4+o}function Qp(s,e,t){const[n,a]=gr(t==null?void 0:t.in,s,e);return n.getFullYear()-a.getFullYear()}function BU(s,e,t){const[n,a]=gr(t==null?void 0:t.in,s,e),i=F1(n,a),o=Math.abs(kc(n,a));n.setDate(n.getDate()-i*o);const l=+(F1(n,a)===-i),c=i*(o-l);return c===0?0:c}function F1(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 CE(s,e){const t=vt(s,e==null?void 0:e.in);return t.setHours(23,59,59,999),t}function NE(s,e){const t=vt(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 Uy(s,e){const t=vt(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 AE(s,e){const t=vt(s,e==null?void 0:e.in);return t.setDate(1),t.setHours(0,0,0,0),t}function ME(s,e){const t=vt(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 Tm(s,e){const t=vt(s,e==null?void 0:e.in);return t.setFullYear(t.getFullYear(),0,1),t.setHours(0,0,0,0),t}function zU(s,e){var l,c;const t=dl(),n=t.weekStartsOn??((c=(l=t.locale)==null?void 0:l.options)==null?void 0:c.weekStartsOn)??0,a=vt(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 FU={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"}},$U=(s,e,t)=>{let n;const a=FU[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 Lb(s){return(e={})=>{const t=e.width?String(e.width):s.defaultWidth;return s.formats[t]||s.formats[s.defaultWidth]}}const HU={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},UU={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},GU={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},WU={date:Lb({formats:HU,defaultWidth:"full"}),time:Lb({formats:UU,defaultWidth:"full"}),dateTime:Lb({formats:GU,defaultWidth:"full"})},qU={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},YU=(s,e,t,n)=>qU[s];function Ou(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 VU={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},KU={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},XU={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"]},ZU={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"]},QU={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"}},JU={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"}},eG=(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"},tG={ordinalNumber:eG,era:Ou({values:VU,defaultWidth:"wide"}),quarter:Ou({values:KU,defaultWidth:"wide",argumentCallback:s=>s-1}),month:Ou({values:XU,defaultWidth:"wide"}),day:Ou({values:ZU,defaultWidth:"wide"}),dayPeriod:Ou({values:QU,defaultWidth:"wide",formattingValues:JU,defaultFormattingWidth:"wide"})};function Iu(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)?sG(l,p=>p.test(o)):nG(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 nG(s,e){for(const t in s)if(Object.prototype.hasOwnProperty.call(s,t)&&e(s[t]))return t}function sG(s,e){for(let t=0;t<s.length;t++)if(e(s[t]))return t}function aG(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 iG=/^(\d+)(th|st|nd|rd)?/i,rG=/\d+/i,oG={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},lG={any:[/^b/i,/^(a|c)/i]},cG={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},uG={any:[/1/i,/2/i,/3/i,/4/i]},dG={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},hG={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]},pG={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},mG={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]},fG={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},gG={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}},bG={ordinalNumber:aG({matchPattern:iG,parsePattern:rG,valueCallback:s=>parseInt(s,10)}),era:Iu({matchPatterns:oG,defaultMatchWidth:"wide",parsePatterns:lG,defaultParseWidth:"any"}),quarter:Iu({matchPatterns:cG,defaultMatchWidth:"wide",parsePatterns:uG,defaultParseWidth:"any",valueCallback:s=>s+1}),month:Iu({matchPatterns:dG,defaultMatchWidth:"wide",parsePatterns:hG,defaultParseWidth:"any"}),day:Iu({matchPatterns:pG,defaultMatchWidth:"wide",parsePatterns:mG,defaultParseWidth:"any"}),dayPeriod:Iu({matchPatterns:fG,defaultMatchWidth:"any",parsePatterns:gG,defaultParseWidth:"any"})},TE={code:"en-US",formatDistance:$U,formatLong:WU,formatRelative:YU,localize:tG,match:bG,options:{weekStartsOn:0,firstWeekContainsDate:1}};function yG(s,e){const t=vt(s,e==null?void 0:e.in);return kc(t,Tm(t))+1}function hv(s,e){const t=vt(s,e==null?void 0:e.in),n=+wc(t)-+LU(t);return Math.round(n/kE)+1}function pv(s,e){var m,p,f,b;const t=vt(s,e==null?void 0:e.in),n=t.getFullYear(),a=dl(),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=xn((e==null?void 0:e.in)||s,0);o.setFullYear(n+1,0,i),o.setHours(0,0,0,0);const l=pr(o,e),c=xn((e==null?void 0:e.in)||s,0);c.setFullYear(n,0,i),c.setHours(0,0,0,0);const d=pr(c,e);return+t>=+l?n+1:+t>=+d?n:n-1}function xG(s,e){var l,c,d,m;const t=dl(),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=pv(s,e),i=xn((e==null?void 0:e.in)||s,0);return i.setFullYear(a,0,n),i.setHours(0,0,0,0),pr(i,e)}function EE(s,e){const t=vt(s,e==null?void 0:e.in),n=+pr(t,e)-+xG(t,e);return Math.round(n/kE)+1}function yn(s,e){const t=s<0?"-":"",n=Math.abs(s).toString().padStart(e,"0");return t+n}const Wr={y(s,e){const t=s.getFullYear(),n=t>0?t:1-t;return yn(e==="yy"?n%100:n,e.length)},M(s,e){const t=s.getMonth();return e==="M"?String(t+1):yn(t+1,2)},d(s,e){return yn(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 yn(s.getHours()%12||12,e.length)},H(s,e){return yn(s.getHours(),e.length)},m(s,e){return yn(s.getMinutes(),e.length)},s(s,e){return yn(s.getSeconds(),e.length)},S(s,e){const t=e.length,n=s.getMilliseconds(),a=Math.trunc(n*Math.pow(10,t-3));return yn(a,e.length)}},Zl={midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},$1={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 Wr.y(s,e)},Y:function(s,e,t,n){const a=pv(s,n),i=a>0?a:1-a;if(e==="YY"){const o=i%100;return yn(o,2)}return e==="Yo"?t.ordinalNumber(i,{unit:"year"}):yn(i,e.length)},R:function(s,e){const t=jE(s);return yn(t,e.length)},u:function(s,e){const t=s.getFullYear();return yn(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 yn(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 yn(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 Wr.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 yn(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=EE(s,n);return e==="wo"?t.ordinalNumber(a,{unit:"week"}):yn(a,e.length)},I:function(s,e,t){const n=hv(s);return e==="Io"?t.ordinalNumber(n,{unit:"week"}):yn(n,e.length)},d:function(s,e,t){return e==="do"?t.ordinalNumber(s.getDate(),{unit:"date"}):Wr.d(s,e)},D:function(s,e,t){const n=yG(s);return e==="Do"?t.ordinalNumber(n,{unit:"dayOfYear"}):yn(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 yn(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 yn(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 yn(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=Zl.noon:n===0?a=Zl.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=Zl.evening:n>=12?a=Zl.afternoon:n>=4?a=Zl.morning:a=Zl.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 Wr.h(s,e)},H:function(s,e,t){return e==="Ho"?t.ordinalNumber(s.getHours(),{unit:"hour"}):Wr.H(s,e)},K:function(s,e,t){const n=s.getHours()%12;return e==="Ko"?t.ordinalNumber(n,{unit:"hour"}):yn(n,e.length)},k:function(s,e,t){let n=s.getHours();return n===0&&(n=24),e==="ko"?t.ordinalNumber(n,{unit:"hour"}):yn(n,e.length)},m:function(s,e,t){return e==="mo"?t.ordinalNumber(s.getMinutes(),{unit:"minute"}):Wr.m(s,e)},s:function(s,e,t){return e==="so"?t.ordinalNumber(s.getSeconds(),{unit:"second"}):Wr.s(s,e)},S:function(s,e){return Wr.S(s,e)},X:function(s,e,t){const n=s.getTimezoneOffset();if(n===0)return"Z";switch(e){case"X":return U1(n);case"XXXX":case"XX":return Bo(n);case"XXXXX":case"XXX":default:return Bo(n,":")}},x:function(s,e,t){const n=s.getTimezoneOffset();switch(e){case"x":return U1(n);case"xxxx":case"xx":return Bo(n);case"xxxxx":case"xxx":default:return Bo(n,":")}},O:function(s,e,t){const n=s.getTimezoneOffset();switch(e){case"O":case"OO":case"OOO":return"GMT"+H1(n,":");case"OOOO":default:return"GMT"+Bo(n,":")}},z:function(s,e,t){const n=s.getTimezoneOffset();switch(e){case"z":case"zz":case"zzz":return"GMT"+H1(n,":");case"zzzz":default:return"GMT"+Bo(n,":")}},t:function(s,e,t){const n=Math.trunc(+s/1e3);return yn(n,e.length)},T:function(s,e,t){return yn(+s,e.length)}};function H1(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+yn(i,2)}function U1(s,e){return s%60===0?(s>0?"-":"+")+yn(Math.abs(s)/60,2):Bo(s,e)}function Bo(s,e=""){const t=s>0?"-":"+",n=Math.abs(s),a=yn(Math.trunc(n/60),2),i=yn(n%60,2);return t+a+e+i}const G1=(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"})}},_E=(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"})}},vG=(s,e)=>{const t=s.match(/(P+)(p+)?/)||[],n=t[1],a=t[2];if(!a)return G1(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}}",G1(n,e)).replace("{{time}}",_E(a,e))},Gy={p:_E,P:vG},wG=/^D+$/,kG=/^Y+$/,SG=["D","DD","YY","YYYY"];function jG(s){return wG.test(s)}function CG(s){return kG.test(s)}function NG(s,e,t){const n=AG(s,e,t);if(console.warn(n),SG.includes(s))throw new RangeError(n)}function AG(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 MG=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,TG=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,EG=/^'([^]*?)'?$/,_G=/''/g,DG=/[a-zA-Z]/;function W1(s,e,t){var m,p,f,b,x,w,k,j;const n=dl(),a=(t==null?void 0:t.locale)??n.locale??TE,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??((j=(k=n.locale)==null?void 0:k.options)==null?void 0:j.weekStartsOn)??0,l=vt(s,t==null?void 0:t.in);if(!Sc(l))throw new RangeError("Invalid time value");let c=e.match(TG).map(S=>{const C=S[0];if(C==="p"||C==="P"){const A=Gy[C];return A(S,a.formatLong)}return S}).join("").match(MG).map(S=>{if(S==="''")return{isToken:!1,value:"'"};const C=S[0];if(C==="'")return{isToken:!1,value:RG(S)};if($1[C])return{isToken:!0,value:S};if(C.match(DG))throw new RangeError("Format string contains an unescaped latin alphabet character `"+C+"`");return{isToken:!1,value:S}});a.localize.preprocessor&&(c=a.localize.preprocessor(l,c));const d={firstWeekContainsDate:i,weekStartsOn:o,locale:a};return c.map(S=>{if(!S.isToken)return S.value;const C=S.value;(!(t!=null&&t.useAdditionalWeekYearTokens)&&CG(C)||!(t!=null&&t.useAdditionalDayOfYearTokens)&&jG(C))&&NG(C,e,String(s));const A=$1[C[0]];return A(l,C,a.localize,d)}).join("")}function RG(s){const e=s.match(EG);return e?e[1].replace(_G,"'"):s}function q1(s,e){return vt(s,e==null?void 0:e.in).getDate()}function PG(s,e){return vt(s,e==null?void 0:e.in).getDay()}function LG(s,e){const t=vt(s,e==null?void 0:e.in),n=t.getFullYear(),a=t.getMonth(),i=xn(t,0);return i.setFullYear(n,a+1,0),i.setHours(0,0,0,0),i.getDate()}function OG(){return Object.assign({},dl())}function Ps(s,e){return vt(s,e==null?void 0:e.in).getHours()}function IG(s,e){const t=vt(s,e==null?void 0:e.in).getDay();return t===0?7:t}function Ls(s,e){return vt(s,e==null?void 0:e.in).getMinutes()}function ia(s,e){return vt(s,e==null?void 0:e.in).getMonth()}function to(s){return vt(s).getSeconds()}function Wy(s){return+vt(s)}function Kt(s,e){return vt(s,e==null?void 0:e.in).getFullYear()}function ur(s,e){return+vt(s)>+vt(e)}function Ni(s,e){return+vt(s)<+vt(e)}function BG(s,e){return+vt(s)==+vt(e)}function zG(s,e){const t=FG(e)?new e(0):xn(e,0);return t.setFullYear(s.getFullYear(),s.getMonth(),s.getDate()),t.setHours(s.getHours(),s.getMinutes(),s.getSeconds(),s.getMilliseconds()),t}function FG(s){var e;return typeof s=="function"&&((e=s.prototype)==null?void 0:e.constructor)===s}const $G=10;class DE{constructor(){U(this,"subPriority",0)}validate(e,t){return!0}}class HG extends DE{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 UG extends DE{constructor(t,n){super();U(this,"priority",$G);U(this,"subPriority",-1);this.context=t||(a=>xn(n,a))}set(t,n){return n.timestampIsSet?t:xn(t,zG(t,this.context))}}class hn{run(e,t,n,a){const i=this.parse(e,t,n,a);return i?{setter:new HG(i.value,this.validate,this.set,this.priority,this.subPriority),rest:i.rest}:null}validate(e,t,n){return!0}}class GG extends hn{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 ts={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}/},ki={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 ns(s,e){return s&&{value:e(s.value),rest:s.rest}}function Wn(s,e){const t=e.match(s);return t?{value:parseInt(t[0],10),rest:e.slice(t[0].length)}:null}function Si(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*Mm+i*Am+o*DU),rest:e.slice(t[0].length)}}function RE(s){return Wn(ts.anyDigitsSigned,s)}function Xn(s,e){switch(s){case 1:return Wn(ts.singleDigit,e);case 2:return Wn(ts.twoDigits,e);case 3:return Wn(ts.threeDigits,e);case 4:return Wn(ts.fourDigits,e);default:return Wn(new RegExp("^\\d{1,"+s+"}"),e)}}function Jp(s,e){switch(s){case 1:return Wn(ts.singleDigitSigned,e);case 2:return Wn(ts.twoDigitsSigned,e);case 3:return Wn(ts.threeDigitsSigned,e);case 4:return Wn(ts.fourDigitsSigned,e);default:return Wn(new RegExp("^-?\\d{1,"+s+"}"),e)}}function mv(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 PE(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 LE(s){return s%400===0||s%4===0&&s%100!==0}class WG extends hn{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 ns(Xn(4,t),i);case"yo":return ns(a.ordinalNumber(t,{unit:"year"}),i);default:return ns(Xn(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=PE(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 qG extends hn{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 ns(Xn(4,t),i);case"Yo":return ns(a.ordinalNumber(t,{unit:"year"}),i);default:return ns(Xn(n.length,t),i)}}validate(t,n){return n.isTwoDigitYear||n.year>0}set(t,n,a,i){const o=pv(t,i);if(a.isTwoDigitYear){const c=PE(a.year,o);return t.setFullYear(c,0,i.firstWeekContainsDate),t.setHours(0,0,0,0),pr(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),pr(t,i)}}class YG extends hn{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 Jp(n==="R"?4:n.length,t)}set(t,n,a){const i=xn(t,0);return i.setFullYear(a,0,4),i.setHours(0,0,0,0),wc(i)}}class VG extends hn{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 Jp(n==="u"?4:n.length,t)}set(t,n,a){return t.setFullYear(a,0,1),t.setHours(0,0,0,0),t}}class KG extends hn{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 Xn(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 XG extends hn{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 Xn(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 ZG extends hn{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 ns(Wn(ts.month,t),i);case"MM":return ns(Xn(2,t),i);case"Mo":return ns(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 QG extends hn{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 ns(Wn(ts.month,t),i);case"LL":return ns(Xn(2,t),i);case"Lo":return ns(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 JG(s,e,t){const n=vt(s,t==null?void 0:t.in),a=EE(n,t)-e;return n.setDate(n.getDate()-a*7),vt(n,t==null?void 0:t.in)}class eW extends hn{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 Wn(ts.week,t);case"wo":return a.ordinalNumber(t,{unit:"week"});default:return Xn(n.length,t)}}validate(t,n){return n>=1&&n<=53}set(t,n,a,i){return pr(JG(t,a,i),i)}}function tW(s,e,t){const n=vt(s,t==null?void 0:t.in),a=hv(n,t)-e;return n.setDate(n.getDate()-a*7),n}class nW extends hn{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 Wn(ts.week,t);case"Io":return a.ordinalNumber(t,{unit:"week"});default:return Xn(n.length,t)}}validate(t,n){return n>=1&&n<=53}set(t,n,a){return wc(tW(t,a))}}const sW=[31,28,31,30,31,30,31,31,30,31,30,31],aW=[31,29,31,30,31,30,31,31,30,31,30,31];class iW extends hn{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 Wn(ts.date,t);case"do":return a.ordinalNumber(t,{unit:"date"});default:return Xn(n.length,t)}}validate(t,n){const a=t.getFullYear(),i=LE(a),o=t.getMonth();return i?n>=1&&n<=aW[o]:n>=1&&n<=sW[o]}set(t,n,a){return t.setDate(a),t.setHours(0,0,0,0),t}}class rW extends hn{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 Wn(ts.dayOfYear,t);case"Do":return a.ordinalNumber(t,{unit:"date"});default:return Xn(n.length,t)}}validate(t,n){const a=t.getFullYear();return LE(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 fv(s,e,t){var p,f,b,x;const n=dl(),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=vt(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 ai(i,m,t)}class oW extends hn{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=fv(t,a,i),t.setHours(0,0,0,0),t}}class lW extends hn{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 ns(Xn(n.length,t),o);case"eo":return ns(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=fv(t,a,i),t.setHours(0,0,0,0),t}}class cW extends hn{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 ns(Xn(n.length,t),o);case"co":return ns(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=fv(t,a,i),t.setHours(0,0,0,0),t}}function uW(s,e,t){const n=vt(s,t==null?void 0:t.in),a=IG(n,t),i=e-a;return ai(n,i,t)}class dW extends hn{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 Xn(n.length,t);case"io":return a.ordinalNumber(t,{unit:"day"});case"iii":return ns(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 ns(a.day(t,{width:"narrow",context:"formatting"}),i);case"iiiiii":return ns(a.day(t,{width:"short",context:"formatting"})||a.day(t,{width:"narrow",context:"formatting"}),i);case"iiii":default:return ns(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=uW(t,a),t.setHours(0,0,0,0),t}}class hW extends hn{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(mv(a),0,0,0),t}}class pW extends hn{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(mv(a),0,0,0),t}}class mW extends hn{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(mv(a),0,0,0),t}}class fW extends hn{constructor(){super(...arguments);U(this,"priority",70);U(this,"incompatibleTokens",["H","K","k","t","T"])}parse(t,n,a){switch(n){case"h":return Wn(ts.hour12h,t);case"ho":return a.ordinalNumber(t,{unit:"hour"});default:return Xn(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 gW extends hn{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 Wn(ts.hour23h,t);case"Ho":return a.ordinalNumber(t,{unit:"hour"});default:return Xn(n.length,t)}}validate(t,n){return n>=0&&n<=23}set(t,n,a){return t.setHours(a,0,0,0),t}}class bW extends hn{constructor(){super(...arguments);U(this,"priority",70);U(this,"incompatibleTokens",["h","H","k","t","T"])}parse(t,n,a){switch(n){case"K":return Wn(ts.hour11h,t);case"Ko":return a.ordinalNumber(t,{unit:"hour"});default:return Xn(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 yW extends hn{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 Wn(ts.hour24h,t);case"ko":return a.ordinalNumber(t,{unit:"hour"});default:return Xn(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 xW extends hn{constructor(){super(...arguments);U(this,"priority",60);U(this,"incompatibleTokens",["t","T"])}parse(t,n,a){switch(n){case"m":return Wn(ts.minute,t);case"mo":return a.ordinalNumber(t,{unit:"minute"});default:return Xn(n.length,t)}}validate(t,n){return n>=0&&n<=59}set(t,n,a){return t.setMinutes(a,0,0),t}}class vW extends hn{constructor(){super(...arguments);U(this,"priority",50);U(this,"incompatibleTokens",["t","T"])}parse(t,n,a){switch(n){case"s":return Wn(ts.second,t);case"so":return a.ordinalNumber(t,{unit:"second"});default:return Xn(n.length,t)}}validate(t,n){return n>=0&&n<=59}set(t,n,a){return t.setSeconds(a,0),t}}class wW extends hn{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 ns(Xn(n.length,t),a)}set(t,n,a){return t.setMilliseconds(a),t}}class kW extends hn{constructor(){super(...arguments);U(this,"priority",10);U(this,"incompatibleTokens",["t","T","x"])}parse(t,n){switch(n){case"X":return Si(ki.basicOptionalMinutes,t);case"XX":return Si(ki.basic,t);case"XXXX":return Si(ki.basicOptionalSeconds,t);case"XXXXX":return Si(ki.extendedOptionalSeconds,t);case"XXX":default:return Si(ki.extended,t)}}set(t,n,a){return n.timestampIsSet?t:xn(t,t.getTime()-Vp(t)-a)}}class SW extends hn{constructor(){super(...arguments);U(this,"priority",10);U(this,"incompatibleTokens",["t","T","X"])}parse(t,n){switch(n){case"x":return Si(ki.basicOptionalMinutes,t);case"xx":return Si(ki.basic,t);case"xxxx":return Si(ki.basicOptionalSeconds,t);case"xxxxx":return Si(ki.extendedOptionalSeconds,t);case"xxx":default:return Si(ki.extended,t)}}set(t,n,a){return n.timestampIsSet?t:xn(t,t.getTime()-Vp(t)-a)}}class jW extends hn{constructor(){super(...arguments);U(this,"priority",40);U(this,"incompatibleTokens","*")}parse(t){return RE(t)}set(t,n,a){return[xn(t,a*1e3),{timestampIsSet:!0}]}}class CW extends hn{constructor(){super(...arguments);U(this,"priority",20);U(this,"incompatibleTokens","*")}parse(t){return RE(t)}set(t,n,a){return[xn(t,a),{timestampIsSet:!0}]}}const NW={G:new GG,y:new WG,Y:new qG,R:new YG,u:new VG,Q:new KG,q:new XG,M:new ZG,L:new QG,w:new eW,I:new nW,d:new iW,D:new rW,E:new oW,e:new lW,c:new cW,i:new dW,a:new hW,b:new pW,B:new mW,h:new fW,H:new gW,K:new bW,k:new yW,m:new xW,s:new vW,S:new wW,X:new kW,x:new SW,t:new jW,T:new CW},AW=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,MW=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,TW=/^'([^]*?)'?$/,EW=/''/g,_W=/\S/,DW=/[a-zA-Z]/;function RW(s,e,t,n){var k,j,S,C,A,_,T,P;const a=()=>xn((n==null?void 0:n.in)||t,NaN),i=OG(),o=(n==null?void 0:n.locale)??i.locale??TE,l=(n==null?void 0:n.firstWeekContainsDate)??((j=(k=n==null?void 0:n.locale)==null?void 0:k.options)==null?void 0:j.firstWeekContainsDate)??i.firstWeekContainsDate??((C=(S=i.locale)==null?void 0:S.options)==null?void 0:C.firstWeekContainsDate)??1,c=(n==null?void 0:n.weekStartsOn)??((_=(A=n==null?void 0:n.locale)==null?void 0:A.options)==null?void 0:_.weekStartsOn)??i.weekStartsOn??((P=(T=i.locale)==null?void 0:T.options)==null?void 0:P.weekStartsOn)??0;if(!e)return s?a():vt(t,n==null?void 0:n.in);const d={firstWeekContainsDate:l,weekStartsOn:c,locale:o},m=[new UG(n==null?void 0:n.in,t)],p=e.match(MW).map(M=>{const D=M[0];if(D in Gy){const R=Gy[D];return R(M,o.formatLong)}return M}).join("").match(AW),f=[];for(let M of p){const D=M[0],R=NW[D];if(R){const{incompatibleTokens:L}=R;if(Array.isArray(L)){const I=f.find(B=>L.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(R.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=R.run(s,M,o.match,d);if(!O)return a();m.push(O.setter),s=O.rest}else{if(D.match(DW))throw new RangeError("Format string contains an unescaped latin alphabet character `"+D+"`");if(M==="''"?M="'":D==="'"&&(M=PW(M)),s.indexOf(M)===0)s=s.slice(M.length);else return a()}}if(s.length>0&&_W.test(s))return a();const b=m.map(M=>M.priority).sort((M,D)=>D-M).filter((M,D,R)=>R.indexOf(M)===D).map(M=>m.filter(D=>D.priority===M).sort((D,R)=>R.subPriority-D.subPriority)).map(M=>M[0]);let x=vt(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 PW(s){return s.match(TW)[1].replace(EW,"'")}function LW(s,e,t){const[n,a]=gr(t==null?void 0:t.in,s,e);return n.getFullYear()===a.getFullYear()&&n.getMonth()===a.getMonth()}function OW(s,e,t){const[n,a]=gr(t==null?void 0:t.in,s,e);return+Uy(n)==+Uy(a)}function IW(s,e,t){const[n,a]=gr(t==null?void 0:t.in,s,e);return n.getFullYear()===a.getFullYear()}function fd(s,e,t){const n=+vt(s,t==null?void 0:t.in),[a,i]=[+vt(e.start,t==null?void 0:t.in),+vt(e.end,t==null?void 0:t.in)].sort((o,l)=>o-l);return n>=a&&n<=i}function BW(s,e,t){return ai(s,-1,t)}function zW(s,e){const t=()=>xn(e==null?void 0:e.in,NaN),a=UW(s);let i;if(a.date){const d=GW(a.date,2);i=WW(d.restDateString,d.year)}if(!i||isNaN(+i))return t();const o=+i;let l=0,c;if(a.time&&(l=qW(a.time),isNaN(l)))return t();if(a.timezone){if(c=YW(a.timezone),isNaN(c))return t()}else{const d=new Date(o+l),m=vt(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 vt(o+l+c,e==null?void 0:e.in)}const np={dateTimeDelimiter:/[T ]/,timeZoneDelimiter:/[Z ]/i,timezone:/([Z+-].*)$/},FW=/^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/,$W=/^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/,HW=/^([+-])(\d{2})(?::?(\d{2}))?$/;function UW(s){const e={},t=s.split(np.dateTimeDelimiter);let n;if(t.length>2)return e;if(/:/.test(t[0])?n=t[0]:(e.date=t[0],n=t[1],np.timeZoneDelimiter.test(e.date)&&(e.date=s.split(np.timeZoneDelimiter)[0],n=s.substr(e.date.length,s.length))),n){const a=np.timezone.exec(n);a?(e.time=n.replace(a[1],""),e.timezone=a[1]):e.time=n}return e}function GW(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 WW(s,e){if(e===null)return new Date(NaN);const t=s.match(FW);if(!t)return new Date(NaN);const n=!!t[4],a=Bu(t[1]),i=Bu(t[2])-1,o=Bu(t[3]),l=Bu(t[4]),c=Bu(t[5])-1;if(n)return QW(e,l,c)?VW(e,l,c):new Date(NaN);{const d=new Date(0);return!XW(e,i,o)||!ZW(e,a)?new Date(NaN):(d.setUTCFullYear(e,i,Math.max(a,o)),d)}}function Bu(s){return s?parseInt(s):1}function qW(s){const e=s.match($W);if(!e)return NaN;const t=Ob(e[1]),n=Ob(e[2]),a=Ob(e[3]);return JW(t,n,a)?t*Mm+n*Am+a*1e3:NaN}function Ob(s){return s&&parseFloat(s.replace(",","."))||0}function YW(s){if(s==="Z")return 0;const e=s.match(HW);if(!e)return 0;const t=e[1]==="+"?-1:1,n=parseInt(e[2]),a=e[3]&&parseInt(e[3])||0;return e7(n,a)?t*(n*Mm+a*Am):NaN}function VW(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 KW=[31,null,31,30,31,30,31,31,30,31,30,31];function OE(s){return s%400===0||s%4===0&&s%100!==0}function XW(s,e,t){return e>=0&&e<=11&&t>=1&&t<=(KW[e]||(OE(s)?29:28))}function ZW(s,e){return e>=1&&e<=(OE(s)?366:365)}function QW(s,e,t){return e>=1&&e<=53&&t>=0&&t<=6}function JW(s,e,t){return s===24?e===0&&t===0:t>=0&&t<60&&e>=0&&e<60&&s>=0&&s<25}function e7(s,e){return e>=0&&e<=59}function Sa(s,e,t){const n=vt(s,t==null?void 0:t.in),a=n.getFullYear(),i=n.getDate(),o=xn(s,0);o.setFullYear(a,e,15),o.setHours(0,0,0,0);const l=LG(o);return n.setMonth(e,Math.min(i,l)),n}function bp(s,e,t){const n=vt(s,t==null?void 0:t.in);return n.setHours(e),n}function yp(s,e,t){const n=vt(s,t==null?void 0:t.in);return n.setMinutes(e),n}function nc(s,e,t){const n=vt(s,t==null?void 0:t.in),a=Math.trunc(n.getMonth()/3)+1,i=e-a;return Sa(n,n.getMonth()+i*3)}function xp(s,e,t){const n=vt(s,t==null?void 0:t.in);return n.setSeconds(e),n}function xi(s,e,t){const n=vt(s,t==null?void 0:t.in);return isNaN(+n)?xn(s,NaN):(n.setFullYear(e),n)}function Xo(s,e,t){return ri(s,-e,t)}function IE(s,e,t){return dv(s,-1,t)}function Y1(s,e,t){return Kp(s,-1,t)}function ro(s,e,t){return ii(s,-e,t)}function Em(){return typeof window<"u"}function Rc(s){return BE(s)?(s.nodeName||"").toLowerCase():"#document"}function Na(s){var e;return(s==null||(e=s.ownerDocument)==null?void 0:e.defaultView)||window}function Ii(s){var e;return(e=(BE(s)?s.ownerDocument:s.document)||window.document)==null?void 0:e.documentElement}function BE(s){return Em()?s instanceof Node||s instanceof Na(s).Node:!1}function Ws(s){return Em()?s instanceof Element||s instanceof Na(s).Element:!1}function Ri(s){return Em()?s instanceof HTMLElement||s instanceof Na(s).HTMLElement:!1}function V1(s){return!Em()||typeof ShadowRoot>"u"?!1:s instanceof ShadowRoot||s instanceof Na(s).ShadowRoot}const t7=new Set(["inline","contents"]);function Ad(s){const{overflow:e,overflowX:t,overflowY:n,display:a}=Ga(s);return/auto|scroll|overlay|hidden|clip/.test(e+n+t)&&!t7.has(a)}const n7=new Set(["table","td","th"]);function s7(s){return n7.has(Rc(s))}const a7=[":popover-open",":modal"];function _m(s){return a7.some(e=>{try{return s.matches(e)}catch{return!1}})}const i7=["transform","translate","scale","rotate","perspective"],r7=["transform","translate","scale","rotate","perspective","filter"],o7=["paint","layout","strict","content"];function gv(s){const e=bv(),t=Ws(s)?Ga(s):s;return i7.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)||r7.some(n=>(t.willChange||"").includes(n))||o7.some(n=>(t.contain||"").includes(n))}function l7(s){let e=oo(s);for(;Ri(e)&&!jc(e);){if(gv(e))return e;if(_m(e))return null;e=oo(e)}return null}function bv(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}const c7=new Set(["html","body","#document"]);function jc(s){return c7.has(Rc(s))}function Ga(s){return Na(s).getComputedStyle(s)}function Dm(s){return Ws(s)?{scrollLeft:s.scrollLeft,scrollTop:s.scrollTop}:{scrollLeft:s.scrollX,scrollTop:s.scrollY}}function oo(s){if(Rc(s)==="html")return s;const e=s.assignedSlot||s.parentNode||V1(s)&&s.host||Ii(s);return V1(e)?e.host:e}function zE(s){const e=oo(s);return jc(e)?s.ownerDocument?s.ownerDocument.body:s.body:Ri(e)&&Ad(e)?e:zE(e)}function gd(s,e,t){var n;e===void 0&&(e=[]),t===void 0&&(t=!0);const a=zE(s),i=a===((n=s.ownerDocument)==null?void 0:n.body),o=Na(a);if(i){const l=qy(o);return e.concat(o,o.visualViewport||[],Ad(a)?a:[],l&&t?gd(l):[])}return e.concat(a,gd(a,[],t))}function qy(s){return s.parent&&Object.getPrototypeOf(s.parent)?s.frameElement:null}const Cc=Math.min,Zo=Math.max,em=Math.round,sp=Math.floor,_i=s=>({x:s,y:s}),u7={left:"right",right:"left",bottom:"top",top:"bottom"},d7={start:"end",end:"start"};function h7(s,e,t){return Zo(s,Cc(e,t))}function Rm(s,e){return typeof s=="function"?s(e):s}function Nc(s){return s.split("-")[0]}function Md(s){return s.split("-")[1]}function p7(s){return s==="x"?"y":"x"}function yv(s){return s==="y"?"height":"width"}const m7=new Set(["top","bottom"]);function Uo(s){return m7.has(Nc(s))?"y":"x"}function xv(s){return p7(Uo(s))}function f7(s,e,t){t===void 0&&(t=!1);const n=Md(s),a=xv(s),i=yv(a);let o=a==="x"?n===(t?"end":"start")?"right":"left":n==="start"?"bottom":"top";return e.reference[i]>e.floating[i]&&(o=tm(o)),[o,tm(o)]}function g7(s){const e=tm(s);return[Yy(s),e,Yy(e)]}function Yy(s){return s.replace(/start|end/g,e=>d7[e])}const K1=["left","right"],X1=["right","left"],b7=["top","bottom"],y7=["bottom","top"];function x7(s,e,t){switch(s){case"top":case"bottom":return t?e?X1:K1:e?K1:X1;case"left":case"right":return e?b7:y7;default:return[]}}function v7(s,e,t,n){const a=Md(s);let i=x7(Nc(s),t==="start",n);return a&&(i=i.map(o=>o+"-"+a),e&&(i=i.concat(i.map(Yy)))),i}function tm(s){return s.replace(/left|right|bottom|top/g,e=>u7[e])}function w7(s){return{top:0,right:0,bottom:0,left:0,...s}}function FE(s){return typeof s!="number"?w7(s):{top:s,right:s,bottom:s,left:s}}function nm(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 k7=typeof document<"u",S7=function(){},sm=k7?y.useLayoutEffect:S7;const j7={...LA},C7=j7.useInsertionEffect,N7=C7||(s=>s());function A7(s){const e=y.useRef(()=>{});return N7(()=>{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 Z1(s,e,t){let{reference:n,floating:a}=s;const i=Uo(e),o=xv(e),l=yv(o),c=Nc(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(Md(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 M7(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}=Rm(e,s),x=FE(b),k=l[f?p==="floating"?"reference":"floating":p],j=nm(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})),S=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)),A=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},_=nm(i.convertOffsetParentRelativeRectToViewportRelativeRect?await i.convertOffsetParentRelativeRectToViewportRelativeRect({elements:l,rect:S,offsetParent:C,strategy:c}):S);return{top:(j.top-_.top+x.top)/A.y,bottom:(_.bottom-j.bottom+x.bottom)/A.y,left:(j.left-_.left+x.left)/A.x,right:(_.right-j.right+x.right)/A.x}}const T7=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}=Z1(d,n,c),f=n,b={},x=0;for(let k=0;k<l.length;k++){var w;const{name:j,fn:S}=l[k],{x:C,y:A,data:_,reset:T}=await S({x:m,y:p,initialPlacement:n,placement:f,strategy:a,middlewareData:b,rects:d,platform:{...o,detectOverflow:(w=o.detectOverflow)!=null?w:M7},elements:{reference:s,floating:e}});m=C??m,p=A??p,b={...b,[j]:{...b[j],..._}},T&&x<=50&&(x++,typeof T=="object"&&(T.placement&&(f=T.placement),T.rects&&(d=T.rects===!0?await o.getElementRects({reference:s,floating:e,strategy:a}):T.rects),{x:m,y:p}=Z1(d,f,c)),k=-1)}return{x:m,y:p,placement:f,strategy:a,middlewareData:b}},E7=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}=Rm(s,e)||{};if(d==null)return{};const p=FE(m),f={x:t,y:n},b=xv(a),x=yv(b),w=await o.getDimensions(d),k=b==="y",j=k?"top":"left",S=k?"bottom":"right",C=k?"clientHeight":"clientWidth",A=i.reference[x]+i.reference[b]-f[b]-i.floating[x],_=f[b]-i.reference[b],T=await(o.getOffsetParent==null?void 0:o.getOffsetParent(d));let P=T?T[C]:0;(!P||!await(o.isElement==null?void 0:o.isElement(T)))&&(P=l.floating[C]||i.floating[x]);const M=A/2-_/2,D=P/2-w[x]/2-1,R=Cc(p[j],D),L=Cc(p[S],D),O=R,I=P-w[x]-L,B=P/2-w[x]/2+M,G=h7(O,B,I),$=!c.arrow&&Md(a)!=null&&B!==G&&i.reference[x]/2-(B<O?R:L)-w[x]/2<0,Y=$?B<O?B-O:B-I:0;return{[b]:f[b]+Y,data:{[b]:G,centerOffset:B-G-Y,...$&&{alignmentOffset:Y}},reset:$}}}),_7=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}=Rm(s,e);if((t=i.arrow)!=null&&t.alignmentOffset)return{};const j=Nc(a),S=Uo(l),C=Nc(l)===l,A=await(c.isRTL==null?void 0:c.isRTL(d.floating)),_=f||(C||!w?[tm(l)]:g7(l)),T=x!=="none";!f&&T&&_.push(...v7(l,w,x,A));const P=[l,..._],M=await c.detectOverflow(e,k),D=[];let R=((n=i.flip)==null?void 0:n.overflows)||[];if(m&&D.push(M[j]),p){const B=f7(a,o,A);D.push(M[B[0]],M[B[1]])}if(R=[...R,{placement:a,overflows:D}],!D.every(B=>B<=0)){var L,O;const B=(((L=i.flip)==null?void 0:L.index)||0)+1,G=P[B];if(G&&(!(p==="alignment"?S!==Uo(G):!1)||R.every(K=>Uo(K.placement)===S?K.overflows[0]>0:!0)))return{data:{index:B,overflows:R},reset:{placement:G}};let $=(O=R.filter(Y=>Y.overflows[0]<=0).sort((Y,K)=>Y.overflows[1]-K.overflows[1])[0])==null?void 0:O.placement;if(!$)switch(b){case"bestFit":{var I;const Y=(I=R.filter(K=>{if(T){const Q=Uo(K.placement);return Q===S||Q==="y"}return!0}).map(K=>[K.placement,K.overflows.filter(Q=>Q>0).reduce((Q,H)=>Q+H,0)]).sort((K,Q)=>K[1]-Q[1])[0])==null?void 0:I[0];Y&&($=Y);break}case"initialPlacement":$=l;break}if(a!==$)return{reset:{placement:$}}}return{}}}},D7=new Set(["left","top"]);async function R7(s,e){const{placement:t,platform:n,elements:a}=s,i=await(n.isRTL==null?void 0:n.isRTL(a.floating)),o=Nc(t),l=Md(t),c=Uo(t)==="y",d=D7.has(o)?-1:1,m=i&&c?-1:1,p=Rm(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 P7=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 R7(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 $E(s){const e=Ga(s);let t=parseFloat(e.width)||0,n=parseFloat(e.height)||0;const a=Ri(s),i=a?s.offsetWidth:t,o=a?s.offsetHeight:n,l=em(t)!==i||em(n)!==o;return l&&(t=i,n=o),{width:t,height:n,$:l}}function vv(s){return Ws(s)?s:s.contextElement}function pc(s){const e=vv(s);if(!Ri(e))return _i(1);const t=e.getBoundingClientRect(),{width:n,height:a,$:i}=$E(e);let o=(i?em(t.width):t.width)/n,l=(i?em(t.height):t.height)/a;return(!o||!Number.isFinite(o))&&(o=1),(!l||!Number.isFinite(l))&&(l=1),{x:o,y:l}}const L7=_i(0);function HE(s){const e=Na(s);return!bv()||!e.visualViewport?L7:{x:e.visualViewport.offsetLeft,y:e.visualViewport.offsetTop}}function O7(s,e,t){return e===void 0&&(e=!1),!t||e&&t!==Na(s)?!1:e}function ll(s,e,t,n){e===void 0&&(e=!1),t===void 0&&(t=!1);const a=s.getBoundingClientRect(),i=vv(s);let o=_i(1);e&&(n?Ws(n)&&(o=pc(n)):o=pc(s));const l=O7(i,t,n)?HE(i):_i(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=Na(i),b=n&&Ws(n)?Na(n):n;let x=f,w=qy(x);for(;w&&n&&b!==x;){const k=pc(w),j=w.getBoundingClientRect(),S=Ga(w),C=j.left+(w.clientLeft+parseFloat(S.paddingLeft))*k.x,A=j.top+(w.clientTop+parseFloat(S.paddingTop))*k.y;c*=k.x,d*=k.y,m*=k.x,p*=k.y,c+=C,d+=A,x=Na(w),w=qy(x)}}return nm({width:m,height:p,x:c,y:d})}function Pm(s,e){const t=Dm(s).scrollLeft;return e?e.left+t:ll(Ii(s)).left+t}function UE(s,e){const t=s.getBoundingClientRect(),n=t.left+e.scrollLeft-Pm(s,t),a=t.top+e.scrollTop;return{x:n,y:a}}function I7(s){let{elements:e,rect:t,offsetParent:n,strategy:a}=s;const i=a==="fixed",o=Ii(n),l=e?_m(e.floating):!1;if(n===o||l&&i)return t;let c={scrollLeft:0,scrollTop:0},d=_i(1);const m=_i(0),p=Ri(n);if((p||!p&&!i)&&((Rc(n)!=="body"||Ad(o))&&(c=Dm(n)),Ri(n))){const b=ll(n);d=pc(n),m.x=b.x+n.clientLeft,m.y=b.y+n.clientTop}const f=o&&!p&&!i?UE(o,c):_i(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 B7(s){return Array.from(s.getClientRects())}function z7(s){const e=Ii(s),t=Dm(s),n=s.ownerDocument.body,a=Zo(e.scrollWidth,e.clientWidth,n.scrollWidth,n.clientWidth),i=Zo(e.scrollHeight,e.clientHeight,n.scrollHeight,n.clientHeight);let o=-t.scrollLeft+Pm(s);const l=-t.scrollTop;return Ga(n).direction==="rtl"&&(o+=Zo(e.clientWidth,n.clientWidth)-a),{width:a,height:i,x:o,y:l}}const Q1=25;function F7(s,e){const t=Na(s),n=Ii(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=bv();(!m||m&&e==="fixed")&&(l=a.offsetLeft,c=a.offsetTop)}const d=Pm(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<=Q1&&(i-=x)}else d<=Q1&&(i+=d);return{width:i,height:o,x:l,y:c}}const $7=new Set(["absolute","fixed"]);function H7(s,e){const t=ll(s,!0,e==="fixed"),n=t.top+s.clientTop,a=t.left+s.clientLeft,i=Ri(s)?pc(s):_i(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 J1(s,e,t){let n;if(e==="viewport")n=F7(s,t);else if(e==="document")n=z7(Ii(s));else if(Ws(e))n=H7(e,t);else{const a=HE(s);n={x:e.x-a.x,y:e.y-a.y,width:e.width,height:e.height}}return nm(n)}function GE(s,e){const t=oo(s);return t===e||!Ws(t)||jc(t)?!1:Ga(t).position==="fixed"||GE(t,e)}function U7(s,e){const t=e.get(s);if(t)return t;let n=gd(s,[],!1).filter(l=>Ws(l)&&Rc(l)!=="body"),a=null;const i=Ga(s).position==="fixed";let o=i?oo(s):s;for(;Ws(o)&&!jc(o);){const l=Ga(o),c=gv(o);!c&&l.position==="fixed"&&(a=null),(i?!c&&!a:!c&&l.position==="static"&&!!a&&$7.has(a.position)||Ad(o)&&!c&&GE(s,o))?n=n.filter(m=>m!==o):a=l,o=oo(o)}return e.set(s,n),n}function G7(s){let{element:e,boundary:t,rootBoundary:n,strategy:a}=s;const o=[...t==="clippingAncestors"?_m(e)?[]:U7(e,this._c):[].concat(t),n],l=o[0],c=o.reduce((d,m)=>{const p=J1(e,m,a);return d.top=Zo(p.top,d.top),d.right=Cc(p.right,d.right),d.bottom=Cc(p.bottom,d.bottom),d.left=Zo(p.left,d.left),d},J1(e,l,a));return{width:c.right-c.left,height:c.bottom-c.top,x:c.left,y:c.top}}function W7(s){const{width:e,height:t}=$E(s);return{width:e,height:t}}function q7(s,e,t){const n=Ri(e),a=Ii(e),i=t==="fixed",o=ll(s,!0,i,e);let l={scrollLeft:0,scrollTop:0};const c=_i(0);function d(){c.x=Pm(a)}if(n||!n&&!i)if((Rc(e)!=="body"||Ad(a))&&(l=Dm(e)),n){const b=ll(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?UE(a,l):_i(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 Ib(s){return Ga(s).position==="static"}function eN(s,e){if(!Ri(s)||Ga(s).position==="fixed")return null;if(e)return e(s);let t=s.offsetParent;return Ii(s)===t&&(t=t.ownerDocument.body),t}function WE(s,e){const t=Na(s);if(_m(s))return t;if(!Ri(s)){let a=oo(s);for(;a&&!jc(a);){if(Ws(a)&&!Ib(a))return a;a=oo(a)}return t}let n=eN(s,e);for(;n&&s7(n)&&Ib(n);)n=eN(n,e);return n&&jc(n)&&Ib(n)&&!gv(n)?t:n||l7(s)||t}const Y7=async function(s){const e=this.getOffsetParent||WE,t=this.getDimensions,n=await t(s.floating);return{reference:q7(s.reference,await e(s.floating),s.strategy),floating:{x:0,y:0,width:n.width,height:n.height}}};function V7(s){return Ga(s).direction==="rtl"}const K7={convertOffsetParentRelativeRectToViewportRelativeRect:I7,getDocumentElement:Ii,getClippingRect:G7,getOffsetParent:WE,getElementRects:Y7,getClientRects:B7,getDimensions:W7,getScale:pc,isElement:Ws,isRTL:V7};function qE(s,e){return s.x===e.x&&s.y===e.y&&s.width===e.width&&s.height===e.height}function X7(s,e){let t=null,n;const a=Ii(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=sp(p),w=sp(a.clientWidth-(m+f)),k=sp(a.clientHeight-(p+b)),j=sp(m),C={rootMargin:-x+"px "+-w+"px "+-k+"px "+-j+"px",threshold:Zo(0,Cc(1,c))||1};let A=!0;function _(T){const P=T[0].intersectionRatio;if(P!==c){if(!A)return o();P?o(!1,P):n=setTimeout(()=>{o(!1,1e-7)},1e3)}P===1&&!qE(d,s.getBoundingClientRect())&&o(),A=!1}try{t=new IntersectionObserver(_,{...C,root:a.ownerDocument})}catch{t=new IntersectionObserver(_,C)}t.observe(s)}return o(!0),i}function Z7(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=vv(s),m=a||i?[...d?gd(d):[],...gd(e)]:[];m.forEach(j=>{a&&j.addEventListener("scroll",t,{passive:!0}),i&&j.addEventListener("resize",t)});const p=d&&l?X7(d,t):null;let f=-1,b=null;o&&(b=new ResizeObserver(j=>{let[S]=j;S&&S.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?ll(s):null;c&&k();function k(){const j=ll(s);w&&!qE(w,j)&&t(),w=j,x=requestAnimationFrame(k)}return t(),()=>{var j;m.forEach(S=>{a&&S.removeEventListener("scroll",t),i&&S.removeEventListener("resize",t)}),p==null||p(),(j=b)==null||j.disconnect(),b=null,c&&cancelAnimationFrame(x)}}const Q7=P7,J7=_7,tN=E7,eq=(s,e,t)=>{const n=new Map,a={platform:K7,...t},i={...a.platform,_c:n};return T7(s,e,{...a,platform:i})};var tq=typeof document<"u",nq=function(){},vp=tq?y.useLayoutEffect:nq;function am(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(!am(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)&&!am(s[i],e[i]))return!1}return!0}return s!==s&&e!==e}function YE(s){return typeof window>"u"?1:(s.ownerDocument.defaultView||window).devicePixelRatio||1}function nN(s,e){const t=YE(s);return Math.round(e*t)/t}function Bb(s){const e=y.useRef(s);return vp(()=>{e.current=s}),e}function sq(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);am(f,n)||b(n);const[x,w]=y.useState(null),[k,j]=y.useState(null),S=y.useCallback(K=>{K!==T.current&&(T.current=K,w(K))},[]),C=y.useCallback(K=>{K!==P.current&&(P.current=K,j(K))},[]),A=i||x,_=o||k,T=y.useRef(null),P=y.useRef(null),M=y.useRef(m),D=c!=null,R=Bb(c),L=Bb(a),O=Bb(d),I=y.useCallback(()=>{if(!T.current||!P.current)return;const K={placement:e,strategy:t,middleware:f};L.current&&(K.platform=L.current),eq(T.current,P.current,K).then(Q=>{const H={...Q,isPositioned:O.current!==!1};B.current&&!am(M.current,H)&&(M.current=H,Tc.flushSync(()=>{p(H)}))})},[f,e,t,L,O]);vp(()=>{d===!1&&M.current.isPositioned&&(M.current.isPositioned=!1,p(K=>({...K,isPositioned:!1})))},[d]);const B=y.useRef(!1);vp(()=>(B.current=!0,()=>{B.current=!1}),[]),vp(()=>{if(A&&(T.current=A),_&&(P.current=_),A&&_){if(R.current)return R.current(A,_,I);I()}},[A,_,I,R,D]);const G=y.useMemo(()=>({reference:T,floating:P,setReference:S,setFloating:C}),[S,C]),$=y.useMemo(()=>({reference:A,floating:_}),[A,_]),Y=y.useMemo(()=>{const K={position:t,left:0,top:0};if(!$.floating)return K;const Q=nN($.floating,m.x),H=nN($.floating,m.y);return l?{...K,transform:"translate("+Q+"px, "+H+"px)",...YE($.floating)>=1.5&&{willChange:"transform"}}:{position:t,left:Q,top:H}},[t,l,$.floating,m.x,m.y]);return y.useMemo(()=>({...m,update:I,refs:G,elements:$,floatingStyles:Y}),[m,I,G,$,Y])}const aq=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?tN({element:n.current,padding:a}).fn(t):{}:n?tN({element:n,padding:a}).fn(t):{}}}},iq=(s,e)=>({...Q7(s),options:[s,e]}),rq=(s,e)=>({...J7(s),options:[s,e]}),oq=(s,e)=>({...aq(s),options:[s,e]}),lq={...LA};let sN=!1,cq=0;const aN=()=>"floating-ui-"+Math.random().toString(36).slice(2,6)+cq++;function uq(){const[s,e]=y.useState(()=>sN?aN():void 0);return sm(()=>{s==null&&e(aN())},[]),y.useEffect(()=>{sN=!0},[]),s}const dq=lq.useId,VE=dq||uq,hq=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,j=VE(),[S,C]=y.useState(!1);if(sm(()=>{if(!a)return;Ga(a).direction==="rtl"&&C(!0)},[a]),!a)return null;const[A,_]=n.split("-"),T=A==="top"||A==="bottom";let P=p;(T&&o!=null&&o.x||!T&&o!=null&&o.y)&&(P=null);const M=m*2,D=M/2,R=l/2*(d/-8+1),L=c/2*d/4,O=!!b,I=P&&_==="end"?"bottom":"top";let B=P&&_==="end"?"right":"left";P&&S&&(B=_==="end"?"left":"right");const G=(i==null?void 0:i.x)!=null?P||i.x:"",$=(i==null?void 0:i.y)!=null?P||i.y:"",Y=b||"M0,0"+(" H"+l)+(" L"+(l-R)+","+(c-L))+(" Q"+l/2+","+c+" "+R+","+(c-L))+" Z",K={top:O?"rotate(180deg)":"",left:O?"rotate(90deg)":"rotate(-90deg)",bottom:O?"":"rotate(180deg)",right:O?"rotate(-90deg)":"rotate(90deg)"}[A];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]:G,[I]:$,[A]:T||O?"100%":"calc(100% - "+M/2+"px)",transform:[K,x].filter(Q=>!!Q).join(" "),...w},children:[M>0&&r.jsx("path",{clipPath:"url(#"+j+")",fill:"none",stroke:f,strokeWidth:M+(b?0:1),d:Y}),r.jsx("path",{stroke:M&&!b?k.fill:"none",d:Y}),r.jsx("clipPath",{id:j,children:r.jsx("rect",{x:-D,y:D*(O?-1:1),width:l+M,height:l})})]})});function pq(){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 mq=y.createContext(null),fq=y.createContext(null),gq=()=>{var s;return((s=y.useContext(mq))==null?void 0:s.id)||null},bq=()=>y.useContext(fq);function yq(s){const{open:e=!1,onOpenChange:t,elements:n}=s,a=VE(),i=y.useRef({}),[o]=y.useState(()=>pq()),l=gq()!=null,[c,d]=y.useState(n.reference),m=A7((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 xq(s){s===void 0&&(s={});const{nodeId:e}=s,t=yq({...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=bq();sm(()=>{m&&(p.current=m)},[m]);const b=sq({...s,elements:{...a,...l&&{reference:l}}}),x=y.useCallback(C=>{const A=Ws(C)?{getBoundingClientRect:()=>C.getBoundingClientRect(),getClientRects:()=>C.getClientRects(),contextElement:C}:C;c(A),b.refs.setReference(A)},[b.refs]),w=y.useCallback(C=>{(Ws(C)||C===null)&&(p.current=C,o(C)),(Ws(b.refs.reference.current)||b.refs.reference.current===null||C!==null&&!Ws(C))&&b.refs.setReference(C)},[b.refs]),k=y.useMemo(()=>({...b.refs,setReference:w,setPositionReference:x,domReference:p}),[b.refs,w,x]),j=y.useMemo(()=>({...b.elements,domReference:m}),[b.elements,m]),S=y.useMemo(()=>({...b,...n,refs:k,elements:j,nodeId:e}),[b,k,j,e,n]);return sm(()=>{n.dataRef.current.floatingContext=S;const C=f==null?void 0:f.nodesRef.current.find(A=>A.id===e);C&&(C.context=S)}),y.useMemo(()=>({...b,context:S,refs:k,elements:j}),[b,k,j,S])}/*!
|